@vivliostyle/core 2.34.1 → 2.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -6
- package/lib/vivliostyle/assets.d.ts +3 -3
- package/lib/vivliostyle/counters.d.ts +9 -0
- package/lib/vivliostyle/css-cascade.d.ts +12 -0
- package/lib/vivliostyle/footnotes.d.ts +1 -1
- package/lib/vivliostyle/layout-helper.d.ts +59 -4
- package/lib/vivliostyle/net.d.ts +1 -1
- package/lib/vivliostyle/page-floats.d.ts +3 -2
- package/lib/vivliostyle/types.d.ts +2 -1
- package/lib/vivliostyle.js +26 -19
- package/lib/vivliostyle.js.map +3 -3
- package/package.json +2 -2
package/lib/vivliostyle.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var bg=Object.create;var Io=Object.defineProperty;var xg=Object.getOwnPropertyDescriptor;var yg=Object.getOwnPropertyNames;var Eg=Object.getPrototypeOf,Sg=Object.prototype.hasOwnProperty;var Ng=(r,t,e)=>t in r?Io(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var vg=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Tg=(r,t)=>{for(var e in t)Io(r,e,{get:t[e],enumerable:!0})},Ep=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of yg(t))!Sg.call(r,s)&&s!==e&&Io(r,s,{get:()=>t[s],enumerable:!(n=xg(t,s))||n.enumerable});return r};var wg=(r,t,e)=>(e=r!=null?bg(Eg(r)):{},Ep(t||!r||!r.__esModule?Io(e,"default",{value:r,enumerable:!0}):e,r)),Pg=r=>Ep(Io({},"__esModule",{value:!0}),r);var d=(r,t,e)=>Ng(r,typeof t!="symbol"?t+"":t,e);var Sh=vg((zb,Eh)=>{var xt=-1,nt=1,Me=0;function Qo(r,t,e,n,s){if(r===t)return r?[[Me,r]]:[];if(e!=null){var o=Wm(r,t,e);if(o)return o}var i=vc(r,t),a=r.substring(0,i);r=r.substring(i),t=t.substring(i),i=Or(r,t);var l=r.substring(r.length-i);r=r.substring(0,r.length-i),t=t.substring(0,t.length-i);var c=Om(r,t);return a&&c.unshift([Me,a]),l&&c.push([Me,l]),Tc(c,s),n&&_m(c),c}function Om(r,t){var e;if(!r)return[[nt,t]];if(!t)return[[xt,r]];var n=r.length>t.length?r:t,s=r.length>t.length?t:r,o=n.indexOf(s);if(o!==-1)return e=[[nt,n.substring(0,o)],[Me,s],[nt,n.substring(o+s.length)]],r.length>t.length&&(e[0][0]=e[2][0]=xt),e;if(s.length===1)return[[xt,r],[nt,t]];var i=Mm(r,t);if(i){var a=i[0],l=i[1],c=i[2],u=i[3],p=i[4],h=Qo(a,c),f=Qo(l,u);return h.concat([[Me,p]],f)}return Dm(r,t)}function Dm(r,t){for(var e=r.length,n=t.length,s=Math.ceil((e+n)/2),o=s,i=2*s,a=new Array(i),l=new Array(i),c=0;c<i;c++)a[c]=-1,l[c]=-1;a[o+1]=0,l[o+1]=0;for(var u=e-n,p=u%2!==0,h=0,f=0,g=0,m=0,E=0;E<s;E++){for(var y=-E+h;y<=E-f;y+=2){var C=o+y,x;y===-E||y!==E&&a[C-1]<a[C+1]?x=a[C+1]:x=a[C-1]+1;for(var N=x-y;x<e&&N<n&&r.charAt(x)===t.charAt(N);)x++,N++;if(a[C]=x,x>e)f+=2;else if(N>n)h+=2;else if(p){var S=o+u-y;if(S>=0&&S<i&&l[S]!==-1){var w=e-l[S];if(x>=w)return ph(r,t,x,N)}}}for(var k=-E+g;k<=E-m;k+=2){var S=o+k,w;k===-E||k!==E&&l[S-1]<l[S+1]?w=l[S+1]:w=l[S-1]+1;for(var I=w-k;w<e&&I<n&&r.charAt(e-w-1)===t.charAt(n-I-1);)w++,I++;if(l[S]=w,w>e)m+=2;else if(I>n)g+=2;else if(!p){var C=o+u-k;if(C>=0&&C<i&&a[C]!==-1){var x=a[C],N=o+x-C;if(w=e-w,x>=w)return ph(r,t,x,N)}}}}return[[xt,r],[nt,t]]}function ph(r,t,e,n){var s=r.substring(0,e),o=t.substring(0,n),i=r.substring(e),a=t.substring(n),l=Qo(s,o),c=Qo(i,a);return l.concat(c)}function vc(r,t){if(!r||!t||r.charAt(0)!==t.charAt(0))return 0;for(var e=0,n=Math.min(r.length,t.length),s=n,o=0;e<s;)r.substring(o,s)==t.substring(o,s)?(e=s,o=e):n=s,s=Math.floor((n-e)/2+e);return Ch(r.charCodeAt(s-1))&&s--,s}function hh(r,t){var e=r.length,n=t.length;if(e==0||n==0)return 0;e>n?r=r.substring(e-n):e<n&&(t=t.substring(0,e));var s=Math.min(e,n);if(r==t)return s;for(var o=0,i=1;;){var a=r.substring(s-i),l=t.indexOf(a);if(l==-1)return o;i+=l,(l==0||r.substring(s-i)==t.substring(0,i))&&(o=i,i++)}}function Or(r,t){if(!r||!t||r.slice(-1)!==t.slice(-1))return 0;for(var e=0,n=Math.min(r.length,t.length),s=n,o=0;e<s;)r.substring(r.length-s,r.length-o)==t.substring(t.length-s,t.length-o)?(e=s,o=e):n=s,s=Math.floor((n-e)/2+e);return bh(r.charCodeAt(r.length-s))&&s--,s}function Mm(r,t){var e=r.length>t.length?r:t,n=r.length>t.length?t:r;if(e.length<4||n.length*2<e.length)return null;function s(f,g,m){for(var E=f.substring(m,m+Math.floor(f.length/4)),y=-1,C="",x,N,S,w;(y=g.indexOf(E,y+1))!==-1;){var k=vc(f.substring(m),g.substring(y)),I=Or(f.substring(0,m),g.substring(0,y));C.length<I+k&&(C=g.substring(y-I,y)+g.substring(y,y+k),x=f.substring(0,m-I),N=f.substring(m+k),S=g.substring(0,y-I),w=g.substring(y+k))}return C.length*2>=f.length?[x,N,S,w,C]:null}var o=s(e,n,Math.ceil(e.length/4)),i=s(e,n,Math.ceil(e.length/2)),a;if(!o&&!i)return null;i?o?a=o[4].length>i[4].length?o:i:a=i:a=o;var l,c,u,p;r.length>t.length?(l=a[0],c=a[1],u=a[2],p=a[3]):(u=a[0],p=a[1],l=a[2],c=a[3]);var h=a[4];return[l,c,u,p,h]}function _m(r){for(var t=!1,e=[],n=0,s=null,o=0,i=0,a=0,l=0,c=0;o<r.length;)r[o][0]==Me?(e[n++]=o,i=l,a=c,l=0,c=0,s=r[o][1]):(r[o][0]==nt?l+=r[o][1].length:c+=r[o][1].length,s&&s.length<=Math.max(i,a)&&s.length<=Math.max(l,c)&&(r.splice(e[n-1],0,[xt,s]),r[e[n-1]+1][0]=nt,n--,n--,o=n>0?e[n-1]:-1,i=0,a=0,l=0,c=0,s=null,t=!0)),o++;for(t&&Tc(r),zm(r),o=1;o<r.length;){if(r[o-1][0]==xt&&r[o][0]==nt){var u=r[o-1][1],p=r[o][1],h=hh(u,p),f=hh(p,u);h>=f?(h>=u.length/2||h>=p.length/2)&&(r.splice(o,0,[Me,p.substring(0,h)]),r[o-1][1]=u.substring(0,u.length-h),r[o+1][1]=p.substring(h),o++):(f>=u.length/2||f>=p.length/2)&&(r.splice(o,0,[Me,u.substring(0,f)]),r[o-1][0]=nt,r[o-1][1]=p.substring(0,p.length-f),r[o+1][0]=xt,r[o+1][1]=u.substring(f),o++),o++}o++}}var fh=/[^a-zA-Z0-9]/,gh=/\s/,mh=/[\r\n]/,Um=/\n\r?\n$/,Hm=/^\r?\n\r?\n/;function zm(r){function t(f,g){if(!f||!g)return 6;var m=f.charAt(f.length-1),E=g.charAt(0),y=m.match(fh),C=E.match(fh),x=y&&m.match(gh),N=C&&E.match(gh),S=x&&m.match(mh),w=N&&E.match(mh),k=S&&f.match(Um),I=w&&g.match(Hm);return k||I?5:S||w?4:y&&!x&&N?3:x||N?2:y||C?1:0}for(var e=1;e<r.length-1;){if(r[e-1][0]==Me&&r[e+1][0]==Me){var n=r[e-1][1],s=r[e][1],o=r[e+1][1],i=Or(n,s);if(i){var a=s.substring(s.length-i);n=n.substring(0,n.length-i),s=a+s.substring(0,s.length-i),o=a+o}for(var l=n,c=s,u=o,p=t(n,s)+t(s,o);s.charAt(0)===o.charAt(0);){n+=s.charAt(0),s=s.substring(1)+o.charAt(0),o=o.substring(1);var h=t(n,s)+t(s,o);h>=p&&(p=h,l=n,c=s,u=o)}r[e-1][1]!=l&&(l?r[e-1][1]=l:(r.splice(e-1,1),e--),r[e][1]=c,u?r[e+1][1]=u:(r.splice(e+1,1),e--))}e++}}function Tc(r,t){r.push([Me,""]);for(var e=0,n=0,s=0,o="",i="",a;e<r.length;){if(e<r.length-1&&!r[e][1]){r.splice(e,1);continue}switch(r[e][0]){case nt:s++,i+=r[e][1],e++;break;case xt:n++,o+=r[e][1],e++;break;case Me:var l=e-s-n-1;if(t){if(l>=0&&yh(r[l][1])){var c=r[l][1].slice(-1);if(r[l][1]=r[l][1].slice(0,-1),o=c+o,i=c+i,!r[l][1]){r.splice(l,1),e--;var u=l-1;r[u]&&r[u][0]===nt&&(s++,i=r[u][1]+i,u--),r[u]&&r[u][0]===xt&&(n++,o=r[u][1]+o,u--),l=u}}if(xh(r[e][1])){var c=r[e][1].charAt(0);r[e][1]=r[e][1].slice(1),o+=c,i+=c}}if(e<r.length-1&&!r[e][1]){r.splice(e,1);break}if(o.length>0||i.length>0){o.length>0&&i.length>0&&(a=vc(i,o),a!==0&&(l>=0?r[l][1]+=i.substring(0,a):(r.splice(0,0,[Me,i.substring(0,a)]),e++),i=i.substring(a),o=o.substring(a)),a=Or(i,o),a!==0&&(r[e][1]=i.substring(i.length-a)+r[e][1],i=i.substring(0,i.length-a),o=o.substring(0,o.length-a)));var p=s+n;o.length===0&&i.length===0?(r.splice(e-p,p),e=e-p):o.length===0?(r.splice(e-p,p,[nt,i]),e=e-p+1):i.length===0?(r.splice(e-p,p,[xt,o]),e=e-p+1):(r.splice(e-p,p,[xt,o],[nt,i]),e=e-p+2)}e!==0&&r[e-1][0]===Me?(r[e-1][1]+=r[e][1],r.splice(e,1)):e++,s=0,n=0,o="",i="";break}}r[r.length-1][1]===""&&r.pop();var h=!1;for(e=1;e<r.length-1;)r[e-1][0]===Me&&r[e+1][0]===Me&&(r[e][1].substring(r[e][1].length-r[e-1][1].length)===r[e-1][1]?(r[e][1]=r[e-1][1]+r[e][1].substring(0,r[e][1].length-r[e-1][1].length),r[e+1][1]=r[e-1][1]+r[e+1][1],r.splice(e-1,1),h=!0):r[e][1].substring(0,r[e+1][1].length)==r[e+1][1]&&(r[e-1][1]+=r[e+1][1],r[e][1]=r[e][1].substring(r[e+1][1].length)+r[e+1][1],r.splice(e+1,1),h=!0)),e++;h&&Tc(r,t)}function Ch(r){return r>=55296&&r<=56319}function bh(r){return r>=56320&&r<=57343}function xh(r){return bh(r.charCodeAt(0))}function yh(r){return Ch(r.charCodeAt(r.length-1))}function Gm(r){for(var t=[],e=0;e<r.length;e++)r[e][1].length>0&&t.push(r[e]);return t}function Nc(r,t,e,n){return yh(r)||xh(n)?null:Gm([[Me,r],[xt,t],[nt,e],[Me,n]])}function Wm(r,t,e){var n=typeof e=="number"?{index:e,length:0}:e.oldRange,s=typeof e=="number"?null:e.newRange,o=r.length,i=t.length;if(n.length===0&&(s===null||s.length===0)){var a=n.index,l=r.slice(0,a),c=r.slice(a),u=s?s.index:null;e:{var p=a+i-o;if(u!==null&&u!==p||p<0||p>i)break e;var h=t.slice(0,p),f=t.slice(p);if(f!==c)break e;var g=Math.min(a,p),m=l.slice(0,g),E=h.slice(0,g);if(m!==E)break e;var y=l.slice(g),C=h.slice(g);return Nc(m,y,C,c)}e:{if(u!==null&&u!==a)break e;var x=a,h=t.slice(0,x),f=t.slice(x);if(h!==l)break e;var N=Math.min(o-x,i-x),S=c.slice(c.length-N),w=f.slice(f.length-N);if(S!==w)break e;var y=c.slice(0,c.length-N),C=f.slice(0,f.length-N);return Nc(l,y,C,S)}}if(n.length>0&&s&&s.length===0)e:{var m=r.slice(0,n.index),S=r.slice(n.index+n.length),g=m.length,N=S.length;if(i<g+N)break e;var E=t.slice(0,g),w=t.slice(i-N);if(m!==E||S!==w)break e;var y=r.slice(g,o-N),C=t.slice(g,i-N);return Nc(m,y,C,S)}return null}function Dr(r,t,e,n){return Qo(r,t,e,n,!0)}Dr.INSERT=nt;Dr.DELETE=xt;Dr.EQUAL=Me;Eh.exports=Dr});var Sb={};Tg(Sb,{CoreViewer:()=>Wi,HOOKS:()=>ht,Navigation:()=>pg,PageProgression:()=>ss,PageSide:()=>Vo,PageViewMode:()=>yb,Profiler:()=>Ki,ReadyState:()=>pl,UserAgentBaseCss:()=>dc,UserAgentPageCss:()=>uc,UserAgentTocCss:()=>pc,UserAgentXml:()=>cc,ValidationTxt:()=>lc,VivliostylePolyfillCss:()=>hc,VivliostyleViewportCss:()=>ac,VivliostyleViewportScreenCss:()=>rc,ZoomType:()=>xb,getHooksForName:()=>We,isDebug:()=>ns,pageProgressionOf:()=>dl,plugin:()=>kg,printHTML:()=>Eb,profile:()=>Ig,profiler:()=>Ye,registerHook:()=>_e,removeHook:()=>Sp,setDebug:()=>ul});module.exports=Pg(Sb);var ns=!1;function ul(r){ns=r}var ss=(e=>(e.LTR="ltr",e.RTL="rtl",e))(ss||{});function dl(r){switch(r){case"ltr":return"ltr";case"rtl":return"rtl";default:throw new Error(`unknown PageProgression: ${r}`)}}var Vo=(e=>(e.LEFT="left",e.RIGHT="right",e))(Vo||{}),pl=(n=>(n.LOADING="loading",n.INTERACTIVE="interactive",n.COMPLETE="complete",n))(pl||{});var fl=(s=>(s[s.DEBUG=1]="DEBUG",s[s.INFO=2]="INFO",s[s.WARN=3]="WARN",s[s.ERROR=4]="ERROR",s))(fl||{}),hl=class{constructor(t){this.opt_console=t;d(this,"listeners",{})}consoleDebug(t){this.opt_console?this.opt_console.debug?this.opt_console.debug(...t):this.opt_console.log(...t):console.debug(...t)}consoleInfo(t){this.opt_console?this.opt_console.info?this.opt_console.info(...t):this.opt_console.log(...t):console.info(...t)}consoleWarn(t){this.opt_console?this.opt_console.warn?this.opt_console.warn(...t):this.opt_console.log(...t):console.warn(...t)}consoleError(t){this.opt_console?this.opt_console.error?this.opt_console.error(...t):this.opt_console.log(...t):console.error(...t)}triggerListeners(t,e){let n=this.listeners[t];n&&n(e)}addListener(t,e){this.listeners[t]=e}debug(...t){let e=Xi(arguments);this.consoleDebug(ji(e)),this.triggerListeners(1,e)}info(...t){let e=Xi(arguments);this.consoleInfo(ji(e)),this.triggerListeners(2,e)}warn(...t){let e=Xi(arguments);this.consoleWarn(ji(e)),this.triggerListeners(3,e)}error(...t){let e=Xi(arguments);this.consoleError(ji(e)),this.triggerListeners(4,e)}};function Xi(r){let t=Array.from(r),e=null;return t[0]instanceof Error&&(e=t.shift()),{error:e,messages:t}}function ji(r){let t=r.error,e=t&&(t.frameTrace||t.stack),n=[].concat(r.messages);return t&&(n.length>0&&(n=n.concat([`
|
|
1
|
+
"use strict";var Fg=Object.create;var Oo=Object.defineProperty;var Bg=Object.getOwnPropertyDescriptor;var Og=Object.getOwnPropertyNames;var Dg=Object.getPrototypeOf,Mg=Object.prototype.hasOwnProperty;var _g=(r,t,e)=>t in r?Oo(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var Ug=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Hg=(r,t)=>{for(var e in t)Oo(r,e,{get:t[e],enumerable:!0})},Vp=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Og(t))!Mg.call(r,s)&&s!==e&&Oo(r,s,{get:()=>t[s],enumerable:!(n=Bg(t,s))||n.enumerable});return r};var zg=(r,t,e)=>(e=r!=null?Fg(Dg(r)):{},Vp(t||!r||!r.__esModule?Oo(e,"default",{value:r,enumerable:!0}):e,r)),Gg=r=>Vp(Oo({},"__esModule",{value:!0}),r);var p=(r,t,e)=>_g(r,typeof t!="symbol"?t+"":t,e);var Bh=Ug((ox,Fh)=>{var Et=-1,st=1,Me=0;function ni(r,t,e,n,s){if(r===t)return r?[[Me,r]]:[];if(e!=null){var o=rC(r,t,e);if(o)return o}var i=Vc(r,t),a=r.substring(0,i);r=r.substring(i),t=t.substring(i),i=Gr(r,t);var l=r.substring(r.length-i);r=r.substring(0,r.length-i),t=t.substring(0,t.length-i);var c=Qm(r,t);return a&&c.unshift([Me,a]),l&&c.push([Me,l]),Fc(c,s),n&&tC(c),c}function Qm(r,t){var e;if(!r)return[[st,t]];if(!t)return[[Et,r]];var n=r.length>t.length?r:t,s=r.length>t.length?t:r,o=n.indexOf(s);if(o!==-1)return e=[[st,n.substring(0,o)],[Me,s],[st,n.substring(o+s.length)]],r.length>t.length&&(e[0][0]=e[2][0]=Et),e;if(s.length===1)return[[Et,r],[st,t]];var i=eC(r,t);if(i){var a=i[0],l=i[1],c=i[2],u=i[3],d=i[4],h=ni(a,c),f=ni(l,u);return h.concat([[Me,d]],f)}return Jm(r,t)}function Jm(r,t){for(var e=r.length,n=t.length,s=Math.ceil((e+n)/2),o=s,i=2*s,a=new Array(i),l=new Array(i),c=0;c<i;c++)a[c]=-1,l[c]=-1;a[o+1]=0,l[o+1]=0;for(var u=e-n,d=u%2!==0,h=0,f=0,g=0,m=0,y=0;y<s;y++){for(var E=-y+h;E<=y-f;E+=2){var C=o+E,x;E===-y||E!==y&&a[C-1]<a[C+1]?x=a[C+1]:x=a[C-1]+1;for(var N=x-E;x<e&&N<n&&r.charAt(x)===t.charAt(N);)x++,N++;if(a[C]=x,x>e)f+=2;else if(N>n)h+=2;else if(d){var S=o+u-E;if(S>=0&&S<i&&l[S]!==-1){var w=e-l[S];if(x>=w)return Th(r,t,x,N)}}}for(var k=-y+g;k<=y-m;k+=2){var S=o+k,w;k===-y||k!==y&&l[S-1]<l[S+1]?w=l[S+1]:w=l[S-1]+1;for(var R=w-k;w<e&&R<n&&r.charAt(e-w-1)===t.charAt(n-R-1);)w++,R++;if(l[S]=w,w>e)m+=2;else if(R>n)g+=2;else if(!d){var C=o+u-k;if(C>=0&&C<i&&a[C]!==-1){var x=a[C],N=o+x-C;if(w=e-w,x>=w)return Th(r,t,x,N)}}}}return[[Et,r],[st,t]]}function Th(r,t,e,n){var s=r.substring(0,e),o=t.substring(0,n),i=r.substring(e),a=t.substring(n),l=ni(s,o),c=ni(i,a);return l.concat(c)}function Vc(r,t){if(!r||!t||r.charAt(0)!==t.charAt(0))return 0;for(var e=0,n=Math.min(r.length,t.length),s=n,o=0;e<s;)r.substring(o,s)==t.substring(o,s)?(e=s,o=e):n=s,s=Math.floor((n-e)/2+e);return Lh(r.charCodeAt(s-1))&&s--,s}function wh(r,t){var e=r.length,n=t.length;if(e==0||n==0)return 0;e>n?r=r.substring(e-n):e<n&&(t=t.substring(0,e));var s=Math.min(e,n);if(r==t)return s;for(var o=0,i=1;;){var a=r.substring(s-i),l=t.indexOf(a);if(l==-1)return o;i+=l,(l==0||r.substring(s-i)==t.substring(0,i))&&(o=i,i++)}}function Gr(r,t){if(!r||!t||r.slice(-1)!==t.slice(-1))return 0;for(var e=0,n=Math.min(r.length,t.length),s=n,o=0;e<s;)r.substring(r.length-s,r.length-o)==t.substring(t.length-s,t.length-o)?(e=s,o=e):n=s,s=Math.floor((n-e)/2+e);return Rh(r.charCodeAt(r.length-s))&&s--,s}function eC(r,t){var e=r.length>t.length?r:t,n=r.length>t.length?t:r;if(e.length<4||n.length*2<e.length)return null;function s(f,g,m){for(var y=f.substring(m,m+Math.floor(f.length/4)),E=-1,C="",x,N,S,w;(E=g.indexOf(y,E+1))!==-1;){var k=Vc(f.substring(m),g.substring(E)),R=Gr(f.substring(0,m),g.substring(0,E));C.length<R+k&&(C=g.substring(E-R,E)+g.substring(E,E+k),x=f.substring(0,m-R),N=f.substring(m+k),S=g.substring(0,E-R),w=g.substring(E+k))}return C.length*2>=f.length?[x,N,S,w,C]:null}var o=s(e,n,Math.ceil(e.length/4)),i=s(e,n,Math.ceil(e.length/2)),a;if(!o&&!i)return null;i?o?a=o[4].length>i[4].length?o:i:a=i:a=o;var l,c,u,d;r.length>t.length?(l=a[0],c=a[1],u=a[2],d=a[3]):(u=a[0],d=a[1],l=a[2],c=a[3]);var h=a[4];return[l,c,u,d,h]}function tC(r){for(var t=!1,e=[],n=0,s=null,o=0,i=0,a=0,l=0,c=0;o<r.length;)r[o][0]==Me?(e[n++]=o,i=l,a=c,l=0,c=0,s=r[o][1]):(r[o][0]==st?l+=r[o][1].length:c+=r[o][1].length,s&&s.length<=Math.max(i,a)&&s.length<=Math.max(l,c)&&(r.splice(e[n-1],0,[Et,s]),r[e[n-1]+1][0]=st,n--,n--,o=n>0?e[n-1]:-1,i=0,a=0,l=0,c=0,s=null,t=!0)),o++;for(t&&Fc(r),oC(r),o=1;o<r.length;){if(r[o-1][0]==Et&&r[o][0]==st){var u=r[o-1][1],d=r[o][1],h=wh(u,d),f=wh(d,u);h>=f?(h>=u.length/2||h>=d.length/2)&&(r.splice(o,0,[Me,d.substring(0,h)]),r[o-1][1]=u.substring(0,u.length-h),r[o+1][1]=d.substring(h),o++):(f>=u.length/2||f>=d.length/2)&&(r.splice(o,0,[Me,u.substring(0,f)]),r[o-1][0]=st,r[o-1][1]=d.substring(0,d.length-f),r[o+1][0]=Et,r[o+1][1]=u.substring(f),o++),o++}o++}}var Ph=/[^a-zA-Z0-9]/,kh=/\s/,Ah=/[\r\n]/,nC=/\n\r?\n$/,sC=/^\r?\n\r?\n/;function oC(r){function t(f,g){if(!f||!g)return 6;var m=f.charAt(f.length-1),y=g.charAt(0),E=m.match(Ph),C=y.match(Ph),x=E&&m.match(kh),N=C&&y.match(kh),S=x&&m.match(Ah),w=N&&y.match(Ah),k=S&&f.match(nC),R=w&&g.match(sC);return k||R?5:S||w?4:E&&!x&&N?3:x||N?2:E||C?1:0}for(var e=1;e<r.length-1;){if(r[e-1][0]==Me&&r[e+1][0]==Me){var n=r[e-1][1],s=r[e][1],o=r[e+1][1],i=Gr(n,s);if(i){var a=s.substring(s.length-i);n=n.substring(0,n.length-i),s=a+s.substring(0,s.length-i),o=a+o}for(var l=n,c=s,u=o,d=t(n,s)+t(s,o);s.charAt(0)===o.charAt(0);){n+=s.charAt(0),s=s.substring(1)+o.charAt(0),o=o.substring(1);var h=t(n,s)+t(s,o);h>=d&&(d=h,l=n,c=s,u=o)}r[e-1][1]!=l&&(l?r[e-1][1]=l:(r.splice(e-1,1),e--),r[e][1]=c,u?r[e+1][1]=u:(r.splice(e+1,1),e--))}e++}}function Fc(r,t){r.push([Me,""]);for(var e=0,n=0,s=0,o="",i="",a;e<r.length;){if(e<r.length-1&&!r[e][1]){r.splice(e,1);continue}switch(r[e][0]){case st:s++,i+=r[e][1],e++;break;case Et:n++,o+=r[e][1],e++;break;case Me:var l=e-s-n-1;if(t){if(l>=0&&Vh(r[l][1])){var c=r[l][1].slice(-1);if(r[l][1]=r[l][1].slice(0,-1),o=c+o,i=c+i,!r[l][1]){r.splice(l,1),e--;var u=l-1;r[u]&&r[u][0]===st&&(s++,i=r[u][1]+i,u--),r[u]&&r[u][0]===Et&&(n++,o=r[u][1]+o,u--),l=u}}if(Ih(r[e][1])){var c=r[e][1].charAt(0);r[e][1]=r[e][1].slice(1),o+=c,i+=c}}if(e<r.length-1&&!r[e][1]){r.splice(e,1);break}if(o.length>0||i.length>0){o.length>0&&i.length>0&&(a=Vc(i,o),a!==0&&(l>=0?r[l][1]+=i.substring(0,a):(r.splice(0,0,[Me,i.substring(0,a)]),e++),i=i.substring(a),o=o.substring(a)),a=Gr(i,o),a!==0&&(r[e][1]=i.substring(i.length-a)+r[e][1],i=i.substring(0,i.length-a),o=o.substring(0,o.length-a)));var d=s+n;o.length===0&&i.length===0?(r.splice(e-d,d),e=e-d):o.length===0?(r.splice(e-d,d,[st,i]),e=e-d+1):i.length===0?(r.splice(e-d,d,[Et,o]),e=e-d+1):(r.splice(e-d,d,[Et,o],[st,i]),e=e-d+2)}e!==0&&r[e-1][0]===Me?(r[e-1][1]+=r[e][1],r.splice(e,1)):e++,s=0,n=0,o="",i="";break}}r[r.length-1][1]===""&&r.pop();var h=!1;for(e=1;e<r.length-1;)r[e-1][0]===Me&&r[e+1][0]===Me&&(r[e][1].substring(r[e][1].length-r[e-1][1].length)===r[e-1][1]?(r[e][1]=r[e-1][1]+r[e][1].substring(0,r[e][1].length-r[e-1][1].length),r[e+1][1]=r[e-1][1]+r[e+1][1],r.splice(e-1,1),h=!0):r[e][1].substring(0,r[e+1][1].length)==r[e+1][1]&&(r[e-1][1]+=r[e+1][1],r[e][1]=r[e][1].substring(r[e+1][1].length)+r[e+1][1],r.splice(e+1,1),h=!0)),e++;h&&Fc(r,t)}function Lh(r){return r>=55296&&r<=56319}function Rh(r){return r>=56320&&r<=57343}function Ih(r){return Rh(r.charCodeAt(0))}function Vh(r){return Lh(r.charCodeAt(r.length-1))}function iC(r){for(var t=[],e=0;e<r.length;e++)r[e][1].length>0&&t.push(r[e]);return t}function Ic(r,t,e,n){return Vh(r)||Ih(n)?null:iC([[Me,r],[Et,t],[st,e],[Me,n]])}function rC(r,t,e){var n=typeof e=="number"?{index:e,length:0}:e.oldRange,s=typeof e=="number"?null:e.newRange,o=r.length,i=t.length;if(n.length===0&&(s===null||s.length===0)){var a=n.index,l=r.slice(0,a),c=r.slice(a),u=s?s.index:null;e:{var d=a+i-o;if(u!==null&&u!==d||d<0||d>i)break e;var h=t.slice(0,d),f=t.slice(d);if(f!==c)break e;var g=Math.min(a,d),m=l.slice(0,g),y=h.slice(0,g);if(m!==y)break e;var E=l.slice(g),C=h.slice(g);return Ic(m,E,C,c)}e:{if(u!==null&&u!==a)break e;var x=a,h=t.slice(0,x),f=t.slice(x);if(h!==l)break e;var N=Math.min(o-x,i-x),S=c.slice(c.length-N),w=f.slice(f.length-N);if(S!==w)break e;var E=c.slice(0,c.length-N),C=f.slice(0,f.length-N);return Ic(l,E,C,S)}}if(n.length>0&&s&&s.length===0)e:{var m=r.slice(0,n.index),S=r.slice(n.index+n.length),g=m.length,N=S.length;if(i<g+N)break e;var y=t.slice(0,g),w=t.slice(i-N);if(m!==y||S!==w)break e;var E=r.slice(g,o-N),C=t.slice(g,i-N);return Ic(m,E,C,S)}return null}function Wr(r,t,e,n){return ni(r,t,e,n,!0)}Wr.INSERT=st;Wr.DELETE=Et;Wr.EQUAL=Me;Fh.exports=Wr});var Mb={};Hg(Mb,{CoreViewer:()=>qi,HOOKS:()=>ft,Navigation:()=>kg,PageProgression:()=>os,PageSide:()=>Do,PageViewMode:()=>Ob,Profiler:()=>nr,ReadyState:()=>yl,UserAgentBaseCss:()=>yc,UserAgentPageCss:()=>xc,UserAgentTocCss:()=>Ec,UserAgentXml:()=>bc,ValidationTxt:()=>Cc,VivliostylePolyfillCss:()=>Sc,VivliostyleViewportCss:()=>mc,VivliostyleViewportScreenCss:()=>gc,ZoomType:()=>Bb,getHooksForName:()=>Ge,isDebug:()=>ss,pageProgressionOf:()=>xl,plugin:()=>Wg,printHTML:()=>Db,profile:()=>Yg,profiler:()=>Ye,registerHook:()=>Ue,removeHook:()=>Fp,setDebug:()=>bl});module.exports=Gg(Mb);var ss=!1;function bl(r){ss=r}var os=(e=>(e.LTR="ltr",e.RTL="rtl",e))(os||{});function xl(r){switch(r){case"ltr":return"ltr";case"rtl":return"rtl";default:throw new Error(`unknown PageProgression: ${r}`)}}var Do=(e=>(e.LEFT="left",e.RIGHT="right",e))(Do||{}),yl=(n=>(n.LOADING="loading",n.INTERACTIVE="interactive",n.COMPLETE="complete",n))(yl||{});var Sl=(s=>(s[s.DEBUG=1]="DEBUG",s[s.INFO=2]="INFO",s[s.WARN=3]="WARN",s[s.ERROR=4]="ERROR",s))(Sl||{}),El=class{constructor(t){this.opt_console=t;p(this,"listeners",{})}consoleDebug(t){this.opt_console?this.opt_console.debug?this.opt_console.debug(...t):this.opt_console.log(...t):console.debug(...t)}consoleInfo(t){this.opt_console?this.opt_console.info?this.opt_console.info(...t):this.opt_console.log(...t):console.info(...t)}consoleWarn(t){this.opt_console?this.opt_console.warn?this.opt_console.warn(...t):this.opt_console.log(...t):console.warn(...t)}consoleError(t){this.opt_console?this.opt_console.error?this.opt_console.error(...t):this.opt_console.log(...t):console.error(...t)}triggerListeners(t,e){let n=this.listeners[t];n&&n(e)}addListener(t,e){this.listeners[t]=e}debug(...t){let e=Ji(arguments);this.consoleDebug(er(e)),this.triggerListeners(1,e)}info(...t){let e=Ji(arguments);this.consoleInfo(er(e)),this.triggerListeners(2,e)}warn(...t){let e=Ji(arguments);this.consoleWarn(er(e)),this.triggerListeners(3,e)}error(...t){let e=Ji(arguments);this.consoleError(er(e)),this.triggerListeners(4,e)}};function Ji(r){let t=Array.from(r),e=null;return t[0]instanceof Error&&(e=t.shift()),{error:e,messages:t}}function er(r){let t=r.error,e=t&&(t.frameTrace||t.stack),n=[].concat(r.messages);return t&&(n.length>0&&(n=n.concat([`
|
|
2
2
|
`])),n=n.concat([t.toString()]),e&&(n=n.concat([`
|
|
3
|
-
`]).concat(e))),n}var V=new
|
|
4
|
-
`}}),V.info(e)}disable(){this.registerTiming=_s,this.registerStartTiming=this.registerStartTiming=_s,this.registerEndTiming=this.registerEndTiming=_s}enable(){this.registerTiming=gl,this.registerStartTiming=this.registerStartTiming=Np,this.registerEndTiming=this.registerEndTiming=Ag}isEnabled(){return this.registerStartTiming===Np}};function _s(){}function gl(r,t,e){e||(e=this.performanceInstance.now());let n=this.timestamps[r];n||(n=this.timestamps[r]=[]);let s,o=n.length;for(let i=o-1;i>=0&&(s=n[i],!(s&&!s[t]));i--)s=null;s||(s={},n.push(s)),s[t]=e}function Np(r,t){this.registerTiming(r,"start",t)}function Ag(r,t){this.registerTiming(r,"end",t)}var Lg={now:Date.now},Rg=window&&window.performance,Ye=new Ki(Rg||Lg);Ye.forceRegisterStartTiming("load_vivliostyle");var Ig={profiler:{registerStartTiming:Ye.registerStartTiming,registerEndTiming:Ye.registerEndTiming,printTimings:Ye.printTimings,disable:Ye.disable,enable:Ye.enable}};var Bo=/^[\s\p{Zs}\p{P}\p{Mn}]*[\p{L}\p{N}]\p{Mn}*(?:[\s\p{Zs}]*\p{P}\p{Mn}*)*/u,Rt="data-adapt-eloff",Tp={};function Hs(r){return JSON.parse(r)}function Tt(r){let t=r.match(/^([^#]*)/);return t?t[1]:r}function Vg(r){let t=r.match(/^([^#?]*)/);return t?t[1]:r}var rn=window.location.href;function Cl(r){rn=r}var $t=window.location.href;function bl(r){$t=r}function Q(r,t){if(/^data:/i.test(t))return r||t;if(!t||r.match(/^\w{2,}:/))return r.toLowerCase().match("^javascript:")?"#":(r.match(/^\w{2,}:\/\/[^\/]+$/)&&(r=`${r}/`),r);t.match(/^\w{2,}:\/\/[^\/]+$/)&&(t=`${t}/`);let e;if(r.match(/^\/\//))return e=t.match(/^(\w{2,}:)\/\//),e?e[1]+r:r;if(r.match(/^\//))return e=t.match(/^(\w{2,}:\/\/[^\/]+)\//),e?e[1]+r:r;if(r.match(/^\.(\/|$)/)&&(r=r.substr(2)),t=Vg(t),r.match(/^#/))return t+r;let n=t.lastIndexOf("/");if(n<0)return r;let s=t.substr(0,n+1)+r,o="";for(e=s.match(/^([^?#]*)([?#].*)$/),e&&(s=e[1],o=e[2]);n=s.indexOf("/../"),!(n<=0);){let i=s.lastIndexOf("/",n-1);if(i<=0)break;s=s.substr(0,i)+s.substr(n+3)}return s.replace(/\/(\.\/)+/g,"/")+o}function Tn(r){let t;return(t=/^(https?:)\/\/github\.com\/([^/]+\/[^/]+)\/(blob\/|tree\/|raw\/)?(.*)$/.exec(r))?r=`${t[1]}//raw.githubusercontent.com/${t[2]}/${t[3]?"":"master/"}${t[4]}`:(t=/^(https?:)\/\/www\.aozora\.gr\.jp\/(cards\/[^/]+\/files\/[^/.]+\.html)$/.exec(r))?r=`${t[1]}//raw.githubusercontent.com/aozorabunko/aozorabunko/master/${t[2]}`:(t=/^(https?:)\/\/gist\.github\.com\/([^/]+\/\w+)(\/|$)(raw(\/|$))?(.*)$/.exec(r))?r=`${t[1]}//gist.githubusercontent.com/${t[2]}/raw/${t[6]}`:(t=/^(https?:)\/\/gist\.github\.com\/([^/]+\/\w+)#file-(.*)-(\w+)$/.exec(r))?r=`${t[1]}//gist.githubusercontent.com/${t[2]}/raw/${t[3]}.${t[4]}`:(t=/^(https?:)\/\/(?:[^/.]+\.)?jsbin\.com\/(?!(?:blog|help)\b)(\w+)((\/\d+)?).*$/.exec(r))&&(r=`${t[1]}//output.jsbin.com/${t[2]}${t[3]}/`),r}function xl(r){return r==null?r:r.toString()}var qi=class{constructor(){d(this,"queue",[null])}length(){return this.queue.length-1}add(t){let e=this.queue.length;for(;e>1;){let n=Math.floor(e/2),s=this.queue[n];if(s.compare(t)>0){this.queue[e]=t;return}this.queue[e]=s,e=n}this.queue[1]=t}peek(){return this.queue[1]}remove(){let t=this.queue[1],e=this.queue.pop(),n=this.queue.length;if(n>1){let s=1;for(;;){let o=s*2;if(o>=n)break;if(this.queue[o].compare(e)>0)o+1<n&&this.queue[o+1].compare(this.queue[o])>0&&o++;else if(o+1<n&&this.queue[o+1].compare(e)>0)o++;else break;this.queue[s]=this.queue[o],s=o}this.queue[s]=e}return t}},yl=["","-webkit-","-moz-"],Us={};function ml(r,t){return CSS.supports(r+t,"unset")}function Fg(r){let t=Us[r];if(t||t===null)return t;switch(r){case"behavior":case"template":case"ua-list-item-count":case"x-first-pseudo":return Us[r]=null,null;case"text-combine-upright":if(ml("-webkit-","text-combine")&&!ml("","text-combine-upright"))return Us[r]=["-webkit-text-combine"],["-webkit-text-combine"];break}for(let e of yl)if(ml(e,r))return t=[e+r],Us[r]=t,t;return V.warn("Property not supported by the browser: ",r),Us[r]=null,null}function T(r,t,e){let n=r==null?void 0:r.style;if(!n)return;if(t.startsWith("--")){n.setProperty(t,e||" ");return}let s=Fg(t);if(s)for(let o of s){switch(o){case"-webkit-text-combine":switch(e){case"all":e="horizontal";break}break;case"text-combine-upright":switch(e){case"all":n.setProperty("text-indent","0");break}break}n.setProperty(o,e)}}function It(r,t,e){try{let n=Us[t];return r.style.getPropertyValue(n?n[0]:t)}catch(n){}return e||""}function Oo(r){let t=r.getAttributeNS("http://www.w3.org/XML/1998/namespace","lang");return!t&&r.namespaceURI=="http://www.w3.org/1999/xhtml"&&(t=r.getAttribute("lang")),t}var Xe=class{constructor(){d(this,"list",[])}append(t){return this.list.push(t),this}clear(){this.list=[]}toString(){let t=this.list.join("");return this.list=[t],t}};function wp(r){return`\\${r.charCodeAt(0).toString(16)} `}function Xt(r){return r.replace(/[^-_a-zA-Z0-9\u0080-\uFFFF]/g,wp)}function os(r){return r.replace(/[\u0000-\u001F"\\]/g,wp)}function El(r){return r.replace(/[\s+&?=#\u007F-\uFFFF]+/g,encodeURIComponent)}function Sl(r){return!!r.match(/^[a-zA-Z\u009E\u009F\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u024F\u037B-\u037D\u0386\u0388-\u0482\u048A-\u0527]$/)}function Bg(r,t){return t=typeof t=="string"?t:"\\u",t+(65536|r.charCodeAt(0)).toString(16).substr(1)}function Nl(r,t){function e(n){return Bg(n,t)}return r.replace(/[^-a-zA-Z0-9_]/g,e)}function an(r){return Nl(r)}function Og(r,t){return t=typeof t=="string"?t:"\\u",r.indexOf(t)===0?String.fromCharCode(parseInt(r.substring(t.length),16)):r}function Pp(r,t){t=typeof t=="string"?t:"\\u";function e(s){return Og(s,t)}let n=new RegExp(`${an(t)}[0-9a-fA-F]{4}`,"g");return r.replace(n,e)}function ft(r,t){let e=0,n=r;for(;;){if(e<=n,e==0||t(e-1),n==r||t(n),e==n)return e;let s=e+n>>1;t(s)?n=s:e=s+1}}function Zi(r,t){return r-t}function vl(r,t){let e={};for(let n of r){let s=t(n);s&&!e[s]&&(e[s]=n)}return e}function kp(r){let t={};for(let e=0;e<r.length;e++)t[r[e]]=!0;return t}function Qi(r,t){let e={};for(let n of r){let s=t(n);s&&(e[s]?e[s].push(n):e[s]=[n])}return e}function Ap(r,t){let e={};for(let n in r)e[n]=t(r[n],n);return e}var vn=class{constructor(){d(this,"listeners",{})}dispatchEvent(t){let e=this.listeners[t.type];if(e){t.target=this,t.currentTarget=this;for(let n=0;n<e.length;n++)e[n](t)}}addEventListener(t,e,n){if(n)return;let s=this.listeners[t];s?s.includes(e)||s.push(e):this.listeners[t]=[e]}removeEventListener(t,e,n){if(n)return;let s=this.listeners[t];if(s){let o=s.indexOf(e);o>=0&&s.splice(o,1)}}},jt={audio:!0,canvas:!0,embed:!0,iframe:!0,img:!0,math:!0,object:!0,picture:!0,svg:!0,video:!0};function Ip(r){if(r.nodeType==1){let t=r.getAttribute("id");if(t)return t}return null}function Dg(r){return`^${r}`}function Lp(r){return r.replace(/[\[\]\(\),=;^]/g,Dg)}function Mg(r){return r.substr(1)}function Tl(r){return r&&r.replace(/\^[\[\]\(\),=;^]/g,Mg)}function _g(r){let t=[];do{let e=r.match(/^(\^,|[^,])*/),n=Tl(e[0]);if(r=r.substr(e[0].length+1),!r&&!t.length)return n;t.push(n)}while(r);return t}function Rp(r){let t={};for(;r;){let e=r.match(/^;([^;=]+)=(([^;]|\^;)*)/);if(!e)return t;t[e[1]]=_g(e[2]),r=r.substr(e[0].length)}return t}var Ji=class{appendTo(t){t.append("!")}applyTo(t){return!1}},er=class{constructor(t,e,n){this.index=t;this.id=e;this.sideBias=n}appendTo(t){t.append("/"),t.append(this.index.toString()),(this.id||this.sideBias)&&(t.append("["),this.id&&t.append(this.id),this.sideBias&&(t.append(";s="),t.append(this.sideBias)),t.append("]"))}applyTo(t){if(t.node.nodeType!=1)throw new Error("E_CFI_NOT_ELEMENT");let e=t.node,n=e.children,s=n.length,o,i=Math.floor(this.index/2)-1;if(i<0||s==0)o=e.firstChild,t.node=o||e;else{if(o=n[Math.min(i,s-1)],this.index&1){let a=o.nextSibling;!a||a.nodeType==1?t.after=!0:o=a}t.node=o}if(this.id&&(t.after||this.id!=Ip(t.node))){let a=e.ownerDocument.getElementById(this.id);a?t.node=a:V.warn("E_CFI_ID_MISMATCH:",this.id)}return t.sideBias=this.sideBias,!0}},tr=class{constructor(t,e,n,s){this.offset=t;this.textBefore=e;this.textAfter=n;this.sideBias=s}applyTo(t){if(this.offset>0&&!t.after){let e=this.offset,n=t.node;for(;;){let s=n.nodeType;if(s==1)break;let o=n.nextSibling;if(3<=s&&s<=5){let i=n.textContent.length;if(e<=i)break;if(!o){e=i;break}e-=i}if(!o){e=0;break}n=o}t.node=n,t.offset=e}return t.sideBias=this.sideBias,!0}appendTo(t){t.append(":"),t.append(this.offset.toString()),(this.textBefore||this.textAfter||this.sideBias)&&(t.append("["),(this.textBefore||this.textAfter)&&(this.textBefore&&t.append(Lp(this.textBefore)),t.append(","),this.textAfter&&t.append(Lp(this.textAfter))),this.sideBias&&(t.append(";s="),t.append(this.sideBias)),t.append("]"))}},Do=class r{constructor(){d(this,"steps",null)}fromString(t){let e=t.match(/^#?epubcfi\((.*)\)$/);if(!e)throw new Error("E_CFI_NOT_CFI");let n=decodeURIComponent(e[1]),s=0,o=[];for(;;){let i;switch(n.charAt(s)){case"/":{if(s++,e=n.substr(s).match(/^(0|[1-9][0-9]*)(\[(.*?)(;([^\]]|\^\])*)?\])?/),!e)throw new Error("E_CFI_NUMBER_EXPECTED");s+=e[0].length;let a=parseInt(e[1],10),l=e[3];i=Rp(e[4]),o.push(new er(a,l,xl(i.s)));break}case":":{if(s++,e=n.substr(s).match(/^(0|[1-9][0-9]*)(\[((([^\];,]|\^[\];,])*)(,(([^\];,]|\^[\];,])*))?)(;([^]]|\^\])*)?\])?/),!e)throw new Error("E_CFI_NUMBER_EXPECTED");s+=e[0].length;let a=parseInt(e[1],10),l=e[4];l&&(l=Tl(l));let c=e[7];c&&(c=Tl(c)),i=Rp(e[10]),o.push(new tr(a,l,c,xl(i.s)));break}case"!":s++,o.push(new Ji);break;case"~":case"@":case"":this.steps=o;return;default:throw new Error("E_CFI_PARSE_ERROR")}}}navigate(t){let e={node:t.documentElement,offset:0,after:!1,sideBias:null,ref:null};for(let n=0;n<this.steps.length;n++)if(!this.steps[n].applyTo(e)){e.ref=new r,e.ref.steps=this.steps.slice(n+1);break}return e}trim(t,e){return t.replace(/\s+/g," ").match(e?/^[ -\uD7FF\uE000-\uFFFF]{0,8}/:/[ -\uD7FF\uE000-\uFFFF]{0,8}$/)[0].replace(/^\s/,"").replace(/\s$/,"")}prependPathFromNode(t,e,n,s){let o=[],i=t.parentNode,a="",l="";for(;t;){switch(t.nodeType){case 3:case 4:case 5:{let c=t.textContent,u=c.length;n?(e+=u,a||(a=c)):(e>u&&(e=u),n=!0,a=c.substr(0,e),l=c.substr(e)),t=t.previousSibling;continue}case 8:t=t.previousSibling;continue}break}for((e>0||a||l)&&(a=this.trim(a,!1),l=this.trim(l,!0),o.push(new tr(e,a,l,s)),s=null);i&&!(!i||i.nodeType==9);){let c=n?null:Ip(t),u=n?1:0;for(;t;)t.nodeType==1&&(u+=2),t=t.previousSibling;o.push(new er(u,c,s)),s=null,t=i,i=i.parentNode,n=!1}o.reverse(),this.steps?(o.push(new Ji),this.steps=o.concat(this.steps)):this.steps=o}toString(){if(!this.steps)return"";let t=new Xe;t.append("epubcfi(");for(let e=0;e<this.steps.length;e++)this.steps[e].appendTo(t);return t.append(")"),t.toString().replace(/%/g,"%25")}};function Pl(){return{fontFamily:"serif",lineHeight:1.25,margin:8,hyphenate:!1,columnWidth:25,horizontal:!1,nightMode:!1,spreadView:!1,pageBorder:1,enabledMediaTypes:{vivliostyle:!0,print:!0},defaultPaperSize:void 0}}function gr(r){return{fontFamily:r.fontFamily,lineHeight:r.lineHeight,margin:r.margin,hyphenate:r.hyphenate,columnWidth:r.columnWidth,horizontal:r.horizontal,nightMode:r.nightMode,spreadView:r.spreadView,pageBorder:r.pageBorder,enabledMediaTypes:Object.assign({},r.enabledMediaTypes),defaultPaperSize:r.defaultPaperSize?Object.assign({},r.defaultPaperSize):void 0}}var Hg=Pl(),Vp={PENDING:{}};function kl(r,t,e,n){let s=Math.min((r-0)/e,(t-0)/n);return`matrix(${s},0,0,${s},0,0)`}function wl(r){return`"${os(`${r}`)}"`}function zg(r){return Xt(`${r}`)}function Wo(r,t){return r?`${Xt(r)}.${Xt(t)}`:Xt(t)}var Fp=0,is=class{constructor(t,e){this.parent=t;this.resolver=e;d(this,"scopeKey");d(this,"children",[]);d(this,"zero");d(this,"one");d(this,"_true");d(this,"_false");d(this,"values",{});d(this,"funcs",{});d(this,"builtIns",{});if(this.scopeKey=`S${Fp++}`,this.zero=new oe(this,0),this.one=new oe(this,1),this._true=new oe(this,!0),this._false=new oe(this,!1),t&&t.children.push(this),!t){let n=this.builtIns;n.floor=Math.floor,n.ceil=Math.ceil,n.round=Math.round,n.sqrt=Math.sqrt,n.min=Math.min,n.max=Math.max,n.letterbox=kl,n["css-string"]=wl,n["css-name"]=zg,n.typeof=s=>typeof s,this.defineBuiltInName("page-width",function(){return this.pageWidth()}),this.defineBuiltInName("page-height",function(){return this.pageHeight()}),this.defineBuiltInName("pref-font-family",function(){return this.pref.fontFamily}),this.defineBuiltInName("pref-night-mode",function(){return this.pref.nightMode}),this.defineBuiltInName("pref-hyphenate",function(){return this.pref.hyphenate}),this.defineBuiltInName("pref-margin",function(){return this.pref.margin}),this.defineBuiltInName("pref-line-height",function(){return this.pref.lineHeight}),this.defineBuiltInName("pref-column-width",function(){return this.pref.columnWidth*this.fontSize}),this.defineBuiltInName("pref-horizontal",function(){return this.pref.horizontal}),this.defineBuiltInName("pref-spread-view",function(){return this.pref.spreadView}),this.defineBuiltInName("pub-title",function(){return wl(this.pubTitle?this.pubTitle:"")}),this.defineBuiltInName("doc-title",function(){return wl(this.docTitle?this.docTitle:"")})}}defineBuiltInName(t,e){this.values[t]=new ie(this,e,t)}defineName(t,e){this.values[t]=e}defineFunc(t,e){this.funcs[t]=e}defineBuiltIn(t,e){this.builtIns[t]=e}};function Bp(r){switch(r==null?void 0:r.toLowerCase()){case"px":case"in":case"pt":case"pc":case"cm":case"mm":case"q":return!0;default:return!1}}function Al(r){switch(r==null?void 0:r.toLowerCase()){case"vw":case"vh":case"vi":case"vb":case"vmin":case"vmax":case"pvw":case"pvh":case"pvi":case"pvb":case"pvmin":case"pvmax":return!0;default:return!1}}function Op(r){switch(r==null?void 0:r.toLowerCase()){case"em":case"ex":case"rem":case"lh":case"rlh":return!0;default:return!1}}function Dp(r){switch(r==null?void 0:r.toLowerCase()){case"rem":case"rlh":return!0;default:return!1}}var $={px:1,in:96,pt:4/3,pc:96/6,cm:96/2.54,mm:96/25.4,q:96/2.54/40,em:16,rem:16,ex:8,lh:20,rlh:20,dppx:1,dpi:1/96,dpcm:2.54/96};function mr(r){switch(r){case"q":return!CSS.supports("font-size","1q");case"lh":return!CSS.supports("line-height","1lh");case"rem":case"rlh":return!0;default:return!1}}var zs=class{constructor(t,e,n,s){this.rootScope=t;this.viewportWidth=e;this.viewportHeight=n;d(this,"actualPageWidth",null);d(this,"pageWidth");d(this,"actualPageHeight",null);d(this,"pageHeight");d(this,"initialFontSize");d(this,"rootFontSize",null);d(this,"isRelativeRootFontSize",null);d(this,"fontSize");d(this,"rootLineHeight",null);d(this,"pref");d(this,"scopes",{});d(this,"pageAreaWidth",null);d(this,"pageAreaHeight",null);d(this,"pageVertical",null);d(this,"pubTitle",null);d(this,"docTitle",null);this.pageWidth=function(){return this.actualPageWidth?this.actualPageWidth:this.pref.spreadView?Math.floor(e/2)-this.pref.pageBorder:e},this.pageHeight=function(){return this.actualPageHeight?this.actualPageHeight:n},this.initialFontSize=s,this.fontSize=function(){return this.rootFontSize?this.rootFontSize:s},this.pref=Hg}getScopeContext(t){let e=this.scopes[t.scopeKey];return e||(e={},this.scopes[t.scopeKey]=e),e}clearScope(t){this.scopes[t.scopeKey]={};for(let e=0;e<t.children.length;e++)this.clearScope(t.children[e])}queryUnitSize(t,e,n){if(Al(t)){let s=this.pageWidth()/100,o=this.pageHeight()/100,i=this.pageAreaWidth!=null?this.pageAreaWidth/100:s,a=this.pageAreaHeight!=null?this.pageAreaHeight/100:o,l=n!=null?n:this.pageVertical;switch(t){case"vw":return i;case"vh":return a;case"vi":return l?a:i;case"vb":return l?i:a;case"vmin":return i<a?i:a;case"vmax":return i>a?i:a;case"pvw":return s;case"pvh":return o;case"pvi":return l?o:s;case"pvb":return l?s:o;case"pvmin":return s<o?s:o;case"pvmax":return s>o?s:o}}return t=="em"||t=="rem"?e?this.initialFontSize:this.fontSize():t=="ex"?$.ex*(e?this.initialFontSize:this.fontSize())/$.em:t=="lh"||t=="rlh"?this.rootLineHeight:$[t]}evalName(t,e){do{let n=t.values[e];if(n||t.resolver&&(n=t.resolver.call(this,e,!1),n))return n;t=t.parent}while(t);throw new Error(`Name '${e}' is undefined`)}evalCall(t,e,n,s){do{let o=t.funcs[e];if(o||t.resolver&&(o=t.resolver.call(this,e,!0),o))return o;let i=t.builtIns[e];if(i){if(s)return t.zero;let a=Array(n.length);for(let l=0;l<n.length;l++)a[l]=n[l].evaluate(this);return new oe(t,i.apply(this,a))}t=t.parent}while(t);throw new Error(`Function '${e}' is undefined`)}evalMediaName(t,e){let n=t==="all"||!!this.pref.enabledMediaTypes[t];return e?!n:n}evalMediaTest(t,e){let n="",s=t.match(/^(min|max)-(.*)$/);s&&(n=s[1],t=s[2]);let o=null,i=null;switch(t){case"width":case"height":case"device-width":case"device-height":case"color":e&&(o=e.evaluate(this));break}switch(t){case"width":i=this.pageWidth();break;case"height":i=this.pageHeight();break;case"device-width":i=window.screen.availWidth;break;case"device-height":i=window.screen.availHeight;break;case"color":i=window.screen.pixelDepth;break}if(i!=null&&o!=null)switch(n){case"min":return i>=Number(o);case"max":return i<=Number(o);default:return i==o}else if(i!=null&&e==null)return i!==0;return!1}evalSupportsTest(t,e,n){return!1}queryVal(t,e){let n=t&&this.scopes[t.scopeKey];return n?n[e]:void 0}storeVal(t,e,n){this.getScopeContext(t)[e]=n}},at=class{constructor(t){this.scope=t;d(this,"key");this.scope=t,this.key=`_${Fp++}`}toString(){let t=new Xe;return this.appendTo(t,0),t.toString()}appendTo(t,e){throw new Error("F_ABSTRACT")}evaluateCore(t){throw new Error("F_ABSTRACT")}expand(t,e){return this}dependCore(t,e,n){return t===this}dependOuter(t,e,n){let s=n[this.key];if(s!=null)return s===Vp.PENDING?!1:s;{n[this.key]=Vp.PENDING;let o=this.dependCore(t,e,n);return n[this.key]=o,o}}depend(t,e){return this.dependOuter(t,e,{})}evaluate(t){let e=t.queryVal(this.scope,this.key);return typeof e!="undefined"||(e=this.evaluateCore(t),this.scope&&t.storeVal(this.scope,this.key,e)),e}isMediaName(){return!1}},nr=class extends at{constructor(e,n){super(e);this.val=n}getOp(){throw new Error("F_ABSTRACT")}evalPrefix(e){throw new Error("F_ABSTRACT")}evaluateCore(e){let n=this.val.evaluate(e);return this.evalPrefix(n)}dependCore(e,n,s){return e===this||this.val.dependOuter(e,n,s)}appendTo(e,n){10<n&&e.append("("),e.append(this.getOp()),this.val.appendTo(e,10),10<n&&e.append(")")}expand(e,n){let s=this.val.expand(e,n);return s===this.val?this:new this.constructor(this.scope,s)}},Gs=class extends at{constructor(e,n,s){super(e);this.lhs=n;this.rhs=s}getPriority(){throw new Error("F_ABSTRACT")}getOp(){throw new Error("F_ABSTRACT")}evalInfix(e,n){throw new Error("F_ABSTRACT")}evaluateCore(e){let n=this.lhs.evaluate(e),s=this.rhs.evaluate(e);return this.evalInfix(n,s)}dependCore(e,n,s){return e===this||this.lhs.dependOuter(e,n,s)||this.rhs.dependOuter(e,n,s)}appendTo(e,n){let s=this.getPriority();s<=n&&e.append("("),this.lhs.appendTo(e,s),e.append(this.getOp()),this.rhs.appendTo(e,s),s<=n&&e.append(")")}expand(e,n){let s=this.lhs.expand(e,n),o=this.rhs.expand(e,n);return s===this.lhs&&o===this.rhs?this:new this.constructor(this.scope,s,o)}},sr=class extends Gs{constructor(t,e,n){super(t,e,n)}getPriority(){return 1}},wn=class extends Gs{constructor(t,e,n){super(t,e,n)}getPriority(){return 2}},or=class extends Gs{constructor(t,e,n){super(t,e,n)}getPriority(){return 3}},Mo=class extends Gs{constructor(t,e,n){super(t,e,n)}getPriority(){return 4}},gt=class extends nr{constructor(t,e){super(t,e)}getOp(){return"!"}evalPrefix(t){return!t}},ir=class extends gt{constructor(t,e){super(t,e)}getOp(){return"not "}},Yt=class extends nr{constructor(t,e){super(t,e)}getOp(){return"-"}evalPrefix(t){return-t}},Ws=class extends sr{constructor(t,e,n){super(t,e,n)}getOp(){return"&&"}evaluateCore(t){return this.lhs.evaluate(t)&&this.rhs.evaluate(t)}},rr=class extends Ws{constructor(t,e,n){super(t,e,n)}getOp(){return" and "}},$s=class extends sr{constructor(t,e,n){super(t,e,n)}getOp(){return"||"}evaluateCore(t){return this.lhs.evaluate(t)||this.rhs.evaluate(t)}},ar=class extends $s{constructor(t,e,n){super(t,e,n)}getOp(){return", "}},lr=class extends $s{constructor(t,e,n){super(t,e,n)}getOp(){return" or "}},cr=class extends wn{constructor(t,e,n){super(t,e,n)}getOp(){return"<"}evalInfix(t,e){return t<e}},ur=class extends wn{constructor(t,e,n){super(t,e,n)}getOp(){return"<="}evalInfix(t,e){return t<=e}},dr=class extends wn{constructor(t,e,n){super(t,e,n)}getOp(){return">"}evalInfix(t,e){return t>e}},rs=class extends wn{constructor(t,e,n){super(t,e,n)}getOp(){return">="}evalInfix(t,e){return t>=e}},Pn=class extends wn{constructor(t,e,n){super(t,e,n)}getOp(){return"=="}evalInfix(t,e){return t==e}},pr=class extends wn{constructor(t,e,n){super(t,e,n)}getOp(){return"!="}evalInfix(t,e){return t!=e}},_o=class extends or{constructor(t,e,n){super(t,e,n)}getOp(){return"+"}evalInfix(t,e){return t+e}},Uo=class extends or{constructor(t,e,n){super(t,e,n)}getOp(){return" - "}evalInfix(t,e){return t-e}},as=class extends Mo{constructor(t,e,n){super(t,e,n)}getOp(){return"*"}evalInfix(t,e){return t*e}},Ho=class extends Mo{constructor(t,e,n){super(t,e,n)}getOp(){return"/"}evalInfix(t,e){return t/e}},Xs=class extends Mo{constructor(t,e,n){super(t,e,n)}getOp(){return"%"}evalInfix(t,e){return t%e}},Vt=class extends at{constructor(e,n,s){var o;super(e);this.num=n;d(this,"unit");this.unit=(o=s==null?void 0:s.toLowerCase())!=null?o:""}appendTo(e,n){e.append(this.num.toString()),e.append(Xt(this.unit))}evaluateCore(e){return this.num*e.queryUnitSize(this.unit,!1)}},J=class extends at{constructor(e,n){super(e);this.qualifiedName=n}appendTo(e,n){e.append(this.qualifiedName)}evaluateCore(e){return e.evalName(this.scope,this.qualifiedName).evaluate(e)}dependCore(e,n,s){return e===this||n.evalName(this.scope,this.qualifiedName).dependOuter(e,n,s)}},zo=class extends at{constructor(e,n,s){super(e);this.not=n;this.name=s}appendTo(e,n){this.not&&e.append("not "),e.append(Xt(this.name))}evaluateCore(e){return e.evalMediaName(this.name,this.not)}isMediaName(){return!0}},ie=class extends at{constructor(e,n,s){super(e);this.fn=n;this.str=s}appendTo(e,n){e.append(this.str)}evaluateCore(e){return this.fn.call(e)}};function Gg(r,t){r.append("(");for(let e=0;e<t.length;e++)e&&r.append(","),t[e].appendTo(r,0);r.append(")")}function Wg(r,t,e){let n=t;for(let s=0;s<t.length;s++){let o=t[s].expand(r,e);if(t!==n)n[s]=o;else if(o!==t[s]){n=Array(t.length);for(let i=0;i<s;i++)n[i]=t[i];n[s]=o}}return n}var ln=class r extends at{constructor(e,n,s){super(e);this.qualifiedName=n;this.params=s}appendTo(e,n){e.append(this.qualifiedName),Gg(e,this.params)}evaluateCore(e){return e.evalCall(this.scope,this.qualifiedName,this.params,!1).expand(e,this.params).evaluate(e)}dependCore(e,n,s){if(e===this)return!0;for(let i=0;i<this.params.length;i++)if(this.params[i].dependOuter(e,n,s))return!0;return n.evalCall(this.scope,this.qualifiedName,this.params,!0).dependOuter(e,n,s)}expand(e,n){let s=Wg(e,this.params,n);return s===this.params?this:new r(this.scope,this.qualifiedName,s)}},hr=class r extends at{constructor(e,n,s,o){super(e);this.cond=n;this.ifTrue=s;this.ifFalse=o}appendTo(e,n){n>0&&e.append("("),this.cond.appendTo(e,0),e.append("?"),this.ifTrue.appendTo(e,0),e.append(":"),this.ifFalse.appendTo(e,0),n>0&&e.append(")")}evaluateCore(e){return this.cond.evaluate(e)?this.ifTrue.evaluate(e):this.ifFalse.evaluate(e)}dependCore(e,n,s){return e===this||this.cond.dependOuter(e,n,s)||this.ifTrue.dependOuter(e,n,s)||this.ifFalse.dependOuter(e,n,s)}expand(e,n){let s=this.cond.expand(e,n),o=this.ifTrue.expand(e,n),i=this.ifFalse.expand(e,n);return s===this.cond&&o===this.ifTrue&&i===this.ifFalse?this:new r(this.scope,s,o,i)}},oe=class extends at{constructor(e,n){super(e);this.val=n}appendTo(e,n){switch(typeof this.val){case"number":case"boolean":e.append(this.val.toString());break;case"string":e.append('"'),e.append(os(this.val)),e.append('"');break;default:throw new Error("F_UNEXPECTED_STATE")}}evaluateCore(e){return this.val}},Go=class r extends at{constructor(e,n,s){super(e);this.name=n;this.value=s}appendTo(e,n){e.append("("),e.append(os(this.name.name)),e.append(":"),this.value.appendTo(e,0),e.append(")")}evaluateCore(e){return e.evalMediaTest(this.name.name,this.value)}dependCore(e,n,s){return e===this||this.value.dependOuter(e,n,s)}expand(e,n){let s=this.value.expand(e,n);return s===this.value?this:new r(this.scope,this.name,s)}},fr=class extends at{constructor(e,n,s,o){super(e);this.name=n;this.value=s;this.isFunc=o}appendTo(e,n){this.isFunc&&e.append(this.name),e.append("("),!this.isFunc&&this.name&&(e.append(this.name),e.append(":")),e.append(this.value),e.append(")")}evaluateCore(e){return e.evalSupportsTest(this.name,this.value,this.isFunc)}},js=class extends at{constructor(e,n){super(e);this.index=n}appendTo(e,n){e.append("$"),e.append(this.index.toString())}expand(e,n){let s=n[this.index];if(!s)throw new Error(`Parameter missing: ${this.index}`);return s}};function et(r,t,e){return t===r._false||t===r.zero||e==r._false||e==r.zero?r._false:t===r._true||t===r.one?e:e===r._true||e===r.one?t:new Ws(r,t,e)}function H(r,t,e){return t===r.zero?e:e===r.zero?t:new _o(r,t,e)}function Y(r,t,e){return t===r.zero?new Yt(r,e):e===r.zero?t:new Uo(r,t,e)}function Ys(r,t,e){return t===r.zero||e===r.zero?r.zero:t===r.one?e:e===r.one?t:new as(r,t,e)}function $o(r,t,e){return t===r.zero?r.zero:e===r.one?t:new Ho(r,t,e)}var lt=class{visitValues(t){for(let e=0;e<t.length;e++)t[e].visit(this);return null}visitEmpty(t){return null}visitSlash(t){return null}visitStr(t){return null}visitIdent(t){return null}visitNumeric(t){return null}visitNum(t){return null}visitInt(t){return this.visitNum(t)}visitHexColor(t){return null}visitURL(t){return null}visitURange(t){return null}visitSpaceList(t){return this.visitValues(t.values),null}visitCommaList(t){return this.visitValues(t.values),null}visitFunc(t){return this.visitValues(t.values),null}visitExpr(t){return null}},Kt=class extends lt{constructor(){super();d(this,"error",!1)}visitValues(e){let n=null;for(let s=0;s<e.length;s++){let o=e[s],i=o.visit(this);if(this.error)return[];if(n)n[s]=i;else if(o!==i){n=new Array(e.length);for(let a=0;a<s;a++)n[a]=e[a];n[s]=i}}return n||e}visitEmpty(e){return e}visitStr(e){return e}visitIdent(e){return e}visitSlash(e){return e}visitNumeric(e){return e}visitNum(e){return e}visitInt(e){return e}visitHexColor(e){return e}visitURL(e){return e}visitURange(e){return e}visitSpaceList(e){let n=this.visitValues(e.values);return this.error?O:n===e.values?e:new K(n)}visitCommaList(e){let n=this.visitValues(e.values);return this.error?O:n===e.values?e:new ge(n)}visitFunc(e){let n=this.visitValues(e.values);return this.error?O:n===e.values?e:new wt(e.name,n)}visitExpr(e){return e}},Ne=class{toString(){let t=new Xe;return this.appendTo(t,!0),t.toString()}stringValue(){let t=new Xe;return this.appendTo(t,!1),t.toString()}toExpr(t,e){return null}appendTo(t,e){t.append("[error]")}isExpr(){return!1}isNumeric(){return!1}isNum(){return!1}isIdent(){return!1}isSpaceList(){return!1}visit(t){return this}},Cr=class Cr extends Ne{static get instance(){return this.empty||(this.empty=new Cr),this.empty}constructor(){super()}toExpr(t,e){return new oe(t,"")}appendTo(t,e){}visit(t){return t.visitEmpty(this)}};d(Cr,"empty");var Ll=Cr,O=Ll.instance,br=class br extends Ne{static get instance(){return this.slash||(this.slash=new br),this.slash}constructor(){super()}toExpr(t,e){return new oe(t,"/")}appendTo(t,e){t.append("/")}visit(t){return t.visitSlash(this)}};d(br,"slash");var Rl=br,qs=Rl.instance,ce=class extends Ne{constructor(e){super();this.str=e}toExpr(e,n){return new oe(e,this.str)}appendTo(e,n){n?(e.append('"'),e.append(os(this.str)),e.append('"')):e.append(this.str)}visit(e){return e.visitStr(this)}},Il={},be=class extends Ne{constructor(e){super();this.name=e;if(Il[e])throw new Error("E_INVALID_CALL");Il[e]=this}toExpr(e,n){return new oe(e,this.name)}appendTo(e,n){n?e.append(Xt(this.name)):e.append(this.name)}visit(e){return e.visitIdent(this)}isIdent(){return!0}};function L(r){let t=Il[r];return t||(t=new be(r)),t}var P=class extends Ne{constructor(e,n){var s;super();this.num=e;d(this,"unit");this.unit=(s=n==null?void 0:n.toLowerCase())!=null?s:""}toExpr(e,n){return this.num==0?e.zero:n&&this.unit=="%"?this.num==100?n:new as(e,n,new oe(e,this.num/100)):new Vt(e,this.num,this.unit)}appendTo(e,n){e.append(this.num.toString()),e.append(this.unit)}visit(e){return e.visitNumeric(this)}isNumeric(){return!0}},tt=class extends Ne{constructor(e){super();this.num=e}toExpr(e,n){return this.num==0?e.zero:this.num==1?e.one:new oe(e,this.num)}appendTo(e,n){e.append(this.num.toString())}visit(e){return e.visitNum(this)}isNum(){return!0}},ct=class extends tt{constructor(t){super(t)}visit(t){return t.visitInt(this)}},Ks=class extends Ne{constructor(e){super();this.hex=e}appendTo(e,n){e.append("#"),e.append(this.hex)}visit(e){return e.visitHexColor(this)}},Ue=class extends Ne{constructor(e){super();this.url=e}appendTo(e,n){e.append('url("'),e.append(os(this.url)),e.append('")')}visit(e){return e.visitURL(this)}},Xo=class extends Ne{constructor(e){super();this.urangeText=e}appendTo(e,n){e.append(this.urangeText)}visit(e){return e.visitURange(this)}};function Vl(r,t,e,n){var o,i;let s=t.length;if(s>0){(o=t[0])==null||o.appendTo(r,n);for(let a=1;a<s;a++)r.append(e),(i=t[a])==null||i.appendTo(r,n)}}var K=class extends Ne{constructor(e){super();this.values=e}appendTo(e,n){Vl(e,this.values," ",n)}visit(e){return e.visitSpaceList(this)}isSpaceList(){return!0}},ge=class extends Ne{constructor(e){super();this.values=e}appendTo(e,n){Vl(e,this.values,",",n)}visit(e){return e.visitCommaList(this)}},wt=class extends Ne{constructor(e,n){super();this.name=e;this.values=n}appendTo(e,n){e.append(Xt(this.name)),e.append("("),Vl(e,this.values,",",n),e.append(")")}visit(e){return e.visitFunc(this)}},F=class extends Ne{constructor(e){super();this.expr=e}toExpr(){return this.expr}appendTo(e,n){this.expr instanceof oe||this.expr instanceof Vt?this.expr.appendTo(e,0):(e.append("-epubx-expr("),this.expr.appendTo(e,0),e.append(")"))}visit(e){return e.visitExpr(this)}isExpr(){return!0}},kn=class extends Ne{constructor(e){super();this.text=e}appendTo(e,n){e.append(this.text||" ")}};function Le(r,t){if(r){if(r.isNumeric()){let e=r;return t.queryUnitSize(e.unit,!1)*e.num}if(r.isNum())return r.num}return 0}function xr(r,t){return new P(Le(r,t),"px")}var b={absolute:L("absolute"),all:L("all"),always:L("always"),anywhere:L("anywhere"),auto:L("auto"),avoid:L("avoid"),balance:L("balance"),balance_all:L("balance-all"),block:L("block"),block_end:L("block-end"),block_start:L("block-start"),both:L("both"),bottom:L("bottom"),border_box:L("border-box"),break_all:L("break-all"),break_word:L("break-word"),clip:L("clip"),crop:L("crop"),cross:L("cross"),column:L("column"),discard:L("discard"),exclusive:L("exclusive"),_false:L("false"),fixed:L("fixed"),flex:L("flex"),flow_root:L("flow-root"),footnote:L("footnote"),footer:L("footer"),grid:L("grid"),header:L("header"),hidden:L("hidden"),horizontal_tb:L("horizontal-tb"),inherit:L("inherit"),initial:L("initial"),inline:L("inline"),inline_block:L("inline-block"),inline_end:L("inline-end"),inline_start:L("inline-start"),inside:L("inside"),keep:L("keep"),landscape:L("landscape"),left:L("left"),line:L("line"),list_item:L("list-item"),ltr:L("ltr"),manual:L("manual"),max_content:L("max-content"),min_content:L("min-content"),none:L("none"),normal:L("normal"),oeb_page_foot:L("oeb-page-foot"),oeb_page_head:L("oeb-page-head"),outside:L("outside"),padding_box:L("padding-box"),page:L("page"),relative:L("relative"),revert:L("revert"),right:L("right"),same:L("same"),scale:L("scale"),snap_block:L("snap-block"),snap_inline:L("snap-inline"),solid:L("solid"),spread:L("spread"),_static:L("static"),rtl:L("rtl"),table:L("table"),table_caption:L("table-caption"),table_cell:L("table-cell"),table_footer_group:L("table-footer-group"),table_header_group:L("table-header-group"),table_row:L("table-row"),top:L("top"),transparent:L("transparent"),unset:L("unset"),vertical_lr:L("vertical-lr"),vertical_rl:L("vertical-rl"),visible:L("visible"),_true:L("true")},Fl=new P(100,"%"),An=new P(100,"pvw"),Ln=new P(100,"pvh"),te=new P(0,"px"),Ab=new Xo("U+0-10FFFF"),Mp={"font-size":1,"line-height":2,color:3};function _(r){return r===b.inherit||r===b.initial||r===b.revert||r===b.unset}function Bl(r,t){let e=Mp[r]||Number.MAX_VALUE,n=Mp[t]||Number.MAX_VALUE;return e-n}function Ct(r){return(r==null?void 0:r.length)>2&&r.startsWith("--")}var He=class{constructor(t,e,n,s){this.x1=t;this.y1=e;this.x2=n;this.y2=s}},Ft=class{constructor(t,e){this.x=t;this.y=e}},Qs=class{constructor(t,e,n,s){this.left=t;this.top=e;this.right=n;this.bottom=s}},yr=class{constructor(t,e,n,s){this.low=t;this.high=e;this.winding=n;this.shapeId=s}},Bt=class{constructor(t,e,n,s){this.y1=t;this.y2=e;this.x1=n;this.x2=s;d(this,"left",null);d(this,"right",null)}};function $g(r,t){return r.low.y-t.low.y||r.low.x-t.low.x}var ls=class r{constructor(t){this.points=t}addSegments(t,e){let n=this.points,s=n.length,o=n[s-1];for(let i=0;i<s;i++){let a=n[i],l;o.y<a.y?l=new yr(o,a,1,e):l=new yr(a,o,-1,e),t.push(l),o=a}}withOffset(t,e){let n=[];for(let s of this.points)n.push(new Ft(s.x+t,s.y+e));return new r(n)}};function Ol(r,t,e,n){let o=[];for(let i=0;i<20;i++){let a=i*2*Math.PI/20;o.push(new Ft(r+e*Math.sin(a),t+n*Math.cos(a)))}return new ls(o)}function jo(r,t,e,n){return new ls([new Ft(r,t),new Ft(e,t),new Ft(e,n),new Ft(r,n)])}var Zs=class{constructor(t,e,n,s){this.x=t;this.winding=e;this.shapeId=n;this.lowOrHigh=s}};function _p(r,t){let e=r.low.x+(r.high.x-r.low.x)*(t-r.low.y)/(r.high.y-r.low.y);if(isNaN(e))throw new Error("Bad intersection");return e}function Xg(r,t,e,n){let s,o,i,a;t.high.y<e&&V.warn("Error: inconsistent segment (1)"),t.low.y<=e?(s=_p(t,e),o=t.winding):(s=t.low.x,o=0),t.high.y>=n?(i=_p(t,n),a=t.winding):(i=t.high.x,a=0),s<i?(r.push(new Zs(s,o,t.shapeId,-1)),r.push(new Zs(i,a,t.shapeId,1))):(r.push(new Zs(i,a,t.shapeId,-1)),r.push(new Zs(s,o,t.shapeId,1)))}function jg(r,t,e){let n=t+e,s=Array(n),o=Array(n),i;for(i=0;i<=n;i++)s[i]=0,o[i]=0;let a=[],l=!1,c=r.length;for(let u=0;u<c;u++){let p=r[u];s[p.shapeId]+=p.winding,o[p.shapeId]+=p.lowOrHigh;let h=!1;for(i=0;i<t;i++)if(s[i]&&!o[i]){h=!0;break}if(h){for(i=t;i<=n;i++)if(s[i]||o[i]){h=!1;break}}l!=h&&(a.push(p.x),l=h)}return a}function Yg(r,t){return t?Math.ceil(r/t)*t:r}function Up(r,t){return t?Math.floor(r/t)*t:r}function Kg(r){return new Ft(r.y,-r.x)}function Js(r){return new He(r.y1,-r.x2,r.y2,-r.x1)}function Er(r){return new He(-r.y2,r.x1,-r.y1,r.x2)}function Hp(r){return new ls(r.points.map(t=>Kg(t)))}function zp(r,t,e,n,s,o){o&&(r=Js(r),t=t.map(C=>Hp(C)),e=e.map(C=>Hp(C)));let i=t.length,a=e?e.length:0,l=[],c=[],u,p,h;for(u=0;u<i;u++)t[u].addSegments(c,u);for(u=0;u<a;u++)e[u].addSegments(c,u+i);let f=c.length;c.sort($g);let g=0;for(;c[g].shapeId>=i;)g++;let m=c[g].low.y;m>r.y1&&l.push(new Bt(r.y1,m,r.x2,r.x2));let E=0,y=[];for(;E<f&&(h=c[E]).low.y<m;)h.high.y>m&&y.push(h),E++;for(;E<f||y.length>0;){let C=r.y2,x=Math.min(Yg(Math.ceil(m+n),s),r.y2);for(p=0;p<y.length&&C>x;p++)h=y[p],h.low.x==h.high.x?h.high.y<C&&(C=Math.max(Up(h.high.y,s),x)):h.low.x!=h.high.x&&(C=x);for(C>r.y2&&(C=r.y2);E<f&&(h=c[E]).low.y<C;){if(h.high.y<m){E++;continue}if(h.low.y<x)h.low.y==h.high.y&&h.low.y==m||(y.push(h),C=x),E++;else{let w=Up(h.low.y,s);w<C&&(C=w);break}}let N=[];for(p=0;p<y.length;p++)Xg(N,y[p],m,C);N.sort((w,k)=>w.x-k.x||w.lowOrHigh-k.lowOrHigh);let S=jg(N,i,a);if(S.length==0)l.push(new Bt(m,C,r.x2,r.x2));else{let w=0,k=r.x1;for(p=0;p<S.length;p+=2){let I=Math.max(r.x1,S[p]),U=Math.min(r.x2,S[p+1])-I;U>w&&(w=U,k=I)}w==0?l.push(new Bt(m,C,r.x2,r.x2)):l.push(new Bt(m,C,Math.max(k,r.x1),Math.min(k+w,r.x2)))}if(C==r.y2)break;for(m=C,p=y.length-1;p>=0;p--)y[p].high.y<=C&&y.splice(p,1)}return Gp(r,l),l}function Gp(r,t){let e=t.length-1,n=new Bt(r.y2,r.y2,r.x1,r.x2);for(;e>=0;){let s=n;n=t[e],(n.y2-n.y1<1||n.x1==s.x1&&n.x2==s.x2)&&(s.y1=n.y1,t.splice(e,1),n=s),e--}}function Wp(r,t){let e=0,n=r.length;for(;e<n;){let s=Math.floor((e+n)/2);t>=r[s].y2?e=s+1:n=s}return e}function $p(r,t){if(!r.length)return t;let e=t.y1,n,s;for(s=0;s<r.length&&(n=r[s],!(n.y2>t.y1&&n.x1-.1<=t.x1&&n.x2+.1>=t.x2));s++)e=Math.max(e,n.y2);let o=e;for(;s<r.length&&(n=r[s],!(n.y1>=t.y2||n.x1-.1>t.x1||n.x2+.1<t.x2));s++)o=n.y2;return s===r.length?o=t.y2:o=Math.min(o,t.y2),o<=e?null:new He(t.x1,e,t.x2,o)}function Xp(r,t){if(!r.length)return t;let e=t.y2,n,s;for(s=r.length-1;s>=0&&(n=r[s],!(s===r.length-1&&n.y2<t.y2));s--){if(n.y1<t.y2&&n.x1-.1<=t.x1&&n.x2+.1>=t.x2)break;e=Math.min(e,n.y1)}let o=Math.min(e,n.y2);for(;s>=0&&(n=r[s],!(n.y2<=t.y1||n.x1-.1>t.x1||n.x2+.1<t.x2));s--)o=n.y1;return o=Math.max(o,t.y1),e<=o?null:new He(t.x1,o,t.x2,e)}function jp(r,t,e,n){let s=e.y1,o=e.x2-e.x1,i=e.y2-e.y1,a=Wp(t,s);for(;;){let l=s+i;if(l>r.y2)return!1;let c=r.x1,u=r.x2;for(let p=a;p<t.length&&t[p].y1<l;p++){let h=t[p];h.x1>c&&(c=h.x1),h.x2<u&&(u=h.x2)}if(c+o<=u||a>=t.length)return n=="left"?(e.x1=c,e.x2=c+o):(e.x1=u-o,e.x2=u),e.y2+=s-e.y1,e.y1=s,!0;s=t[a].y2,a++}}function Yp(r,t,e,n,s){for(n||(n=[new Bt(e.y1,e.y2,e.x1,e.x2)]);n.length>0&&n[0].y2<=r.y1;)n.shift();if(n.length==0)return;n[0].y1<r.y1&&(n[0].y1=r.y1);let o,i=t.length==0?r.y1:t[t.length-1].y2;i<r.y2&&t.push(new Bt(i,r.y2,r.x1,r.x2));let a=Wp(t,n[0].y1);for(let l of n){if(a==t.length)break;for(t[a].y1<l.y1&&(o=t[a],a++,t.splice(a,0,new Bt(l.y1,o.y2,o.x1,o.x2)),o.y2=l.y1);a<t.length&&(o=t[a++],o.y2>l.y2&&(t.splice(a,0,new Bt(l.y2,o.y2,o.x1,o.x2)),o.y2=l.y2),l.x1!=l.x2&&(s=="left"?o.x1=Math.min(l.x2,r.x2):o.x2=Math.max(l.x1,r.x1)),o.y2!=l.y2););}Gp(r,t)}var Dl=class extends lt{constructor(){super();d(this,"propSet",{})}visitIdent(e){return this.propSet[e.name]=!0,e}visitSpaceList(e){return this.visitValues(e.values),e}};function Kp(r){if(r){let t=new Dl;try{return r.visit(t),t.propSet}catch(e){V.warn(e,"toSet:")}}return{}}var Ml=class extends lt{constructor(e){super();this.value=e}visitInt(e){return this.value=e.num,e}};function Hl(r,t){if(r){let e=new Ml(t);try{return r.visit(e),e.value}catch(n){V.warn(n,"toInt: ")}}return t}var _l=class extends lt{constructor(){super();d(this,"collect",!1);d(this,"coords",[]);d(this,"name",null)}visitNumeric(e){return this.collect&&this.coords.push(e),null}visitNum(e){return this.collect&&e.num==0&&this.coords.push(new P(0,"px")),null}visitSpaceList(e){return this.visitValues(e.values),null}visitFunc(e){return this.collect||(this.collect=!0,this.visitValues(e.values),this.collect=!1,this.name=e.name.toLowerCase()),null}getShape(e,n,s,o,i){if(this.coords.length>0){let a=[];switch(this.coords.forEach((l,c)=>{if(l.unit=="%"){let u=c%2==0?s:o;c==3&&this.name=="circle"&&(u=Math.sqrt((s*s+o*o)/2)),a.push(l.num*u/100)}else a.push(l.num*i.queryUnitSize(l.unit,!1))}),this.name){case"polygon":if(a.length%2==0){let l=[];for(let c=0;c<a.length;c+=2)l.push(new Ft(e+a[c],n+a[c+1]));return new ls(l)}break;case"rectangle":if(a.length==4)return jo(e+a[0],n+a[1],e+a[0]+a[2],n+a[1]+a[3]);break;case"ellipse":if(a.length==4)return Ol(e+a[0],n+a[1],a[2],a[3]);break;case"circle":if(a.length==3)return Ol(e+a[0],n+a[1],a[2],a[2]);break}}return null}};function vr(r,t,e,n,s,o){if(r){let i=new _l;try{return r.visit(i),i.getShape(t,e,n,s,o)}catch(a){V.warn(a,"toShape:")}}return jo(t,e,t+n,e+s)}var Ul=class extends lt{constructor(e){super();this.reset=e;d(this,"counters",{});d(this,"name",null)}visitIdent(e){return this.name=e.toString(),this.reset?this.counters[this.name]=0:this.counters[this.name]=(this.counters[this.name]||0)+1,e}visitInt(e){return this.name&&(this.counters[this.name]+=e.num-(this.reset?0:1)),e}visitSpaceList(e){return this.visitValues(e.values),e}};function cs(r,t){let e=new Ul(t);try{r.visit(e)}catch(n){V.warn(n,"toCounters:")}return e.counters}var Nr=class extends Kt{constructor(e,n){super();this.baseUrl=e;this.transformer=n}visitURL(e){return new Ue(this.transformer.transformURL(e.url,this.baseUrl))}};function zl(r){let t={};return Object.keys(r).forEach(e=>{t[e]=Array.from(r[e])}),t}var Xl=class{constructor(t,e){this.targetId=t;this.resolved=e;d(this,"pageCounters",null);d(this,"spineIndex",-1);d(this,"pageIndex",-1)}equals(t){return this===t?!0:t?this.targetId===t.targetId&&this.resolved===t.resolved&&this.spineIndex===t.spineIndex&&this.pageIndex===t.pageIndex:!1}isResolved(){return this.resolved}resolve(){this.resolved=!0}unresolve(){this.resolved=!1}},jl=class{constructor(t,e){this.counterStore=t;this.baseURL=e}countersOfId(t,e){t=this.counterStore.documentURLTransformer.transformFragment(t,this.baseURL),this.counterStore.countersById[t]=e}getExprContentListener(){return this.counterStore.getExprContentListener()}},Yl=class{constructor(t,e,n,s){this.counterStore=t;this.baseURL=e;this.rootScope=n;this.pageScope=s;d(this,"styler",null);d(this,"namedStringValues",{});d(this,"runningElements",{})}setStyler(t){this.styler=t}getFragment(t){let e=t.match(/^[^#]*#(.*)$/);return e?e[1]:null}getTransformedId(t){let e=this.counterStore.documentURLTransformer.transformURL(Q(t,this.baseURL),this.baseURL);return e.charAt(0)==="#"&&(e=e.substring(1)),e}getPageCounterVal(t,e){let n=()=>{let i=this.counterStore.currentPageCounters[t];return i&&i.length?i[i.length-1]:null},s=new ie(this.pageScope,()=>e(n()),`page-counter-${t}`),o=i=>e(i[i.length-1]);return this.counterStore.registerPageCounterExpr(t,o,s),s}getPageCountersVal(t,e){let n=()=>this.counterStore.currentPageCounters[t]||[],s=new ie(this.pageScope,()=>e(n()),`page-counters-${t}`);return this.counterStore.registerPageCounterExpr(t,e,s),s}getTargetCounters(t,e,n){let s=this.counterStore.countersById[e];return!s&&n&&t&&(this.styler.styleUntilIdIsReached(t),s=this.counterStore.countersById[e]),s||null}getTargetPageCounters(t){return this.counterStore.currentPage.elementsById[t]?this.counterStore.currentPageCounters:this.counterStore.pageCountersById[t]||null}getTargetCounterVal(t,e,n){let s=this.getFragment(t),o=this.getTransformedId(t),i=this.getTargetCounters(s,o,!1);if(i&&i[e]){let l=i[e];return new oe(this.rootScope,n(l[l.length-1]||null))}let a=new ie(this.pageScope,()=>{if(i=this.getTargetCounters(s,o,!0),i)if(i[e]){let l=i[e];return n(l[l.length-1]||null)}else{let l=this.getTargetPageCounters(o);if(l)if(this.counterStore.resolveReference(o),l[e]){let c=l[e];return n(c[c.length-1]||null)}else return n(0);else return this.counterStore.saveReferenceOfCurrentPage(o,!1),"??"}else return this.counterStore.saveReferenceOfCurrentPage(o,!1),"??"},`target-counter-${e}-of-${t}`);return this.counterStore.registerTargetCounterExpr(e,n,a,o),a}getTargetCountersVal(t,e,n){let s=this.getFragment(t),o=this.getTransformedId(t);return new ie(this.pageScope,()=>{let i=this.getTargetPageCounters(o);if(i){this.counterStore.resolveReference(o);let a=i[e]||[],c=this.getTargetCounters(s,o,!0)[e]||[];return n(a.concat(c))}else return this.counterStore.saveReferenceOfCurrentPage(o,!1),"??"},`target-counters-${e}-of-${t}`)}getNamedStringVal(t,e){return new ie(this.pageScope,()=>this.getRunningValue(this.namedStringValues,t,e),`named-string-${e}-${t}`)}getRunningElementVal(t,e){return new ie(this.pageScope,()=>this.getRunningValue(this.runningElements,t,e),`running-element-${e}-${t}`)}getRunningValue(t,e,n){let s=t[e];if(!s)return"";let o=Object.keys(s).map(g=>parseInt(g,10)).sort(Zi),i=this.counterStore.currentPage,a=i.isBlankPage?i.offset-1:i.offset,l=i.isBlankPage?a:Math.max(a,...Array.from(i.container.querySelectorAll(`[${Rt}]`)).map(g=>parseInt(g.getAttribute(Rt),10))),c=-1,u=-1,p=-1,h=-1;for(let g=0;g<o.length;g++){let m=o[g],E=g>0?o[g-1]:-1,y=g<o.length-1?o[g+1]:-1;if(m>l)break;if(m>=a){if(c<0&&(c=m,h=-1),u<0)if(m===a)u=m;else{E<c&&(u=E);let C=i.container.querySelector(`[${Rt}="${m}"]`);if(!C)u<0&&(u=m);else{let x=i.container.querySelector(`[${Rt}="${a}"]`);if(x||(x=i.container.querySelector(`[${Rt}="0"]`)),x){for(let N=x;N;N=N.firstElementChild)if(N===C){u=m;break}}}}p=m}else(y>l||y<0)&&(c=u=p=h=m)}return s[{first:c,start:u,last:p,"first-except":h}[n]]||""}setNamedString(t,e,n){let s=this.namedStringValues[t]||(this.namedStringValues[t]={});s[n]=e}setRunningElement(t,e){let n=this.runningElements[t]||(this.runningElements[t]={});n[e]=String(e)}},Tr=class{constructor(t){this.documentURLTransformer=t;d(this,"countersById",{});d(this,"pageCountersById",{});d(this,"currentPageCounters",{});d(this,"previousPageCounters",{});d(this,"currentPageCountersStack",[]);d(this,"pageIndicesById",{});d(this,"currentPage",null);d(this,"newReferencesOfCurrentPage",[]);d(this,"referencesToSolve",[]);d(this,"referencesToSolveStack",[]);d(this,"unresolvedReferences",{});d(this,"resolvedReferences",{});d(this,"pagesCounterExprs",[]);d(this,"pageCounterExprs",[]);d(this,"targetCounterExprs",[]);this.currentPageCounters.page=[0]}createCounterListener(t){return new jl(this,t)}createCounterResolver(t,e,n){return new Yl(this,t,e,n)}setCurrentPage(t){this.currentPage=t}definePageCounter(t,e){this.currentPageCounters[t]?this.currentPageCounters[t].push(e):this.currentPageCounters[t]=[e]}forceSetPageCounter(t){let e=this.currentPageCounters.page;!e||!e.length?this.currentPageCounters.page=[t]:e[e.length-1]=t}updatePageCounters(t,e){this.previousPageCounters=zl(this.currentPageCounters);let n,s=t["counter-reset"];if(s){let a=s.evaluate(e);a&&(n=cs(a,!0))}if(n)for(let a in n)this.definePageCounter(a,n[a]);let o,i=t["counter-increment"];if(i){let a=i.evaluate(e);a&&(o=cs(a,!1))}o?"page"in o||(o.page=1):(o={},o.page=1);for(let a in o){this.currentPageCounters[a]||this.definePageCounter(a,0);let l=this.currentPageCounters[a];l[l.length-1]+=o[a]}}pushPageCounters(t){this.currentPageCountersStack.push(this.currentPageCounters),this.currentPageCounters=zl(t)}popPageCounters(){this.currentPageCounters=this.currentPageCountersStack.pop()}resolveReference(t){let e=this.unresolvedReferences[t],n=this.resolvedReferences[t];n||(n=this.resolvedReferences[t]=[]);let s=!1;for(let o=0;o<this.referencesToSolve.length;){let i=this.referencesToSolve[o];if(i.targetId===t){if(i.resolve(),this.referencesToSolve.splice(o,1),e){let a=e.indexOf(i);a>=0&&e.splice(a,1)}n.push(i),s=!0}else o++}s||this.saveReferenceOfCurrentPage(t,!0)}saveReferenceOfCurrentPage(t,e){if(!this.newReferencesOfCurrentPage.some(n=>n.targetId===t)){let n=new Xl(t,e);this.newReferencesOfCurrentPage.push(n)}}finishPage(t,e){let n=Object.keys(this.currentPage.elementsById);if(n.length>0){let i=zl(this.currentPageCounters);n.forEach(a=>{this.pageCountersById[a]=i;let l=this.pageIndicesById[a];if(l&&l.pageIndex<e){let c=this.resolvedReferences[a];if(c){let u=this.unresolvedReferences[a];u||(u=this.unresolvedReferences[a]=[]);let p;for(;p=c.shift();)p.unresolve(),u.push(p)}}this.pageIndicesById[a]={spineIndex:t,pageIndex:e}})}let s=this.previousPageCounters,o;for(;o=this.newReferencesOfCurrentPage.shift();){o.pageCounters=s,o.spineIndex=t,o.pageIndex=e;let i;o.isResolved()?(i=this.resolvedReferences[o.targetId],i||(i=this.resolvedReferences[o.targetId]=[])):(i=this.unresolvedReferences[o.targetId],i||(i=this.unresolvedReferences[o.targetId]=[])),i.every(a=>!o.equals(a))&&i.push(o)}this.currentPage=null}getUnresolvedRefsToPage(t){let e=[];Object.keys(t.elementsById).forEach(i=>{let a=this.unresolvedReferences[i];a&&(e=e.concat(a))}),e.sort((i,a)=>i.spineIndex-a.spineIndex||i.pageIndex-a.pageIndex);let s=[],o=null;return e.forEach(i=>{!o||o.spineIndex!==i.spineIndex||o.pageIndex!==i.pageIndex?(o={spineIndex:i.spineIndex,pageIndex:i.pageIndex,pageCounters:i.pageCounters,refs:[i]},s.push(o)):o.refs.push(i)}),s}pushReferencesToSolve(t){this.referencesToSolveStack.push(this.referencesToSolve),this.referencesToSolve=t}popReferencesToSolve(){this.referencesToSolve=this.referencesToSolveStack.pop()}registerPageCounterExpr(t,e,n){t==="pages"?this.pagesCounterExprs.push({expr:n,format:e}):this.pageCounterExprs.push({expr:n,format:e})}registerTargetCounterExpr(t,e,n,s){this.targetCounterExprs.push({name:t,expr:n,format:e,transformedId:s})}getExprContentListener(){return this.exprContentListener.bind(this)}exprContentListener(t,e,n){if(t instanceof ie){if(t.str=="viv-leader"){let i=n.createElementNS("http://www.w3.org/1999/xhtml","span");return i.textContent=e,i.setAttribute("data-viv-leader",t.key),i.setAttribute("data-viv-leader-value",e),i}else if(t.str.startsWith("running-element-")){let i=e&&n.querySelectorAll(`[${Rt}="${e}"]`);if(!i||i.length===0)return null;let l=i[i.length-1].cloneNode(!0);return this.fixPageCounterInRunningElement(l),l.style.position="",l.style.visibility="",l}else if(t.str.startsWith("target-counter-")){let i=n.createElementNS("http://www.w3.org/1999/xhtml","span");return i.textContent=e,i.setAttribute($l,t.key),i}}let s=this.pagesCounterExprs.findIndex(i=>i.expr===t)>=0,o=!s&&this.pageCounterExprs.findIndex(i=>i.expr===t)>=0;if(s||o){let i=n.createElementNS("http://www.w3.org/1999/xhtml","span");return i.textContent=e,i.setAttribute(s?Gl:Wl,t.key),i}else return null}fixPageCounterInRunningElement(t){let e=t.querySelectorAll(`[${Wl}]`);for(let s of e){let o=s.getAttribute(Wl),i=this.pageCounterExprs.find(u=>u.expr.key===o),a=(i==null?void 0:i.expr).str,l=a==null?void 0:a.replace(/^page-counters?-/,""),c=this.currentPageCounters[l];c&&(s.textContent=i.format(c))}let n=t.querySelectorAll(`[${$l}]`);for(let s of n)s.setAttribute(qp,!0)}finishLastPage(t){let e=t.root.querySelectorAll(`[${Gl}]`),n=t.contentContainer.childElementCount;for(let o of e){let i=o.getAttribute(Gl),a=this.pagesCounterExprs.findIndex(l=>l.expr.key===i);a>=0,o.textContent=this.pagesCounterExprs[a].format([n])}let s=t.root.querySelectorAll(`[${qp}]`);for(let o of s){let i=o.getAttribute($l),a=this.targetCounterExprs.find(l=>l.expr.key===i);if(a&&a.transformedId){let l=this.pageCountersById[a.transformedId];if(l){let c=l[a.name];c&&(o.textContent=a.format(c[c.length-1]))}}}}createLayoutConstraint(t){return new Kl(this,t)}},Gl="data-vivliostyle-pages-counter",Wl="data-vivliostyle-page-counter",$l="data-vivliostyle-target-counter",qp="data-vivliostyle-target-counter-in-running",Kl=class{constructor(t,e){this.counterStore=t;this.pageIndex=e}allowLayout(t){if(!t||t.after)return!0;let e=t.viewNode;if(!e||e.nodeType!==1)return!0;let n=e.getAttribute("data-vivliostyle-id")||e.getAttribute("id")||e.getAttribute("name");if(!n||!this.counterStore.resolvedReferences[n]&&!this.counterStore.unresolvedReferences[n])return!0;let s=this.counterStore.pageIndicesById[n];return s?this.pageIndex>=s.pageIndex:!0}};function Zg(r){if(r=r.substr(1),r.match(/^[^0-9a-fA-F\n\r]$/))return r;let t=parseInt(r,16);return isNaN(t)?"":t===0||t>=55296&&t<=57343||t>1114111?"\uFFFD":String.fromCodePoint(t)}function us(r){return r.replace(/\\([0-9a-fA-F]{1,6}(\r\n|[ \n\r\t\f])?|[^0-9a-fA-F\n\r])/g,Zg)}var Zl=class{constructor(){d(this,"type");d(this,"precededBySpace",!1);d(this,"num",0);d(this,"text","");d(this,"position",0);this.type=0}toString(){switch(this.type){case 10:return"(";case 11:return")";case 12:return"{";case 13:return"}";case 14:return"[";case 15:return"]";case 16:return",";case 17:return";";case 18:return":";case 19:return"/";case 21:return"%";case 22:return"?";case 23:return"+";case 24:return"-";case 25:return"||";case 26:return"&&";case 31:return"!";case 32:return"$";case 33:return"^";case 34:return"|";case 35:return"~";case 36:return"*";case 37:return">";case 38:return"<";case 39:return"=";case 41:return"!=";case 42:return"$=";case 43:return"^=";case 44:return"|=";case 45:return"~=";case 46:return"*=";case 47:return">=";case 48:return"<=";case 49:return"==";case 50:return"::";case 51:return"<!--";case 52:return"-->";case 3:return this.num.toString()+this.text;case 4:case 5:return this.num.toString();case 20:return"@"+this.text;case 7:return"#"+this.text;case 6:return this.text+"(";case 9:return"."+this.text;case 0:return"/*EOF*/";default:return this.text}}};function ke(r,t){let e=Array(128),n;for(n=0;n<128;n++)e[n]=r;for(e[NaN]=r==35?35:72,n=0;n<t.length;n+=2)e[t[n]]=t[n+1];return e}var cn=[72,72,72,72,72,72,72,72,72,1,1,72,1,1,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,1,4,34,6,7,8,9,33,10,11,12,13,14,15,16,17,2,2,2,2,2,2,2,2,2,2,18,19,20,21,22,23,24,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,25,29,26,30,3,72,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,27,31,28,32,72];cn[NaN]=80;var qt=[43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,52,43,43,43,43,39,43,43,39,39,39,39,39,39,39,39,39,39,43,43,43,43,43,43,43,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,43,44,43,43,39,43,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,43,43,43,43,43];qt[NaN]=43;var Qg=[72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,78,59,72,59,59,59,59,59,59,59,59,59,59,72,72,72,72,72,72,72,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,72,61,72,72,78,72,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,72,72,72,72,72];qt[NaN]=43;var Qp=[35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,57,59,35,58,58,58,58,58,58,58,58,58,58,35,35,35,35,35,35,35,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,35,61,35,35,60,35,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,35,35,35,35,35];Qp[NaN]=35;var Jp=[45,45,45,45,45,45,45,45,45,73,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,73,45,45,45,45,45,45,45,53,45,45,45,45,45,45,45,39,39,39,39,39,39,39,39,39,39,45,45,45,45,45,45,45,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,45,44,45,45,39,45,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,45,45,45,45,45];Jp[NaN]=45;var Ql=[37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,41,37,37,37,37,37,37,37,37,42,37,39,39,39,39,39,39,39,39,39,39,37,37,37,37,37,37,37,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,37,37,37,37,40,37,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,37,37,37,37,37];Ql[NaN]=37;var Jl=[38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,41,38,38,38,38,38,38,38,38,38,38,39,39,39,39,39,39,39,39,39,39,38,38,38,38,38,38,38,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,38,38,38,38,40,38,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,38,38,38,38,38];Jl[NaN]=38;var ds=ke(35,[61,36]),Jg=ke(35,[58,77]),em=ke(35,[61,36,124,50]),tm=ke(35,[38,51]),nm=ke(35,[42,54]),sm=ke(39,[42,55]),om=ke(54,[42,55,47,56]),im=ke(62,[62,82]),rm=ke(35,[61,36,33,70]),am=ke(62,[45,71]),lm=ke(63,[45,81]),ql=ke(76,[10,72,13,72]),cm=ke(39,[39,46,10,72,13,72,92,48]),um=ke(39,[34,46,10,72,13,72,92,49]),dm=ke(39,[39,47,10,74,13,74,92,48]),pm=ke(39,[34,47,10,74,13,74,92,49]),Zp=ke(64,[9,39,32,39,34,66,39,65,41,72,10,39,13,39]),hm=ke(39,[41,67,9,79,10,79,13,79,32,79,92,75,40,72,91,72,93,72,123,72,125,72,NaN,67]),fm=ke(39,[39,68,10,74,13,74,92,75,NaN,67]),gm=ke(39,[34,68,10,74,13,74,92,75,NaN,67]),mm=ke(72,[9,39,10,39,13,39,32,39,41,69]),Cm=15,Oe=class{constructor(t,e){this.input=t;this.handler=e;d(this,"indexMask");d(this,"buffer");d(this,"tail",0);d(this,"curr",0);d(this,"position",0);this.indexMask=Cm,this.buffer=Array(this.indexMask+1);for(let n=0;n<=this.indexMask;n++)this.buffer[n]=new Zl}token(){return this.tail==this.curr&&this.fillBuffer(),this.buffer[this.curr]}nthToken(t){return(this.tail-this.curr&this.indexMask)<=t&&this.fillBuffer(),this.buffer[this.curr+t&this.indexMask]}consume(){this.curr=this.curr+1&this.indexMask}fillBuffer(){let t=this.tail,e=this.curr,n=this.indexMask;if(t>=e?e+=n:e--,e==t)throw new Error("F_CSSTOK_INTERNAL");let s=cn,o=this.input,i=this.position,a=this.buffer,l=0,c=0,u="",p=0,h=!1,f=a[t],g=-9;for(;;){let m=o.charCodeAt(i);switch(s[m]||s[65]){case 72:u=o.substring(c,i),isNaN(m)?l=0:l=54,s=cn;break;case 1:i++,h=!0;continue;case 2:c=i++,s=Ql;continue;case 3:l=1,c=i++,s=qt;continue;case 4:c=i++,l=31,s=ds;continue;case 33:l=2,c=++i,s=cm;continue;case 34:l=2,c=++i,s=um;continue;case 6:c=++i,l=7,s=qt;continue;case 7:c=i++,l=32,s=ds;continue;case 8:c=i++,l=21;break;case 9:c=i++,l=32,s=tm;continue;case 10:c=i++,l=10;break;case 11:c=i++,l=11;break;case 12:c=i++,l=36,s=ds;continue;case 13:c=i++,l=23;break;case 14:c=i++,l=16;break;case 15:l=24,c=i++,s=Qp;continue;case 16:c=i++,s=Qg;continue;case 78:c=i++,l=9,s=qt;continue;case 17:c=i++,l=19,s=nm;continue;case 18:c=i++,l=18,s=Jg;continue;case 77:i++,l=50;break;case 19:c=i++,l=17;break;case 20:c=i++,l=38,s=rm;continue;case 21:c=i++,l=39,s=ds;continue;case 22:c=i++,l=37,s=ds;continue;case 23:c=i++,l=22;break;case 24:c=++i,l=20,s=qt;continue;case 25:c=i++,l=14;break;case 26:c=i++,l=15;break;case 27:c=i++,l=12;break;case 28:c=i++,l=13;break;case 29:c=i++,g=c,l=1,s=ql;continue;case 30:c=i++,l=33,s=ds;continue;case 31:c=i++,l=34,s=em;continue;case 32:c=i++,l=35,s=ds;continue;case 35:break;case 36:i++,l=l+41-31;break;case 37:l=5,p=parseInt(o.substring(c,i),10);break;case 38:l=4,p=parseFloat(o.substring(c,i));break;case 39:i++;continue;case 40:l=3,p=parseFloat(o.substring(c,i)),c=i++,s=qt;continue;case 41:l=3,p=parseFloat(o.substring(c,i)),u="%",c=i++;break;case 42:i++,s=Jl;continue;case 43:if(u=us(o.substring(c,i)),l===27&&m===63||l===1&&u.toLowerCase()==="u"&&/^(\bu\+[?0-9a-f]+(-[?0-9a-f]+)?|,|\s+|\/\*([^*]|\*[^/])*\*\/)+[;}]/i.test(o.substring(i-1))){l=27,i++;continue}break;case 44:g=i++,s=ql;continue;case 45:u=us(o.substring(c,i));break;case 46:u=o.substring(c,i),i++;break;case 47:u=us(o.substring(c,i)),i++;break;case 48:g=i,i+=2,s=dm;continue;case 49:g=i,i+=2,s=pm;continue;case 50:i++,l=25;break;case 51:i++,l=26;break;case 52:if(u=o.substring(c,i),l==1){if(i++,u.toLowerCase()=="url"){s=Zp;continue}l=6}break;case 53:if(u=us(o.substring(c,i)),l==1){if(i++,u.toLowerCase()=="url"){s=Zp;continue}l=6}break;case 54:s=sm,i++;continue;case 55:s=om,i++;continue;case 56:s=cn,i++;continue;case 57:s=im,i++,o[i]!==">"&&(l=1,s=qt);continue;case 81:l=51,u=o.substring(c,++i),s=cn;break;case 82:l=52,u=o.substring(c,++i),s=cn;break;case 58:l=5,s=Ql,i++;continue;case 59:l=4,s=Jl,i++;continue;case 60:l=1,s=qt,i++;continue;case 61:l=1,s=ql,g=i++;continue;case 62:i--;break;case 63:i-=2;break;case 64:c=i++,s=hm;continue;case 65:c=++i,s=fm;continue;case 66:c=++i,s=gm;continue;case 67:l=8,u=us(o.substring(c,i)),i++;break;case 69:i++;break;case 70:s=am,i++;continue;case 71:s=lm,i++;continue;case 79:if(i-g<8&&o.substring(g+1,i+1).match(/^[0-9a-fA-F]{0,6}(\r\n|[\n\r])|[ \t]$/)){i++;continue}case 68:l=8,u=us(o.substring(c,i)),i++,s=mm;continue;case 74:if(i++,i-g<9&&o.substring(g+1,i).match(/^[0-9a-fA-F]{0,6}(\r\n|[\n\r])$/))continue;l=54,u="E_CSS_UNEXPECTED_NEWLINE",s=cn;break;case 73:if(i-g<9&&o.substring(g+1,i+1).match(/^[0-9a-fA-F]{0,6}[ \t]$/)){i++,s=qt;continue}u=us(o.substring(c,i));break;case 75:g=i++;continue;case 76:i++,s=Jp;continue;default:if(s!==cn){l=54,u="E_CSS_UNEXPECTED_STATE";break}c=i,l=0}if(f.type=l,f.precededBySpace=h,f.num=p,f.text=u,f.position=c,t++,t>=e)break;s=cn,h=!1,f=a[t&n]}this.position=i,this.tail=t&n}};var ve=null,ec=null;function Ko(){return ve}function A(r){if(!ve)throw new Error("E_TASK_NO_CONTEXT");ve.name||(ve.name=r);let t=ve,e=new no(t,t.top,r);return t.top=e,e.state=1,e}function bm(r){return new nc(r||new tc)}function v(r){return new Yo(r)}function un(r,t,e){let n=A(r);n.handler=e;try{t(n)}catch(s){n.task.raise(s,n)}return n.result()}function eh(r,t){return(ve?ve.getScheduler():ec||bm()).run(r,t)}var tc=class{currentTime(){return new Date().valueOf()}setTimeout(t,e){return setTimeout(t,e)}clearTimeout(t){clearTimeout(t)}},nc=class{constructor(t){this.timer=t;d(this,"timeout",1);d(this,"slice",25);d(this,"sliceOverTime",0);d(this,"queue");d(this,"wakeupTime",null);d(this,"timeoutToken",null);d(this,"inTimeSlice",!1);d(this,"order",0);this.queue=new qi,ec||(ec=this)}setSlice(t){this.slice=t}setTimeout(t){this.timeout=t}isTimeSliceOver(){return this.timer.currentTime()>=this.sliceOverTime}arm(){if(this.inTimeSlice)return;let e=this.queue.peek().scheduledTime,n=this.timer.currentTime();if(this.timeoutToken!=null){if(n+this.timeout>this.wakeupTime)return;this.timer.clearTimeout(this.timeoutToken)}let s=e-n;s<=this.timeout&&(s=this.timeout),this.wakeupTime=n+s,this.timeoutToken=this.timer.setTimeout(()=>{this.timeoutToken=null,this.doTimeSlice()},s)}schedule(t,e){let n=t,s=this.timer.currentTime();n.order=this.order++,n.scheduledTime=s+(e||0),this.queue.add(n),this.arm()}doTimeSlice(){this.timeoutToken!=null&&(this.timer.clearTimeout(this.timeoutToken),this.timeoutToken=null),this.inTimeSlice=!0;try{let t=this.timer.currentTime();for(this.sliceOverTime=t+this.slice;this.queue.length();){let e=this.queue.peek();if(e.scheduledTime>t||(this.queue.remove(),e.canceled||e.resumeInternal(),t=this.timer.currentTime(),t>=this.sliceOverTime))break}}catch(t){V.error(t)}this.inTimeSlice=!1,this.queue.length()&&this.arm()}run(t,e){let n=new sc(this,e||"");n.top=new no(n,null,"bootstrap"),n.top.state=1,n.top.then(()=>{let o=()=>{n.running=!1;for(let i of n.callbacks)try{i()}catch(a){V.error(a)}};try{t().then(i=>{n.result=i,o()})}catch(i){n.raise(i),o()}});let s=ve;return ve=n,this.schedule(n.top.suspend("bootstrap")),ve=s,n}},wr=class{constructor(t){this.task=t;d(this,"scheduledTime",0);d(this,"order",0);d(this,"result",null);d(this,"canceled",!1)}compare(t){let e=t;return e.scheduledTime-this.scheduledTime||e.order-this.order}getTask(){return this.task}schedule(t,e){this.result=t,this.task.scheduler.schedule(this,e)}resumeInternal(){let t=this.task;if(this.task=null,t&&t.continuation==this){t.continuation=null;let e=ve;return ve=t,t.top.finish(this.result),ve=e,!0}return!1}cancel(){this.canceled=!0}},sc=class{constructor(t,e){this.scheduler=t;this.name=e;d(this,"callbacks",[]);d(this,"exception",null);d(this,"running",!0);d(this,"result",null);d(this,"waitTarget",null);d(this,"top",null);d(this,"continuation",null)}getName(){return this.name}interrupt(t){if(this.raise(t||new Error("E_TASK_INTERRUPT")),this!==ve&&this.continuation){this.continuation.cancel();let e=new wr(this);this.waitTarget="interrupt",this.continuation=e,this.scheduler.schedule(e)}}getScheduler(){return this.scheduler}isRunning(){return this.running}whenDone(t){this.callbacks.push(t)}join(){let t=A("Task.join");if(!this.running)t.finish(this.result);else{let e=t.suspend(this);this.whenDone(()=>{e.schedule(this.result)})}return t.result()}unwind(){for(;this.top&&!this.top.handler;)this.top=this.top.parent;if(this.top&&this.top.handler&&this.exception){let t=this.exception;this.exception=null,this.top.handler(this.top,t)}else this.exception&&V.error(this.exception,"Unhandled exception in task",this.name)}raise(t,e){if(this.fillStack(t),e){let n=this.top;for(;n&&n!=e;)n=n.parent;n==e&&(this.top=n)}this.exception=t,this.unwind()}fillStack(t){let e=t.frameTrace;if(!e){e=t.stack?`${t.stack}
|
|
3
|
+
`]).concat(e))),n}var V=new El;var ft=(u=>(u.SIMPLE_PROPERTY="SIMPLE_PROPERTY",u.PREPROCESS_SINGLE_DOCUMENT="PREPROCESS_SINGLE_DOCUMENT",u.PREPROCESS_TEXT_CONTENT="PREPROCESS_TEXT_CONTENT",u.PREPROCESS_ELEMENT_STYLE="PREPROCESS_ELEMENT_STYLE",u.POLYFILLED_INHERITED_PROPS="POLYFILLED_INHERITED_PROPS",u.CONFIGURATION="CONFIGURATION",u.RESOLVE_TEXT_NODE_BREAKER="RESOLVE_TEXT_NODE_BREAKER",u.RESOLVE_FORMATTING_CONTEXT="RESOLVE_FORMATTING_CONTEXT",u.RESOLVE_LAYOUT_PROCESSOR="RESOLVE_LAYOUT_PROCESSOR",u.POST_LAYOUT_BLOCK="POST_LAYOUT_BLOCK",u))(ft||{}),tr={};function Ue(r,t,e){if(!ft[r])V.warn(new Error(`Skipping unknown plugin hook '${r}'.`));else{let n=tr[r];n||(n=tr[r]=[]),e?n.unshift(t):n.push(t)}}function Fp(r,t){if(!ft[r])V.warn(new Error(`Ignoring unknown plugin hook '${r}'.`));else{let e=tr[r];if(e){let n=e.indexOf(t);n>=0&&e.splice(n,1)}}}function Ge(r){return tr[r]||[]}var Wg={registerHook:Ue,removeHook:Fp};var nr=class{constructor(t){this.performanceInstance=t;p(this,"timestamps",{});p(this,"registerTiming");p(this,"registerStartTiming");p(this,"registerEndTiming");this.registerTiming=Gs,this.registerStartTiming=this.registerStartTiming=Gs,this.registerEndTiming=this.registerEndTiming=Gs}forceRegisterStartTiming(t,e){Nl.call(this,t,"start",e)}forceRegisterEndTiming(t,e){Nl.call(this,t,"end",e)}printTimings(){let t=this.timestamps,e="";Object.keys(t).forEach(n=>{let s=t[n],o=s.length;for(let i=0;i<o;i++){let a=s[i];e+=n,o>1&&(e+=`(${i})`),e+=` => start: ${a.start}, end: ${a.end}, duration: ${a.end-a.start}
|
|
4
|
+
`}}),V.info(e)}disable(){this.registerTiming=Gs,this.registerStartTiming=this.registerStartTiming=Gs,this.registerEndTiming=this.registerEndTiming=Gs}enable(){this.registerTiming=Nl,this.registerStartTiming=this.registerStartTiming=Bp,this.registerEndTiming=this.registerEndTiming=$g}isEnabled(){return this.registerStartTiming===Bp}};function Gs(){}function Nl(r,t,e){e||(e=this.performanceInstance.now());let n=this.timestamps[r];n||(n=this.timestamps[r]=[]);let s,o=n.length;for(let i=o-1;i>=0&&(s=n[i],!(s&&!s[t]));i--)s=null;s||(s={},n.push(s)),s[t]=e}function Bp(r,t){this.registerTiming(r,"start",t)}function $g(r,t){this.registerTiming(r,"end",t)}var Xg={now:Date.now},jg=window&&window.performance,Ye=new nr(jg||Xg);Ye.forceRegisterStartTiming("load_vivliostyle");var Yg={profiler:{registerStartTiming:Ye.registerStartTiming,registerEndTiming:Ye.registerEndTiming,printTimings:Ye.printTimings,disable:Ye.disable,enable:Ye.enable}};var is=/^[\s\p{Zs}\p{P}\p{Mn}]*[\p{L}\p{N}]\p{Mn}*(?:[\s\p{Zs}]*\p{P}\p{Mn}*)*/u,Vt="data-adapt-eloff",Dp={};function $s(r){return JSON.parse(r)}function Pt(r){let t=r.match(/^([^#]*)/);return t?t[1]:r}function qg(r){let t=r.match(/^([^#?]*)/);return t?t[1]:r}var ln=window.location.href;function Tl(r){ln=r}var Xt=window.location.href;function wl(r){Xt=r}function J(r,t){if(/^data:/i.test(t))return r||t;if(!t||r.match(/^\w{2,}:/))return r.toLowerCase().match("^javascript:")?"#":(r.match(/^\w{2,}:\/\/[^\/]+$/)&&(r=`${r}/`),r);t.match(/^\w{2,}:\/\/[^\/]+$/)&&(t=`${t}/`);let e;if(r.match(/^\/\//))return e=t.match(/^(\w{2,}:)\/\//),e?e[1]+r:r;if(r.match(/^\//))return e=t.match(/^(\w{2,}:\/\/[^\/]+)\//),e?e[1]+r:r;if(r.match(/^\.(\/|$)/)&&(r=r.substr(2)),t=qg(t),r.match(/^#/))return t+r;let n=t.lastIndexOf("/");if(n<0)return r;let s=t.substr(0,n+1)+r,o="";for(e=s.match(/^([^?#]*)([?#].*)$/),e&&(s=e[1],o=e[2]);n=s.indexOf("/../"),!(n<=0);){let i=s.lastIndexOf("/",n-1);if(i<=0)break;s=s.substr(0,i)+s.substr(n+3)}return s.replace(/\/(\.\/)+/g,"/")+o}function Pn(r){let t;return(t=/^(https?:)\/\/github\.com\/([^/]+\/[^/]+)\/(blob\/|tree\/|raw\/)?(.*)$/.exec(r))?r=`${t[1]}//raw.githubusercontent.com/${t[2]}/${t[3]?"":"master/"}${t[4]}`:(t=/^(https?:)\/\/www\.aozora\.gr\.jp\/(cards\/[^/]+\/files\/[^/.]+\.html)$/.exec(r))?r=`${t[1]}//raw.githubusercontent.com/aozorabunko/aozorabunko/master/${t[2]}`:(t=/^(https?:)\/\/gist\.github\.com\/([^/]+\/\w+)(\/|$)(raw(\/|$))?(.*)$/.exec(r))?r=`${t[1]}//gist.githubusercontent.com/${t[2]}/raw/${t[6]}`:(t=/^(https?:)\/\/gist\.github\.com\/([^/]+\/\w+)(?:#|%23)file-(.*)-(\w+)$/.exec(r))?r=`${t[1]}//gist.githubusercontent.com/${t[2]}/raw/${t[3]}.${t[4]}`:(t=/^(https?:)\/\/(?:[^/.]+\.)?jsbin\.com\/(?!(?:blog|help)\b)(\w+)((\/\d+)?).*$/.exec(r))&&(r=`${t[1]}//output.jsbin.com/${t[2]}${t[3]}/`),r}function Pl(r){return r==null?r:r.toString()}var sr=class{constructor(){p(this,"queue",[null])}length(){return this.queue.length-1}add(t){let e=this.queue.length;for(;e>1;){let n=Math.floor(e/2),s=this.queue[n];if(s.compare(t)>0){this.queue[e]=t;return}this.queue[e]=s,e=n}this.queue[1]=t}peek(){return this.queue[1]}remove(){let t=this.queue[1],e=this.queue.pop(),n=this.queue.length;if(n>1){let s=1;for(;;){let o=s*2;if(o>=n)break;if(this.queue[o].compare(e)>0)o+1<n&&this.queue[o+1].compare(this.queue[o])>0&&o++;else if(o+1<n&&this.queue[o+1].compare(e)>0)o++;else break;this.queue[s]=this.queue[o],s=o}this.queue[s]=e}return t}},kl=["","-webkit-","-moz-"],Ws={};function vl(r,t){return CSS.supports(r+t,"unset")}function Kg(r){let t=Ws[r];if(t||t===null)return t;switch(r){case"behavior":case"template":case"ua-list-item-count":case"x-first-pseudo":return Ws[r]=null,null;case"text-combine-upright":if(vl("-webkit-","text-combine")&&!vl("","text-combine-upright"))return Ws[r]=["-webkit-text-combine"],["-webkit-text-combine"];break}for(let e of kl)if(vl(e,r))return t=[e+r],Ws[r]=t,t;return V.warn("Property not supported by the browser: ",r),Ws[r]=null,null}function T(r,t,e){let n=r==null?void 0:r.style;if(!n)return;if(t.startsWith("--")){n.setProperty(t,e||" ");return}let s=Kg(t);if(s)for(let o of s){switch(o){case"-webkit-text-combine":switch(e){case"all":e="horizontal";break}break;case"text-combine-upright":switch(e){case"all":n.setProperty("text-indent","0");break}break}n.setProperty(o,e)}}function gt(r,t,e){try{let n=Ws[t];return r.style.getPropertyValue(n?n[0]:t)}catch(n){}return e||""}function _o(r){let t=r.getAttributeNS("http://www.w3.org/XML/1998/namespace","lang");return!t&&r.namespaceURI=="http://www.w3.org/1999/xhtml"&&(t=r.getAttribute("lang")),t}var $e=class{constructor(){p(this,"list",[])}append(t){return this.list.push(t),this}clear(){this.list=[]}toString(){let t=this.list.join("");return this.list=[t],t}};function Mp(r){return`\\${r.charCodeAt(0).toString(16)} `}function jt(r){return r.replace(/[^-_a-zA-Z0-9\u0080-\uFFFF]/g,Mp)}function rs(r){return r.replace(/[\u0000-\u001F"\\]/g,Mp)}function Al(r){return r.replace(/[\s+&?=#\u007F-\uFFFF]+/g,encodeURIComponent)}function Ll(r){return!!r.match(/^[a-zA-Z\u009E\u009F\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u024F\u037B-\u037D\u0386\u0388-\u0482\u048A-\u0527]$/)}function Zg(r,t){return t=typeof t=="string"?t:"\\u",t+(65536|r.charCodeAt(0)).toString(16).substr(1)}function Rl(r,t){function e(n){return Zg(n,t)}return r.replace(/[^-a-zA-Z0-9_]/g,e)}function cn(r){return Rl(r)}function Qg(r,t){return t=typeof t=="string"?t:"\\u",r.indexOf(t)===0?String.fromCharCode(parseInt(r.substring(t.length),16)):r}function _p(r,t){t=typeof t=="string"?t:"\\u";function e(s){return Qg(s,t)}let n=new RegExp(`${cn(t)}[0-9a-fA-F]{4}`,"g");return r.replace(n,e)}function mt(r,t){let e=0,n=r;for(;;){if(e<=n,e==0||t(e-1),n==r||t(n),e==n)return e;let s=e+n>>1;t(s)?n=s:e=s+1}}function or(r,t){return r-t}function Il(r,t){let e={};for(let n of r){let s=t(n);s&&!e[s]&&(e[s]=n)}return e}function Up(r){let t={};for(let e=0;e<r.length;e++)t[r[e]]=!0;return t}function ir(r,t){let e={};for(let n of r){let s=t(n);s&&(e[s]?e[s].push(n):e[s]=[n])}return e}function Hp(r,t){let e={};for(let n in r)e[n]=t(r[n],n);return e}var wn=class{constructor(){p(this,"listeners",{})}dispatchEvent(t){let e=this.listeners[t.type];if(e){t.target=this,t.currentTarget=this;for(let n=0;n<e.length;n++)e[n](t)}}addEventListener(t,e,n){if(n)return;let s=this.listeners[t];s?s.includes(e)||s.push(e):this.listeners[t]=[e]}removeEventListener(t,e,n){if(n)return;let s=this.listeners[t];if(s){let o=s.indexOf(e);o>=0&&s.splice(o,1)}}},Yt={audio:!0,canvas:!0,embed:!0,iframe:!0,img:!0,math:!0,object:!0,picture:!0,svg:!0,video:!0};function Wp(r){if(r.nodeType==1){let t=r.getAttribute("id");if(t)return t}return null}function Jg(r){return`^${r}`}function zp(r){return r.replace(/[\[\]\(\),=;^]/g,Jg)}function em(r){return r.substr(1)}function Vl(r){return r&&r.replace(/\^[\[\]\(\),=;^]/g,em)}function tm(r){let t=[];do{let e=r.match(/^(\^,|[^,])*/),n=Vl(e[0]);if(r=r.substr(e[0].length+1),!r&&!t.length)return n;t.push(n)}while(r);return t}function Gp(r){let t={};for(;r;){let e=r.match(/^;([^;=]+)=(([^;]|\^;)*)/);if(!e)return t;t[e[1]]=tm(e[2]),r=r.substr(e[0].length)}return t}var rr=class{appendTo(t){t.append("!")}applyTo(t){return!1}},ar=class{constructor(t,e,n){this.index=t;this.id=e;this.sideBias=n}appendTo(t){t.append("/"),t.append(this.index.toString()),(this.id||this.sideBias)&&(t.append("["),this.id&&t.append(this.id),this.sideBias&&(t.append(";s="),t.append(this.sideBias)),t.append("]"))}applyTo(t){if(t.node.nodeType!=1)throw new Error("E_CFI_NOT_ELEMENT");let e=t.node,n=e.children,s=n.length,o,i=Math.floor(this.index/2)-1;if(i<0||s==0)o=e.firstChild,t.node=o||e;else{if(o=n[Math.min(i,s-1)],this.index&1){let a=o.nextSibling;!a||a.nodeType==1?t.after=!0:o=a}t.node=o}if(this.id&&(t.after||this.id!=Wp(t.node))){let a=e.ownerDocument.getElementById(this.id);a?t.node=a:V.warn("E_CFI_ID_MISMATCH:",this.id)}return t.sideBias=this.sideBias,!0}},lr=class{constructor(t,e,n,s){this.offset=t;this.textBefore=e;this.textAfter=n;this.sideBias=s}applyTo(t){if(this.offset>0&&!t.after){let e=this.offset,n=t.node;for(;;){let s=n.nodeType;if(s==1)break;let o=n.nextSibling;if(3<=s&&s<=5){let i=n.textContent.length;if(e<=i)break;if(!o){e=i;break}e-=i}if(!o){e=0;break}n=o}t.node=n,t.offset=e}return t.sideBias=this.sideBias,!0}appendTo(t){t.append(":"),t.append(this.offset.toString()),(this.textBefore||this.textAfter||this.sideBias)&&(t.append("["),(this.textBefore||this.textAfter)&&(this.textBefore&&t.append(zp(this.textBefore)),t.append(","),this.textAfter&&t.append(zp(this.textAfter))),this.sideBias&&(t.append(";s="),t.append(this.sideBias)),t.append("]"))}},Uo=class r{constructor(){p(this,"steps",null)}fromString(t){let e=t.match(/^#?epubcfi\((.*)\)$/);if(!e)throw new Error("E_CFI_NOT_CFI");let n=decodeURIComponent(e[1]),s=0,o=[];for(;;){let i;switch(n.charAt(s)){case"/":{if(s++,e=n.substr(s).match(/^(0|[1-9][0-9]*)(\[(.*?)(;([^\]]|\^\])*)?\])?/),!e)throw new Error("E_CFI_NUMBER_EXPECTED");s+=e[0].length;let a=parseInt(e[1],10),l=e[3];i=Gp(e[4]),o.push(new ar(a,l,Pl(i.s)));break}case":":{if(s++,e=n.substr(s).match(/^(0|[1-9][0-9]*)(\[((([^\];,]|\^[\];,])*)(,(([^\];,]|\^[\];,])*))?)(;([^]]|\^\])*)?\])?/),!e)throw new Error("E_CFI_NUMBER_EXPECTED");s+=e[0].length;let a=parseInt(e[1],10),l=e[4];l&&(l=Vl(l));let c=e[7];c&&(c=Vl(c)),i=Gp(e[10]),o.push(new lr(a,l,c,Pl(i.s)));break}case"!":s++,o.push(new rr);break;case"~":case"@":case"":this.steps=o;return;default:throw new Error("E_CFI_PARSE_ERROR")}}}navigate(t){let e={node:t.documentElement,offset:0,after:!1,sideBias:null,ref:null};for(let n=0;n<this.steps.length;n++)if(!this.steps[n].applyTo(e)){e.ref=new r,e.ref.steps=this.steps.slice(n+1);break}return e}trim(t,e){return t.replace(/\s+/g," ").match(e?/^[ -\uD7FF\uE000-\uFFFF]{0,8}/:/[ -\uD7FF\uE000-\uFFFF]{0,8}$/)[0].replace(/^\s/,"").replace(/\s$/,"")}prependPathFromNode(t,e,n,s){let o=[],i=t.parentNode,a="",l="";for(;t;){switch(t.nodeType){case 3:case 4:case 5:{let c=t.textContent,u=c.length;n?(e+=u,a||(a=c)):(e>u&&(e=u),n=!0,a=c.substr(0,e),l=c.substr(e)),t=t.previousSibling;continue}case 8:t=t.previousSibling;continue}break}for((e>0||a||l)&&(a=this.trim(a,!1),l=this.trim(l,!0),o.push(new lr(e,a,l,s)),s=null);i&&!(!i||i.nodeType==9);){let c=n?null:Wp(t),u=n?1:0;for(;t;)t.nodeType==1&&(u+=2),t=t.previousSibling;o.push(new ar(u,c,s)),s=null,t=i,i=i.parentNode,n=!1}o.reverse(),this.steps?(o.push(new rr),this.steps=o.concat(this.steps)):this.steps=o}toString(){if(!this.steps)return"";let t=new $e;t.append("epubcfi(");for(let e=0;e<this.steps.length;e++)this.steps[e].appendTo(t);return t.append(")"),t.toString().replace(/%/g,"%25")}};function Bl(){return{fontFamily:"serif",lineHeight:1.25,margin:8,hyphenate:!1,columnWidth:25,horizontal:!1,nightMode:!1,spreadView:!1,pageBorder:1,enabledMediaTypes:{vivliostyle:!0,print:!0},defaultPaperSize:void 0}}function Sr(r){return{fontFamily:r.fontFamily,lineHeight:r.lineHeight,margin:r.margin,hyphenate:r.hyphenate,columnWidth:r.columnWidth,horizontal:r.horizontal,nightMode:r.nightMode,spreadView:r.spreadView,pageBorder:r.pageBorder,enabledMediaTypes:Object.assign({},r.enabledMediaTypes),defaultPaperSize:r.defaultPaperSize?Object.assign({},r.defaultPaperSize):void 0}}var sm=Bl(),$p={PENDING:{}};function Ol(r,t,e,n){let s=Math.min((r-0)/e,(t-0)/n);return`matrix(${s},0,0,${s},0,0)`}function Fl(r){return`"${rs(`${r}`)}"`}function om(r){return jt(`${r}`)}function jo(r,t){return r?`${jt(r)}.${jt(t)}`:jt(t)}var Xp=0,as=class{constructor(t,e){this.parent=t;this.resolver=e;p(this,"scopeKey");p(this,"children",[]);p(this,"zero");p(this,"one");p(this,"_true");p(this,"_false");p(this,"values",{});p(this,"funcs",{});p(this,"builtIns",{});if(this.scopeKey=`S${Xp++}`,this.zero=new ie(this,0),this.one=new ie(this,1),this._true=new ie(this,!0),this._false=new ie(this,!1),t&&t.children.push(this),!t){let n=this.builtIns;n.floor=Math.floor,n.ceil=Math.ceil,n.round=Math.round,n.sqrt=Math.sqrt,n.min=Math.min,n.max=Math.max,n.letterbox=Ol,n["css-string"]=Fl,n["css-name"]=om,n.typeof=s=>typeof s,this.defineBuiltInName("page-width",function(){return this.pageWidth()}),this.defineBuiltInName("page-height",function(){return this.pageHeight()}),this.defineBuiltInName("pref-font-family",function(){return this.pref.fontFamily}),this.defineBuiltInName("pref-night-mode",function(){return this.pref.nightMode}),this.defineBuiltInName("pref-hyphenate",function(){return this.pref.hyphenate}),this.defineBuiltInName("pref-margin",function(){return this.pref.margin}),this.defineBuiltInName("pref-line-height",function(){return this.pref.lineHeight}),this.defineBuiltInName("pref-column-width",function(){return this.pref.columnWidth*this.fontSize}),this.defineBuiltInName("pref-horizontal",function(){return this.pref.horizontal}),this.defineBuiltInName("pref-spread-view",function(){return this.pref.spreadView}),this.defineBuiltInName("pub-title",function(){return Fl(this.pubTitle?this.pubTitle:"")}),this.defineBuiltInName("doc-title",function(){return Fl(this.docTitle?this.docTitle:"")})}}defineBuiltInName(t,e){this.values[t]=new Z(this,e,t)}defineName(t,e){this.values[t]=e}defineFunc(t,e){this.funcs[t]=e}defineBuiltIn(t,e){this.builtIns[t]=e}};function jp(r){switch(r==null?void 0:r.toLowerCase()){case"px":case"in":case"pt":case"pc":case"cm":case"mm":case"q":return!0;default:return!1}}function Dl(r){switch(r==null?void 0:r.toLowerCase()){case"vw":case"vh":case"vi":case"vb":case"vmin":case"vmax":case"pvw":case"pvh":case"pvi":case"pvb":case"pvmin":case"pvmax":return!0;default:return!1}}function Yp(r){switch(r==null?void 0:r.toLowerCase()){case"em":case"ex":case"rem":case"lh":case"rlh":return!0;default:return!1}}function qp(r){switch(r==null?void 0:r.toLowerCase()){case"rem":case"rlh":return!0;default:return!1}}var Y={px:1,in:96,pt:4/3,pc:96/6,cm:96/2.54,mm:96/25.4,q:96/2.54/40,em:16,rem:16,ex:8,lh:20,rlh:20,dppx:1,dpi:1/96,dpcm:2.54/96};function Nr(r){switch(r){case"q":return!CSS.supports("font-size","1q");case"lh":return!CSS.supports("line-height","1lh");case"rem":case"rlh":return!0;default:return!1}}var Xs=class{constructor(t,e,n,s){this.rootScope=t;this.viewportWidth=e;this.viewportHeight=n;p(this,"actualPageWidth",null);p(this,"pageWidth");p(this,"actualPageHeight",null);p(this,"pageHeight");p(this,"initialFontSize");p(this,"rootFontSize",null);p(this,"isRelativeRootFontSize",null);p(this,"fontSize");p(this,"rootLineHeight",null);p(this,"pref");p(this,"scopes",{});p(this,"pageAreaWidth",null);p(this,"pageAreaHeight",null);p(this,"pageVertical",null);p(this,"pubTitle",null);p(this,"docTitle",null);this.pageWidth=function(){return this.actualPageWidth?this.actualPageWidth:this.pref.spreadView?Math.floor(e/2)-this.pref.pageBorder:e},this.pageHeight=function(){return this.actualPageHeight?this.actualPageHeight:n},this.initialFontSize=s,this.fontSize=function(){return this.rootFontSize?this.rootFontSize:s},this.pref=sm}getScopeContext(t){let e=this.scopes[t.scopeKey];return e||(e={},this.scopes[t.scopeKey]=e),e}clearScope(t){this.scopes[t.scopeKey]={};for(let e=0;e<t.children.length;e++)this.clearScope(t.children[e])}queryUnitSize(t,e,n){if(Dl(t)){let s=this.pageWidth()/100,o=this.pageHeight()/100,i=this.pageAreaWidth!=null?this.pageAreaWidth/100:s,a=this.pageAreaHeight!=null?this.pageAreaHeight/100:o,l=n!=null?n:this.pageVertical;switch(t){case"vw":return i;case"vh":return a;case"vi":return l?a:i;case"vb":return l?i:a;case"vmin":return i<a?i:a;case"vmax":return i>a?i:a;case"pvw":return s;case"pvh":return o;case"pvi":return l?o:s;case"pvb":return l?s:o;case"pvmin":return s<o?s:o;case"pvmax":return s>o?s:o}}return t=="em"||t=="rem"?e?this.initialFontSize:this.fontSize():t=="ex"?Y.ex*(e?this.initialFontSize:this.fontSize())/Y.em:t=="lh"||t=="rlh"?this.rootLineHeight:Y[t]}evalName(t,e){do{let n=t.values[e];if(n||t.resolver&&(n=t.resolver.call(this,e,!1),n))return n;t=t.parent}while(t);throw new Error(`Name '${e}' is undefined`)}evalCall(t,e,n,s){do{let o=t.funcs[e];if(o||t.resolver&&(o=t.resolver.call(this,e,!0),o))return o;let i=t.builtIns[e];if(i){if(s)return t.zero;let a=Array(n.length);for(let l=0;l<n.length;l++)a[l]=n[l].evaluate(this);return new ie(t,i.apply(this,a))}t=t.parent}while(t);throw new Error(`Function '${e}' is undefined`)}evalMediaName(t,e){let n=t==="all"||!!this.pref.enabledMediaTypes[t];return e?!n:n}evalMediaTest(t,e){let n="",s=t.match(/^(min|max)-(.*)$/);s&&(n=s[1],t=s[2]);let o=null,i=null;switch(t){case"width":case"height":case"device-width":case"device-height":case"color":e&&(o=e.evaluate(this));break}switch(t){case"width":i=this.pageWidth();break;case"height":i=this.pageHeight();break;case"device-width":i=window.screen.availWidth;break;case"device-height":i=window.screen.availHeight;break;case"color":i=window.screen.pixelDepth;break}if(i!=null&&o!=null)switch(n){case"min":return i>=Number(o);case"max":return i<=Number(o);default:return i==o}else if(i!=null&&e==null)return i!==0;return!1}evalSupportsTest(t,e,n){return!1}queryVal(t,e){let n=t&&this.scopes[t.scopeKey];return n?n[e]:void 0}storeVal(t,e,n){this.getScopeContext(t)[e]=n}},lt=class{constructor(t){this.scope=t;p(this,"key");this.scope=t,this.key=`_${Xp++}`}toString(){let t=new $e;return this.appendTo(t,0),t.toString()}appendTo(t,e){throw new Error("F_ABSTRACT")}evaluateCore(t){throw new Error("F_ABSTRACT")}expand(t,e){return this}dependCore(t,e,n){return t===this}dependOuter(t,e,n){let s=n[this.key];if(s!=null)return s===$p.PENDING?!1:s;{n[this.key]=$p.PENDING;let o=this.dependCore(t,e,n);return n[this.key]=o,o}}depend(t,e){return this.dependOuter(t,e,{})}evaluate(t){let e=t.queryVal(this.scope,this.key);return typeof e!="undefined"||(e=this.evaluateCore(t),this.scope&&t.storeVal(this.scope,this.key,e)),e}isMediaName(){return!1}},cr=class extends lt{constructor(e,n){super(e);this.val=n}getOp(){throw new Error("F_ABSTRACT")}evalPrefix(e){throw new Error("F_ABSTRACT")}evaluateCore(e){let n=this.val.evaluate(e);return this.evalPrefix(n)}dependCore(e,n,s){return e===this||this.val.dependOuter(e,n,s)}appendTo(e,n){10<n&&e.append("("),e.append(this.getOp()),this.val.appendTo(e,10),10<n&&e.append(")")}expand(e,n){let s=this.val.expand(e,n);return s===this.val?this:new this.constructor(this.scope,s)}},js=class extends lt{constructor(e,n,s){super(e);this.lhs=n;this.rhs=s}getPriority(){throw new Error("F_ABSTRACT")}getOp(){throw new Error("F_ABSTRACT")}evalInfix(e,n){throw new Error("F_ABSTRACT")}evaluateCore(e){let n=this.lhs.evaluate(e),s=this.rhs.evaluate(e);return this.evalInfix(n,s)}dependCore(e,n,s){return e===this||this.lhs.dependOuter(e,n,s)||this.rhs.dependOuter(e,n,s)}appendTo(e,n){let s=this.getPriority();s<=n&&e.append("("),this.lhs.appendTo(e,s),e.append(this.getOp()),this.rhs.appendTo(e,s),s<=n&&e.append(")")}expand(e,n){let s=this.lhs.expand(e,n),o=this.rhs.expand(e,n);return s===this.lhs&&o===this.rhs?this:new this.constructor(this.scope,s,o)}},ur=class extends js{constructor(t,e,n){super(t,e,n)}getPriority(){return 1}},kn=class extends js{constructor(t,e,n){super(t,e,n)}getPriority(){return 2}},dr=class extends js{constructor(t,e,n){super(t,e,n)}getPriority(){return 3}},Ho=class extends js{constructor(t,e,n){super(t,e,n)}getPriority(){return 4}},Ct=class extends cr{constructor(t,e){super(t,e)}getOp(){return"!"}evalPrefix(t){return!t}},pr=class extends Ct{constructor(t,e){super(t,e)}getOp(){return"not "}},qt=class extends cr{constructor(t,e){super(t,e)}getOp(){return"-"}evalPrefix(t){return-t}},Ys=class extends ur{constructor(t,e,n){super(t,e,n)}getOp(){return"&&"}evaluateCore(t){return this.lhs.evaluate(t)&&this.rhs.evaluate(t)}},hr=class extends Ys{constructor(t,e,n){super(t,e,n)}getOp(){return" and "}},qs=class extends ur{constructor(t,e,n){super(t,e,n)}getOp(){return"||"}evaluateCore(t){return this.lhs.evaluate(t)||this.rhs.evaluate(t)}},fr=class extends qs{constructor(t,e,n){super(t,e,n)}getOp(){return", "}},gr=class extends qs{constructor(t,e,n){super(t,e,n)}getOp(){return" or "}},mr=class extends kn{constructor(t,e,n){super(t,e,n)}getOp(){return"<"}evalInfix(t,e){return t<e}},Cr=class extends kn{constructor(t,e,n){super(t,e,n)}getOp(){return"<="}evalInfix(t,e){return t<=e}},br=class extends kn{constructor(t,e,n){super(t,e,n)}getOp(){return">"}evalInfix(t,e){return t>e}},ls=class extends kn{constructor(t,e,n){super(t,e,n)}getOp(){return">="}evalInfix(t,e){return t>=e}},An=class extends kn{constructor(t,e,n){super(t,e,n)}getOp(){return"=="}evalInfix(t,e){return t==e}},xr=class extends kn{constructor(t,e,n){super(t,e,n)}getOp(){return"!="}evalInfix(t,e){return t!=e}},zo=class extends dr{constructor(t,e,n){super(t,e,n)}getOp(){return"+"}evalInfix(t,e){return t+e}},Go=class extends dr{constructor(t,e,n){super(t,e,n)}getOp(){return" - "}evalInfix(t,e){return t-e}},cs=class extends Ho{constructor(t,e,n){super(t,e,n)}getOp(){return"*"}evalInfix(t,e){return t*e}},Wo=class extends Ho{constructor(t,e,n){super(t,e,n)}getOp(){return"/"}evalInfix(t,e){return t/e}},Ks=class extends Ho{constructor(t,e,n){super(t,e,n)}getOp(){return"%"}evalInfix(t,e){return t%e}},Ft=class extends lt{constructor(e,n,s){var o;super(e);this.num=n;p(this,"unit");this.unit=(o=s==null?void 0:s.toLowerCase())!=null?o:""}appendTo(e,n){e.append(this.num.toString()),e.append(jt(this.unit))}evaluateCore(e){return this.num*e.queryUnitSize(this.unit,!1)}},ee=class extends lt{constructor(e,n){super(e);this.qualifiedName=n}appendTo(e,n){e.append(this.qualifiedName)}evaluateCore(e){return e.evalName(this.scope,this.qualifiedName).evaluate(e)}dependCore(e,n,s){return e===this||n.evalName(this.scope,this.qualifiedName).dependOuter(e,n,s)}},$o=class extends lt{constructor(e,n,s){super(e);this.not=n;this.name=s}appendTo(e,n){this.not&&e.append("not "),e.append(jt(this.name))}evaluateCore(e){return e.evalMediaName(this.name,this.not)}isMediaName(){return!0}},Z=class extends lt{constructor(e,n,s){super(e);this.fn=n;this.str=s}appendTo(e,n){e.append(this.str)}evaluateCore(e){return this.fn.call(e)}};function im(r,t){r.append("(");for(let e=0;e<t.length;e++)e&&r.append(","),t[e].appendTo(r,0);r.append(")")}function rm(r,t,e){let n=t;for(let s=0;s<t.length;s++){let o=t[s].expand(r,e);if(t!==n)n[s]=o;else if(o!==t[s]){n=Array(t.length);for(let i=0;i<s;i++)n[i]=t[i];n[s]=o}}return n}var un=class r extends lt{constructor(e,n,s){super(e);this.qualifiedName=n;this.params=s}appendTo(e,n){e.append(this.qualifiedName),im(e,this.params)}evaluateCore(e){return e.evalCall(this.scope,this.qualifiedName,this.params,!1).expand(e,this.params).evaluate(e)}dependCore(e,n,s){if(e===this)return!0;for(let i=0;i<this.params.length;i++)if(this.params[i].dependOuter(e,n,s))return!0;return n.evalCall(this.scope,this.qualifiedName,this.params,!0).dependOuter(e,n,s)}expand(e,n){let s=rm(e,this.params,n);return s===this.params?this:new r(this.scope,this.qualifiedName,s)}},yr=class r extends lt{constructor(e,n,s,o){super(e);this.cond=n;this.ifTrue=s;this.ifFalse=o}appendTo(e,n){n>0&&e.append("("),this.cond.appendTo(e,0),e.append("?"),this.ifTrue.appendTo(e,0),e.append(":"),this.ifFalse.appendTo(e,0),n>0&&e.append(")")}evaluateCore(e){return this.cond.evaluate(e)?this.ifTrue.evaluate(e):this.ifFalse.evaluate(e)}dependCore(e,n,s){return e===this||this.cond.dependOuter(e,n,s)||this.ifTrue.dependOuter(e,n,s)||this.ifFalse.dependOuter(e,n,s)}expand(e,n){let s=this.cond.expand(e,n),o=this.ifTrue.expand(e,n),i=this.ifFalse.expand(e,n);return s===this.cond&&o===this.ifTrue&&i===this.ifFalse?this:new r(this.scope,s,o,i)}},ie=class extends lt{constructor(e,n){super(e);this.val=n}appendTo(e,n){switch(typeof this.val){case"number":case"boolean":e.append(this.val.toString());break;case"string":e.append('"'),e.append(rs(this.val)),e.append('"');break;default:throw new Error("F_UNEXPECTED_STATE")}}evaluateCore(e){return this.val}},Xo=class r extends lt{constructor(e,n,s){super(e);this.name=n;this.value=s}appendTo(e,n){e.append("("),e.append(rs(this.name.name)),e.append(":"),this.value.appendTo(e,0),e.append(")")}evaluateCore(e){return e.evalMediaTest(this.name.name,this.value)}dependCore(e,n,s){return e===this||this.value.dependOuter(e,n,s)}expand(e,n){let s=this.value.expand(e,n);return s===this.value?this:new r(this.scope,this.name,s)}},Er=class extends lt{constructor(e,n,s,o){super(e);this.name=n;this.value=s;this.isFunc=o}appendTo(e,n){this.isFunc&&e.append(this.name),e.append("("),!this.isFunc&&this.name&&(e.append(this.name),e.append(":")),e.append(this.value),e.append(")")}evaluateCore(e){return e.evalSupportsTest(this.name,this.value,this.isFunc)}},Zs=class extends lt{constructor(e,n){super(e);this.index=n}appendTo(e,n){e.append("$"),e.append(this.index.toString())}expand(e,n){let s=n[this.index];if(!s)throw new Error(`Parameter missing: ${this.index}`);return s}};function tt(r,t,e){return t===r._false||t===r.zero||e==r._false||e==r.zero?r._false:t===r._true||t===r.one?e:e===r._true||e===r.one?t:new Ys(r,t,e)}function z(r,t,e){return t===r.zero?e:e===r.zero?t:new zo(r,t,e)}function K(r,t,e){return t===r.zero?new qt(r,e):e===r.zero?t:new Go(r,t,e)}function Qs(r,t,e){return t===r.zero||e===r.zero?r.zero:t===r.one?e:e===r.one?t:new cs(r,t,e)}function Yo(r,t,e){return t===r.zero?r.zero:e===r.one?t:new Wo(r,t,e)}var ct=class{visitValues(t){for(let e=0;e<t.length;e++)t[e].visit(this);return null}visitEmpty(t){return null}visitSlash(t){return null}visitStr(t){return null}visitIdent(t){return null}visitNumeric(t){return null}visitNum(t){return null}visitInt(t){return this.visitNum(t)}visitHexColor(t){return null}visitURL(t){return null}visitURange(t){return null}visitSpaceList(t){return this.visitValues(t.values),null}visitCommaList(t){return this.visitValues(t.values),null}visitFunc(t){return this.visitValues(t.values),null}visitExpr(t){return null}},Kt=class extends ct{constructor(){super();p(this,"error",!1)}visitValues(e){let n=null;for(let s=0;s<e.length;s++){let o=e[s],i=o.visit(this);if(this.error)return[];if(n)n[s]=i;else if(o!==i){n=new Array(e.length);for(let a=0;a<s;a++)n[a]=e[a];n[s]=i}}return n||e}visitEmpty(e){return e}visitStr(e){return e}visitIdent(e){return e}visitSlash(e){return e}visitNumeric(e){return e}visitNum(e){return e}visitInt(e){return e}visitHexColor(e){return e}visitURL(e){return e}visitURange(e){return e}visitSpaceList(e){let n=this.visitValues(e.values);return this.error?O:n===e.values?e:new q(n)}visitCommaList(e){let n=this.visitValues(e.values);return this.error?O:n===e.values?e:new ge(n)}visitFunc(e){let n=this.visitValues(e.values);return this.error?O:n===e.values?e:new kt(e.name,n)}visitExpr(e){return e}},Se=class{toString(){let t=new $e;return this.appendTo(t,!0),t.toString()}stringValue(){let t=new $e;return this.appendTo(t,!1),t.toString()}toExpr(t,e){return null}appendTo(t,e){t.append("[error]")}isExpr(){return!1}isNumeric(){return!1}isNum(){return!1}isIdent(){return!1}isSpaceList(){return!1}visit(t){return this}},vr=class vr extends Se{static get instance(){return this.empty||(this.empty=new vr),this.empty}constructor(){super()}toExpr(t,e){return new ie(t,"")}appendTo(t,e){}visit(t){return t.visitEmpty(this)}};p(vr,"empty");var Ml=vr,O=Ml.instance,Tr=class Tr extends Se{static get instance(){return this.slash||(this.slash=new Tr),this.slash}constructor(){super()}toExpr(t,e){return new ie(t,"/")}appendTo(t,e){t.append("/")}visit(t){return t.visitSlash(this)}};p(Tr,"slash");var _l=Tr,eo=_l.instance,ce=class extends Se{constructor(e){super();this.str=e}toExpr(e,n){return new ie(e,this.str)}appendTo(e,n){n?(e.append('"'),e.append(rs(this.str)),e.append('"')):e.append(this.str)}visit(e){return e.visitStr(this)}},Ul={},be=class extends Se{constructor(e){super();this.name=e;if(Ul[e])throw new Error("E_INVALID_CALL");Ul[e]=this}toExpr(e,n){return new ie(e,this.name)}appendTo(e,n){n?e.append(jt(this.name)):e.append(this.name)}visit(e){return e.visitIdent(this)}isIdent(){return!0}};function L(r){let t=Ul[r];return t||(t=new be(r)),t}var P=class extends Se{constructor(e,n){var s;super();this.num=e;p(this,"unit");this.unit=(s=n==null?void 0:n.toLowerCase())!=null?s:""}toExpr(e,n){return this.num==0?e.zero:n&&this.unit=="%"?this.num==100?n:new cs(e,n,new ie(e,this.num/100)):new Ft(e,this.num,this.unit)}appendTo(e,n){e.append(this.num.toString()),e.append(this.unit)}visit(e){return e.visitNumeric(this)}isNumeric(){return!0}},nt=class extends Se{constructor(e){super();this.num=e}toExpr(e,n){return this.num==0?e.zero:this.num==1?e.one:new ie(e,this.num)}appendTo(e,n){e.append(this.num.toString())}visit(e){return e.visitNum(this)}isNum(){return!0}},ut=class extends nt{constructor(t){super(t)}visit(t){return t.visitInt(this)}},Js=class extends Se{constructor(e){super();this.hex=e}appendTo(e,n){e.append("#"),e.append(this.hex)}visit(e){return e.visitHexColor(this)}},Oe=class extends Se{constructor(e){super();this.url=e}appendTo(e,n){e.append('url("'),e.append(rs(this.url)),e.append('")')}visit(e){return e.visitURL(this)}},qo=class extends Se{constructor(e){super();this.urangeText=e}appendTo(e,n){e.append(this.urangeText)}visit(e){return e.visitURange(this)}};function Hl(r,t,e,n){var o,i;let s=t.length;if(s>0){(o=t[0])==null||o.appendTo(r,n);for(let a=1;a<s;a++)r.append(e),(i=t[a])==null||i.appendTo(r,n)}}var q=class extends Se{constructor(e){super();this.values=e}appendTo(e,n){Hl(e,this.values," ",n)}visit(e){return e.visitSpaceList(this)}isSpaceList(){return!0}},ge=class extends Se{constructor(e){super();this.values=e}appendTo(e,n){Hl(e,this.values,",",n)}visit(e){return e.visitCommaList(this)}},kt=class extends Se{constructor(e,n){super();this.name=e;this.values=n}appendTo(e,n){e.append(jt(this.name)),e.append("("),Hl(e,this.values,",",n),e.append(")")}visit(e){return e.visitFunc(this)}},B=class extends Se{constructor(e){super();this.expr=e}toExpr(){return this.expr}appendTo(e,n){this.expr instanceof ie||this.expr instanceof Ft?this.expr.appendTo(e,0):(e.append("-epubx-expr("),this.expr.appendTo(e,0),e.append(")"))}visit(e){return e.visitExpr(this)}isExpr(){return!0}},Ln=class extends Se{constructor(e){super();this.text=e}appendTo(e,n){e.append(this.text||" ")}};function ke(r,t){if(r){if(r.isNumeric()){let e=r;return t.queryUnitSize(e.unit,!1)*e.num}if(r.isNum())return r.num}return 0}function wr(r,t){return new P(ke(r,t),"px")}var b={absolute:L("absolute"),all:L("all"),always:L("always"),anywhere:L("anywhere"),auto:L("auto"),avoid:L("avoid"),balance:L("balance"),balance_all:L("balance-all"),block:L("block"),block_end:L("block-end"),block_start:L("block-start"),both:L("both"),bottom:L("bottom"),border_box:L("border-box"),break_all:L("break-all"),break_word:L("break-word"),clip:L("clip"),crop:L("crop"),cross:L("cross"),column:L("column"),discard:L("discard"),exclusive:L("exclusive"),_false:L("false"),fixed:L("fixed"),flex:L("flex"),flow_root:L("flow-root"),footnote:L("footnote"),footer:L("footer"),grid:L("grid"),header:L("header"),hidden:L("hidden"),horizontal_tb:L("horizontal-tb"),inherit:L("inherit"),initial:L("initial"),inline:L("inline"),inline_block:L("inline-block"),inline_end:L("inline-end"),inline_start:L("inline-start"),inside:L("inside"),keep:L("keep"),landscape:L("landscape"),left:L("left"),line:L("line"),list_item:L("list-item"),ltr:L("ltr"),manual:L("manual"),max_content:L("max-content"),min_content:L("min-content"),none:L("none"),normal:L("normal"),oeb_page_foot:L("oeb-page-foot"),oeb_page_head:L("oeb-page-head"),outside:L("outside"),padding_box:L("padding-box"),page:L("page"),relative:L("relative"),revert:L("revert"),right:L("right"),same:L("same"),scale:L("scale"),snap_block:L("snap-block"),snap_inline:L("snap-inline"),solid:L("solid"),spread:L("spread"),_static:L("static"),rtl:L("rtl"),table:L("table"),table_caption:L("table-caption"),table_cell:L("table-cell"),table_footer_group:L("table-footer-group"),table_header_group:L("table-header-group"),table_row:L("table-row"),top:L("top"),transparent:L("transparent"),unset:L("unset"),vertical_lr:L("vertical-lr"),vertical_rl:L("vertical-rl"),visible:L("visible"),_true:L("true")},zl=new P(100,"%"),Rn=new P(100,"pvw"),In=new P(100,"pvh"),ne=new P(0,"px"),$b=new qo("U+0-10FFFF"),Kp={"font-size":1,"line-height":2,color:3};function U(r){return r===b.inherit||r===b.initial||r===b.revert||r===b.unset}function Gl(r,t){let e=Kp[r]||Number.MAX_VALUE,n=Kp[t]||Number.MAX_VALUE;return e-n}function xt(r){return(r==null?void 0:r.length)>2&&r.startsWith("--")}var He=class{constructor(t,e,n,s){this.x1=t;this.y1=e;this.x2=n;this.y2=s}},Bt=class{constructor(t,e){this.x=t;this.y=e}},no=class{constructor(t,e,n,s){this.left=t;this.top=e;this.right=n;this.bottom=s}},Pr=class{constructor(t,e,n,s){this.low=t;this.high=e;this.winding=n;this.shapeId=s}},Ot=class{constructor(t,e,n,s){this.y1=t;this.y2=e;this.x1=n;this.x2=s;p(this,"left",null);p(this,"right",null)}};function am(r,t){return r.low.y-t.low.y||r.low.x-t.low.x}var us=class r{constructor(t){this.points=t}addSegments(t,e){let n=this.points,s=n.length,o=n[s-1];for(let i=0;i<s;i++){let a=n[i],l;o.y<a.y?l=new Pr(o,a,1,e):l=new Pr(a,o,-1,e),t.push(l),o=a}}withOffset(t,e){let n=[];for(let s of this.points)n.push(new Bt(s.x+t,s.y+e));return new r(n)}};function Wl(r,t,e,n){let o=[];for(let i=0;i<20;i++){let a=i*2*Math.PI/20;o.push(new Bt(r+e*Math.sin(a),t+n*Math.cos(a)))}return new us(o)}function Ko(r,t,e,n){return new us([new Bt(r,t),new Bt(e,t),new Bt(e,n),new Bt(r,n)])}var to=class{constructor(t,e,n,s){this.x=t;this.winding=e;this.shapeId=n;this.lowOrHigh=s}};function Zp(r,t){let e=r.low.x+(r.high.x-r.low.x)*(t-r.low.y)/(r.high.y-r.low.y);if(isNaN(e))throw new Error("Bad intersection");return e}function lm(r,t,e,n){let s,o,i,a;t.high.y<e&&V.warn("Error: inconsistent segment (1)"),t.low.y<=e?(s=Zp(t,e),o=t.winding):(s=t.low.x,o=0),t.high.y>=n?(i=Zp(t,n),a=t.winding):(i=t.high.x,a=0),s<i?(r.push(new to(s,o,t.shapeId,-1)),r.push(new to(i,a,t.shapeId,1))):(r.push(new to(i,a,t.shapeId,-1)),r.push(new to(s,o,t.shapeId,1)))}function cm(r,t,e){let n=t+e,s=Array(n),o=Array(n),i;for(i=0;i<=n;i++)s[i]=0,o[i]=0;let a=[],l=!1,c=r.length;for(let u=0;u<c;u++){let d=r[u];s[d.shapeId]+=d.winding,o[d.shapeId]+=d.lowOrHigh;let h=!1;for(i=0;i<t;i++)if(s[i]&&!o[i]){h=!0;break}if(h){for(i=t;i<=n;i++)if(s[i]||o[i]){h=!1;break}}l!=h&&(a.push(d.x),l=h)}return a}function um(r,t){return t?Math.ceil(r/t)*t:r}function Qp(r,t){return t?Math.floor(r/t)*t:r}function dm(r){return new Bt(r.y,-r.x)}function so(r){return new He(r.y1,-r.x2,r.y2,-r.x1)}function kr(r){return new He(-r.y2,r.x1,-r.y1,r.x2)}function Jp(r){return new us(r.points.map(t=>dm(t)))}function eh(r,t,e,n,s,o){o&&(r=so(r),t=t.map(C=>Jp(C)),e=e.map(C=>Jp(C)));let i=t.length,a=e?e.length:0,l=[],c=[],u,d,h;for(u=0;u<i;u++)t[u].addSegments(c,u);for(u=0;u<a;u++)e[u].addSegments(c,u+i);let f=c.length;c.sort(am);let g=0;for(;c[g].shapeId>=i;)g++;let m=c[g].low.y;m>r.y1&&l.push(new Ot(r.y1,m,r.x2,r.x2));let y=0,E=[];for(;y<f&&(h=c[y]).low.y<m;)h.high.y>m&&E.push(h),y++;for(;y<f||E.length>0;){let C=r.y2,x=Math.min(um(Math.ceil(m+n),s),r.y2);for(d=0;d<E.length&&C>x;d++)h=E[d],h.low.x==h.high.x?h.high.y<C&&(C=Math.max(Qp(h.high.y,s),x)):h.low.x!=h.high.x&&(C=x);for(C>r.y2&&(C=r.y2);y<f&&(h=c[y]).low.y<C;){if(h.high.y<m){y++;continue}if(h.low.y<x)h.low.y==h.high.y&&h.low.y==m||(E.push(h),C=x),y++;else{let w=Qp(h.low.y,s);w<C&&(C=w);break}}let N=[];for(d=0;d<E.length;d++)lm(N,E[d],m,C);N.sort((w,k)=>w.x-k.x||w.lowOrHigh-k.lowOrHigh);let S=cm(N,i,a);if(S.length==0)l.push(new Ot(m,C,r.x2,r.x2));else{let w=0,k=r.x1;for(d=0;d<S.length;d+=2){let R=Math.max(r.x1,S[d]),G=Math.min(r.x2,S[d+1])-R;G>w&&(w=G,k=R)}w==0?l.push(new Ot(m,C,r.x2,r.x2)):l.push(new Ot(m,C,Math.max(k,r.x1),Math.min(k+w,r.x2)))}if(C==r.y2)break;for(m=C,d=E.length-1;d>=0;d--)E[d].high.y<=C&&E.splice(d,1)}return th(r,l),l}function th(r,t){let e=t.length-1,n=new Ot(r.y2,r.y2,r.x1,r.x2);for(;e>=0;){let s=n;n=t[e],(n.y2-n.y1<1||n.x1==s.x1&&n.x2==s.x2)&&(s.y1=n.y1,t.splice(e,1),n=s),e--}}function nh(r,t){let e=0,n=r.length;for(;e<n;){let s=Math.floor((e+n)/2);t>=r[s].y2?e=s+1:n=s}return e}function sh(r,t){if(!r.length)return t;let e=t.y1,n,s;for(s=0;s<r.length&&(n=r[s],!(n.y2>t.y1&&n.x1-.1<=t.x1&&n.x2+.1>=t.x2));s++)e=Math.max(e,n.y2);let o=e;for(;s<r.length&&(n=r[s],!(n.y1>=t.y2||n.x1-.1>t.x1||n.x2+.1<t.x2));s++)o=n.y2;return s===r.length?o=t.y2:o=Math.min(o,t.y2),o<=e?null:new He(t.x1,e,t.x2,o)}function oh(r,t){if(!r.length)return t;let e=t.y2,n,s;for(s=r.length-1;s>=0&&(n=r[s],!(s===r.length-1&&n.y2<t.y2));s--){if(n.y1<t.y2&&n.x1-.1<=t.x1&&n.x2+.1>=t.x2)break;e=Math.min(e,n.y1)}let o=Math.min(e,n.y2);for(;s>=0&&(n=r[s],!(n.y2<=t.y1||n.x1-.1>t.x1||n.x2+.1<t.x2));s--)o=n.y1;return o=Math.max(o,t.y1),e<=o?null:new He(t.x1,o,t.x2,e)}function ih(r,t,e,n){let s=e.y1,o=e.x2-e.x1,i=e.y2-e.y1,a=nh(t,s);for(;;){let l=s+i;if(l>r.y2)return!1;let c=r.x1,u=r.x2;for(let d=a;d<t.length&&t[d].y1<l;d++){let h=t[d];h.x1>c&&(c=h.x1),h.x2<u&&(u=h.x2)}if(c+o<=u||a>=t.length)return n=="left"?(e.x1=c,e.x2=c+o):(e.x1=u-o,e.x2=u),e.y2+=s-e.y1,e.y1=s,!0;s=t[a].y2,a++}}function rh(r,t,e,n,s){for(n||(n=[new Ot(e.y1,e.y2,e.x1,e.x2)]);n.length>0&&n[0].y2<=r.y1;)n.shift();if(n.length==0)return;n[0].y1<r.y1&&(n[0].y1=r.y1);let o,i=t.length==0?r.y1:t[t.length-1].y2;i<r.y2&&t.push(new Ot(i,r.y2,r.x1,r.x2));let a=nh(t,n[0].y1);for(let l of n){if(a==t.length)break;for(t[a].y1<l.y1&&(o=t[a],a++,t.splice(a,0,new Ot(l.y1,o.y2,o.x1,o.x2)),o.y2=l.y1);a<t.length&&(o=t[a++],o.y2>l.y2&&(t.splice(a,0,new Ot(l.y2,o.y2,o.x1,o.x2)),o.y2=l.y2),l.x1!=l.x2&&(s=="left"?o.x1=Math.min(l.x2,r.x2):o.x2=Math.max(l.x1,r.x1)),o.y2!=l.y2););}th(r,t)}var $l=class extends ct{constructor(){super();p(this,"propSet",{})}visitIdent(e){return this.propSet[e.name]=!0,e}visitSpaceList(e){return this.visitValues(e.values),e}};function ah(r){if(r){let t=new $l;try{return r.visit(t),t.propSet}catch(e){V.warn(e,"toSet:")}}return{}}var Xl=class extends ct{constructor(e){super();this.value=e}visitInt(e){return this.value=e.num,e}};function ql(r,t){if(r){let e=new Xl(t);try{return r.visit(e),e.value}catch(n){V.warn(n,"toInt: ")}}return t}var jl=class extends ct{constructor(){super();p(this,"collect",!1);p(this,"coords",[]);p(this,"name",null)}visitNumeric(e){return this.collect&&this.coords.push(e),null}visitNum(e){return this.collect&&e.num==0&&this.coords.push(new P(0,"px")),null}visitSpaceList(e){return this.visitValues(e.values),null}visitFunc(e){return this.collect||(this.collect=!0,this.visitValues(e.values),this.collect=!1,this.name=e.name.toLowerCase()),null}getShape(e,n,s,o,i){if(this.coords.length>0){let a=[];switch(this.coords.forEach((l,c)=>{if(l.unit=="%"){let u=c%2==0?s:o;c==3&&this.name=="circle"&&(u=Math.sqrt((s*s+o*o)/2)),a.push(l.num*u/100)}else a.push(l.num*i.queryUnitSize(l.unit,!1))}),this.name){case"polygon":if(a.length%2==0){let l=[];for(let c=0;c<a.length;c+=2)l.push(new Bt(e+a[c],n+a[c+1]));return new us(l)}break;case"rectangle":if(a.length==4)return Ko(e+a[0],n+a[1],e+a[0]+a[2],n+a[1]+a[3]);break;case"ellipse":if(a.length==4)return Wl(e+a[0],n+a[1],a[2],a[3]);break;case"circle":if(a.length==3)return Wl(e+a[0],n+a[1],a[2],a[2]);break}}return null}};function Rr(r,t,e,n,s,o){if(r){let i=new jl;try{return r.visit(i),i.getShape(t,e,n,s,o)}catch(a){V.warn(a,"toShape:")}}return Ko(t,e,t+n,e+s)}var Yl=class extends ct{constructor(e){super();this.reset=e;p(this,"counters",{});p(this,"name",null)}visitIdent(e){return this.name=e.toString(),this.reset?this.counters[this.name]=0:this.counters[this.name]=(this.counters[this.name]||0)+1,e}visitInt(e){return this.name&&(this.counters[this.name]+=e.num-(this.reset?0:1)),e}visitSpaceList(e){return this.visitValues(e.values),e}};function ds(r,t){let e=new Yl(t);try{r.visit(e)}catch(n){V.warn(n,"toCounters:")}return e.counters}var Lr=class extends Kt{constructor(e,n){super();this.baseUrl=e;this.transformer=n}visitURL(e){return new Oe(this.transformer.transformURL(e.url,this.baseUrl))}};function Kl(r){let t={};return Object.keys(r).forEach(e=>{t[e]=Array.from(r[e])}),t}function Zo(r,t){if(t==="content"){let e=r.cloneNode(!0);return e.querySelectorAll("[data-adapt-pseudo]").forEach(s=>s.remove()),e.textContent||""}else{let e=r.querySelector(`[data-adapt-pseudo="${t}"]`);return e&&e.textContent||""}}var tc=class{constructor(t,e){this.targetId=t;this.resolved=e;p(this,"pageCounters",null);p(this,"spineIndex",-1);p(this,"pageIndex",-1)}equals(t){return this===t?!0:t?this.targetId===t.targetId&&this.resolved===t.resolved&&this.spineIndex===t.spineIndex&&this.pageIndex===t.pageIndex:!1}isResolved(){return this.resolved}resolve(){this.resolved=!0}unresolve(){this.resolved=!1}},nc=class{constructor(t,e){this.counterStore=t;this.baseURL=e}countersOfId(t,e){t=this.counterStore.documentURLTransformer.transformFragment(t,this.baseURL),this.counterStore.countersById[t]=e}getExprContentListener(){return this.counterStore.getExprContentListener()}},sc=class{constructor(t,e,n,s){this.counterStore=t;this.baseURL=e;this.rootScope=n;this.pageScope=s;p(this,"styler",null);p(this,"namedStringValues",{});p(this,"runningElements",{})}setStyler(t){this.styler=t}getFragment(t){let e=t.match(/^[^#]*#(.*)$/);return e?e[1]:null}getTransformedId(t){let e=this.counterStore.documentURLTransformer.transformURL(J(t,this.baseURL),this.baseURL);return e.charAt(0)==="#"&&(e=e.substring(1)),e}getPageCounterVal(t,e){let n=()=>{let i=this.counterStore.currentPageCounters[t];return i&&i.length?i[i.length-1]:null},s=new Z(this.pageScope,()=>e(n()),`page-counter-${t}`),o=i=>e(i[i.length-1]);return this.counterStore.registerPageCounterExpr(t,o,s),s}getPageCountersVal(t,e){let n=()=>this.counterStore.currentPageCounters[t]||[],s=new Z(this.pageScope,()=>e(n()),`page-counters-${t}`);return this.counterStore.registerPageCounterExpr(t,e,s),s}getTargetCounters(t,e,n){let s=this.counterStore.countersById[e];return!s&&n&&t&&(this.styler.styleUntilIdIsReached(t),s=this.counterStore.countersById[e]),s||null}getTargetPageCounters(t){return this.counterStore.currentPage.elementsById[t]?this.counterStore.currentPageCounters:this.counterStore.pageCountersById[t]||null}getTargetPageText(t,e){if(this.counterStore.currentPage.elementsById[t]){let n=this.counterStore.currentPage.elementsById[t];if(n&&n.length>0){let s=n[0];return e==="before"||e==="after"?Zo(s,e):Zo(s,"content")}return""}else{if(t in this.counterStore.pageTextById){let n=this.counterStore.pageTextById[t];return n[e]!==void 0?n[e]:n.content||""}return null}}getTargetCounterVal(t,e,n){let s=this.getFragment(t),o=this.getTransformedId(t),i=this.getTargetCounters(s,o,!1);if(i&&i[e]){let l=i[e];return new ie(this.rootScope,n(l[l.length-1]||null))}let a=new Z(this.pageScope,()=>{if(i=this.getTargetCounters(s,o,!0),i)if(i[e]){let l=i[e];return n(l[l.length-1]||null)}else{let l=this.getTargetPageCounters(o);if(l)if(this.counterStore.resolveReference(o),l[e]){let c=l[e];return n(c[c.length-1]||null)}else return n(0);else return this.counterStore.saveReferenceOfCurrentPage(o,!1),"??"}else return this.counterStore.saveReferenceOfCurrentPage(o,!1),"??"},`target-counter-${e}-of-${t}`);return this.counterStore.registerTargetCounterExpr(e,n,a,o),a}getTargetCountersVal(t,e,n){let s=this.getFragment(t),o=this.getTransformedId(t);return new Z(this.pageScope,()=>{let i=this.getTargetPageCounters(o);if(i){this.counterStore.resolveReference(o);let a=i[e]||[],c=this.getTargetCounters(s,o,!0)[e]||[];return n(a.concat(c))}else return this.counterStore.saveReferenceOfCurrentPage(o,!1),"??"},`target-counters-${e}-of-${t}`)}getTargetTextVal(t,e){let n=this.getTransformedId(t),s=new Z(this.pageScope,()=>{if(e==="first-letter"){let i=this.getTargetPageText(n,"before"),a=this.getTargetPageText(n,"content"),l=this.getTargetPageText(n,"after");if(i===null&&a===null&&l===null)return this.counterStore.saveReferenceOfCurrentPage(n,!1),"??";let c=(i!=null?i:"")+(a!=null?a:"")+(l!=null?l:"");this.counterStore.resolveReference(n);let u=c.match(is);return u?u[0]:""}let o=this.getTargetPageText(n,e);return o!==null?(this.counterStore.resolveReference(n),o):(this.counterStore.saveReferenceOfCurrentPage(n,!1),"??")},`target-text-${e}-of-${t}`);return this.counterStore.registerTargetTextExpr(e,s,n),s}getNamedStringVal(t,e){return new Z(this.pageScope,()=>this.getRunningValue(this.namedStringValues,t,e),`named-string-${e}-${t}`)}getRunningElementVal(t,e){return new Z(this.pageScope,()=>this.getRunningValue(this.runningElements,t,e),`running-element-${e}-${t}`)}getRunningValue(t,e,n){let s=t[e];if(!s)return"";let o=Object.keys(s).map(g=>parseInt(g,10)).sort(or),i=this.counterStore.currentPage,a=i.isBlankPage?i.offset-1:i.offset,l=i.isBlankPage?a:Math.max(a,...Array.from(i.container.querySelectorAll(`[${Vt}]`)).map(g=>parseInt(g.getAttribute(Vt),10))),c=-1,u=-1,d=-1,h=-1;for(let g=0;g<o.length;g++){let m=o[g],y=g>0?o[g-1]:-1,E=g<o.length-1?o[g+1]:-1;if(m>l)break;if(m>=a){if(c<0&&(c=m,h=-1),u<0)if(m===a)u=m;else{y<c&&(u=y);let C=i.container.querySelector(`[${Vt}="${m}"]`);if(!C)u<0&&(u=m);else{let x=i.container.querySelector(`[${Vt}="${a}"]`);if(x||(x=i.container.querySelector(`[${Vt}="0"]`)),x){for(let N=x;N;N=N.firstElementChild)if(N===C){u=m;break}}}}d=m}else(E>l||E<0)&&(c=u=d=h=m)}return s[{first:c,start:u,last:d,"first-except":h}[n]]||""}setNamedString(t,e,n){let s=this.namedStringValues[t]||(this.namedStringValues[t]={});s[n]=e}setRunningElement(t,e){let n=this.runningElements[t]||(this.runningElements[t]={});n[e]=String(e)}},Ir=class{constructor(t){this.documentURLTransformer=t;p(this,"countersById",{});p(this,"pageCountersById",{});p(this,"pageTextById",{});p(this,"currentPageCounters",{});p(this,"previousPageCounters",{});p(this,"currentPageCountersStack",[]);p(this,"pageIndicesById",{});p(this,"currentPage",null);p(this,"newReferencesOfCurrentPage",[]);p(this,"referencesToSolve",[]);p(this,"referencesToSolveStack",[]);p(this,"unresolvedReferences",{});p(this,"resolvedReferences",{});p(this,"pagesCounterExprs",[]);p(this,"pageCounterExprs",[]);p(this,"targetCounterExprs",[]);p(this,"targetTextExprs",[]);this.currentPageCounters.page=[0]}createCounterListener(t){return new nc(this,t)}createCounterResolver(t,e,n){return new sc(this,t,e,n)}setCurrentPage(t){this.currentPage=t}definePageCounter(t,e){this.currentPageCounters[t]?this.currentPageCounters[t].push(e):this.currentPageCounters[t]=[e]}forceSetPageCounter(t){let e=this.currentPageCounters.page;!e||!e.length?this.currentPageCounters.page=[t]:e[e.length-1]=t}updatePageCounters(t,e){this.previousPageCounters=Kl(this.currentPageCounters);let n,s=t["counter-reset"];if(s){let a=s.evaluate(e);a&&(n=ds(a,!0))}if(n)for(let a in n)this.definePageCounter(a,n[a]);let o,i=t["counter-increment"];if(i){let a=i.evaluate(e);a&&(o=ds(a,!1))}o?"page"in o||(o.page=1):(o={},o.page=1);for(let a in o){this.currentPageCounters[a]||this.definePageCounter(a,0);let l=this.currentPageCounters[a];l[l.length-1]+=o[a]}}pushPageCounters(t){this.currentPageCountersStack.push(this.currentPageCounters),this.currentPageCounters=Kl(t)}popPageCounters(){this.currentPageCounters=this.currentPageCountersStack.pop()}resolveReference(t){let e=this.unresolvedReferences[t],n=this.resolvedReferences[t];n||(n=this.resolvedReferences[t]=[]);let s=!1;for(let o=0;o<this.referencesToSolve.length;){let i=this.referencesToSolve[o];if(i.targetId===t){if(i.resolve(),this.referencesToSolve.splice(o,1),e){let a=e.indexOf(i);a>=0&&e.splice(a,1)}n.push(i),s=!0}else o++}s||this.saveReferenceOfCurrentPage(t,!0)}saveReferenceOfCurrentPage(t,e){if(!this.newReferencesOfCurrentPage.some(n=>n.targetId===t)){let n=new tc(t,e);this.newReferencesOfCurrentPage.push(n)}}finishPage(t,e){let n=Object.keys(this.currentPage.elementsById);if(n.length>0){let i=Kl(this.currentPageCounters);n.forEach(a=>{this.pageCountersById[a]=i;let l=this.currentPage.elementsById[a];if(l&&l.length>0){let u=l[0];this.pageTextById[a]={content:Zo(u,"content"),before:Zo(u,"before"),after:Zo(u,"after")}}let c=this.pageIndicesById[a];if(c&&c.pageIndex<e){let u=this.resolvedReferences[a];if(u){let d=this.unresolvedReferences[a];d||(d=this.unresolvedReferences[a]=[]);let h;for(;h=u.shift();)h.unresolve(),d.push(h)}}this.pageIndicesById[a]={spineIndex:t,pageIndex:e}})}let s=this.previousPageCounters,o;for(;o=this.newReferencesOfCurrentPage.shift();){o.pageCounters=s,o.spineIndex=t,o.pageIndex=e;let i;o.isResolved()?(i=this.resolvedReferences[o.targetId],i||(i=this.resolvedReferences[o.targetId]=[])):(i=this.unresolvedReferences[o.targetId],i||(i=this.unresolvedReferences[o.targetId]=[])),i.every(a=>!o.equals(a))&&i.push(o)}this.currentPage=null}getUnresolvedRefsToPage(t){let e=[];Object.keys(t.elementsById).forEach(i=>{let a=this.unresolvedReferences[i];a&&(e=e.concat(a))}),e.sort((i,a)=>i.spineIndex-a.spineIndex||i.pageIndex-a.pageIndex);let s=[],o=null;return e.forEach(i=>{!o||o.spineIndex!==i.spineIndex||o.pageIndex!==i.pageIndex?(o={spineIndex:i.spineIndex,pageIndex:i.pageIndex,pageCounters:i.pageCounters,refs:[i]},s.push(o)):o.refs.push(i)}),s}pushReferencesToSolve(t){this.referencesToSolveStack.push(this.referencesToSolve),this.referencesToSolve=t}popReferencesToSolve(){this.referencesToSolve=this.referencesToSolveStack.pop()}registerPageCounterExpr(t,e,n){t==="pages"?this.pagesCounterExprs.push({expr:n,format:e}):this.pageCounterExprs.push({expr:n,format:e})}registerTargetCounterExpr(t,e,n,s){this.targetCounterExprs.push({name:t,expr:n,format:e,transformedId:s})}registerTargetTextExpr(t,e,n){this.targetTextExprs.push({pseudoElement:t,expr:e,transformedId:n})}getExprContentListener(){return this.exprContentListener.bind(this)}exprContentListener(t,e,n){if(t instanceof Z){if(t.str=="viv-leader"){let i=n.createElementNS("http://www.w3.org/1999/xhtml","span");return i.textContent=e,i.setAttribute("data-viv-leader",t.key),i.setAttribute("data-viv-leader-value",e),i}else if(t.str.startsWith("running-element-")){let i=e&&n.querySelectorAll(`[${Vt}="${e}"]`);if(!i||i.length===0)return null;let l=i[i.length-1].cloneNode(!0);return this.fixPageCounterInRunningElement(l),l.style.position="",l.style.visibility="",l}else if(t.str.startsWith("target-counter-")){let i=n.createElementNS("http://www.w3.org/1999/xhtml","span");return i.textContent=e,i.setAttribute(Jl,t.key),i}else if(t.str.startsWith("target-text-")){let i=n.createElementNS("http://www.w3.org/1999/xhtml","span");return i.textContent=e,i.setAttribute(ec,t.key),i}}let s=this.pagesCounterExprs.findIndex(i=>i.expr===t)>=0,o=!s&&this.pageCounterExprs.findIndex(i=>i.expr===t)>=0;if(s||o){let i=n.createElementNS("http://www.w3.org/1999/xhtml","span");return i.textContent=e,i.setAttribute(s?Zl:Ql,t.key),i}else return null}fixPageCounterInRunningElement(t){let e=t.querySelectorAll(`[${Ql}]`);for(let o of e){let i=o.getAttribute(Ql),a=this.pageCounterExprs.find(d=>d.expr.key===i),l=(a==null?void 0:a.expr).str,c=l==null?void 0:l.replace(/^page-counters?-/,""),u=this.currentPageCounters[c];u&&(o.textContent=a.format(u))}let n=t.querySelectorAll(`[${Jl}]`);for(let o of n)o.setAttribute(lh,!0);let s=t.querySelectorAll(`[${ec}]`);for(let o of s)o.setAttribute(ch,!0)}finishLastPage(t){var i;let e=t.root.querySelectorAll(`[${Zl}]`),n=t.contentContainer.childElementCount;for(let a of e){let l=a.getAttribute(Zl),c=this.pagesCounterExprs.findIndex(u=>u.expr.key===l);c>=0,a.textContent=this.pagesCounterExprs[c].format([n])}let s=t.root.querySelectorAll(`[${lh}]`);for(let a of s){let l=a.getAttribute(Jl),c=this.targetCounterExprs.find(u=>u.expr.key===l);if(c&&c.transformedId){let u=this.pageCountersById[c.transformedId];if(u){let d=u[c.name];d&&(a.textContent=c.format(d[d.length-1]))}}}let o=t.root.querySelectorAll(`[${ch}]`);for(let a of o){let l=a.getAttribute(ec),c=this.targetTextExprs.find(u=>u.expr.key===l);if(c&&c.transformedId){let u=this.pageTextById[c.transformedId];u&&(a.textContent=(i=u[c.pseudoElement])!=null?i:"")}}}createLayoutConstraint(t){return new oc(this,t)}},Zl="data-vivliostyle-pages-counter",Ql="data-vivliostyle-page-counter",Jl="data-vivliostyle-target-counter",ec="data-vivliostyle-target-text",lh="data-vivliostyle-target-counter-in-running",ch="data-vivliostyle-target-text-in-running",oc=class{constructor(t,e){this.counterStore=t;this.pageIndex=e}allowLayout(t){if(!t||t.after)return!0;let e=t.viewNode;if(!e||e.nodeType!==1)return!0;let n=e.getAttribute("data-vivliostyle-id")||e.getAttribute("id")||e.getAttribute("name");if(!n||!this.counterStore.resolvedReferences[n]&&!this.counterStore.unresolvedReferences[n])return!0;let s=this.counterStore.pageIndicesById[n];return s?this.pageIndex>=s.pageIndex:!0}};function hm(r){if(r=r.substr(1),r.match(/^[^0-9a-fA-F\n\r]$/))return r;let t=parseInt(r,16);return isNaN(t)?"":t===0||t>=55296&&t<=57343||t>1114111?"\uFFFD":String.fromCodePoint(t)}function ps(r){return r.replace(/\\([0-9a-fA-F]{1,6}(\r\n|[ \n\r\t\f])?|[^0-9a-fA-F\n\r])/g,hm)}var rc=class{constructor(){p(this,"type");p(this,"precededBySpace",!1);p(this,"num",0);p(this,"text","");p(this,"position",0);this.type=0}toString(){switch(this.type){case 10:return"(";case 11:return")";case 12:return"{";case 13:return"}";case 14:return"[";case 15:return"]";case 16:return",";case 17:return";";case 18:return":";case 19:return"/";case 21:return"%";case 22:return"?";case 23:return"+";case 24:return"-";case 25:return"||";case 26:return"&&";case 31:return"!";case 32:return"$";case 33:return"^";case 34:return"|";case 35:return"~";case 36:return"*";case 37:return">";case 38:return"<";case 39:return"=";case 41:return"!=";case 42:return"$=";case 43:return"^=";case 44:return"|=";case 45:return"~=";case 46:return"*=";case 47:return">=";case 48:return"<=";case 49:return"==";case 50:return"::";case 51:return"<!--";case 52:return"-->";case 3:return this.num.toString()+this.text;case 4:case 5:return this.num.toString();case 20:return"@"+this.text;case 7:return"#"+this.text;case 6:return this.text+"(";case 9:return"."+this.text;case 0:return"/*EOF*/";default:return this.text}}};function we(r,t){let e=Array(128),n;for(n=0;n<128;n++)e[n]=r;for(e[NaN]=r==35?35:72,n=0;n<t.length;n+=2)e[t[n]]=t[n+1];return e}var dn=[72,72,72,72,72,72,72,72,72,1,1,72,1,1,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,1,4,34,6,7,8,9,33,10,11,12,13,14,15,16,17,2,2,2,2,2,2,2,2,2,2,18,19,20,21,22,23,24,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,25,29,26,30,3,72,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,27,31,28,32,72];dn[NaN]=80;var Zt=[43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,52,43,43,43,43,39,43,43,39,39,39,39,39,39,39,39,39,39,43,43,43,43,43,43,43,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,43,44,43,43,39,43,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,43,43,43,43,43];Zt[NaN]=43;var fm=[72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,78,59,72,59,59,59,59,59,59,59,59,59,59,72,72,72,72,72,72,72,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,72,61,72,72,78,72,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,72,72,72,72,72];Zt[NaN]=43;var dh=[35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,57,59,35,58,58,58,58,58,58,58,58,58,58,35,35,35,35,35,35,35,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,35,61,35,35,60,35,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,35,35,35,35,35];dh[NaN]=35;var ph=[45,45,45,45,45,45,45,45,45,73,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,73,45,45,45,45,45,45,45,53,45,45,45,45,45,45,45,39,39,39,39,39,39,39,39,39,39,45,45,45,45,45,45,45,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,45,44,45,45,39,45,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,45,45,45,45,45];ph[NaN]=45;var ac=[37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,41,37,37,37,37,37,37,37,37,42,37,39,39,39,39,39,39,39,39,39,39,37,37,37,37,37,37,37,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,37,37,37,37,40,37,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,37,37,37,37,37];ac[NaN]=37;var lc=[38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,41,38,38,38,38,38,38,38,38,38,38,39,39,39,39,39,39,39,39,39,39,38,38,38,38,38,38,38,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,38,38,38,38,40,38,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,38,38,38,38,38];lc[NaN]=38;var hs=we(35,[61,36]),gm=we(35,[58,77]),mm=we(35,[61,36,124,50]),Cm=we(35,[38,51]),bm=we(35,[42,54]),xm=we(39,[42,55]),ym=we(54,[42,55,47,56]),Em=we(62,[62,82]),Sm=we(35,[61,36,33,70]),Nm=we(62,[45,71]),vm=we(63,[45,81]),ic=we(76,[10,72,13,72]),Tm=we(39,[39,46,10,72,13,72,92,48]),wm=we(39,[34,46,10,72,13,72,92,49]),Pm=we(39,[39,47,10,74,13,74,92,48]),km=we(39,[34,47,10,74,13,74,92,49]),uh=we(64,[9,39,32,39,34,66,39,65,41,72,10,39,13,39]),Am=we(39,[41,67,9,79,10,79,13,79,32,79,92,75,40,72,91,72,93,72,123,72,125,72,NaN,67]),Lm=we(39,[39,68,10,74,13,74,92,75,NaN,67]),Rm=we(39,[34,68,10,74,13,74,92,75,NaN,67]),Im=we(72,[9,39,10,39,13,39,32,39,41,69]),Vm=15,De=class{constructor(t,e){this.input=t;this.handler=e;p(this,"indexMask");p(this,"buffer");p(this,"tail",0);p(this,"curr",0);p(this,"position",0);this.indexMask=Vm,this.buffer=Array(this.indexMask+1);for(let n=0;n<=this.indexMask;n++)this.buffer[n]=new rc}token(){return this.tail==this.curr&&this.fillBuffer(),this.buffer[this.curr]}nthToken(t){return(this.tail-this.curr&this.indexMask)<=t&&this.fillBuffer(),this.buffer[this.curr+t&this.indexMask]}consume(){this.curr=this.curr+1&this.indexMask}fillBuffer(){let t=this.tail,e=this.curr,n=this.indexMask;if(t>=e?e+=n:e--,e==t)throw new Error("F_CSSTOK_INTERNAL");let s=dn,o=this.input,i=this.position,a=this.buffer,l=0,c=0,u="",d=0,h=!1,f=a[t],g=-9;for(;;){let m=o.charCodeAt(i);switch(s[m]||s[65]){case 72:u=o.substring(c,i),isNaN(m)?l=0:l=54,s=dn;break;case 1:i++,h=!0;continue;case 2:c=i++,s=ac;continue;case 3:l=1,c=i++,s=Zt;continue;case 4:c=i++,l=31,s=hs;continue;case 33:l=2,c=++i,s=Tm;continue;case 34:l=2,c=++i,s=wm;continue;case 6:c=++i,l=7,s=Zt;continue;case 7:c=i++,l=32,s=hs;continue;case 8:c=i++,l=21;break;case 9:c=i++,l=32,s=Cm;continue;case 10:c=i++,l=10;break;case 11:c=i++,l=11;break;case 12:c=i++,l=36,s=hs;continue;case 13:c=i++,l=23;break;case 14:c=i++,l=16;break;case 15:l=24,c=i++,s=dh;continue;case 16:c=i++,s=fm;continue;case 78:c=i++,l=9,s=Zt;continue;case 17:c=i++,l=19,s=bm;continue;case 18:c=i++,l=18,s=gm;continue;case 77:i++,l=50;break;case 19:c=i++,l=17;break;case 20:c=i++,l=38,s=Sm;continue;case 21:c=i++,l=39,s=hs;continue;case 22:c=i++,l=37,s=hs;continue;case 23:c=i++,l=22;break;case 24:c=++i,l=20,s=Zt;continue;case 25:c=i++,l=14;break;case 26:c=i++,l=15;break;case 27:c=i++,l=12;break;case 28:c=i++,l=13;break;case 29:c=i++,g=c,l=1,s=ic;continue;case 30:c=i++,l=33,s=hs;continue;case 31:c=i++,l=34,s=mm;continue;case 32:c=i++,l=35,s=hs;continue;case 35:break;case 36:i++,l=l+41-31;break;case 37:l=5,d=parseInt(o.substring(c,i),10);break;case 38:l=4,d=parseFloat(o.substring(c,i));break;case 39:i++;continue;case 40:l=3,d=parseFloat(o.substring(c,i)),c=i++,s=Zt;continue;case 41:l=3,d=parseFloat(o.substring(c,i)),u="%",c=i++;break;case 42:i++,s=lc;continue;case 43:if(u=ps(o.substring(c,i)),l===27&&m===63||l===1&&u.toLowerCase()==="u"&&/^(\bu\+[?0-9a-f]+(-[?0-9a-f]+)?|,|\s+|\/\*([^*]|\*[^/])*\*\/)+[;}]/i.test(o.substring(i-1))){l=27,i++;continue}break;case 44:g=i++,s=ic;continue;case 45:u=ps(o.substring(c,i));break;case 46:u=o.substring(c,i),i++;break;case 47:u=ps(o.substring(c,i)),i++;break;case 48:g=i,i+=2,s=Pm;continue;case 49:g=i,i+=2,s=km;continue;case 50:i++,l=25;break;case 51:i++,l=26;break;case 52:if(u=o.substring(c,i),l==1){if(i++,u.toLowerCase()=="url"){s=uh;continue}l=6}break;case 53:if(u=ps(o.substring(c,i)),l==1){if(i++,u.toLowerCase()=="url"){s=uh;continue}l=6}break;case 54:s=xm,i++;continue;case 55:s=ym,i++;continue;case 56:s=dn,i++;continue;case 57:s=Em,i++,o[i]!==">"&&(l=1,s=Zt);continue;case 81:l=51,u=o.substring(c,++i),s=dn;break;case 82:l=52,u=o.substring(c,++i),s=dn;break;case 58:l=5,s=ac,i++;continue;case 59:l=4,s=lc,i++;continue;case 60:l=1,s=Zt,i++;continue;case 61:l=1,s=ic,g=i++;continue;case 62:i--;break;case 63:i-=2;break;case 64:c=i++,s=Am;continue;case 65:c=++i,s=Lm;continue;case 66:c=++i,s=Rm;continue;case 67:l=8,u=ps(o.substring(c,i)),i++;break;case 69:i++;break;case 70:s=Nm,i++;continue;case 71:s=vm,i++;continue;case 79:if(i-g<8&&o.substring(g+1,i+1).match(/^[0-9a-fA-F]{0,6}(\r\n|[\n\r])|[ \t]$/)){i++;continue}case 68:l=8,u=ps(o.substring(c,i)),i++,s=Im;continue;case 74:if(i++,i-g<9&&o.substring(g+1,i).match(/^[0-9a-fA-F]{0,6}(\r\n|[\n\r])$/))continue;l=54,u="E_CSS_UNEXPECTED_NEWLINE",s=dn;break;case 73:if(i-g<9&&o.substring(g+1,i+1).match(/^[0-9a-fA-F]{0,6}[ \t]$/)){i++,s=Zt;continue}u=ps(o.substring(c,i));break;case 75:g=i++;continue;case 76:i++,s=ph;continue;default:if(s!==dn){l=54,u="E_CSS_UNEXPECTED_STATE";break}c=i,l=0}if(f.type=l,f.precededBySpace=h,f.num=d,f.text=u,f.position=c,t++,t>=e)break;s=dn,h=!1,f=a[t&n]}this.position=i,this.tail=t&n}};var Ne=null,cc=null;function Jo(){return Ne}function A(r){if(!Ne)throw new Error("E_TASK_NO_CONTEXT");Ne.name||(Ne.name=r);let t=Ne,e=new ro(t,t.top,r);return t.top=e,e.state=1,e}function Fm(r){return new dc(r||new uc)}function v(r){return new Qo(r)}function pn(r,t,e){let n=A(r);n.handler=e;try{t(n)}catch(s){n.task.raise(s,n)}return n.result()}function hh(r,t){return(Ne?Ne.getScheduler():cc||Fm()).run(r,t)}var uc=class{currentTime(){return new Date().valueOf()}setTimeout(t,e){return setTimeout(t,e)}clearTimeout(t){clearTimeout(t)}},dc=class{constructor(t){this.timer=t;p(this,"timeout",1);p(this,"slice",25);p(this,"sliceOverTime",0);p(this,"queue");p(this,"wakeupTime",null);p(this,"timeoutToken",null);p(this,"inTimeSlice",!1);p(this,"order",0);this.queue=new sr,cc||(cc=this)}setSlice(t){this.slice=t}setTimeout(t){this.timeout=t}isTimeSliceOver(){return this.timer.currentTime()>=this.sliceOverTime}arm(){if(this.inTimeSlice)return;let e=this.queue.peek().scheduledTime,n=this.timer.currentTime();if(this.timeoutToken!=null){if(n+this.timeout>this.wakeupTime)return;this.timer.clearTimeout(this.timeoutToken)}let s=e-n;s<=this.timeout&&(s=this.timeout),this.wakeupTime=n+s,this.timeoutToken=this.timer.setTimeout(()=>{this.timeoutToken=null,this.doTimeSlice()},s)}schedule(t,e){let n=t,s=this.timer.currentTime();n.order=this.order++,n.scheduledTime=s+(e||0),this.queue.add(n),this.arm()}doTimeSlice(){this.timeoutToken!=null&&(this.timer.clearTimeout(this.timeoutToken),this.timeoutToken=null),this.inTimeSlice=!0;try{let t=this.timer.currentTime();for(this.sliceOverTime=t+this.slice;this.queue.length();){let e=this.queue.peek();if(e.scheduledTime>t||(this.queue.remove(),e.canceled||e.resumeInternal(),t=this.timer.currentTime(),t>=this.sliceOverTime))break}}catch(t){V.error(t)}this.inTimeSlice=!1,this.queue.length()&&this.arm()}run(t,e){let n=new pc(this,e||"");n.top=new ro(n,null,"bootstrap"),n.top.state=1,n.top.then(()=>{let o=()=>{n.running=!1;for(let i of n.callbacks)try{i()}catch(a){V.error(a)}};try{t().then(i=>{n.result=i,o()})}catch(i){n.raise(i),o()}});let s=Ne;return Ne=n,this.schedule(n.top.suspend("bootstrap")),Ne=s,n}},Vr=class{constructor(t){this.task=t;p(this,"scheduledTime",0);p(this,"order",0);p(this,"result",null);p(this,"canceled",!1)}compare(t){let e=t;return e.scheduledTime-this.scheduledTime||e.order-this.order}getTask(){return this.task}schedule(t,e){this.result=t,this.task.scheduler.schedule(this,e)}resumeInternal(){let t=this.task;if(this.task=null,t&&t.continuation==this){t.continuation=null;let e=Ne;return Ne=t,t.top.finish(this.result),Ne=e,!0}return!1}cancel(){this.canceled=!0}},pc=class{constructor(t,e){this.scheduler=t;this.name=e;p(this,"callbacks",[]);p(this,"exception",null);p(this,"running",!0);p(this,"result",null);p(this,"waitTarget",null);p(this,"top",null);p(this,"continuation",null)}getName(){return this.name}interrupt(t){if(this.raise(t||new Error("E_TASK_INTERRUPT")),this!==Ne&&this.continuation){this.continuation.cancel();let e=new Vr(this);this.waitTarget="interrupt",this.continuation=e,this.scheduler.schedule(e)}}getScheduler(){return this.scheduler}isRunning(){return this.running}whenDone(t){this.callbacks.push(t)}join(){let t=A("Task.join");if(!this.running)t.finish(this.result);else{let e=t.suspend(this);this.whenDone(()=>{e.schedule(this.result)})}return t.result()}unwind(){for(;this.top&&!this.top.handler;)this.top=this.top.parent;if(this.top&&this.top.handler&&this.exception){let t=this.exception;this.exception=null,this.top.handler(this.top,t)}else this.exception&&V.error(this.exception,"Unhandled exception in task",this.name)}raise(t,e){if(this.fillStack(t),e){let n=this.top;for(;n&&n!=e;)n=n.parent;n==e&&(this.top=n)}this.exception=t,this.unwind()}fillStack(t){let e=t.frameTrace;if(!e){e=t.stack?`${t.stack}
|
|
5
5
|
---- async ---
|
|
6
6
|
`:"";for(let n=this.top;n;n=n.parent)e+=" ",e+=n.getName(),e+=`
|
|
7
|
-
`;t.frameTrace=e}}},
|
|
7
|
+
`;t.frameTrace=e}}},Qo=class r{constructor(t){this.value=t}then(t){t(this.value)}thenAsync(t){return t(this.value)}thenReturn(t){return new r(t)}thenFinish(t){t.finish(this.value)}isPending(){return!1}get(){return this.value}},hc=class{constructor(t){this.frame=t}then(t){this.frame.then(t)}thenAsync(t){if(this.isPending()){let e=new ro(this.frame.task,this.frame.parent,"AsyncResult.thenAsync");return e.state=1,this.frame.parent=e,this.frame.then(n=>{t(n).then(s=>{e.finish(s)})}),e.result()}else return t(this.frame.res)}thenReturn(t){return this.isPending()?this.thenAsync(()=>new Qo(t)):new Qo(t)}thenFinish(t){this.isPending()?this.then(e=>{t.finish(e)}):t.finish(this.frame.res)}isPending(){return this.frame.state==1}get(){if(this.isPending())throw new Error("Result is pending");return this.frame.res}},ro=class{constructor(t,e,n){this.task=t;this.parent=e;this.name=n;p(this,"res",null);p(this,"state");p(this,"callback",null);p(this,"handler",null);this.state=0}checkEnvironment(){if(!Ne)throw new Error("F_TASK_NO_CONTEXT");if(this!==Ne.top)throw new Error("F_TASK_NOT_TOP_FRAME")}result(){return new hc(this)}finish(t){this.checkEnvironment(),Ne&&!Ne.exception&&(this.res=t),this.state=2;let e=this.parent;if(Ne&&(Ne.top=e),this.callback){try{this.callback(t)}catch(n){this.task.raise(n,e)}this.state=3}}getTask(){return this.task}getName(){return this.name}getScheduler(){return this.task.scheduler}then(t){switch(this.state){case 1:if(this.callback)throw new Error("F_TASK_FRAME_ALREADY_HAS_CALLBACK");this.callback=t;break;case 2:{let e=this.task,n=this.parent;try{t(this.res),this.state=3}catch(s){this.state=3,e.raise(s,n)}break}case 3:throw new Error("F_TASK_DEAD_FRAME");default:throw new Error(`F_TASK_UNEXPECTED_FRAME_STATE ${this.state}`)}}timeSlice(){let t=A("Frame.timeSlice");return t.getScheduler().isTimeSliceOver()?(V.debug("-- time slice --"),t.suspend().schedule(!0)):t.finish(!0),t.result()}sleep(t){let e=A("Frame.sleep");return e.suspend().schedule(!0,t),e.result()}loop(t){let e=A("Frame.loop"),n=s=>{try{for(;s;){let o=t();if(o.isPending()){o.then(n);return}else o.then(i=>{s=i})}e.finish(!0)}catch(o){e.task.raise(o,e)}};return n(!0),e.result()}loopWithFrame(t){let e=Ne;if(!e)throw new Error("E_TASK_NO_CONTEXT");return this.loop(()=>{let n;do{let s=new fc(e,e.top);e.top=s,s.state=1,t(s),n=s.result()}while(!n.isPending()&&n.get());return n})}suspend(t){if(this.checkEnvironment(),this.task.continuation)throw new Error("E_TASK_ALREADY_SUSPENDED");let e=new Vr(this.task);return this.task.continuation=e,Ne=null,this.task.waitTarget=t||null,e}},fc=class extends ro{constructor(t,e){super(t,e,"loop")}continueLoop(){this.finish(!0)}breakLoop(){this.finish(!1)}};var Qt=class{constructor(t,e){this.fetch=t;p(this,"name");p(this,"arrived",!1);p(this,"resource",null);p(this,"task",null);p(this,"piggybacks",[]);this.name=e}start(){this.task||(this.task=Jo().getScheduler().run(()=>{let t=A("Fetcher.run");return this.fetch().then(e=>{let n=this.piggybacks;if(this.arrived=!0,this.resource=e,this.task=null,this.piggybacks=[],n)for(let s=0;s<n.length;s++)try{n[s](e)}catch(o){V.error(o,"Error:")}t.finish(e)}),t.result()},this.name))}piggyback(t){this.arrived?t(this.resource):this.piggybacks.push(t)}get(){return this.arrived?v(this.resource):(this.start(),this.task.join())}hasArrived(){return this.arrived}},Vn=r=>{if(r.length==0)return v(!0);if(r.length==1)return r[0].get().thenReturn(!0);let t=A("waitForFetches"),e=0;return t.loop(()=>{for(;e<r.length;){let n=r[e++];if(!n.hasArrived())return n.get().thenReturn(!0)}return v(!1)}).then(()=>{t.finish(!0)}),t.result()};var gc=`
|
|
8
8
|
@media screen {
|
|
9
9
|
[data-vivliostyle-viewer-viewport] {
|
|
10
10
|
background: #aaaaaa;
|
|
@@ -52,25 +52,28 @@
|
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
[data-vivliostyle-viewer-viewport][data-vivliostyle-spread-view="true"]
|
|
55
|
+
[data-vivliostyle-spread-container]
|
|
55
56
|
[data-vivliostyle-page-container][data-vivliostyle-page-side="left"] {
|
|
56
57
|
margin-right: 1px;
|
|
57
58
|
transform-origin: right top;
|
|
58
59
|
}
|
|
59
60
|
|
|
60
61
|
[data-vivliostyle-viewer-viewport][data-vivliostyle-spread-view="true"]
|
|
62
|
+
[data-vivliostyle-spread-container]
|
|
61
63
|
[data-vivliostyle-page-container][data-vivliostyle-page-side="right"] {
|
|
62
64
|
margin-left: 1px;
|
|
63
65
|
transform-origin: left top;
|
|
64
66
|
}
|
|
65
67
|
|
|
66
68
|
[data-vivliostyle-viewer-viewport][data-vivliostyle-spread-view="true"]
|
|
69
|
+
[data-vivliostyle-spread-container]
|
|
67
70
|
[data-vivliostyle-page-container][data-vivliostyle-unpaired-page="true"] {
|
|
68
71
|
margin-left: auto;
|
|
69
72
|
margin-right: auto;
|
|
70
73
|
transform-origin: center top;
|
|
71
74
|
}
|
|
72
75
|
}
|
|
73
|
-
`,
|
|
76
|
+
`,mc=`
|
|
74
77
|
[data-vivliostyle-layout-box] {
|
|
75
78
|
position: absolute;
|
|
76
79
|
left: 0;
|
|
@@ -173,7 +176,9 @@
|
|
|
173
176
|
@supports (zoom: 8) {
|
|
174
177
|
[data-vivliostyle-spread-container] [data-vivliostyle-page-container] {
|
|
175
178
|
zoom: var(--viv-outputPixelRatio,1);
|
|
176
|
-
transform: scale(calc(1 / var(--viv-outputPixelRatio,1)));
|
|
179
|
+
/* transform: scale(calc(1 / var(--viv-outputPixelRatio,1))); */
|
|
180
|
+
/* Use matrix instead of scale (Workaround for issue #1555) */
|
|
181
|
+
transform: matrix(calc(1 / var(--viv-outputPixelRatio,1)), 0, 5e-324, calc(1 / var(--viv-outputPixelRatio,1)), 0, 0);
|
|
177
182
|
transform-origin: left top;
|
|
178
183
|
}
|
|
179
184
|
}
|
|
@@ -201,7 +206,7 @@
|
|
|
201
206
|
}
|
|
202
207
|
}
|
|
203
208
|
}
|
|
204
|
-
`,
|
|
209
|
+
`,Cc=`
|
|
205
210
|
/*
|
|
206
211
|
* Copyright 2013 Google, Inc.
|
|
207
212
|
* Copyright 2015 Daishinsha Inc.
|
|
@@ -264,7 +269,6 @@ border-image-outset = [NUM | LENGTH]{1,4};
|
|
|
264
269
|
border-image-repeat = [ stretch | repeat | round | space ]{1,2};
|
|
265
270
|
bottom = APLENGTH;
|
|
266
271
|
caption-side = top | bottom;
|
|
267
|
-
clear = none | left | right | top | bottom | inline-start | inline-end | block-start | block-end | inside | outside | both | all | same;
|
|
268
272
|
clip = rect(ALENGTH{4}) | rect(SPACE(ALENGTH{4})) | auto;
|
|
269
273
|
color = COLOR;
|
|
270
274
|
LIST_STYLE_TYPE = IDENT;
|
|
@@ -276,6 +280,8 @@ CONTENT_LIST = [ STRING | URI | counter(IDENT LIST_STYLE_TYPE?) |
|
|
|
276
280
|
target-counter(ATTR IDENT LIST_STYLE_TYPE?) |
|
|
277
281
|
target-counters([ STRING | URI ] IDENT STRING LIST_STYLE_TYPE?) |
|
|
278
282
|
target-counters(ATTR IDENT STRING LIST_STYLE_TYPE?) |
|
|
283
|
+
target-text([ STRING | URI ] [content | before | after | first-letter]?) |
|
|
284
|
+
target-text(ATTR [content | before | after | first-letter]?) |
|
|
279
285
|
leader([ dotted | solid | space ] | STRING ) |
|
|
280
286
|
open-quote | close-quote | no-open-quote | no-close-quote |
|
|
281
287
|
content([ text | before | after | first-letter ]?) |
|
|
@@ -502,6 +508,7 @@ crop-offset = auto | LENGTH;
|
|
|
502
508
|
crop-marks-line-color = auto | COLOR;
|
|
503
509
|
|
|
504
510
|
/* CSS Page Floats */
|
|
511
|
+
clear = none | left | right | top | bottom | inline-start | inline-end | block-start | block-end | inside | outside | both | all | same | column | region | page;
|
|
505
512
|
float-reference = inline | column | region | page;
|
|
506
513
|
float = none | footnote | [ block-start || block-end || inline-start || inline-end || snap-block || snap-inline || left || right || top || bottom || inside || outside ];
|
|
507
514
|
float-min-wrap-block = PPLENGTH;
|
|
@@ -829,7 +836,7 @@ word-wrap = overflow-wrap;
|
|
|
829
836
|
[adapt,webkit]start = inline-start;
|
|
830
837
|
[adapt,webkit]end = inline-end;
|
|
831
838
|
|
|
832
|
-
`,
|
|
839
|
+
`,bc=`
|
|
833
840
|
<!DOCTYPE html>
|
|
834
841
|
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:s="http://www.pyroxy.com/ns/shadow">
|
|
835
842
|
<head>
|
|
@@ -852,7 +859,7 @@ word-wrap = overflow-wrap;
|
|
|
852
859
|
<s:template id="table-cell"><div data-vivliostyle-flow-root="true" class="-vivliostyle-table-cell-container"><s:content/></div></s:template>
|
|
853
860
|
|
|
854
861
|
</body>
|
|
855
|
-
</html>`,
|
|
862
|
+
</html>`,xc=`
|
|
856
863
|
@namespace "http://www.w3.org/1999/xhtml";
|
|
857
864
|
|
|
858
865
|
:root {
|
|
@@ -979,7 +986,7 @@ word-wrap = overflow-wrap;
|
|
|
979
986
|
margin: 10%;
|
|
980
987
|
}
|
|
981
988
|
}
|
|
982
|
-
`,
|
|
989
|
+
`,yc=`
|
|
983
990
|
@namespace "http://www.w3.org/1999/xhtml";
|
|
984
991
|
@namespace m "http://www.w3.org/1998/Math/MathML";
|
|
985
992
|
@namespace epub "http://www.idpf.org/2007/ops";
|
|
@@ -1353,7 +1360,7 @@ epub|case[required-namespace::supported] ~ epub|case {
|
|
|
1353
1360
|
epub|case[required-namespace::supported] ~ epub|default {
|
|
1354
1361
|
display: none;
|
|
1355
1362
|
}
|
|
1356
|
-
`,
|
|
1363
|
+
`,Ec=`
|
|
1357
1364
|
@namespace "http://www.w3.org/1999/xhtml";
|
|
1358
1365
|
|
|
1359
1366
|
*:not([data-vivliostyle-role=doc-toc],
|
|
@@ -1383,7 +1390,7 @@ epub|case[required-namespace::supported] ~ epub|default {
|
|
|
1383
1390
|
[data-vivliostyle-role=doc-toc]:is(ol,ul) {
|
|
1384
1391
|
-adapt-behavior: toc-container;
|
|
1385
1392
|
}
|
|
1386
|
-
`,
|
|
1393
|
+
`,Sc=`
|
|
1387
1394
|
[data-viv-margin-discard~="block-start"] {
|
|
1388
1395
|
margin-block-start: 0 !important;
|
|
1389
1396
|
}
|
|
@@ -1502,12 +1509,12 @@ span[data-viv-leader] {
|
|
|
1502
1509
|
text-orientation: mixed;
|
|
1503
1510
|
white-space: pre;
|
|
1504
1511
|
}
|
|
1505
|
-
`;function hs(r,t,e){let n=A("fetchFromURL"),s={method:e||"GET",mode:"cors"},o=n.suspend(),i={status:0,statusText:"",url:r,contentType:null,responseText:null,responseXML:null,responseBlob:null};return fetch(r,s).then(a=>{var l;return i.status=a.status,i.url=a.url,i.statusText=a.statusText,i.contentType=(l=a.headers.get("Content-Type"))==null?void 0:l.replace(/;.*$/,"").toLowerCase(),a.ok?t==="blob"?a.blob():t==="arraybuffer"?a.arrayBuffer():t==="json"?a.json():/\/aozorabunko\/[^/]+\/cards\/[^/]+\/files\/[^/.]+\.html$/.test(r)?(i.contentType="text/html",a.arrayBuffer().then(c=>new TextDecoder("Shift_JIS").decode(c))):(/^data:,(<|%3c)/i.test(r)&&(i.contentType="text/html"),a.text()):a.text()}).then(a=>{t==="blob"&&a instanceof Blob?i.responseBlob=a:t==="arraybuffer"&&a instanceof ArrayBuffer?i.responseBlob=fc([a]):t==="json"?i.responseText=JSON.stringify(a):typeof a=="string"&&(i.responseText=a),o.schedule(i)}).catch(a=>{V.warn(a,`Error fetching ${r}`),o.schedule(i)}),n.result()}function fc(r,t){let e=t||"application/octet-stream";return new Blob(r,{type:e})}function th(r){let t=A("readBlob"),e=new FileReader,n=t.suspend(e);return e.addEventListener("load",()=>{n.schedule(e.result)},!1),e.readAsArrayBuffer(r),t.result()}function nh(r){return URL.createObjectURL(r)}var ps=class{constructor(t,e){this.parser=t;this.type=e;d(this,"resources",{});d(this,"fetchers",{})}load(t,e,n){t=Tt(t);let s=this.resources[t];return typeof s!="undefined"?v(s):this.fetch(t,e,n).get()}fetchInner(t,e,n){let s=A("fetch"),o=t.endsWith("?viv-toc-box");o&&(t=t.replace("?viv-toc-box",""));let i=Q("user-agent.xml",$t),a=!o&&t===i;return a&&(t=`data:application/xml,${encodeURIComponent(cc)}`),hs(t,this.type).then(l=>{if(l.status>=400&&e)throw new Error((n||`Failed to fetch required resource: ${t}`)+` (${l.status}${l.statusText?" "+l.statusText:""})`);o?(t+="?viv-toc-box",l.url+="?viv-toc-box"):a&&(l.url=t=i),this.parser(l,this).then(c=>{delete this.fetchers[t],this.resources[t]=c,s.finish(c)})}),s.result()}fetch(t,e,n){if(t=Tt(t),this.resources[t])return null;let o=this.fetchers[t];return o||(o=new Zt(()=>this.fetchInner(t,e,n),`Fetch ${t}`),this.fetchers[t]=o,o.start()),o}get(t){return this.resources[Tt(t)]}delete(t){delete this.resources[Tt(t)]}};function xm(r,t){let e=r.responseText;return v(e?Hs(e):null)}function sh(){return new ps(xm,"text")}function In(r,t,e){let n=new Zt(()=>{let s=A("loadElement"),o=s.suspend(r),i=!1,a=l=>{i||(i=!0,o.schedule(l?l.type:"timeout"))};return r.addEventListener("load",a,!1),r.addEventListener("error",a,!1),r.addEventListener("abort",a,!1),r.namespaceURI=="http://www.w3.org/2000/svg"?(t&&r.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",t),setTimeout(a,300)):r.localName==="script"?setTimeout(a,3e3):t&&(r.src=t,e&&(r.alt=e)),s.result()},`loadElement ${t||r.localName}`);return n.start(),n}var oh=0,ym=16777216,gc=33554432,Rr=50331648,Ir=67108864,Em=83886080,Sm=100663296;var qo=class{constructor(t){this.scope=t;d(this,"flavor");this.flavor="Author"}getCurrentToken(){return null}getScope(){return this.scope}error(t,e){}startStylesheet(t){this.flavor=t}tagSelector(t,e){}classSelector(t){}pseudoclassSelector(t,e){}pseudoelementSelector(t,e){}idSelector(t){}attributeSelector(t,e,n,s){}descendantSelector(){}childSelector(){}adjacentSiblingSelector(){}followingSiblingSelector(){}nextSelector(){}startSelectorRule(){}startFontFaceRule(){}startFootnoteRule(t){}startViewportRule(){}startDefineRule(){}startRegionRule(){}startPageRule(){}startPageMarginBoxRule(t){}startWhenRule(t){}startMediaRule(t){this.startWhenRule(t)}startFlowRule(t){}startPageTemplateRule(){}startPageMasterRule(t,e,n){}startPartitionRule(t,e,n){}startPartitionGroupRule(t,e,n){}startRuleBody(){}property(t,e,n){}endRule(){}startFuncWithSelector(t){}endFuncWithSelector(){}pushSelectorText(t){}getImportantSpecificity(){switch(this.flavor){case"UA":return oh;case"User":return Sm;default:return Em}}getBaseSpecificity(){switch(this.flavor){case"UA":return oh;case"User":return ym;default:return gc}}},kr=class extends qo{constructor(){super(null);d(this,"stack",[]);d(this,"tokenizer",null);d(this,"slave",null)}pushHandler(e){this.stack.push(this.slave),this.slave=e}popHandler(){this.slave=this.stack.pop()}getCurrentToken(){return this.tokenizer?this.tokenizer.token():null}getScope(){return this.slave.getScope()}error(e,n){this.slave.error(e,n)}errorMsg(e,n){var s;V.warn(e,(s=n==null?void 0:n.toString())!=null?s:"")}startStylesheet(e){super.startStylesheet(e),this.stack.length>0&&(this.slave=this.stack[0],this.stack=[]),this.slave.startStylesheet(e)}tagSelector(e,n){this.slave.tagSelector(e,n)}classSelector(e){this.slave.classSelector(e)}pseudoclassSelector(e,n){this.slave.pseudoclassSelector(e,n)}pseudoelementSelector(e,n){this.slave.pseudoelementSelector(e,n)}idSelector(e){this.slave.idSelector(e)}attributeSelector(e,n,s,o){this.slave.attributeSelector(e,n,s,o)}descendantSelector(){this.slave.descendantSelector()}childSelector(){this.slave.childSelector()}adjacentSiblingSelector(){this.slave.adjacentSiblingSelector()}followingSiblingSelector(){this.slave.followingSiblingSelector()}nextSelector(){this.slave.nextSelector()}startSelectorRule(){this.slave.startSelectorRule()}startFontFaceRule(){this.slave.startFontFaceRule()}startFootnoteRule(e){this.slave.startFootnoteRule(e)}startViewportRule(){this.slave.startViewportRule()}startDefineRule(){this.slave.startDefineRule()}startRegionRule(){this.slave.startRegionRule()}startPageRule(){this.slave.startPageRule()}startPageMarginBoxRule(e){this.slave.startPageMarginBoxRule(e)}startWhenRule(e){this.slave.startWhenRule(e)}startFlowRule(e){this.slave.startFlowRule(e)}startPageTemplateRule(){this.slave.startPageTemplateRule()}startPageMasterRule(e,n,s){this.slave.startPageMasterRule(e,n,s)}startPartitionRule(e,n,s){this.slave.startPartitionRule(e,n,s)}startPartitionGroupRule(e,n,s){this.slave.startPartitionGroupRule(e,n,s)}startRuleBody(){this.slave.startRuleBody()}property(e,n,s){this.slave.property(e,n,s)}endRule(){this.slave.endRule()}startFuncWithSelector(e){this.slave.startFuncWithSelector(e)}endFuncWithSelector(){this.slave.endFuncWithSelector()}pushSelectorText(e){this.slave.pushSelectorText(e)}},Ar=class extends qo{constructor(e,n,s){super(e);this.owner=n;this.topLevel=s;d(this,"depth",0);n&&(this.flavor=n.flavor)}getCurrentToken(){var e;return(e=this.owner)==null?void 0:e.getCurrentToken()}error(e,n){var s;(s=this.owner)==null||s.errorMsg(e,n)}startRuleBody(){this.depth++}endRule(){--this.depth==0&&!this.topLevel&&this.owner.popHandler()}},Qt=class extends Ar{constructor(t,e,n){super(t,e,n)}report(t){this.error(t,this.getCurrentToken())}reportAndSkip(t){this.report(t),this.owner.pushHandler(new Ar(this.scope,this.owner,!1))}startSelectorRule(){this.reportAndSkip("E_CSS_UNEXPECTED_SELECTOR")}startFontFaceRule(){this.reportAndSkip("E_CSS_UNEXPECTED_FONT_FACE")}startFootnoteRule(t){this.reportAndSkip("E_CSS_UNEXPECTED_FOOTNOTE")}startViewportRule(){this.reportAndSkip("E_CSS_UNEXPECTED_VIEWPORT")}startDefineRule(){this.reportAndSkip("E_CSS_UNEXPECTED_DEFINE")}startRegionRule(){this.reportAndSkip("E_CSS_UNEXPECTED_REGION")}startPageRule(){this.reportAndSkip("E_CSS_UNEXPECTED_PAGE")}startWhenRule(t){this.reportAndSkip("E_CSS_UNEXPECTED_WHEN")}startFlowRule(t){this.reportAndSkip("E_CSS_UNEXPECTED_FLOW")}startPageTemplateRule(){this.reportAndSkip("E_CSS_UNEXPECTED_PAGE_TEMPLATE")}startPageMasterRule(t,e,n){this.reportAndSkip("E_CSS_UNEXPECTED_PAGE_MASTER")}startPartitionRule(t,e,n){this.reportAndSkip("E_CSS_UNEXPECTED_PARTITION")}startPartitionGroupRule(t,e,n){this.reportAndSkip("E_CSS_UNEXPECTED_PARTITION_GROUP")}startFuncWithSelector(t){this.reportAndSkip("E_CSS_UNEXPECTED_SELECTOR_FUNC")}endFuncWithSelector(){this.reportAndSkip("E_CSS_UNEXPECTED_END_SELECTOR_FUNC")}property(t,e,n){this.error("E_CSS_UNEXPECTED_PROPERTY",this.getCurrentToken())}},me=[],Lr=[],re=[],Ee=[],Pt=[],ut=[],ye=[],Ae=[],ne=[],Ve=[],qe=[],Ie=[],xe=[];var oo=55,io=56,Pr=57;me[1]=28,me[36]=29,me[7]=29,me[9]=29,me[14]=29,me[18]=29,me[50]=29,me[20]=30,me[13]=27,me[0]=200,Lr[1]=46,Lr[0]=200,ut[1]=2,ut[36]=4,ut[7]=6,ut[9]=8,ut[14]=10,ut[18]=14,ut[50]=42,re[37]=11,re[23]=12,re[35]=56,re[1]=1,re[36]=3,re[7]=5,re[9]=7,re[14]=9,re[12]=13,re[18]=55,re[50]=58,re[16]=41,Ee[37]=11,Ee[23]=12,Ee[35]=56,Ee[1]=1,Ee[36]=3,Ee[7]=5,Ee[9]=7,Ee[14]=9,Ee[18]=55,Pt[1]=2,Pt[36]=4,Pt[7]=6,Pt[9]=8,Pt[18]=14,Pt[50]=42,Pt[14]=10,Pt[12]=13,ye[1]=15,ye[7]=16,ye[4]=17,ye[5]=18,ye[3]=19,ye[2]=20,ye[8]=21,ye[27]=57,ye[16]=22,ye[19]=23,ye[6]=24,ye[11]=25,ye[17]=26,ye[13]=48,ye[31]=47,ye[23]=54,ye[0]=44,Ae[1]=31,Ae[4]=32,Ae[5]=32,Ae[3]=33,Ae[2]=34,Ae[10]=40,Ae[6]=38,Ae[31]=36,Ae[24]=36,Ae[32]=35,ne[1]=45,ne[16]=37,ne[37]=37,ne[38]=37,ne[47]=37,ne[48]=37,ne[39]=37,ne[49]=37,ne[41]=37,ne[26]=37,ne[25]=37,ne[23]=37,ne[24]=37,ne[19]=37,ne[21]=37,ne[36]=37,ne[18]=37,ne[22]=37,ne[11]=39,ne[12]=43,ne[17]=49,Ve[0]=200,Ve[12]=50,Ve[13]=51,Ve[14]=50,Ve[15]=51,Ve[10]=50,Ve[11]=51,Ve[17]=53,qe[0]=200,qe[12]=50,qe[13]=52,qe[14]=50,qe[15]=51,qe[10]=50,qe[11]=51,qe[17]=53,Ie[0]=200,Ie[12]=50,Ie[13]=51,Ie[14]=50,Ie[15]=51,Ie[10]=50,Ie[11]=51,xe[11]=0,xe[16]=0,xe[22]=1,xe[18]=1,xe[26]=2,xe[25]=2,xe[38]=3,xe[37]=3,xe[48]=3,xe[47]=3,xe[39]=3,xe[49]=3,xe[41]=3,xe[23]=4,xe[24]=4,xe[36]=5,xe[19]=5,xe[21]=5,xe[0]=6,xe[oo]=2,xe[io]=2;var Vn=class{constructor(t,e,n,s){this.actions=t;this.tokenizer=e;this.handler=n;this.baseURL=s;d(this,"valStack",[]);d(this,"namespacePrefixToURI",{});d(this,"defaultNamespaceURI",null);d(this,"propName",null);d(this,"propImportant",!1);d(this,"exprContext");d(this,"result",null);d(this,"importReady",!1);d(this,"importURL",null);d(this,"importCondition",null);d(this,"errorBrackets",[]);d(this,"ruleStack",[]);d(this,"regionRule",!1);d(this,"pageRule",!1);d(this,"inStyleDeclaration",!1);this.exprContext=2}extractVals(t,e){let n=[],s=this.valStack;for(;e<s.length&&(n.push(s[e++]),e!==s.length);){if(s[e++]!==t)throw new Error("Unexpected state");e===s.length&&n.push(O)}return n}valStackReduce(t,e){let n=this.valStack,s=n.length,o=0,i;do if(i=n[--s],t===")"&&i instanceof kn){if(i.text===")")o++;else if(i.text==="("){if(o===0)return null;o--}}while(typeof i!="undefined"&&typeof i!="string");let a=n.length-(s+1);if(a>1&&n.splice(s+1,a,new K(n.slice(s+1,n.length))),t==",")return null;s++;do i=n[--s];while(typeof i!="undefined"&&(typeof i!="string"||i==","));if(a=n.length-(s+1),i=="("){t!=")"&&e.type!==0&&(this.handler.error("E_CSS_MISMATCHED_C_PAR",e),this.actions=qe);let c=new wt(n[s-1],this.extractVals(",",s+1));if(n.splice(s-1,a+2,c),c.name==="var"){let u=c.values[0]instanceof be&&c.values[0].name;(!Ct(u)||u===this.propName)&&(this.handler.error(`E_CSS_INVALID_VAR ${c.toString()}`,e),this.actions=qe)}return c}if(t!=";"||s>=0)return this.handler.error("E_CSS_UNEXPECTED_VAL_END",e),this.actions=qe,null;if(a>1)return new ge(this.extractVals(",",s+1));let l=n[0];return l instanceof Ne?l:l?new kn(l.toString()):O}exprError(t,e){this.actions=this.propName?qe:Ve,V.warn(t,e.toString())}exprStackReduce(t,e){let n=this.valStack,s=this.handler,o=n.pop(),i;for(;;){let a=n.pop();if(t==11){let l=[o];for(;a==16;)l.unshift(n.pop()),a=n.pop();if(typeof a=="string"){if(a=="{"){for(;l.length>=2;){let c=l.shift(),u=l.shift(),p=new ar(s.getScope(),c,u);l.unshift(p)}return n.push(new F(l[0])),!0}else if(a=="("){let c=n.pop(),u=n.pop();o=new ln(s.getScope(),Wo(u,c),l),t=0;continue}}if(a==10){o.isMediaName()&&(o=new Go(s.getScope(),o,null)),t=0;continue}}else if(typeof a=="string"){n.push(a);break}if(a<0)if(a==-31)o=new gt(s.getScope(),o);else if(a==-24)o=new Yt(s.getScope(),o);else if(a==-Pr)o=new ir(s.getScope(),o);else return this.exprError("F_UNEXPECTED_STATE",e),!1;else{if(xe[t]>xe[a]){n.push(a);break}switch(i=n.pop(),a){case 26:o=new Ws(s.getScope(),i,o);break;case oo:o=new rr(s.getScope(),i,o);break;case io:o=new lr(s.getScope(),i,o);break;case 25:o=new $s(s.getScope(),i,o);break;case 38:o=new cr(s.getScope(),i,o);break;case 37:o=new dr(s.getScope(),i,o);break;case 48:o=new ur(s.getScope(),i,o);break;case 47:o=new rs(s.getScope(),i,o);break;case 39:case 49:o=new Pn(s.getScope(),i,o);break;case 41:o=new pr(s.getScope(),i,o);break;case 23:o=new _o(s.getScope(),i,o);break;case 24:o=new Uo(s.getScope(),i,o);break;case 36:o=new as(s.getScope(),i,o);break;case 19:o=new Ho(s.getScope(),i,o);break;case 21:o=new Xs(s.getScope(),i,o);break;case 18:if(n.length>1)switch(n[n.length-1]){case 22:n.pop(),o=new hr(s.getScope(),n.pop(),i,o);break;case 10:if(i.isMediaName())o=new Go(s.getScope(),i,o);else return this.exprError("E_CSS_MEDIA_TEST",e),!1;break}else return this.exprError("E_CSS_EXPR_COND",e),!1;break;case 22:if(t!=18)return this.exprError("E_CSS_EXPR_COND",e),!1;case 10:return n.push(i),n.push(a),n.push(o),!1;default:return this.exprError("F_UNEXPECTED_STATE",e),!1}}}return n.push(o),!1}readSupportsTest(t){let e=t.type===6,n=this.tokenizer,s,o;if(e)o=t.text,s=t.position+o.length+1;else if(t.type===10){let h=n.nthToken(1),f=n.nthToken(2);if(h.type===1&&f.type===18)n.consume(),n.consume(),o=h.text,s=f.position+1;else{if(h.type===10||h.type===6||h.type===1&&h.text.toLowerCase()==="not"&&(f.type===10||f.type===6))return null;s=t.position+1}}else return null;let i=0,a,l=0;for(;i>=0;)switch(n.consume(),a=n.token(),a.type){case 11:i--;break;case 10:case 6:i++;break;case 16:i===0&&l++;break;case 0:return this.exprError("E_CSS_UNEXPECTED_EOF",a),null}n.consume();let c=a.position,u=e&&o==="selector"&&l>0?"":n.input.substring(s,c).trim();return new fr(this.handler.getScope(),o,u,e)}readPseudoParams(){let t=[];for(;;){let e=this.tokenizer.token();switch(e.type){case 1:t.push(e.text);break;case 23:t.push("+");break;case 4:case 5:t.push(e.num);break;default:return t}this.tokenizer.consume()}}readNthPseudoParams(){let t=!1,e=this.tokenizer.token();if(e.type===23)t=!0,this.tokenizer.consume(),e=this.tokenizer.token();else if(e.type===1&&(e.text==="even"||e.text==="odd"))return this.tokenizer.consume(),[2,e.text==="odd"?1:0];switch(e.type){case 3:if(t&&e.num<0)return null;case 1:if(t&&e.text.charAt(0)==="-")return null;if(e.text==="n"||e.text==="-n"){if(t&&e.precededBySpace)return null;let n=e.text==="-n"?-1:1;e.type===3&&(n=e.num);let s=0;this.tokenizer.consume(),e=this.tokenizer.token();let o=e.type===24,i=e.type===23||o;if(i&&(this.tokenizer.consume(),e=this.tokenizer.token()),e.type===5){if(s=e.num,1/s===-1/0){if(s=0,i)return null}else if(s<0){if(i)return null}else if(s>=0&&!i)return null;this.tokenizer.consume()}else if(i)return null;return[n,o&&s>0?-s:s]}else if(e.text==="n-"||e.text==="-n-"){if(t&&e.precededBySpace)return null;let n=e.text==="-n-"?-1:1;if(e.type===3&&(n=e.num),this.tokenizer.consume(),e=this.tokenizer.token(),e.type===5)return e.num<0||1/e.num===-1/0?null:(this.tokenizer.consume(),[n,e.num])}else{let n=e.text.match(/^n(-[0-9]+)$/);if(n)return t&&e.precededBySpace?null:(this.tokenizer.consume(),[e.type===3?e.num:1,parseInt(n[1],10)]);if(n=e.text.match(/^-n(-[0-9]+)$/),n)return this.tokenizer.consume(),[-1,parseInt(n[1],10)]}return null;case 5:return t&&(e.precededBySpace||e.num<0)?null:(this.tokenizer.consume(),[0,e.num])}return null}makeCondition(t,e){let n=this.handler.getScope();if(!n)return null;if(e=e||n._true,t){let s=t.split(/\s+/);for(let o of s)switch(o){case"vertical":e=et(n,e,new gt(n,new J(n,"pref-horizontal")));break;case"horizontal":e=et(n,e,new J(n,"pref-horizontal"));break;case"day":e=et(n,e,new gt(n,new J(n,"pref-night-mode")));break;case"night":e=et(n,e,new J(n,"pref-night-mode"));break;default:e=n._false}}return e===n._true?null:new F(e)}isInsidePropertyOnlyRule(){switch(this.ruleStack[this.ruleStack.length-1]){case"[selector]":case"font-face":case"-epubx-flow":case"-epubx-viewport":case"-epubx-define":case"-adapt-footnote-area":return!0}return!1}runParser(t,e,n,s,o,i){let a=this.handler,l=this.tokenizer,c=this.valStack,u,p,h,f,g,m,E,y=null;for(n&&(this.inStyleDeclaration=!0),s&&(this.exprContext=2,this.valStack.push("{"));t>0;--t){if(u=l.token(),o&&y===null&&(y=u.position-1,l.input[y]==="("&&y++),this.actions===ye&&this.errorBrackets.length>0&&(u.type===this.errorBrackets[this.errorBrackets.length-1]||u.type===17||u.type===31)){if(u.type===this.errorBrackets[this.errorBrackets.length-1]&&(this.errorBrackets.pop(),u.type===11&&this.valStackReduce(")",u))){l.consume();continue}c.push(new kn(u.toString())),l.consume();continue}switch(this.actions[u.type]){case 28:if(!this.inStyleDeclaration||l.nthToken(1).type!=18){this.isInsidePropertyOnlyRule()?(a.error("E_CSS_COLON_EXPECTED",l.nthToken(1)),this.actions=qe):(this.actions=ut,a.startSelectorRule());continue}this.propName=u.text,this.propImportant=!1,l.consume(),l.consume(),this.actions=ye,c.splice(0,c.length);continue;case 46:if(l.nthToken(1).type!=18){this.actions=qe,a.error("E_CSS_COLON_EXPECTED",l.nthToken(1));continue}this.propName=u.text,this.propImportant=!1,l.consume(),l.consume(),this.actions=ye,c.splice(0,c.length);continue;case 29:this.actions=ut,a.startSelectorRule();continue;case 1:if(!u.precededBySpace){this.actions=Ie,a.error("E_CSS_SPACE_EXPECTED",u);continue}a.descendantSelector();case 2:if(l.nthToken(1).type==34)if(l.consume(),l.consume(),h=this.namespacePrefixToURI[u.text],h!=null)switch(u=l.token(),u.type){case 1:a.tagSelector(h,u.text),o?this.actions=Ee:this.actions=re,l.consume();break;case 36:a.tagSelector(h,null),o?this.actions=Ee:this.actions=re,l.consume();break;default:this.actions=Ve,a.error("E_CSS_NAMESPACE",u)}else this.actions=Ve,a.error("E_CSS_UNDECLARED_PREFIX",u);else a.tagSelector(this.defaultNamespaceURI,u.text),o?this.actions=Ee:this.actions=re,l.consume();continue;case 3:if(!u.precededBySpace){this.actions=Ie,a.error("E_CSS_SPACE_EXPECTED",u);continue}a.descendantSelector();case 4:if(l.nthToken(1).type==34)switch(l.consume(),l.consume(),u=l.token(),u.type){case 1:a.tagSelector(null,u.text),o?this.actions=Ee:this.actions=re,l.consume();break;case 36:a.tagSelector(null,null),o?this.actions=Ee:this.actions=re,l.consume();break;default:this.actions=Ve,a.error("E_CSS_NAMESPACE",u)}else a.tagSelector(this.defaultNamespaceURI,null),o?this.actions=Ee:this.actions=re,l.consume();continue;case 5:u.precededBySpace&&a.descendantSelector();case 6:if(!u.text){a.error("E_CSS_SYNTAX",u),l.consume();continue}a.idSelector(u.text),o?this.actions=Ee:this.actions=re,l.consume();continue;case 7:u.precededBySpace&&a.descendantSelector();case 8:a.classSelector(u.text),o?this.actions=Ee:this.actions=re,l.consume();continue;case 55:u.precededBySpace&&a.descendantSelector();case 14:l.consume(),u=l.token();e:switch(u.type){case 1:a.pseudoclassSelector(u.text,null),l.consume(),o?this.actions=Ee:this.actions=re;continue;case 6:switch(f=u.text,l.consume(),f){case"is":case"not":case"where":case"has":this.actions=ut,a.startFuncWithSelector(f),this.runParser(Number.POSITIVE_INFINITY,!1,!1,!1,!0,f==="has")?this.actions=re:this.actions=Ie;continue;case"lang":case"href-epub-type":if(u=l.token(),u.type===1){E=[u.text],l.consume(),f==="href-epub-type"&&l.token().type===16&&(l.consume(),u=l.token(),u.type===1&&(E.push(u.text),l.consume()));break}else break e;case"nth-child":case"nth-of-type":case"nth-last-child":case"nth-last-of-type":case"nth":if(E=this.readNthPseudoParams(),E)break;break e;default:E=this.readPseudoParams()}if(u=l.token(),u.type==11){a.pseudoclassSelector(f,E),l.consume(),o?this.actions=Ee:this.actions=re;continue}break}a.error("E_CSS_PSEUDOCLASS_SYNTAX",u),this.actions=Ve;continue;case 58:u.precededBySpace&&a.descendantSelector();case 42:switch(l.consume(),u=l.token(),u.type){case 1:a.pseudoelementSelector(u.text,null),o?this.actions=Ee:this.actions=re,l.consume();continue;case 6:if(f=u.text,l.consume(),f=="nth-fragment"){if(E=this.readNthPseudoParams(),E===null)break}else E=this.readPseudoParams();if(u=l.token(),u.type==11){a.pseudoelementSelector(f,E),o?this.actions=Ee:this.actions=re,l.consume();continue}break}a.error("E_CSS_PSEUDOELEM_SYNTAX",u),this.actions=Ve;continue;case 9:u.precededBySpace&&a.descendantSelector();case 10:if(l.consume(),u=l.token(),u.type==1)f=u.text,l.consume();else if(u.type==36)f=null,l.consume();else if(u.type==34)f="";else{this.actions=Ie,a.error("E_CSS_ATTR",u),l.consume();continue}if(u=l.token(),u.type==34){if(h=f&&this.namespacePrefixToURI[f],h===void 0){this.actions=Ie,a.error("E_CSS_UNDECLARED_PREFIX",u),l.consume();continue}if(l.consume(),u=l.token(),u.type!=1){this.actions=Ie,a.error("E_CSS_ATTR_NAME_EXPECTED",u);continue}f=u.text,l.consume(),u=l.token()}else h="";switch(u.type){case 39:case 45:case 44:case 43:case 42:case 46:case 50:g=u.type,l.consume(),u=l.token();break;case 15:a.attributeSelector(h,f,0,null),o?this.actions=Ee:this.actions=re,l.consume();continue;default:this.actions=Ie,a.error("E_CSS_ATTR_OP_EXPECTED",u);continue}switch(u.type){case 1:case 2:a.attributeSelector(h,f,g,u.text),l.consume(),u=l.token();break;default:this.actions=Ie,a.error("E_CSS_ATTR_VAL_EXPECTED",u);continue}if(u.type!=15){this.actions=Ie,a.error("E_CSS_ATTR",u);continue}o?this.actions=Ee:this.actions=re,l.consume();continue;case 11:a.childSelector(),this.actions=Pt,l.consume();continue;case 12:a.adjacentSiblingSelector(),this.actions=Pt,l.consume();continue;case 56:a.followingSiblingSelector(),this.actions=Pt,l.consume();continue;case 13:this.regionRule?(this.ruleStack.push("-epubx-region"),this.regionRule=!1):this.pageRule?(this.ruleStack.push("page"),this.pageRule=!1,this.inStyleDeclaration=!0):(this.ruleStack.push("[selector]"),this.inStyleDeclaration=!0),a.startRuleBody(),this.actions=me,l.consume();continue;case 41:a.nextSelector(),this.actions=ut,l.consume();continue;case 15:c.push(L(u.text)),l.consume();continue;case 16:g=parseInt(u.text,16),c.push(new Ks(u.text)),l.consume();continue;case 17:c.push(new tt(u.num)),l.consume();continue;case 18:c.push(new ct(u.num)),l.consume();continue;case 19:c.push(new P(u.num,u.text)),l.consume();continue;case 20:c.push(new ce(u.text)),l.consume();continue;case 21:c.push(new Ue(Q(u.text,this.baseURL))),l.consume();continue;case 57:c.push(new Xo(u.text)),l.consume();continue;case 22:this.valStackReduce(",",u),c.push(","),l.consume();continue;case 23:c.push(qs),l.consume();continue;case 24:f=u.text.toLowerCase(),f=="-epubx-expr"||f=="env"?(this.actions=Ae,this.exprContext=0,c.push("{")):(c.push(f),c.push("("),this.errorBrackets.length>0&&this.errorBrackets.push(11)),l.consume();continue;case 25:this.valStackReduce(")",u),l.consume();continue;case 47:if(l.consume(),u=l.token(),p=l.nthToken(1),u.type==1&&u.text.toLowerCase()=="important"&&(p.type==17||p.type==0||p.type==13)){l.consume(),this.propImportant=!0;continue}this.exprError("E_CSS_SYNTAX",u);continue;case 54:switch(p=l.nthToken(1),p.type){case 4:case 3:case 5:if(!p.precededBySpace){l.consume();continue}}c.push(new kn("+")),l.consume();continue;case 26:l.consume();case 48:m=this.valStackReduce(";",u),m&&this.propName&&a.property(this.propName,m,this.propImportant),this.actions=n?Lr:me;continue;case 44:for(l.consume();c.length>0;){let C=c.length;if(m=this.valStackReduce(";",u),!m||c.length===C)break}return e?(this.result=m,!0):(this.propName&&m&&a.property(this.propName,m,this.propImportant),!0);case 31:if(p=l.nthToken(1),p.type==9)l.nthToken(2).type==10&&!l.nthToken(2).precededBySpace?(c.push(u.text,p.text,"("),l.consume()):(c.push(new J(a.getScope(),Wo(u.text,p.text))),this.actions=ne),l.consume();else{if(this.exprContext==2||this.exprContext==3)u.text.toLowerCase()=="not"?(l.consume(),c.push(new zo(a.getScope(),!0,p.text))):(u.text.toLowerCase()=="only"&&(l.consume(),u=p),c.push(new zo(a.getScope(),!1,u.text)));else if(this.exprContext===4&&u.text.toLowerCase()==="not"&&c[c.length-1]!==oo&&c[c.length-1]!==io&&(p.type===10||p.type===6)){c.push(-Pr),l.consume();continue}else c.push(new J(a.getScope(),u.text));this.actions=ne}l.consume();continue;case 38:if(this.exprContext===4){c.push(this.readSupportsTest(u)),this.actions=ne;continue}c.push(null,u.text,"("),l.consume();continue;case 32:c.push(new oe(a.getScope(),u.num)),l.consume(),this.actions=ne;continue;case 33:f=u.text,f=="%"&&(this.propName&&this.propName.match(/height|^(top|bottom)$/)?f="vh":f="vw"),c.push(new Vt(a.getScope(),u.num,f)),l.consume(),this.actions=ne;continue;case 34:c.push(new oe(a.getScope(),u.text)),l.consume(),this.actions=ne;continue;case 35:l.consume(),u=l.token(),u.type!=5||u.precededBySpace?this.exprError("E_CSS_SYNTAX",u):(c.push(new js(a.getScope(),u.num)),l.consume(),this.actions=ne);continue;case 36:c.push(-u.type),l.consume();continue;case 37:this.actions=Ae,this.exprStackReduce(u.type,u),c.push(u.type),l.consume();continue;case 45:u.text.toLowerCase()==="and"&&c[c.length-2]!==io&&c[c.length-2]!==-Pr?(this.actions=Ae,this.exprStackReduce(oo,u),c.push(oo),l.consume()):u.text.toLowerCase()==="or"&&c[c.length-2]!==oo&&c[c.length-2]!==-Pr?(this.actions=Ae,this.exprStackReduce(io,u),c.push(io),l.consume()):this.exprError("E_CSS_SYNTAX",u);continue;case 39:this.exprStackReduce(u.type,u)&&(this.actions=ye),l.consume();continue;case 43:this.exprStackReduce(11,u)&&(this.propName||this.exprContext==3?this.exprError("E_CSS_UNEXPECTED_BRC",u):(this.exprContext==1?a.startWhenRule(c.pop()):a.startMediaRule(c.pop()),this.ruleStack.push("media"),a.startRuleBody(),this.actions=me)),l.consume();continue;case 49:if(this.exprStackReduce(11,u))return this.propName||this.exprContext!=3?(this.exprError("E_CSS_UNEXPECTED_SEMICOL",u),this.actions=me,l.consume(),!1):(this.importCondition=c.pop(),this.importReady=!0,this.actions=me,l.consume(),!1);l.consume();continue;case 40:if(this.exprContext===4){let C=this.readSupportsTest(u);if(C){c.push(C),this.actions=ne;continue}}c.push(u.type),l.consume();continue;case 27:if(this.actions=me,l.consume(),a.endRule(),this.inStyleDeclaration=!1,this.ruleStack.length)switch(this.ruleStack.pop(),this.ruleStack[this.ruleStack.length-1]){case"page":case"-epubx-page-master":case"-epubx-partition-group":this.inStyleDeclaration=!0}continue;case 30:switch(f=u.text.toLowerCase(),f){case"import":if(l.consume(),u=l.token(),u.type==2||u.type==8){if(this.importURL=u.text,l.consume(),u=l.token(),u.type==17||u.type==0)return this.importReady=!0,l.consume(),!1;this.propName=null,this.exprContext=3,this.actions=Ae,c.push("{");continue}a.error("E_CSS_IMPORT_SYNTAX",u),this.actions=Ve;continue;case"namespace":switch(l.consume(),u=l.token(),u.type){case 1:if(f=u.text,l.consume(),u=l.token(),(u.type==2||u.type==8)&&l.nthToken(1).type==17){this.namespacePrefixToURI[f]=u.text,l.consume(),l.consume();continue}break;case 2:case 8:if(l.nthToken(1).type==17){this.defaultNamespaceURI=u.text,l.consume(),l.consume();continue}break}a.error("E_CSS_NAMESPACE_SYNTAX",u),this.actions=Ve;continue;case"charset":if(l.consume(),u=l.token(),u.type==2&&l.nthToken(1).type==17){f=u.text.toLowerCase(),f!="utf-8"&&f!="utf-16"&&a.error(`E_CSS_UNEXPECTED_CHARSET ${f}`,u),l.consume(),l.consume();continue}a.error("E_CSS_CHARSET_SYNTAX",u),this.actions=Ve;continue;case"font-face":case"-epubx-page-template":case"-epubx-define":case"-epubx-viewport":if(l.nthToken(1).type==12){switch(l.consume(),l.consume(),f){case"font-face":a.startFontFaceRule(),this.inStyleDeclaration=!0;break;case"-epubx-page-template":a.startPageTemplateRule();break;case"-epubx-define":a.startDefineRule(),this.inStyleDeclaration=!0;break;case"-epubx-viewport":a.startViewportRule(),this.inStyleDeclaration=!0;break}this.ruleStack.push(f),a.startRuleBody();continue}break;case"-adapt-footnote-area":switch(l.consume(),u=l.token(),u.type){case 12:l.consume(),a.startFootnoteRule(null),this.ruleStack.push(f),a.startRuleBody(),this.inStyleDeclaration=!0;continue;case 50:if(l.consume(),u=l.token(),u.type==1&&l.nthToken(1).type==12){f=u.text,l.consume(),l.consume(),a.startFootnoteRule(f),this.ruleStack.push("-adapt-footnote-area"),a.startRuleBody(),this.inStyleDeclaration=!0;continue}break}break;case"-epubx-region":l.consume(),a.startRegionRule(),this.regionRule=!0,this.actions=ut;continue;case"page":l.consume(),a.startPageRule(),this.pageRule=!0,this.actions=Pt;continue;case"top-left-corner":case"top-left":case"top-center":case"top-right":case"top-right-corner":case"right-top":case"right-middle":case"right-bottom":case"bottom-right-corner":case"bottom-right":case"bottom-center":case"bottom-left":case"bottom-left-corner":case"left-bottom":case"left-middle":case"left-top":if(l.consume(),u=l.token(),u.type==12){l.consume(),a.startPageMarginBoxRule(f),this.ruleStack.push(f),a.startRuleBody(),this.inStyleDeclaration=!0;continue}break;case"-epubx-when":l.consume(),this.propName=null,this.exprContext=1,this.actions=Ae,c.push("{");continue;case"media":l.consume(),this.propName=null,this.exprContext=2,this.actions=Ae,c.push("{");continue;case"supports":l.consume(),this.propName=null,this.exprContext=4,this.actions=Ae,c.push("{");continue;case"-epubx-flow":if(l.nthToken(1).type==1&&l.nthToken(2).type==12){a.startFlowRule(l.nthToken(1).text),l.consume(),l.consume(),l.consume(),this.ruleStack.push(f),a.startRuleBody(),this.inStyleDeclaration=!0;continue}break;case"-epubx-page-master":case"-epubx-partition":case"-epubx-partition-group":{l.consume(),u=l.token();let C=null,x=null,N=[];for(u.type==1&&(C=u.text,l.consume(),u=l.token()),u.type==18&&l.nthToken(1).type==1&&(x=l.nthToken(1).text,l.consume(),l.consume(),u=l.token());u.type==6&&u.text.toLowerCase()=="class"&&l.nthToken(1).type==1&&l.nthToken(2).type==11;)N.push(l.nthToken(1).text),l.consume(),l.consume(),l.consume(),u=l.token();if(u.type==12){switch(l.consume(),f){case"-epubx-page-master":a.startPageMasterRule(C,x,N);break;case"-epubx-partition":a.startPartitionRule(C,x,N);break;case"-epubx-partition-group":a.startPartitionGroupRule(C,x,N);break}this.ruleStack.push(f),a.startRuleBody(),this.inStyleDeclaration=!0;continue}break}case"":a.error(`E_CSS_UNEXPECTED_AT${f}`,u),this.actions=Ie;continue;default:a.error(`E_CSS_AT_UNKNOWN ${f}`,u),this.actions=Ve;continue}a.error(`E_CSS_AT_SYNTAX ${f}`,u),this.actions=Ve;continue;case 50:this.errorBrackets.push(u.type+1),l.consume();continue;case 52:if(this.errorBrackets.length==0){this.actions=me;continue}case 51:if(o&&this.errorBrackets.length==0&&u.type==11)return l.consume(),a.endFuncWithSelector(),!0;this.errorBrackets.length>0&&this.errorBrackets[this.errorBrackets.length-1]==u.type&&this.errorBrackets.pop(),this.errorBrackets.length==0&&u.type==13&&(this.actions=me),l.consume();continue;case 53:this.errorBrackets.length==0&&(this.actions=me),l.consume();continue;case 200:return!0;default:if(s)return this.exprStackReduce(11,u)?(this.result=c.pop(),!0):!1;if(o){switch(u.type){case 16:case 11:if(this.actions===ut)a.error("E_CSS_SYNTAX",u);else{let C=l.input.substring(y,u.position);a.pushSelectorText(C),y=u.position+1}if(u.type===16){a.nextSelector(),this.actions=ut,l.consume();continue}else return a.endFuncWithSelector(),l.consume(),!0;case 37:case 23:case 35:if(i){this.actions=re;continue}break;case 12:case 14:case 10:this.errorBrackets.push(u.type+1);break}a.error("E_CSS_SYNTAX",u),l.consume(),this.actions=Ie;continue}if(this.actions!==Ve&&this.actions!==Ie&&this.actions!==qe){if(u.type==54)a.error("E_CSS_SYNTAX",u);else if(this.actions===ye){switch(u.type){case 10:case 12:case 14:this.errorBrackets.push(u.type+1);break}c.push(new kn(u.toString())),l.consume();continue}else if(u.type===12&&this.actions==Ae&&c.length>0){a.startMediaRule(c.pop()),this.ruleStack.push("media"),a.startRuleBody(),this.actions=me,l.consume();continue}else{if(u.type===17&&this.actions==Ae)return this.actions=me,l.consume(),!1;a.error("E_CSS_SYNTAX",u)}this.isInsidePropertyOnlyRule()?this.actions=qe:this.actions=Ie;continue}l.consume();continue}}return!1}},Zo=class extends qo{constructor(e){super(null);this.scope=e}error(e,n){V.warn(e,n.toString())}getScope(){return this.scope}};function Nm(r,t,e,n,s){let o=A("parseStylesheet"),i=new Vn(me,r,t,e),a=null;return s&&(a=vm(new Oe(s,t),t,e)),a=i.makeCondition(n,a&&a.toExpr()),a&&(t.startMediaRule(a),t.startRuleBody()),o.loop(()=>{for(;!i.runParser(100,!1,!1,!1,!1);){if(i.importReady){let c=Q(i.importURL,e);i.importCondition&&(t.startMediaRule(i.importCondition),t.startRuleBody());let u=A("parseStylesheet.import");return mc(c,t,null,null).then(()=>{i.importCondition&&t.endRule(),i.importReady=!1,i.importURL=null,i.importCondition=null,u.finish(!0)}),u.result()}let l=o.timeSlice();if(l.isPending)return l}return v(!1)}).then(()=>{a&&t.endRule(),o.finish(!0)}),o.result()}function Vr(r,t,e,n,s){return un("parseStylesheetFromText",o=>{let i=new Oe(r,t);Nm(i,t,e,n,s).thenFinish(o)},(o,i)=>{V.warn(i,`Failed to parse stylesheet text: ${r}`),o.finish(!1)})}function mc(r,t,e,n){return un("parseStylesheetFromURL",s=>{hs(r).then(o=>{o.responseText?Vr(o.responseText,t,r,e,n).then(i=>{i||V.warn(`Failed to parse stylesheet from ${r}`),s.finish(!0)}):s.finish(!0)})},(s,o)=>{V.warn(o,"Exception while fetching and parsing:",r),s.finish(!0)})}function Jt(r,t,e){let n=new Vn(ye,t,new Zo(r),e);return n.runParser(Number.POSITIVE_INFINITY,!0,!1,!1,!1),n.result}function rh(r,t,e){new Vn(Lr,r,t,e).runParser(Number.POSITIVE_INFINITY,!1,!0,!1,!1)}function vm(r,t,e){let n=new Vn(Ae,r,t,e);return n.runParser(Number.POSITIVE_INFINITY,!1,!1,!0,!1),n.result}var Tm={"z-index":!0,"column-count":!0,"flow-linger":!0,opacity:!0,page:!0,"flow-priority":!0,utilization:!0};function wm(r){return!!Tm[r]}function ah(r,t,e){let n=t.evaluate(r);switch(typeof n){case"number":return wm(e)?n==Math.round(n)?new ct(n):new tt(n):new P(n,"px");case"string":return n?Jt(t.scope,new Oe(n,null),""):O;case"boolean":return n?b._true:b._false;case"undefined":return O}throw new Error("E_UNEXPECTED")}function lh(r,t){let e={};return Object.keys(r).forEach(n=>{let s=e[n]={},o=r[n];Object.keys(o).forEach(i=>{s[i]=o[i].map(a=>{let l=t?a.logical:a.physical,c=t?a.physical:a.logical;return{regexp:new RegExp(`(-?)${l}(-?)`),to:`$1${c}$2`}})})}),e}function ch(r,t,e,n){let s=n[t];if(!s)throw new Error(`unknown writing-mode: ${t}`);let o=s[e||"ltr"];if(!o)throw new Error(`unknown direction: ${e}`);for(let i of o){let a=r.replace(i.regexp,i.to);if(a!==r)return a}return r}var uh={"horizontal-tb":{ltr:[{logical:"inline-start",physical:"left"},{logical:"inline-end",physical:"right"},{logical:"block-start",physical:"top"},{logical:"block-end",physical:"bottom"},{logical:"inline-size",physical:"width"},{logical:"block-size",physical:"height"}],rtl:[{logical:"inline-start",physical:"right"},{logical:"inline-end",physical:"left"},{logical:"block-start",physical:"top"},{logical:"block-end",physical:"bottom"},{logical:"inline-size",physical:"width"},{logical:"block-size",physical:"height"}]},"vertical-rl":{ltr:[{logical:"inline-start",physical:"top"},{logical:"inline-end",physical:"bottom"},{logical:"block-start",physical:"right"},{logical:"block-end",physical:"left"},{logical:"inline-size",physical:"height"},{logical:"block-size",physical:"width"}],rtl:[{logical:"inline-start",physical:"bottom"},{logical:"inline-end",physical:"top"},{logical:"block-start",physical:"right"},{logical:"block-end",physical:"left"},{logical:"inline-size",physical:"height"},{logical:"block-size",physical:"width"}]},"vertical-lr":{ltr:[{logical:"inline-start",physical:"top"},{logical:"inline-end",physical:"bottom"},{logical:"block-start",physical:"left"},{logical:"block-end",physical:"right"},{logical:"inline-size",physical:"height"},{logical:"block-size",physical:"width"}],rtl:[{logical:"inline-start",physical:"bottom"},{logical:"inline-end",physical:"top"},{logical:"block-start",physical:"left"},{logical:"block-end",physical:"right"},{logical:"inline-size",physical:"height"},{logical:"block-size",physical:"width"}]}},Pm=lh(uh,!0);function Cc(r,t,e){return ch(r,t,e||null,Pm)}var km=lh(uh,!1);function bc(r,t,e){return ch(r,t,e||null,km)}var Am={"horizontal-tb":[{logical:"line-left",physical:"left"},{logical:"line-right",physical:"right"},{logical:"over",physical:"top"},{logical:"under",physical:"bottom"}],"vertical-rl":[{logical:"line-left",physical:"top"},{logical:"line-right",physical:"bottom"},{logical:"over",physical:"right"},{logical:"under",physical:"left"}],"vertical-lr":[{logical:"line-left",physical:"top"},{logical:"line-right",physical:"bottom"},{logical:"over",physical:"right"},{logical:"under",physical:"left"}]};function dh(r,t){let e=Am[t];if(!e)throw new Error(`unknown writing-mode: ${t}`);for(let n=0;n<e.length;n++)if(e[n].physical===r)return e[n].logical;return r}function ro(r,t,e){var h;let n=t,s={width:n.style.width,height:n.style.height};function o(f){return r.getElementComputedStyle(t).getPropertyValue(f)}let a=o("writing-mode")!=="horizontal-tb",l=a?"height":"width",c=a?"width":"height";function u(f,g){n.style[f]=g;let m=o(f);return n.style[f]=s[f],m}let p={};for(let f of e){let g;switch(f){case"max-content inline size":g=u(l,"max-content");break;case"min-content inline size":g=u(l,"min-content");break;case"fit-content inline size":g=u(l,"fit-content");break;case"max-content block size":g=u(c,"max-content");break;case"min-content block size":g=u(c,"min-content");break;case"fit-content block size":g=u(c,"fit-content");break;case"max-content width":g=u("width","max-content");break;case"max-content height":g=u("height","max-content");break;case"min-content width":g=u("width","min-content");break;case"min-content height":g=u("height","min-content");break;case"fit-content width":g=u("width","fit-content");break;case"fit-content height":g=u("height","fit-content");break}g==="0px"&&t.childNodes.length===1&&((h=t.firstElementChild)==null?void 0:h.localName)==="img"&&!t.firstElementChild.complete&&(g="1px"),p[f]=parseFloat(g)}return p}function ms(r){var t,e;return((t=r==null?void 0:r.style)==null?void 0:t["box-decoration-break"])==="clone"||((e=r==null?void 0:r.style)==null?void 0:e["-webkit-box-decoration-break"])==="clone"}function yc(r){let t=r.getAttribute("data-viv-box-break");return t?t.split(" "):[]}function Ec(r,t){r.setAttribute("data-viv-box-break",t.join(" "))}function dt(r,t){let e=yc(r);e.includes(t)||(e.push(t),Ec(r,e))}function Rm(r){let t=r.getAttribute("data-viv-margin-discard");return t?t.split(" "):[]}function Im(r,t){r.setAttribute("data-viv-margin-discard",t.join(" "))}function Fr(r,t){let e=Rm(r);e.includes(t)||(e.push(t),Im(r,e))}function Vm(r){let t=r.name,e=r.value;switch(t){case"page-break-before":case"page-break-after":case"page-break-inside":return{name:t.replace(/^page-/,""),value:e===b.always?b.page:e,important:r.important};default:return r}}var Br={page:!0,left:!0,right:!0,recto:!0,verso:!0,column:!0,region:!0};function De(r){return!!Br[r]}var Fm={left:!0,right:!0,recto:!0,verso:!0};function Fn(r){return!!Fm[r]}var Bm={avoid:!0,"avoid-page":!0,"avoid-column":!0,"avoid-region":!0};function ao(r){return!!Bm[r]}function Fe(r,t){if(r)if(t){if(Fn(t))return t;if(Fn(r))return r;{let e=De(r),n=De(t);if(e&&n)switch(t){case"column":return r;case"region":return r==="column"?t:r;default:return t}else return n?t:e?r:ao(t)?t:ao(r)?r:t}}else return r;else return t}function Sc(r){return De(r)?r:"auto"}_e("SIMPLE_PROPERTY",Vm);var lo=wg(Sh());function Nh(r,t){return(0,lo.default)(r,t,0)}function wc(r){return r.reduce((t,e)=>e[0]===lo.default.DELETE?t:t+e[1],"")}function vh(r,t){return wh(r,t,1)}function Th(r,t){return wh(r,t,-1)}function wh(r,t,e){let n=0,s=0;return r.some(o=>{for(let i=0;i<o[1].length;i++){switch(o[0]*e){case lo.default.INSERT:n++;break;case lo.default.DELETE:n--,s++;break;case lo.default.EQUAL:s++;break}if(s>t)return!0}return!1}),Math.max(Math.min(t,s-1)+n,0)}var Mr;(t=>{function r(e){return e&&e.formattingContextType==="Block"}t.isInstanceOfBlockFormattingContext=r})(Mr||(Mr={}));var Bn;(t=>{let r;(i=>(i.INLINE="inline",i.COLUMN="column",i.REGION="region",i.PAGE="page"))(r=t.FloatReference||(t.FloatReference={}))})(Bn||(Bn={}));var Jo;(t=>{function r(e){return e&&e.flagmentLayoutConstraintType=="AfterIfContinue"}t.isInstanceOfAfterIfContinuesLayoutConstraint=r})(Jo||(Jo={}));var en;(e=>{function r(n){return n?n.formattingContextType==="RepetitiveElementsOwner"||Ot.isInstanceOfTableFormattingContext(n):!1}e.isInstanceOfRepetitiveElementsOwnerFormattingContext=r;function t(n){return n?n.flagmentLayoutConstraintType==="RepetitiveElementsOwner"||Ot.isInstanceOfTableRowLayoutConstraint(n):!1}e.isInstanceOfRepetitiveElementsOwnerLayoutConstraint=t})(en||(en={}));var Ot;(e=>{function r(n){return n&&n.formattingContextType==="Table"}e.isInstanceOfTableFormattingContext=r;function t(n){return n&&n.flagmentLayoutConstraintType==="TableRow"}e.isInstanceOfTableRowLayoutConstraint=t})(Ot||(Ot={}));var kt;(e=>{let r;(i=>(i[i.IGNORE=0]="IGNORE",i[i.NEWLINE=1]="NEWLINE",i[i.PRESERVE=2]="PRESERVE"))(r=e.Whitespace||(e.Whitespace={}));let t;(a=>(a[a.NONE=0]="NONE",a[a.CONTENT=1]="CONTENT",a[a.ROOTLESS=2]="ROOTLESS",a[a.ROOTED=3]="ROOTED"))(t=e.ShadowType||(e.ShadowType={}))})(kt||(kt={}));var Ph={transform:!0,"transform-origin":!0},kh={top:!0,bottom:!0,left:!0,right:!0},Dn=class{constructor(t,e,n){this.target=t;this.name=e;this.value=n}},$m={show:function(r){r.style.visibility="visible"},hide:function(r){r.style.visibility="hidden"},play:function(r){r.currentTime=0,r.play()},pause:function(r){r.pause()},resume:function(r){r.play()},mute:function(r){r.muted=!0},unmute:function(r){r.muted=!1}};function Xm(r,t){let e=$m[t];return e?()=>{for(let n=0;n<r.length;n++)try{e(r[n])}catch(s){}}:null}var On=class On extends vn{constructor(e,n){super();this.container=e;this.bleedBox=n;d(this,"pageAreaElement",null);d(this,"delayedItems",[]);d(this,"hrefHandler");d(this,"elementsById",{});d(this,"dimensions",{width:0,height:0});d(this,"isFirstPage",!1);d(this,"isLastPage",!1);d(this,"isBlankPage",!1);d(this,"isAutoPageWidth",!0);d(this,"isAutoPageHeight",!0);d(this,"spineIndex",0);d(this,"position",null);d(this,"offset",-1);d(this,"side",null);d(this,"fetchers",[]);d(this,"marginBoxes",{top:{},bottom:{},left:{},right:{}});d(this,"pageType",null);this.hrefHandler=s=>{let o=s.currentTarget,i=o.getAttribute("href")||o.getAttributeNS("http://www.w3.org/1999/xlink","href");if(i){let a={type:"hyperlink",target:null,currentTarget:null,anchorElement:o,href:i,preventDefault(){s.preventDefault()}};this.dispatchEvent(a)}}}setAutoPageWidth(e){this.isAutoPageWidth=e,e?this.container.setAttribute(On.AUTO_PAGE_WIDTH_ATTRIBUTE,"true"):this.container.removeAttribute(On.AUTO_PAGE_WIDTH_ATTRIBUTE)}setAutoPageHeight(e){this.isAutoPageHeight=e,e?this.container.setAttribute(On.AUTO_PAGE_HEIGHT_ATTRIBUTE,"true"):this.container.removeAttribute(On.AUTO_PAGE_HEIGHT_ATTRIBUTE)}registerElementWithId(e,n){let s=this.elementsById[n];s?s.push(e):this.elementsById[n]=[e]}finish(e,n){Object.keys(this.elementsById).forEach(i=>{let a=this.elementsById[i];for(let l=0;l<a.length;)this.container.contains(a[l])?l++:a.splice(l,1);a.length===0&&delete this.elementsById[i]});let s=this.delayedItems;for(let i=0;i<s.length;i++){let a=s[i];a.target===this.container&&a.name==="transform"&&!this.isAutoPageWidth&&!this.isAutoPageHeight||T(a.target,a.name,a.value.toString())}let o=n.getElementClientRect(this.container);this.dimensions.width=o.width,this.dimensions.height=o.height;for(let i=0;i<e.length;i++){let a=e[i],l=this.elementsById[a.ref],c=this.elementsById[a.observer];if(l&&c){let u=Xm(l,a.action);if(u)for(let p=0;p<c.length;p++)c[p].addEventListener(a.event,u,!1)}}}};d(On,"AUTO_PAGE_WIDTH_ATTRIBUTE","data-vivliostyle-auto-page-width"),d(On,"AUTO_PAGE_HEIGHT_ATTRIBUTE","data-vivliostyle-auto-page-height");var co=On,Mt="data-adapt-spec",Ze=kt.Whitespace;function $r(r){switch(r){case"normal":case"nowrap":return Ze.IGNORE;case"pre-line":return Ze.NEWLINE;case"pre":case"pre-wrap":case"break-spaces":return Ze.PRESERVE;default:return null}}function ue(r,t){if(!r)return!0;if(r.nodeType==1)return!1;let e=r.textContent;switch(t){case Ze.PRESERVE:return e.length==0;case Ze.NEWLINE:return!!e.match(/^[ \t]*$/);case Ze.IGNORE:default:return!!e.match(/^[ \t\r\n\f]*$/)}}var _r=class{constructor(t,e){this.flowName=t;this.parentFlowName=e;d(this,"forcedBreakOffsets",[]);d(this,"formattingContext",null)}},Ur=class{constructor(t,e,n,s,o,i,a,l,c){this.flowName=t;this.element=e;this.startOffset=n;this.priority=s;this.linger=o;this.exclusive=i;this.repeated=a;this.last=l;this.breakBefore=c;d(this,"startPage",-1)}isBetter(t){return this.exclusive?!t.exclusive||this.priority>t.priority?!0:this.last:!1}};function Ah(r,t){return r.top-t.top}function Lh(r,t){return t.right-r.right}function Rh(r,t){var e,n;return r===t?!0:!r||!t?!1:(r.node===t.node||!!r.shadowContext&&!!t.shadowContext&&r.shadowType===kt.ShadowType.ROOTLESS&&t.shadowType===kt.ShadowType.ROOTLESS&&((e=r.node)==null?void 0:e.outerHTML)===((n=t.node)==null?void 0:n.outerHTML))&&r.shadowType===t.shadowType&&kc(r.shadowContext,t.shadowContext)&&kc(r.nodeShadow,t.nodeShadow)&&Rh(r.shadowSibling,t.shadowSibling)}function Dt(r,t){if(r===t)return!0;if(!r||!t||r.offsetInNode!==t.offsetInNode||r.after!==t.after||r.steps.length!==t.steps.length)return!1;for(let e=0;e<r.steps.length;e++)if(!Rh(r.steps[e],t.steps[e]))return!1;return!0}function Ih(r){return{steps:[{node:r,shadowType:yt.NONE,shadowContext:null,nodeShadow:null,shadowSibling:null,formattingContext:null,fragmentIndex:0}],offsetInNode:0,after:!1,preprocessedTextContent:null}}function xs(r,t){return{steps:[{node:r.sourceNode,shadowType:yt.NONE,shadowContext:r.shadowContext,nodeShadow:null,shadowSibling:null,formattingContext:null,fragmentIndex:t!=null?t:r.fragmentIndex}],offsetInNode:0,after:!1,preprocessedTextContent:r.preprocessedTextContent}}function po(r,t){let e=new Mn(r.node,t,0);return e.shadowType=r.shadowType,e.shadowContext=r.shadowContext,e.nodeShadow=r.nodeShadow,e.shadowSibling=r.shadowSibling?po(r.shadowSibling,t.copy()):null,e.formattingContext=r.formattingContext,e.fragmentIndex=r.fragmentIndex+1,e}var yt=kt.ShadowType,bs=class{constructor(t,e,n,s,o,i,a){this.owner=t;this.root=e;this.xmldoc=n;this.parentShadow=s;this.type=i;this.styler=a;d(this,"subShadow",null);o&&(o.subShadow=this)}equals(t){return t?this.owner===t.owner&&this.xmldoc===t.xmldoc&&this.type===t.type&&kc(this.parentShadow,t.parentShadow):!1}};function kc(r,t){return r===t||!!r&&!!t&&r.equals(t)}var Hr=class{constructor(t,e){this.outer=t;this.count=e}},Mn=class r{constructor(t,e,n){this.sourceNode=t;this.parent=e;this.boxOffset=n;d(this,"offsetInNode",0);d(this,"after",!1);d(this,"shadowType");d(this,"shadowContext");d(this,"nodeShadow",null);d(this,"shadowSibling",null);d(this,"shared",!1);d(this,"inline",!0);d(this,"overflow",!1);d(this,"breakPenalty");d(this,"display",null);d(this,"floatReference");d(this,"floatSide",null);d(this,"clearSide",null);d(this,"floatMinWrapBlock",null);d(this,"columnSpan",null);d(this,"verticalAlign","baseline");d(this,"captionSide","top");d(this,"inlineBorderSpacing",0);d(this,"blockBorderSpacing",0);d(this,"flexContainer",!1);d(this,"whitespace");d(this,"hyphenateCharacter");d(this,"breakWord");d(this,"establishesBFC",!1);d(this,"containingBlockForAbsolute",!1);d(this,"breakBefore",null);d(this,"breakAfter",null);d(this,"viewNode",null);d(this,"clearSpacer",null);d(this,"inheritedProps");d(this,"vertical");d(this,"direction");d(this,"firstPseudo");d(this,"lang",null);d(this,"preprocessedTextContent",null);d(this,"formattingContext");d(this,"repeatOnBreak",null);d(this,"pluginProps",{});d(this,"fragmentIndex",1);d(this,"afterIfContinues",null);d(this,"footnotePolicy",null);d(this,"pageType");this.shadowType=yt.NONE,this.shadowContext=e?e.shadowContext:null,this.breakPenalty=e?e.breakPenalty:0,this.floatReference=Bn.FloatReference.INLINE,this.whitespace=e?e.whitespace:Ze.IGNORE,this.hyphenateCharacter=e?e.hyphenateCharacter:null,this.breakWord=e?e.breakWord:!1,this.inheritedProps=e?e.inheritedProps:{},this.vertical=e?e.vertical:!1,this.direction=e?e.direction:"ltr",this.firstPseudo=e?e.firstPseudo:null,this.formattingContext=e?e.formattingContext:null,this.pageType=e?e.pageType:null}resetView(){this.inline=!0,this.breakPenalty=this.parent?this.parent.breakPenalty:0,this.viewNode=null,this.clearSpacer=null,this.offsetInNode=0,this.after=!1,this.display=null,this.floatReference=Bn.FloatReference.INLINE,this.floatSide=null,this.clearSide=null,this.floatMinWrapBlock=null,this.columnSpan=null,this.verticalAlign="baseline",this.flexContainer=!1,this.whitespace=this.parent?this.parent.whitespace:Ze.IGNORE,this.hyphenateCharacter=this.parent?this.parent.hyphenateCharacter:null,this.breakWord=this.parent?this.parent.breakWord:!1,this.breakBefore=null,this.breakAfter=null,this.nodeShadow=null,this.establishesBFC=!1,this.containingBlockForAbsolute=!1,this.vertical=this.parent?this.parent.vertical:!1,this.nodeShadow=null,this.preprocessedTextContent=null,this.formattingContext=this.parent?this.parent.formattingContext:null,this.repeatOnBreak=null,this.pluginProps={},this.fragmentIndex=1,this.afterIfContinues=null,this.footnotePolicy=null}cloneItem(){let t=new r(this.sourceNode,this.parent,this.boxOffset);return t.offsetInNode=this.offsetInNode,t.after=this.after,t.nodeShadow=this.nodeShadow,t.shadowType=this.shadowType,t.shadowContext=this.shadowContext,t.shadowSibling=this.shadowSibling,t.inline=this.inline,t.breakPenalty=this.breakPenalty,t.display=this.display,t.floatReference=this.floatReference,t.floatSide=this.floatSide,t.clearSide=this.clearSide,t.floatMinWrapBlock=this.floatMinWrapBlock,t.columnSpan=this.columnSpan,t.verticalAlign=this.verticalAlign,t.captionSide=this.captionSide,t.inlineBorderSpacing=this.inlineBorderSpacing,t.blockBorderSpacing=this.blockBorderSpacing,t.establishesBFC=this.establishesBFC,t.containingBlockForAbsolute=this.containingBlockForAbsolute,t.flexContainer=this.flexContainer,t.whitespace=this.whitespace,t.hyphenateCharacter=this.hyphenateCharacter,t.breakWord=this.breakWord,t.breakBefore=this.breakBefore,t.breakAfter=this.breakAfter,t.viewNode=this.viewNode,t.clearSpacer=this.clearSpacer,t.firstPseudo=this.firstPseudo,t.vertical=this.vertical,t.overflow=this.overflow,t.preprocessedTextContent=this.preprocessedTextContent,t.formattingContext=this.formattingContext,t.repeatOnBreak=this.repeatOnBreak,t.pluginProps=Object.create(this.pluginProps),t.fragmentIndex=this.fragmentIndex,t.afterIfContinues=this.afterIfContinues,t.footnotePolicy=this.footnotePolicy,t}modify(){return this.shared?this.cloneItem():this}copy(){let t=this;do{if(t.shared)break;t.shared=!0,t=t.parent}while(t);return this}clone(){let t=this.cloneItem(),e=t,n;for(;(n=e.parent)!=null;)n=n.cloneItem(),e.parent=n,e=n;return t}toNodePositionStep(){return{node:this.sourceNode,shadowType:this.shadowType,shadowContext:this.shadowContext,nodeShadow:this.nodeShadow,shadowSibling:this.shadowSibling?this.shadowSibling.toNodePositionStep():null,formattingContext:this.formattingContext,fragmentIndex:this.fragmentIndex}}toNodePosition(){var s,o,i;let t=this,e=[];t.shadowType===kt.ShadowType.ROOTLESS&&(t.floatReference!==Bn.FloatReference.INLINE||t.floatSide==="footnote")&&((i=(o=(s=t.shadowContext)==null?void 0:s.styler)==null?void 0:o.style)!=null&&i._pseudos)&&(t=t.parent);do(!t.firstPseudo||!t.parent||t.parent.firstPseudo===t.firstPseudo)&&e.push(t.toNodePositionStep()),t=t.parent;while(t);let n=this.preprocessedTextContent?Th(this.preprocessedTextContent,this.offsetInNode):this.offsetInNode;return{steps:e,offsetInNode:n,after:this.after,preprocessedTextContent:this.preprocessedTextContent}}isInsideBFC(){let t=this.parent;for(;t;){if(t.establishesBFC)return!0;t=t.parent}return!1}getContainingBlockForAbsolute(){let t=this.parent;for(;t;){if(t.containingBlockForAbsolute)return t;t=t.parent}return null}belongsTo(t){return this.formattingContext===t&&!!this.parent&&this.parent.formattingContext===t}},pt=class r{constructor(t){this.primary=t;d(this,"floats",null)}clone(){let t=new r(this.primary);if(this.floats){t.floats=[];for(let e=0;e<this.floats.length;++e)t.floats[e]=this.floats[e]}return t}isSamePosition(t){if(!t)return!1;if(this===t)return!0;if(!Dt(this.primary,t.primary))return!1;if(this.floats){if(!t.floats||this.floats.length!==t.floats.length)return!1;for(let e=0;e<this.floats.length;e++)if(!Dt(this.floats[e],t.floats[e]))return!1}else if(t.floats)return!1;return!0}},zr=class r{constructor(t,e){this.chunkPosition=t;this.flowChunk=e}clone(){return new r(this.chunkPosition.clone(),this.flowChunk)}isSamePosition(t){return!!t&&(this===t||this.chunkPosition.isSamePosition(t.chunkPosition))}},Gr=class r{constructor(){d(this,"positions",[]);d(this,"startBreakType",null);d(this,"breakAfter",null)}clone(){let t=new r,e=this.positions,n=t.positions;for(let s=0;s<e.length;s++)n[s]=e[s].clone();return t.startBreakType=this.startBreakType,t.breakAfter=this.breakAfter,t}isSamePosition(t){if(this===t)return!0;if(!t||this.positions.length!==t.positions.length)return!1;for(let e=0;e<this.positions.length;e++)if(!this.positions[e].isSamePosition(t.positions[e]))return!1;return!0}hasContent(t){return this.positions.length>0&&this.positions[0].flowChunk.startOffset<=t}},Wr=class r{constructor(){d(this,"page",0);d(this,"flows",{});d(this,"flowPositions",{});d(this,"isBlankPage",!1);d(this,"highestSeenOffset",0);d(this,"highestSeenNode");d(this,"lookupPositionOffset")}clone(){let t=new r;t.page=this.page,t.isBlankPage=this.isBlankPage,t.highestSeenNode=this.highestSeenNode,t.highestSeenOffset=this.highestSeenOffset,t.lookupPositionOffset=this.lookupPositionOffset,t.flows=this.flows;for(let e in this.flowPositions)t.flowPositions[e]=this.flowPositions[e].clone();return t}isSamePosition(t){if(this===t)return!0;if(!t||this.page!==t.page)return!1;let e=Object.keys(this.flowPositions),n=Object.keys(t.flowPositions);if(e.length!==n.length)return!1;for(let s of e)if(!this.flowPositions[s].isSamePosition(t.flowPositions[s]))return!1;return!0}hasContent(t,e){let n=this.flowPositions[t];return n?n.hasContent(e):!1}startSideOfFlow(t){var n;let e=(n=this.flowPositions[t])==null?void 0:n.startBreakType;return e&&Fn(e)?e:"any"}firstFlowChunkOfFlow(t){let e=this.flowPositions[t];if(!e)return null;let n=e.positions[0];return n?n.flowChunk:null}},uo=class{constructor(t){this.element=t;d(this,"left",0);d(this,"top",0);d(this,"marginLeft",0);d(this,"marginRight",0);d(this,"marginTop",0);d(this,"marginBottom",0);d(this,"borderLeft",0);d(this,"borderRight",0);d(this,"borderTop",0);d(this,"borderBottom",0);d(this,"paddingLeft",0);d(this,"paddingRight",0);d(this,"paddingTop",0);d(this,"paddingBottom",0);d(this,"width",0);d(this,"height",0);d(this,"originX",0);d(this,"originY",0);d(this,"exclusions",null);d(this,"innerShape",null);d(this,"computedBlockSize",0);d(this,"snapWidth",0);d(this,"snapHeight",0);d(this,"snapOffsetX",0);d(this,"snapOffsetY",0);d(this,"vertical",!1);d(this,"rtl",!1);d(this,"borderBoxSizing",!1)}getInsetTop(){return this.marginTop+(this.borderBoxSizing?0:this.borderTop+this.paddingTop)}getInsetBottom(){return this.marginBottom+(this.borderBoxSizing?0:this.borderBottom+this.paddingBottom)}getInsetLeft(){return this.marginLeft+(this.borderBoxSizing?0:this.borderLeft+this.paddingLeft)}getInsetRight(){return this.marginRight+(this.borderBoxSizing?0:this.borderRight+this.paddingRight)}getInsetBefore(){return this.vertical?this.getInsetRight():this.getInsetTop()}getInsetAfter(){return this.vertical?this.getInsetLeft():this.getInsetBottom()}getInsetStart(){return this.vertical?this.getInsetTop():this.getInsetLeft()}getInsetEnd(){return this.vertical?this.getInsetBottom():this.getInsetRight()}getBeforeEdge(t){return this.vertical?t.right:t.top}getAfterEdge(t){return this.vertical?t.left:t.bottom}getStartEdge(t){return this.vertical?this.rtl?t.bottom:t.top:this.rtl?t.right:t.left}getEndEdge(t){return this.vertical?this.rtl?t.top:t.bottom:this.rtl?t.left:t.right}getInlineSize(t){return this.vertical?t.bottom-t.top:t.right-t.left}getBoxSize(t){return this.vertical?t.right-t.left:t.bottom-t.top}getBoxDir(){return this.vertical?-1:1}getInlineDir(){return this.rtl?-1:1}copyFrom(t){this.element=t.element,this.left=t.left,this.top=t.top,this.marginLeft=t.marginLeft,this.marginRight=t.marginRight,this.marginTop=t.marginTop,this.marginBottom=t.marginBottom,this.borderLeft=t.borderLeft,this.borderRight=t.borderRight,this.borderTop=t.borderTop,this.borderBottom=t.borderBottom,this.paddingLeft=t.paddingLeft,this.paddingRight=t.paddingRight,this.paddingTop=t.paddingTop,this.paddingBottom=t.paddingBottom,this.width=t.width,this.height=t.height,this.originX=t.originX,this.originY=t.originY,this.innerShape=t.innerShape,this.exclusions=t.exclusions,this.computedBlockSize=t.computedBlockSize,this.snapWidth=t.snapWidth,this.snapHeight=t.snapHeight,this.vertical=t.vertical,this.rtl=t.rtl,this.borderBoxSizing=t.borderBoxSizing}setVerticalPosition(t,e){this.top=t,this.height=e,T(this.element,"top",`${t}px`),T(this.element,"height",`${e}px`)}setHorizontalPosition(t,e){this.left=t,this.width=e,T(this.element,"left",`${t}px`),T(this.element,"width",`${e}px`)}setBlockPosition(t,e){if(this.vertical){let n=e+this.marginLeft+this.marginRight+(this.borderBoxSizing?0:this.paddingLeft+this.paddingRight+this.borderLeft+this.borderRight);this.setHorizontalPosition(t+n*this.getBoxDir(),e)}else this.setVerticalPosition(t,e)}setInlinePosition(t,e){if(this.vertical)if(this.rtl){let n=e+this.marginTop+this.marginBottom+(this.borderBoxSizing?0:this.paddingTop+this.paddingBottom+this.borderTop+this.borderBottom);this.setVerticalPosition(t+n*this.getInlineDir(),e)}else this.setVerticalPosition(t,e);else if(this.rtl){let n=e+this.marginLeft+this.marginRight+(this.borderBoxSizing?0:this.paddingLeft+this.paddingRight+this.borderLeft+this.borderRight);this.setHorizontalPosition(t+n*this.getInlineDir(),e)}else this.setHorizontalPosition(t,e)}clear(){let t=this.element,e;for(;e=t.lastChild;)t.removeChild(e)}getInnerShape(){let t=this.getInnerRect();return this.innerShape?this.innerShape.withOffset(t.x1,t.y1):jo(t.x1,t.y1,t.x2,t.y2)}getInnerRect(){let t=this.originX+this.left+this.getInsetLeft(),e=this.originY+this.top+this.getInsetTop();return new He(t,e,t+this.width,e+this.height)}getPaddingRect(){let t=this.originX+this.left+this.marginLeft+this.borderLeft,e=this.originY+this.top+this.marginTop+this.borderTop,n=this.paddingLeft+this.width+this.paddingRight,s=this.paddingTop+this.height+this.paddingBottom;return new He(t,e,t+n,e+s)}getOuterShape(t,e){let n=this.getOuterRect();return vr(t,n.x1,n.y1,n.x2-n.x1,n.y2-n.y1,e)}getOuterRect(){let t=this.originX+this.left,e=this.originY+this.top,n=this.getInsetLeft()+this.width+this.getInsetRight(),s=this.getInsetTop()+this.height+this.getInsetBottom();return new He(t,e,t+n,e+s)}},dn=class extends lt{constructor(e,n,s,o){super();this.elem=e;this.context=n;this.rootContentValue=s;this.exprContentListener=o}visitStrInner(e,n){var s;if(!n){if(((s=this.elem.lastChild)==null?void 0:s.nodeType)===3){this.elem.lastChild.textContent+=e;return}n=this.elem.ownerDocument.createTextNode(e)}this.elem.appendChild(n)}visitStr(e){return this.visitStrInner(e.str),null}visitURL(e){if(this.rootContentValue.url)this.elem.setAttribute("src",e.url);else{let n=this.elem.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml","img");n.setAttribute("src",e.url),this.elem.appendChild(n)}return null}visitSpaceList(e){return this.visitValues(e.values),null}visitExpr(e){let n=e.toExpr(),s=n.evaluate(this.context);if(typeof s=="string"){n instanceof J&&(s=Jt(n.scope,new Oe(s,null),"").stringValue()),this.elem.ownerDocument;let o=this.exprContentListener(n,s,this.elem.ownerDocument);!o&&s&&n instanceof ie&&n.str.startsWith("running-element-")&&(s=""),this.visitStrInner(s,o)}return null}};function Et(r){return r!=null&&r!==O&&r!==b.normal&&r!==b.none&&!_(r)}var de=Bn.FloatReference;function Fh(r){switch(r){case"inline":return de.INLINE;case"column":return de.COLUMN;case"region":return de.REGION;case"page":return de.PAGE;default:throw new Error(`Unknown float-reference: ${r}`)}}function _n(r){switch(r){case de.INLINE:return!1;case de.COLUMN:case de.REGION:case de.PAGE:return!0;default:throw new Error(`Unknown float-reference: ${r}`)}}function Rc(r,t,e,n){let s=t?"vertical-rl":"horizontal-tb";if((r==="top"||r==="bottom")&&(r=bc(r,s,e)),r==="block-start"&&(r="inline-start"),r==="block-end"&&(r="inline-end"),r==="inline-start"||r==="inline-end"){let o=Cc(r,s,e),i=dh(o,s);i==="line-left"?r="left":i==="line-right"&&(r="right")}else r==="inside"?r=n==="left"?"right":"left":r==="outside"&&(r=n==="left"?"left":"right");return r!=="left"&&r!=="right"&&(V.warn(`Invalid float value: ${r}. Fallback to left.`),r="left"),r}var ti=class{constructor(t,e,n,s,o,i){this.nodePosition=t;this.floatReference=e;this.floatSide=n;this.clearSide=s;this.flowName=o;this.floatMinWrapBlock=i;d(this,"order",null);d(this,"id",null)}getOrder(){if(this.order===null)throw new Error("The page float is not yet added");return this.order}getId(){if(!this.id)throw new Error("The page float is not yet added");return this.id}isAllowedOnContext(t){return t.isAnchorAlreadyAppeared(this.getId())}isAllowedToPrecede(t){return!1}},Ac=class{constructor(){d(this,"floats",[]);d(this,"nextPageFloatIndex",0)}nextOrder(){return this.nextPageFloatIndex++}createPageFloatId(t){return`pf${t}`}addPageFloat(t){if(this.floats.findIndex(n=>Dt(n.nodePosition,t.nodePosition))>=0)throw new Error("A page float with the same source node is already registered");{let n=t.order=this.nextOrder();t.id=this.createPageFloatId(n),this.floats.push(t)}}findPageFloatByNodePosition(t){let e=this.floats.findIndex(n=>Dt(n.nodePosition,t));return e>=0?this.floats[e]:null}findPageFloatById(t){let e=this.floats.findIndex(n=>n.id===t);return e>=0?this.floats[e]:null}},ni=class{constructor(t,e,n,s,o){this.floatReference=t;this.floatSide=e;this.continuations=n;this.area=s;this.continues=o}hasFloat(t){return this.continuations.some(e=>e.float===t)}findNotAllowedFloat(t){for(let e=this.continuations.length-1;e>=0;e--){let n=this.continuations[e].float;if(!n.isAllowedOnContext(t))return n}return null}getOuterShape(){return this.area.getOuterShape(null,null)}getOuterRect(){return this.area.getOuterRect()}getOrder(){let t=this.continuations.map(e=>e.float);return Math.min.apply(null,t.map(e=>e.getOrder()))}shouldBeStashedBefore(t){return this.getOrder()<t.getOrder()}addContinuations(t){t.forEach(e=>{this.continuations.push(e)})}getFlowName(){let t=this.continuations[0].float.flowName;return this.continuations.every(e=>e.float.flowName===t),t}},si=class{constructor(t,e){this.float=t;this.nodePosition=e}equals(t){return t?this===t?!0:this.float===t.float&&Dt(this.nodePosition,t.nodePosition):!1}},pn=class{constructor(t,e,n,s,o,i,a){this.parent=t;this.floatReference=e;this.container=n;this.flowName=s;this.generatingNodePosition=o;d(this,"children",[]);d(this,"writingMode");d(this,"direction");d(this,"invalidated",!1);d(this,"floatStore");d(this,"forbiddenFloats",[]);d(this,"floatFragments",[]);d(this,"stashedFloatFragments",[]);d(this,"floatAnchors",{});d(this,"floatsDeferredToNext",[]);d(this,"floatsDeferredFromPrevious");d(this,"layoutConstraints",[]);d(this,"locked",!1);t&&t.children.push(this),this.writingMode=i||t&&t.writingMode||b.horizontal_tb,this.direction=a||t&&t.direction||b.ltr,this.floatStore=t?t.floatStore:new Ac;let l=this.getPreviousSibling();this.floatsDeferredFromPrevious=l?[].concat(l.floatsDeferredToNext):[]}getParent(t){if(!this.parent)throw new Error(`No PageFloatLayoutContext for ${t}`);return this.parent}getPreviousSiblingOf(t,e,n,s){let o=this.children.indexOf(t);o<0&&(o=this.children.length);for(let i=o-1;i>=0;i--){let a=this.children[i];if(a.floatReference===e&&a.flowName===n&&Dt(a.generatingNodePosition,s))return a;if(a=a.getPreviousSiblingOf(null,e,n,s),a)return a}return null}getPreviousSibling(){let t=this,e=this.parent,n;for(;e;){if(n=e.getPreviousSiblingOf(t,this.floatReference,this.flowName,this.generatingNodePosition),n)return n;t=e,e=e.parent}return null}getContainer(t){return!t||t===this.floatReference?this.container:this.getParent(t).getContainer(t)}setContainer(t){this.container=t,this.reattachFloatFragments()}addPageFloat(t){this.floatStore.addPageFloat(t)}getPageFloatLayoutContext(t){return t===this.floatReference?this:this.getParent(t).getPageFloatLayoutContext(t)}findPageFloatByNodePosition(t){return this.floatStore.findPageFloatByNodePosition(t)}forbid(t){let e=t.getId(),n=t.floatReference;n===this.floatReference?this.forbiddenFloats.includes(e)||(this.forbiddenFloats.push(e),new _t().findByFloat(t).forbid(t,this)):this.getParent(n).forbid(t)}isForbidden(t){let e=t.getId(),n=t.floatReference;return n===this.floatReference?this.forbiddenFloats.includes(e):this.getParent(n).isForbidden(t)}addPageFloatFragment(t,e){let n=t.floatReference;n!==this.floatReference?this.getParent(n).addPageFloatFragment(t,e):this.floatFragments.includes(t)||(this.floatFragments.push(t),this.floatFragments.sort((s,o)=>s.getOrder()-o.getOrder())),e||this.invalidate()}removePageFloatFragment(t,e){let n=t.floatReference;if(n!==this.floatReference)this.getParent(n).removePageFloatFragment(t,e);else{let s=this.floatFragments.indexOf(t);if(s>=0){let o=this.floatFragments.splice(s,1)[0],i=o.area&&o.area.element;i&&i.parentNode&&i.parentNode.removeChild(i),e||this.invalidate()}}}findPageFloatFragment(t){if(t.floatReference!==this.floatReference)return this.getParent(t.floatReference).findPageFloatFragment(t);let e=this.floatFragments.findIndex(n=>n.hasFloat(t));return e>=0?this.floatFragments[e]:null}hasFloatFragments(t){return this.floatFragments.length>0&&(!t||this.floatFragments.some(t))?!0:this.parent?this.parent.hasFloatFragments(t):!1}hasContinuingFloatFragmentsInFlow(t){return this.hasFloatFragments(e=>e.continues&&e.getFlowName()===t)}registerPageFloatAnchor(t,e){this.floatAnchors[t.getId()]=e}collectPageFloatAnchors(){let t=Object.assign({},this.floatAnchors);return this.children.reduce((e,n)=>Object.assign(e,n.collectPageFloatAnchors()),t)}isAnchorAlreadyAppeared(t){if(this.getDeferredPageFloatContinuations().some(o=>o.float.getId()===t))return!0;let s=this.collectPageFloatAnchors()[t];return s&&this.container&&this.container.element?this.container.element.contains(s):!1}deferPageFloat(t){let e=t.float;if(e.floatReference===this.floatReference){let n=this.floatsDeferredToNext.findIndex(s=>s.float===e);n>=0?this.floatsDeferredToNext.splice(n,1,t):this.floatsDeferredToNext.push(t)}else this.getParent(e.floatReference).deferPageFloat(t)}hasPrecedingFloatsDeferredToNext(t,e){if(!e&&t.floatReference!==this.floatReference)return this.getParent(t.floatReference).hasPrecedingFloatsDeferredToNext(t,!1);let n=t.getOrder();return this.floatsDeferredToNext.some(o=>o.float.getOrder()<n&&!t.isAllowedToPrecede(o.float))?!0:this.parent?this.parent.hasPrecedingFloatsDeferredToNext(t,!0):!1}getLastFollowingFloatInFragments(t){let e=t.getOrder(),n=null;if(this.floatFragments.forEach(s=>{s.continuations.forEach(o=>{let i=o.float,a=i.getOrder();a>e&&(!n||a>n.getOrder())&&(n=i)})}),this.parent){let s=this.parent.getLastFollowingFloatInFragments(t);s&&(!n||s.getOrder()>n.getOrder())&&(n=s)}return n}getDeferredPageFloatContinuations(t){t=t||this.flowName;let e=this.floatsDeferredFromPrevious.filter(n=>!t||n.float.flowName===t);return this.parent&&(e=this.parent.getDeferredPageFloatContinuations(t).concat(e)),e.sort((n,s)=>n.float.getOrder()-s.float.getOrder())}getPageFloatContinuationsDeferredToNext(t){t=t||this.flowName;let e=this.floatsDeferredToNext.filter(n=>!t||n.float.flowName===t);return this.parent?this.parent.getPageFloatContinuationsDeferredToNext(t).concat(e):e}getFloatsDeferredToNextInChildContexts(){let t=[],e=[];for(let n=this.children.length-1;n>=0;n--){let s=this.children[n];e.includes(s.flowName)||(e.push(s.flowName),t=t.concat(s.floatsDeferredToNext.map(o=>o.float)),t=t.concat(s.getFloatsDeferredToNextInChildContexts()))}return t}checkAndForbidNotAllowedFloat(){if(this.checkAndForbidFloatFollowingDeferredFloat())return!0;for(let t=this.floatFragments.length-1;t>=0;t--){let e=this.floatFragments[t],n=e.findNotAllowedFloat(this);if(n)return this.locked?this.invalidate():(this.removePageFloatFragment(e),this.forbid(n),this.removeEndFloatFragments(e.floatSide)),!0}return this.floatReference===de.REGION&&this.parent.locked?this.parent.checkAndForbidNotAllowedFloat():!1}checkAndForbidFloatFollowingDeferredFloat(){let t=this.getFloatsDeferredToNextInChildContexts(),e=this.floatFragments.reduce((n,s)=>n.concat(s.continuations.map(o=>o.float)),[]);e.sort((n,s)=>s.getOrder()-n.getOrder());for(let n of e){let s=n.getOrder();if(t.some(o=>!n.isAllowedToPrecede(o)&&s>o.getOrder())){if(this.locked)this.invalidate();else{this.forbid(n);let o=this.findPageFloatFragment(n);this.removePageFloatFragment(o)}return!0}}return!1}finish(){if(!this.checkAndForbidNotAllowedFloat()){for(let t=this.floatsDeferredToNext.length-1;t>=0;t--)if(!this.floatsDeferredToNext[t].float.isAllowedOnContext(this)){if(this.locked){this.invalidate();return}this.floatsDeferredToNext.splice(t,1)}this.floatsDeferredFromPrevious.forEach(t=>{this.floatsDeferredToNext.findIndex(e=>t.equals(e))>=0||this.floatFragments.some(e=>e.hasFloat(t.float))||this.floatsDeferredToNext.push(t)})}}hasSameContainerAs(t){return!!this.container&&!!t.container&&this.container.element===t.container.element}invalidate(){this.invalidated=!0,!this.locked&&(this.container&&(this.children.forEach(t=>{this.hasSameContainerAs(t)&&t.floatFragments.forEach(e=>{let n=e.area.element;n&&n.parentNode&&n.parentNode.removeChild(n)})}),this.container.clear()),this.children.forEach(t=>{t.layoutConstraints.splice(0)}),this.children.splice(0),Object.keys(this.floatAnchors).forEach(t=>{delete this.floatAnchors[t]}))}detachChildren(){let t=this.children.splice(0);return t.forEach(e=>{e.floatFragments.forEach(n=>{let s=n.area.element;s&&s.parentNode&&s.parentNode.removeChild(s)})}),t}attachChildren(t){t.forEach(e=>{this.children.push(e),e.reattachFloatFragments()})}isInvalidated(){return this.invalidated||!!this.parent&&this.parent.isInvalidated()}validate(){this.invalidated=!1}toLogical(t){let e=this.writingMode.toString(),n=this.direction.toString();if(t==="inside"||t==="outside"){let s=!!this.container.element.closest("[data-vivliostyle-page-side='left']");t=t==="inside"?s?"right":"left":s?"left":"right"}return bc(t,e,n)}toPhysical(t){let e=this.writingMode.toString(),n=this.direction.toString();return Cc(t,e,n)}toLogicalFloatSides(t){let e=t.split(" "),n=[];for(let a of e){let l=this.toLogical(a);n.includes(l)||n.push(l)}let s=[],o=!1,i=!1;for(let a=0;a<n.length;a++){let l=n[a];l.includes("block")?o||(n.slice(a+1).some(c=>c.includes("block"))?(s.push("snap-block"),o=!0):s.push(l)):l.includes("inline")&&(i||(n.slice(a+1).some(c=>c.includes("inline"))?(s.push("snap-inline"),i=!0):s.push(l)))}return s}removeEndFloatFragments(t){let e=this.toLogicalFloatSides(t)[0];if(e==="block-end"||e==="inline-end"){let n=0;for(;n<this.floatFragments.length;){let s=this.floatFragments[n];this.toLogicalFloatSides(s.floatSide)[0]===e?this.removePageFloatFragment(s):n++}}}stashEndFloatFragments(t){let e=t.floatReference;if(e!==this.floatReference){this.getParent(e).stashEndFloatFragments(t);return}let n=this.toLogicalFloatSides(t.floatSide)[0];if(n==="block-end"||n==="snap-block"||n==="inline-end"||n==="snap-inline"){let s=0;for(;s<this.floatFragments.length;){let o=this.floatFragments[s],i=this.toLogicalFloatSides(o.floatSide)[0];(i===n||n==="snap-block"&&i==="block-end"||n==="snap-inline"&&i==="inline-end")&&o.shouldBeStashedBefore(t)?(this.stashedFloatFragments.push(o),this.floatFragments.splice(s,1)):s++}}}restoreStashedFragments(t){if(t!==this.floatReference){this.getParent(t).restoreStashedFragments(t);return}this.stashedFloatFragments.forEach(e=>{this.addPageFloatFragment(e,!0)}),this.stashedFloatFragments.splice(0)}discardStashedFragments(t){if(t!==this.floatReference){this.getParent(t).discardStashedFragments(t);return}this.stashedFloatFragments.splice(0)}getStashedFloatFragments(t){return t===this.floatReference?this.stashedFloatFragments.concat().sort((e,n)=>n.getOrder()-e.getOrder()):this.getParent(t).getStashedFloatFragments(t)}getLimitValue(t,e,n,s){this.container;let o=this.toLogical(t),i=this.toPhysical(t),a=this.getLimitValueInner(o,e,n,s);if(this.parent&&this.parent.container){let l=this.parent.getLimitValue(i,e,n,s);switch(i){case"top":return Math.max(a,l);case"left":return Math.max(a,l);case"bottom":return Math.min(a,l);case"right":return Math.min(a,l);default:}}return a}getLimitValueInner(t,e,n,s){this.container;let o=this.getLimitValuesInner(e,n,s);switch(t){case"block-start":return this.container.vertical?o.right:o.top;case"block-end":return this.container.vertical?o.left:o.bottom;case"inline-start":return this.container.vertical?this.container.rtl?o.bottom:o.top:this.container.rtl?o.right:o.left;case"inline-end":return this.container.vertical?this.container.rtl?o.top:o.bottom:this.container.rtl?o.left:o.right;default:throw new Error(`Unknown logical side: ${t}`)}}getLimitValuesInner(t,e,n){this.container;let s=this.container.originX,o=this.container.originY,i=this.container.getPaddingRect(),a={top:i.y1-o,left:i.x1-s,bottom:i.y2-o,right:i.x2-s,floatMinWrapBlockStart:0,floatMinWrapBlockEnd:0};function l(u,p,h){return u.unit==="%"?h*u.num/100:t.convertLengthToPx(u,p,e)}let c=this.floatFragments;return c.length>0&&(a=c.reduce((u,p)=>{if(n&&!n(p,this))return u;let h=this.toLogicalFloatSides(p.floatSide)[0],f=p.area,g=p.continuations[0].float.floatMinWrapBlock,m=u.top,E=u.left,y=u.bottom,C=u.right,x=u.floatMinWrapBlockStart,N=u.floatMinWrapBlockEnd;switch(h){case"inline-start":f.vertical?m=Math.max(m,f.top+f.height):E=Math.max(E,f.left+f.width);break;case"block-start":f.vertical?(g&&f.left<C&&(x=l(g,f.rootViewNodes[0],i.x2-i.x1)),C=Math.min(C,f.left)):(g&&f.top+f.height>m&&(x=l(g,f.rootViewNodes[0],i.y2-i.y1)),m=Math.max(m,f.top+f.height));break;case"inline-end":f.vertical?y=Math.min(y,f.top):C=Math.min(C,f.left);break;case"block-end":f.vertical?(g&&f.left+f.width>E&&(N=l(g,f.rootViewNodes[0],i.x2-i.x1)),E=Math.max(E,f.left+f.width)):(g&&f.top<y&&(N=l(g,f.rootViewNodes[0],i.y2-i.y1)),y=Math.min(y,f.top));break;default:throw new Error(`Unknown logical float side: ${h}`)}return{top:m,left:E,bottom:y,right:C,floatMinWrapBlockStart:x,floatMinWrapBlockEnd:N}},a)),a.left+=s,a.right+=s,a.top+=o,a.bottom+=o,a}setFloatAreaDimensions(t,e,n,s,o,i,a){if(e!==this.floatReference)return this.getParent(e).setFloatAreaDimensions(t,e,n,s,o,i,a);let l=this.toLogicalFloatSides(n);if(l[0]==="snap-block"){if(!a["block-start"]&&!a["block-end"])return null}else if(l[0]==="snap-inline"){if(!a["inline-start"]&&!a["inline-end"])return null}else if(!a[l[0]])return null;t.clientLayout;let c=this.getLimitValue("block-start",t.layoutContext,t.clientLayout),u=this.getLimitValue("block-end",t.layoutContext,t.clientLayout),p=this.getLimitValue("inline-start",t.layoutContext,t.clientLayout),h=this.getLimitValue("inline-end",t.layoutContext,t.clientLayout),f=t.vertical?t.originX:t.originY,g=t.vertical?t.originY:t.originX;c=t.vertical?Math.min(c,t.left+t.getInsetLeft()+t.width+t.getInsetRight()+f):Math.max(c,t.top+f),u=t.vertical?Math.max(u,t.left+f):Math.min(u,t.top+t.getInsetTop()+t.height+t.getInsetBottom()+f);function m(N,S){let w=N(t.bands,S);return w?(t.vertical&&(w=Er(w)),c=t.vertical?Math.min(c,w.x2):Math.max(c,w.y1),u=t.vertical?Math.max(u,w.x1):Math.min(u,w.y2),!0):i}let E,y,C,x;if(o){let N=t.vertical?Js(new He(u,p,c,h)):new He(p,c,h,u);if((l[0]==="block-start"||l[0]==="snap-block"||l[0]==="inline-start"||l[0]==="snap-inline")&&!m($p,N)||(l[0]==="block-end"||l[0]==="snap-block"||l[0]==="inline-end"||l[0]==="snap-inline")&&!m(Xp,N)||(C=(u-c)*t.getBoxDir(),E=C-t.getInsetBefore()-t.getInsetAfter(),x=(h-p)*t.getInlineDir(),y=x-t.getInsetStart()-t.getInsetEnd(),!i&&(E<=0||y<=0)))return null}else{E=t.computedBlockSize,C=E+t.getInsetBefore()+t.getInsetAfter();let N=(u-c)*t.getBoxDir();if(l[0]==="snap-block"){if(s===null)l[0]="block-start";else{let w=this.container.getPaddingRect(),k=this.container.getBoxDir()*(s-(this.container.vertical?w.x2:w.y1)),I=this.container.getBoxDir()*((this.container.vertical?w.x1:w.y2)-s-C);k<=I?l[0]="block-start":l[0]="block-end"}if(!a[l[0]])if(a["block-end"])l[0]="block-end";else return null}else if(l[0]==="snap-inline")if(s===null)l[0]="inline-start";else if(a["inline-start"])l[0]="inline-start";else if(a["inline-end"])l[0]="inline-end";else return null;if(!i&&N<C)return null;l[0]==="inline-start"||l[0]==="inline-end"||l[1]?y=ro(t.clientLayout,t.element,["fit-content inline size"])["fit-content inline size"]:t.adjustContentRelativeSize?y=t.getContentInlineSize():y=t.vertical?t.height:t.width,x=y+t.getInsetStart()+t.getInsetEnd();let S=(h-p)*t.getInlineDir();if(!i&&S<x)return null}return c-=f,u-=f,p-=g,h-=g,l.some(N=>N==="inline-start"||N==="snap-inline")||l.length===1&&(l[0]==="block-start"||l[0]==="snap-block")?t.setInlinePosition(p,y):(l.some(N=>N==="inline-end")||l.length===1&&l[0]==="block-end")&&t.setInlinePosition(h-x*t.getInlineDir(),y),l.some(N=>N==="block-start"||N==="snap-block")||l.length===1&&(l[0]==="inline-start"||l[0]==="snap-inline")?t.setBlockPosition(c,E):(l.some(N=>N==="block-end")||l.length===1&&l[0]==="inline-end")&&t.setBlockPosition(u-C*t.getBoxDir(),E),l.join(" ")}getFloatFragmentExclusions(){let t=this.floatFragments.map(e=>e.getOuterShape());return this.parent?this.parent.getFloatFragmentExclusions().concat(t):t}reattachFloatFragments(){let t=this.container.element&&this.container.element.parentNode;t&&this.floatFragments.forEach(e=>{t.appendChild(e.area.element)})}getMaxReachedAfterEdge(){let t=this.getContainer().vertical;return this.floatFragments.reduce((e,n)=>{let s=n.getOuterRect();return t?Math.min(e,s.x1):Math.max(e,s.y2)},t?1/0:0)}getBlockStartEdgeOfBlockEndFloats(){let t=this.getContainer().vertical;return this.floatFragments.filter(e=>e.floatSide==="block-end").reduce((e,n)=>{let s=n.getOuterRect();return t?Math.max(e,s.x2):Math.min(e,s.y1)},t?0:1/0)}getPageFloatClearEdge(t,e){function n(u){return p=>u.isAnchorAlreadyAppeared(p.float.getId())}function s(u,p){return u.continuations.some(n(p))}let o=e.getPaddingRect(),i=e.vertical?o.x1:o.y2,a=this;for(;a;){if(a.floatsDeferredToNext.some(n(a)))return i;a=a.parent}e.clientLayout;let l=this.getLimitValue("block-start",e.layoutContext,e.clientLayout,s);return this.getLimitValue("block-end",e.layoutContext,e.clientLayout,s)*e.getBoxDir()<i*e.getBoxDir()?i:l}getPageFloatPlacementCondition(t,e,n){if(t.floatReference!==this.floatReference)return this.getParent(t.floatReference).getPageFloatPlacementCondition(t,e,n);let s={"block-start":!0,"block-end":!0,"inline-start":!0,"inline-end":!0};if(!n)return s;let o=this.toLogicalFloatSides(e)[0],i=this.toLogical(n),a;i==="all"?a=["block-start","block-end","inline-start","inline-end"]:i==="both"?a=["inline-start","inline-end"]:i==="same"?o==="snap-block"?a=["block-start","block-end"]:a=[o]:a=[i];let l=t.getOrder();function c(h){return f=>f.floatSide===h&&f.getOrder()<l}function u(h,f){return h.children.some(g=>g.floatFragments.some(c(f))||u(g,f))}function p(h,f){let g=h.parent;return!!g&&(g.floatFragments.some(c(f))||p(g,f))}return a.forEach(h=>{switch(h){case"block-start":case"inline-start":s[h]=!u(this,h);break;case"block-end":case"inline-end":s[h]=!p(this,h);break;default:throw new Error(`Unexpected side: ${h}`)}}),s}getLayoutConstraints(){return(this.parent?this.parent.getLayoutConstraints():[]).concat(this.layoutConstraints)}addLayoutConstraint(t,e){e===this.floatReference?this.layoutConstraints.push(t):this.getParent(e).addLayoutConstraint(t,e)}isColumnFullWithPageFloats(t){let e=t.layoutContext,n=t.clientLayout;let s=this,o=null;for(;s&&s.container;){let l=s.getLimitValuesInner(e,n);o?t.vertical?(l.right<o.right&&(o.right=l.right,o.floatMinWrapBlockStart=l.floatMinWrapBlockStart),l.left>o.left&&(o.left=l.left,o.floatMinWrapBlockEnd=l.floatMinWrapBlockEnd)):(l.top>o.top&&(o.top=l.top,o.floatMinWrapBlockStart=l.floatMinWrapBlockStart),l.bottom<o.bottom&&(o.bottom=l.bottom,o.floatMinWrapBlockEnd=l.floatMinWrapBlockEnd)):o=l,s=s.parent}let i=Math.max(o.floatMinWrapBlockStart,o.floatMinWrapBlockEnd);return(t.vertical?o.right-o.left:o.bottom-o.top)<=i}getMaxBlockSizeOfPageFloats(){let t=this.getContainer().vertical;return this.floatFragments.length?Math.max.apply(null,this.floatFragments.map(e=>{let n=e.area;return t?n.width:n.height})):0}lock(){this.locked=!0}unlock(){this.locked=!1}isLocked(){return this.locked}},ei=[],_t=class{static register(t){ei.push(t)}findByNodeContext(t){for(let e=ei.length-1;e>=0;e--){let n=ei[e];if(n.appliesToNodeContext(t))return n}throw new Error(`No PageFloatLayoutStrategy found for ${t}`)}findByFloat(t){for(let e=ei.length-1;e>=0;e--){let n=ei[e];if(n.appliesToFloat(t))return n}throw new Error(`No PageFloatLayoutStrategy found for ${t}`)}},Lc=class{appliesToNodeContext(t){return _n(t.floatReference)}appliesToFloat(t){return!0}createPageFloat(t,e,n){let s=t.floatReference;t.floatSide;let o=t.floatSide,i=t.toNodePosition();return n.resolveFloatReferenceFromColumnSpan(s,t.columnSpan,t).thenAsync(a=>{s=a,e.flowName;let l=new ti(i,s,o,t.clearSide,e.flowName,t.floatMinWrapBlock);return e.addPageFloat(l),v(l)})}createPageFloatFragment(t,e,n,s){let o=t[0].float;return new ni(o.floatReference,e,t,n,s)}findPageFloatFragment(t,e){return e.findPageFloatFragment(t)}adjustPageFloatArea(t,e,n){}forbid(t,e){}};_t.register(new Lc);var Ym=ni,oi=class r extends ti{constructor(e,n,s,o,i){super(e,n,"block-end",null,s,i);this.footnotePolicy=o}isAllowedToPrecede(e){return!(e instanceof r)}},jr=class extends Ym{constructor(t,e,n,s){super(t,"block-end",e,n,s)}getOrder(){return 1/0}shouldBeStashedBefore(t){return t instanceof oi?!0:this.getOrder()<t.getOrder()}},Ic=class{constructor(t){this.footnote=t}allowLayout(t){let e=t.toNodePosition();return!Dt(e,this.footnote.nodePosition)}},Vc=class{appliesToNodeContext(t){return t.floatSide==="footnote"}appliesToFloat(t){return t instanceof oi}createPageFloat(t,e,n){let s=de.REGION,o=e.getPageFloatLayoutContext(s);e.getPageFloatLayoutContext(de.PAGE).hasSameContainerAs(o)&&(s=de.PAGE);let a=t.toNodePosition();e.flowName;let l=new oi(a,s,e.flowName,t.footnotePolicy,t.floatMinWrapBlock);return e.addPageFloat(l),v(l)}createPageFloatFragment(t,e,n,s){let o=t[0].float;return new jr(o.floatReference,t,n,s)}findPageFloatFragment(t,e){let s=e.getPageFloatLayoutContext(t.floatReference).floatFragments.filter(o=>o instanceof jr);return s.length<=1,s[0]||null}adjustPageFloatArea(t,e,n){t.isFootnote=!0,t.adjustContentRelativeSize=!1;let s=t.element;t.vertical=n.layoutContext.applyFootnoteStyle(e.vertical,n.layoutContext.nodeContext&&n.layoutContext.nodeContext.direction==="rtl",s),t.convertPercentageSizesToPx(s),n.setComputedInsets(s,t),n.setComputedWidthAndHeight(s,t)}forbid(t,e){let n=t;switch(n.footnotePolicy){case b.line:{let s=new Ic(n);e.addLayoutConstraint(s,n.floatReference);break}}}};_t.register(new Vc);var Km="data-vivliostyle-flow-root";function Oh(r){return r.getAttribute(Km)==="true"}function Bh(r){let t=(r==null?void 0:r.toString())||"block",e;switch(t){case"inline-flex":e="flex";break;case"inline-grid":e="grid";break;case"inline-table":e="table";break;case"inline":case"table-row-group":case"table-column":case"table-column-group":case"table-header-group":case"table-footer-group":case"table-row":case"table-cell":case"table-caption":case"inline-block":e="block";break;default:e=t}return L(e)}function Yr(r){return r===b.absolute||r===b.fixed}function ii(r){return r instanceof wt&&r.name==="running"}function Fc(r,t,e,n){return r===b.none||(Yr(t)?(e=b.none,r=Bh(r)):(e&&e!==b.none&&!_(e)||n)&&(r=Bh(r))),{display:r,position:t,float:e}}function Kr(r,t,e,n){return Fc(r,t,e,n).display===b.block}function hn(r){switch(r.toString()){case"inline":case"inline-block":case"inline-list-item":case"inline-flex":case"inline-grid":case"ruby":case"inline-table":return!0;default:return!1}}function qr(r){switch(r.toString()){case"ruby-base":case"ruby-text":case"ruby-base-container":case"ruby-text-container":return!0;default:return!1}}function Dh(r,t,e,n,s,o,i){return s=s||o||b.horizontal_tb,!!i||!!e&&e!==b.none&&!_(e)||Yr(t)||r===b.inline_block||r===b.table_cell||r===b.table_caption||r==b.flex||r==b.grid||r==b.flow_root||(r===b.block||r===b.list_item)&&!!n&&n!==b.visible&&n!==b.clip&&!_(n)||!!o&&s!==o}function Mh(r){return r===b.relative||r===b.absolute||r===b.fixed}function Un(r,t,e,n){let s=r.viewNode;if(!s)return NaN;let o=s.nodeType===1?s:s.parentElement;if(o&&o.namespaceURI==="http://www.w3.org/1999/xhtml"){let i=o.style;if(i&&hn(i.display)&&/^([\d\.]|super|(text-)?top)/.test(i.verticalAlign))return NaN}if(s===o){if(r.after||!r.inline){if(r.after&&!r.inline&&o.querySelector("ruby")){let a=o.parentNode,l=o.nextSibling;a.removeChild(o),a.insertBefore(o,l)}let i=t.getElementClientRect(o);if(i.left===0&&i.top===0&&i.right===0&&i.bottom===0)return NaN;if(i.right>=i.left&&i.bottom>=i.top)return r.after?n?i.left:i.bottom:n?i.right:i.top}return NaN}else{let i=NaN,a=s.ownerDocument.createRange(),l=s.textContent.length;if(!l)return NaN;r.after&&(e+=l),e>=l&&(e=l-1),a.setStart(s,e),a.setEnd(s,e+1);let c=t.getRangeClientRects(a);return c=c.filter(u=>u.right>u.left&&u.bottom>u.top),c.length?(n?i=Math.min.apply(null,c.map(u=>u.left)):i=Math.max.apply(null,c.map(u=>u.bottom)),i):NaN}}function ri(r,t,e){let n=t.clientLayout.getElementClientRect(r),s=t.getComputedMargin(r);return e?n.width+s.left+s.right:n.height+s.top+s.bottom}function fn(r){for(;r;){if(r.parentNode===r.ownerDocument)return!1;r=r.parentNode}return!0}function Qr(r,t){var e;if(r)for(let n=r.lastChild,s=n;n!==t;n=s)s=n.previousSibling,!(n.nodeType===1&&n.hasAttribute("data-vivliostyle-float-box-moved")&&((e=t.style)==null?void 0:e.display)==="inline")&&r.removeChild(n)}function Jr(r){return!!r.getAttribute(Mt)}function ys(r){var n;if((r==null?void 0:r.nodeType)!==1)return!1;let t=r;if(Jr(t))return!0;let e=(n=t.style)==null?void 0:n.position;return e==="absolute"||e==="fixed"}function gn(r){let t=r==null?void 0:r.viewNode;return(t==null?void 0:t.nodeType)===1&&Jr(t)}function _h(r){return r!=="inline"&&(hn(r)||qr(r))}function Bc(r){var t;for(let e=r.parent;e;e=e.parent)if((e.display!=="inline"||e.vertical!==((t=e.parent)==null?void 0:t.vertical))&&hn(e.display))return e;return null}var Es=class{calculateOffset(t){return Hn(this.getNodeContext(),t.collectElementsOffset())}breakPositionChosen(t){}getNodeContext(){return null}};function Hn(r,t){return{current:t.reduce((e,n)=>e+n.calculateOffset(r),0),minimum:t.reduce((e,n)=>e+n.calculateMinimumOffset(r),0)}}var tn=class extends Es{constructor(e,n,s,o){super();this.position=e;this.breakOnEdge=n;this.overflows=s;this.computedBlockSize=o;d(this,"overflowIfRepetitiveElementsDropped");d(this,"isEdgeUpdated",!1);d(this,"edge",0);this.overflowIfRepetitiveElementsDropped=s}findAcceptableBreak(e,n){return this.updateOverflows(e),n<this.getMinBreakPenalty()?null:e.findEdgeBreakPosition(this)}getMinBreakPenalty(){if(!this.isEdgeUpdated)throw new Error("EdgeBreakPosition.prototype.updateEdge not called");let e=this.isFirstContentOfRepetitiveElementsOwner()&&!this.overflowIfRepetitiveElementsDropped;return(ao(this.breakOnEdge)?1:0)+(this.overflows&&!e?3:0)+(this.position.parent?this.position.parent.breakPenalty:0)}updateEdge(e){var s;let n=e.calculateClonedPaddingBorder(this.position);if(this.edge=Un(this.position,e.clientLayout,0,e.vertical)+n,!this.position.after&&!this.position.inline){let o=e.parseComputedLength(e.clientLayout.getElementComputedStyle(this.position.viewNode).marginBlockStart);this.edge-=(e.vertical?-1:1)*o}else if(this.position.after&&((s=this.position.shadowContext)==null?void 0:s.root.id)==="table-cell"){let o=e.element.parentElement,i=o==null?void 0:o.closest("table, [style*='display: table;']");if(i){let a=i.style.borderCollapse==="collapse",l=0,c=0;for(let u=o;u;u=u.parentElement){let p=e.clientLayout.getElementComputedStyle(u);if((u===o||u===i&&!a)&&(l+=e.parseComputedLength(p.paddingBlockEnd)),u===i&&!a&&(l+=e.parseComputedLength(p.borderSpacing.replace(/^\S+ (\S+)$/,"$1"))),a?c=Math.max(c,e.parseComputedLength(p.borderBlockEndWidth)):(u===o||u===i)&&(c+=e.parseComputedLength(p.borderBlockEndWidth)),u===i)break}this.edge+=(e.vertical?-1:1)*(l+c)}}this.isEdgeUpdated=!0}updateOverflows(e){this.isEdgeUpdated||this.updateEdge(e);let n=this.edge,s=this.calculateOffset(e);this.overflowIfRepetitiveElementsDropped=e.isOverflown(n+(e.vertical?-1:1)*s.minimum),this.overflows=this.position.overflow=e.isOverflown(n+(e.vertical?-1:1)*s.current)}getNodeContext(){return this.position}isFirstContentOfRepetitiveElementsOwner(){let e=this.getNodeContext();if(!e||!e.parent)return!1;let{formattingContext:n}=e.parent;if(!en.isInstanceOfRepetitiveElementsOwnerFormattingContext(n))return!1;let s=n.getRepetitiveElements();return s?s.isFirstContentNode(e):!1}};var zn=class{find(t){let e=We("RESOLVE_LAYOUT_PROCESSOR");for(let n=0;n<e.length;n++){let s=e[n](t);if(s)return s}throw new Error(`No processor found for a formatting context: ${t.getName()}`)}},nn=class{layout(t,e,n){return e.isFloatNodeContext(t)?e.layoutFloatOrFootnote(t):e.isBreakable(t)?e.layoutBreakableBlock(t):e.layoutUnbreakable(t)}createEdgeBreakPosition(t,e,n,s){return new tn(t.copy(),e,n,s)}startNonInlineElementNode(t){return!1}afterNonInlineElementNode(t,e){return!1}clearOverflownViewNodes(t,e,n,s){var a;if(!n.viewNode||!n.viewNode.parentNode||n.shadowType===kt.ShadowType.ROOTLESS&&gn(n))return;let o=n.viewNode;((a=o.parentElement)==null?void 0:a.localName)==="viv-ts-inner"&&(o=o.parentElement.parentElement);let i=o.parentNode;Qr(i,o),s&&i.removeChild(o)}finishBreak(t,e,n,s){let o=n||e.viewNode!=null&&e.viewNode.nodeType==1&&!e.after;return t.clearOverflownViewNodes(e,o),s&&t.layoutContext.processFragmentedBlockEdge(e),v(!0)}},fo=class{constructor(t){this.parent=t;d(this,"formattingContextType","Block")}getName(){return"Block formatting context (BlockFormattingContext)"}isFirstTime(t,e){return e}getParent(){return this.parent}saveState(){}restoreState(t){}},ai=new nn,Uh=Mr.isInstanceOfBlockFormattingContext;_e("RESOLVE_FORMATTING_CONTEXT",(r,t,e,n,s,o)=>{let i=r.parent;return!i&&r.formattingContext||i&&r.formattingContext!==i.formattingContext?null:r.establishesBFC||!r.formattingContext&&Kr(e,n,s,o)?new fo(i?i.formattingContext:null):null});_e("RESOLVE_LAYOUT_PROCESSOR",r=>r instanceof fo?ai:null);var Gn=class{constructor(){d(this,"initialBreakPositions",null);d(this,"initialStateOfFormattingContext",null);d(this,"initialPosition");d(this,"initialFragmentLayoutConstraints")}layout(t,e){return this.prepareLayout(t,e),this.tryLayout(t,e)}tryLayout(t,e){let n=A("AbstractLayoutRetryer.tryLayout");this.saveState(t,e);let s=this.resolveLayoutMode(t);return s.doLayout(t,e).then(o=>{let i=s.accept(o,e);i=s.postLayout(o,this.initialPosition,e,i),i?n.finish(o):(this.initialPosition,this.clearNodes(this.initialPosition),this.restoreState(t,e),this.tryLayout(this.initialPosition,e).thenFinish(n))}),n.result()}prepareLayout(t,e){}clearNodes(t){let e=t.viewNode||t.parent.viewNode,n;for(;n=e.lastChild;)e.removeChild(n);let s;for(;s=e.nextSibling;)s.parentNode.removeChild(s)}saveState(t,e){this.initialPosition=t.copy(),this.initialBreakPositions=[].concat(e.breakPositions),this.initialFragmentLayoutConstraints=[].concat(e.fragmentLayoutConstraints),t.formattingContext&&(this.initialStateOfFormattingContext=t.formattingContext.saveState())}restoreState(t,e){e.breakPositions=this.initialBreakPositions,e.fragmentLayoutConstraints=this.initialFragmentLayoutConstraints,t.formattingContext&&t.formattingContext.restoreState(this.initialStateOfFormattingContext)}};var Mc=class{initialState(t){return{nodeContext:t,atUnforcedBreak:!1,break:!1}}startNonDisplayableNode(t){}afterNonDisplayableNode(t){}startIgnoredTextNode(t){}afterIgnoredTextNode(t){}startNonElementNode(t){}afterNonElementNode(t){}startInlineElementNode(t){}afterInlineElementNode(t){}startNonInlineElementNode(t){}afterNonInlineElementNode(t){}finish(t){}},Ss=class{constructor(t,e){this.strategy=t;this.layoutContext=e}iterate(t){let e=this.strategy,n=e.initialState(t),s=A("LayoutIterator");return s.loopWithFrame(o=>{let i;for(;n.nodeContext;){n.nodeContext.viewNode?n.nodeContext.viewNode.nodeType!==1?ue(n.nodeContext.viewNode,n.nodeContext.whitespace)?n.nodeContext.after?i=e.afterIgnoredTextNode(n):i=e.startIgnoredTextNode(n):n.nodeContext.after?i=e.afterNonElementNode(n):i=e.startNonElementNode(n):n.nodeContext.inline?n.nodeContext.after?i=e.afterInlineElementNode(n):i=e.startInlineElementNode(n):n.nodeContext.after?i=e.afterNonInlineElementNode(n):i=e.startNonInlineElementNode(n):n.nodeContext.after?i=e.afterNonDisplayableNode(n):i=e.startNonDisplayableNode(n);let l=(i&&i.isPending()?i:v(!0)).thenAsync(()=>n.break?v(null):this.layoutContext.nextInTree(n.nodeContext,n.atUnforcedBreak));if(l.isPending()){l.then(c=>{n.break?o.breakLoop():(n.nodeContext=c,o.continueLoop())});return}else if(n.break){o.breakLoop();return}else n.nodeContext=l.get()}e.finish(n),o.breakLoop()}).then(()=>{s.finish(n.nodeContext)}),s.result()}},mn=class extends Mc{constructor(e){super();this.leadingEdge=e}startNonInlineBox(e){}endEmptyNonInlineBox(e){}endNonInlineBox(e){}initialState(e){return{nodeContext:e,atUnforcedBreak:!!this.leadingEdge&&e.after,break:!1,leadingEdge:this.leadingEdge,breakAtTheEdge:null,onStartEdges:!1,leadingEdgeContexts:[],lastAfterNodeContext:null}}processForcedBreak(e,n){let s=!e.leadingEdge&&De(e.breakAtTheEdge);if(s){let o=e.nodeContext=e.leadingEdgeContexts[0]||e.nodeContext;o.viewNode.parentNode.removeChild(o.viewNode),n.pageBreakType=e.breakAtTheEdge}return s}saveEdgeAndProcessOverflow(e,n){let s=n.checkOverflowAndSaveEdgeAndBreakPosition(e.lastAfterNodeContext,null,!0,e.breakAtTheEdge);return s&&(e.nodeContext=(e.lastAfterNodeContext||e.nodeContext).modify(),e.nodeContext.overflow=!0),s}processLayoutConstraint(e,n,s){let o=e.nodeContext,i=!n.allowLayout(o);return i&&(s.checkOverflowAndSaveEdgeAndBreakPosition(e.lastAfterNodeContext,null,!1,e.breakAtTheEdge),o=e.nodeContext=o.modify(),o.overflow=!0),i}startNonElementNode(e){e.onStartEdges=!1}startNonInlineElementNode(e){return e.leadingEdgeContexts.push(e.nodeContext.copy()),e.breakAtTheEdge=Fe(e.breakAtTheEdge,e.nodeContext.breakBefore),e.onStartEdges=!0,this.startNonInlineBox(e)}afterNonInlineElementNode(e){let n,s;return e.onStartEdges?(n=this.endEmptyNonInlineBox(e),s=n&&n.isPending()?n:v(!0),s=s.thenAsync(()=>(e.break||(e.leadingEdgeContexts=[],e.leadingEdge=!1,e.atUnforcedBreak=!1,e.breakAtTheEdge=null),v(!0)))):(n=this.endNonInlineBox(e),s=n&&n.isPending()?n:v(!0)),s.thenAsync(()=>(e.break||(e.onStartEdges=!1,e.lastAfterNodeContext=e.nodeContext.copy(),e.breakAtTheEdge=Fe(e.breakAtTheEdge,e.nodeContext.breakAfter)),v(!0)))}};var ta=[];function zh(){ta=[]}function Hc(r,t,e){return r-=e,t===0?r===0:r%t===0&&r/t>=0}var _c=class{constructor(t){this.matchers=t}matches(){return this.matchers.some(t=>t.matches())}},Uc=class{constructor(t){this.matchers=t}matches(){return this.matchers.every(t=>t.matches())}},go=class go{constructor(t,e,n){this.elementOffset=t;this.a=e;this.b=n}static registerFragmentIndex(t,e,n){let s=go.fragmentIndices;(!s[t]||s[t].priority<=n)&&(s[t]={fragmentIndex:e,priority:n})}static clearFragmentIndices(){go.fragmentIndices={}}matches(){let t=go.fragmentIndices[this.elementOffset];return t!=null&&t.fragmentIndex!=null&&Hc(t.fragmentIndex,this.a,this.b)}};d(go,"fragmentIndices",{});var Wn=go,Ns=class{static buildViewConditionMatcher(t,e){let n=e.split("_");return n[0]=="NFS"?new Wn(t,parseInt(n[1],10),parseInt(n[2],10)):(`${e}`,null)}static buildAllMatcher(t){return new Uc(t)}static buildAnyMatcher(t){return new _c(t)}};var Pu={"border-collapse":!0,"border-spacing":!0,"caption-side":!0,"clip-rule":!0,color:!0,"color-interpolation":!0,"color-rendering":!0,cursor:!0,direction:!0,"empty-cells":!0,fill:!0,"fill-opacity":!0,"fill-rule":!0,"font-kerning":!0,"font-size":!0,"font-size-adjust":!0,"font-family":!0,"font-feature-settings":!0,"font-style":!0,"font-stretch":!0,"font-variant-ligatures":!0,"font-variant-caps":!0,"font-variant-numeric":!0,"font-variant-east-asian":!0,"font-weight":!0,"glyph-orientation-vertical":!0,"hanging-punctuation":!0,hyphens:!0,"hyphenate-character":!0,"hyphenate-limit-chars":!0,"hyphenate-limit-last":!0,"image-rendering":!0,"image-resolution":!0,"letter-spacing":!0,"line-break":!0,"line-height":!0,"list-style-image":!0,"list-style-position":!0,"list-style-type":!0,marker:!0,"marker-end":!0,"marker-mid":!0,"marker-start":!0,orphans:!0,"overflow-wrap":!0,"paint-order":!0,"pointer-events":!0,quotes:!0,"ruby-align":!0,"ruby-position":!0,"shape-rendering":!0,stroke:!0,"stroke-dasharray":!0,"stroke-dashoffset":!0,"stroke-linecap":!0,"stroke-linejoin":!0,"stroke-miterlimit":!0,"stroke-opacity":!0,"stroke-width":!0,"tab-size":!0,"text-align":!0,"text-align-last":!0,"text-anchor":!0,"text-autospace":!0,"text-decoration-skip":!0,"text-decoration-skip-ink":!0,"text-emphasis-color":!0,"text-emphasis-position":!0,"text-emphasis-style":!0,"text-fill-color":!0,"text-combine-upright":!0,"text-indent":!0,"text-justify":!0,"text-orientation":!0,"text-rendering":!0,"text-shadow":!0,"text-size-adjust":!0,"text-spacing-trim":!0,"text-stroke-color":!0,"text-stroke-width":!0,"text-transform":!0,"text-underline-offset":!0,"text-underline-position":!0,"text-wrap":!0,"text-wrap-mode":!0,"text-wrap-style":!0,visibility:!0,"white-space":!0,widows:!0,"word-break":!0,"word-spacing":!0,"writing-mode":!0},qm=["image-resolution","orphans","widows"];function Yh(){return We("POLYFILLED_INHERITED_PROPS").reduce((t,e)=>t.concat(e()),[].concat(qm))}var Zm={"http://www.idpf.org/2007/ops":!0,"http://www.w3.org/1999/xhtml":!0,"http://www.w3.org/2000/svg":!0,"http://www.w3.org/1998/Math/MathML":!0},Wc=["margin-%","padding-%","border-%-width","border-%-style","border-%-color","%"],Qm=["max-%","min-%","%"],Wh=(()=>{let r=["left","right","top","bottom"],t={width:!0,height:!0,"max-width":!0,"max-height":!0,"min-width":!0,"min-height":!0};for(let e=0;e<Wc.length;e++)for(let n=0;n<r.length;n++){let s=Wc[e].replace("%",r[n]);t[s]=!0}return t})();function yo(r,t){let e={};for(let n of Wc)for(let s in r){let o=n.replace("%",s),i=n.replace("%",r[s]);e[o]=i,e[i]=o}for(let n of Qm)for(let s in t){let o=n.replace("%",s),i=n.replace("%",t[s]);e[o]=i,e[i]=o}return e}var ku=yo({"block-start":"right","block-end":"left","inline-start":"top","inline-end":"bottom"},{"block-size":"width","inline-size":"height"}),Au=yo({"block-start":"top","block-end":"bottom","inline-start":"left","inline-end":"right"},{"block-size":"height","inline-size":"width"}),Jm=yo({"block-start":"right","block-end":"left","inline-start":"bottom","inline-end":"top"},{"block-size":"width","inline-size":"height"}),eC=yo({"block-start":"top","block-end":"bottom","inline-start":"right","inline-end":"left"},{"block-size":"height","inline-size":"width"}),tC=yo({inside:"right",outside:"left"},{}),nC=yo({inside:"left",outside:"right"},{}),M=class r{constructor(t,e){this.value=t;this.priority=e}getBaseValue(){return this}filterValue(t){let e=this.value.visit(t);return e===this.value?this:new r(e,this.priority)}increaseSpecificity(t){return t==0?this:new r(this.value,this.priority+t)}evaluate(t,e,n,s){return e&&Ct(e)?this.value:gi(t,this.value,e,n,s)}isEnabled(t){return!0}},ci=class r extends M{constructor(e,n,s){super(e,n);this.condition=s}getBaseValue(){return new M(this.value,this.priority)}filterValue(e){let n=this.value.visit(e);return n===this.value?this:new r(n,this.priority,this.condition)}increaseSpecificity(e){return e==0?this:new r(this.value,this.priority+e,this.condition)}isEnabled(e){try{return!!this.condition.evaluate(e)}catch(n){V.warn(n)}return!1}};function $c(r,t,e){return(!t||e.priority>=t.priority)&&e.isEnabled(r)?e.getBaseValue():t}function sn(r,t,e,n){if(r)if(!e)delete r[t];else{let s=r[t];(!s||e.priority>=s.priority)&&(n?e.isEnabled(n)&&(r[t]=e.getBaseValue()):r[t]=e)}}var Kh={"region-id":!0,"fragment-selector-id":!0};function sC(r){return!!Kh[r]}function Xc(r){return r.charAt(0)==="_"&&r!=="_viewConditionalStyles"}function Ts(r){return r.charAt(0)!=="_"&&!Kh[r]}function Xn(r){return!!Pu[r]||Ct(r)}function pe(r,t){return r[t]}function Cn(r,t,e){e?r[t]=e:delete r[t]}function St(r,t){return r[t]}function Eo(r,t){let e=r[t];return e||(e={},r[t]=e),e}var qh=r=>{let t=r._viewConditionalStyles;return t||(t=[],r._viewConditionalStyles=t),t};function Lu(r,t){return r[t]}function Zh(r,t){let e=r[t];return e||(e=[],r[t]=e),e}function fi(r,t,e,n,s,o,i){var l,c;if([{id:s,styleKey:"_pseudos"},{id:o,styleKey:"_regions"}].forEach(u=>{if(u.id){let p=Eo(t,u.styleKey);t=p[u.id],t||(t={},p[u.id]=t)}}),i){let u=qh(t);t={},u.push({styles:t,matcher:i})}for(let u in e)if(!Xc(u))if(sC(u)){let p=Lu(e,u),h=Zh(t,u);Array.prototype.push.apply(h,p)}else{let p=pe(e,u);if(!p.isEnabled(r))continue;let h=p.increaseSpecificity(n);sn(t,u,h,r);let f=(c=(l=r.style)==null?void 0:l.validatorSet.shorthands[u])==null?void 0:c.propList;if(f)for(let g of f){let m=new M(O,h.priority);sn(t,g,m,r)}}}function Qh(r,t){let e={};for(let n=0;n<t.length;n++)fi(r,e,t[n],0,null,null,null);return e}function Jh(r,t){if(r.length>0){r.sort((n,s)=>s.getPriority()-n.getPriority());let e=null;for(let n=r.length-1;n>=0;n--)e=r[n],e.chained=t,t=e;return e}return t}var sa=class extends Kt{constructor(e,n){super();this.props=e;this.context=n;d(this,"propName","")}setPropName(e){this.propName=e}getFontSize(){let e=pe(this.props,"font-size");if(!e.value.isNumeric())return $.em;let n=e.value;if(!Bp(n.unit))throw new Error("Unexpected state");return n.num*$[n.unit]}visitNumeric(e){return this.context,this.propName==="font-size"?Ru(e,this.getFontSize(),this.context):e.unit==="em"||e.unit==="ex"||e.unit==="rem"||e.unit==="lh"||e.unit==="rlh"?ua(e,this.getFontSize(),this.context):e}visitExpr(e){return this.propName=="font-size"?gi(this.context,e,this.propName).visit(this):e}};function ua(r,t,e){let n=r.unit,s=r.num;if(n==="em"||n==="ex"){let o=$[n]/$.em;return new P(s*o*t,"px")}else return n==="rem"?new P(s*e.fontSize(),"px"):n==="rlh"?new P(s*e.rootLineHeight,"px"):r}function Ru(r,t,e){r=ua(r,t,e);let n=r.unit,s=r.num;return n==="px"?r:n==="%"?new P(s/100*t,"px"):new P(s*e.queryUnitSize(n,!1),"px")}var bn=class{apply(t){}mergeWith(t){return new jc([this,t])}clone(){return this}},Co=class extends bn{constructor(e){super();this.conditionItem=e}apply(e){e.pushConditionItem(this.conditionItem.fresh(e))}},jc=class r extends bn{constructor(e){super();this.list=e}apply(e){for(let n=0;n<this.list.length;n++)this.list[n].apply(e)}mergeWith(e){return this.list.push(e),this}clone(){return new r([].concat(this.list))}},ws=class extends bn{constructor(e,n,s,o,i){super();this.style=e;this.specificity=n;this.pseudoelement=s;this.regionId=o;this.viewConditionId=i}apply(e){fi(e.context,e.currentStyle,this.style,this.specificity,this.pseudoelement,this.regionId,e.buildViewConditionMatcher(this.viewConditionId))}},q=class extends bn{constructor(){super();d(this,"chained",null)}apply(e){this.chained.apply(e)}getPriority(){return 0}makePrimary(e){return!1}},Yc=class extends q{constructor(e){super();this.className=e}apply(e){e.currentClassNames.includes(this.className)&&this.chained.apply(e)}getPriority(){return 10}makePrimary(e){return this.chained&&e.insertInTable(e.classes,this.className,this.chained),!0}},Kc=class extends q{constructor(e){super();this.id=e}apply(e){(e.currentId==this.id||e.currentXmlId==this.id)&&this.chained.apply(e)}getPriority(){return 11}makePrimary(e){return this.chained&&e.insertInTable(e.ids,this.id,this.chained),!0}},oa=class extends q{constructor(e){super();this.localName=e}apply(e){e.currentLocalName==this.localName&&this.chained.apply(e)}getPriority(){return 8}makePrimary(e){return this.chained&&e.insertInTable(e.tags,this.localName,this.chained),!0}},qc=class extends q{constructor(e,n){super();this.ns=e;this.localName=n}apply(e){e.currentLocalName==this.localName&&e.currentNamespace==this.ns&&this.chained.apply(e)}getPriority(){return 8}makePrimary(e){if(this.chained){let n=e.nsPrefix[this.ns];n||(n=`ns${e.nsCount++}:`,e.nsPrefix[this.ns]=n);let s=n+this.localName;e.insertInTable(e.nstags,s,this.chained)}return!0}},Zc=class extends q{constructor(e,n){super();this.epubTypePatt=e;this.targetLocalName=n}apply(e){let n=e.currentElement;if(n instanceof HTMLAnchorElement&&n.hash&&n.href==n.baseURI.replace(/#.*$/,"")+n.hash){let s=n.hash.substring(1),o=n.ownerDocument.getElementById(s);if(o&&(!this.targetLocalName||o.localName==this.targetLocalName)){let i=o.getAttributeNS("http://www.idpf.org/2007/ops","type")||o.getAttribute("epub:type");i&&i.match(this.epubTypePatt)&&this.chained.apply(e)}}}},Qc=class extends q{constructor(e){super();this.ns=e}apply(e){e.currentNamespace==this.ns&&this.chained.apply(e)}};function da(r,t,e,n){if(!r)return!1;if(t!==null)return n(r,t,e);for(let s of r.getAttributeNames())if((s===e||s.endsWith(`:${e}`))&&n(r,s===e?"":r.lookupNamespaceURI(s.split(":")[0]),e))return!0;return!1}var ia=class extends q{constructor(e,n){super();this.ns=e;this.name=n}apply(e){da(e.currentElement,this.ns,this.name,(n,s,o)=>n.hasAttributeNS(s,o))&&this.chained.apply(e)}},Jc=class extends q{constructor(e,n,s){super();this.ns=e;this.name=n;this.value=s}apply(e){da(e.currentElement,this.ns,this.name,(n,s,o)=>n.getAttributeNS(s,o)==this.value)&&this.chained.apply(e)}getPriority(){return this.name=="type"&&this.ns=="http://www.idpf.org/2007/ops"?9:0}makePrimary(e){return this.name=="type"&&this.ns=="http://www.idpf.org/2007/ops"?(this.chained&&e.insertInTable(e.epubtypes,this.value,this.chained),!0):!1}},eu=class extends q{constructor(e,n){super();this.ns=e;this.name=n}apply(e){da(e.currentElement,this.ns,this.name,(n,s,o)=>!!Zm[n.getAttributeNS(s,o)])&&this.chained.apply(e)}getPriority(){return 0}makePrimary(e){return!1}},vs=class extends q{constructor(e,n,s){super();this.ns=e;this.name=n;this.regexp=s}apply(e){da(e.currentElement,this.ns,this.name,(n,s,o)=>{var i;return!!((i=n.getAttributeNS(s,o))!=null&&i.match(this.regexp))})&&this.chained.apply(e)}},tu=class extends q{constructor(e){super();this.langRegExp=e}apply(e){e.lang.match(this.langRegExp)&&this.chained.apply(e)}},ra=class extends q{constructor(){super()}apply(t){t.isFirst&&this.chained.apply(t)}getPriority(){return 6}},nu=class extends q{constructor(){super()}apply(t){t.isRoot&&this.chained.apply(t)}getPriority(){return 12}},$n=class extends q{constructor(e,n){super();this.a=e;this.b=n}matchANPlusB(e){return Hc(e,this.a,this.b)}},su=class extends $n{constructor(t,e){super(t,e)}apply(t){this.matchANPlusB(t.currentSiblingOrder)&&this.chained.apply(t)}getPriority(){return 5}},ui=class extends $n{constructor(t,e){super(t,e)}apply(t){let e=t.currentSiblingTypeCounts[t.currentNamespace][t.currentLocalName];this.matchANPlusB(e)&&this.chained.apply(t)}getPriority(){return 5}},di=class extends $n{constructor(t,e){super(t,e)}apply(t){let e=t.currentFollowingSiblingOrder;e===null&&(e=t.currentFollowingSiblingOrder=t.currentElement.parentNode.childElementCount-t.currentSiblingOrder+1),this.matchANPlusB(e)&&this.chained.apply(t)}getPriority(){return 4}},pi=class extends $n{constructor(t,e){super(t,e)}apply(t){let e=t.currentFollowingSiblingTypeCounts;if(!e[t.currentNamespace]){let n=t.currentElement;do{let s=n.namespaceURI,o=n.localName,i=e[s];i||(i=e[s]={}),i[o]=(i[o]||0)+1}while(n=n.nextElementSibling)}this.matchANPlusB(e[t.currentNamespace][t.currentLocalName])&&this.chained.apply(t)}getPriority(){return 4}},ou=class extends q{constructor(){super()}apply(t){let e=t.currentElement.firstChild;for(;e;){switch(e.nodeType){case Node.ELEMENT_NODE:return;case Node.TEXT_NODE:if(e.length>0)return}e=e.nextSibling}this.chained.apply(t)}getPriority(){return 4}},iu=class extends q{constructor(){super()}apply(t){t.currentElement.disabled===!1&&this.chained.apply(t)}getPriority(){return 5}},ru=class extends q{constructor(){super()}apply(t){t.currentElement.disabled===!0&&this.chained.apply(t)}getPriority(){return 5}},au=class extends q{constructor(){super()}apply(t){let e=t.currentElement;(e.selected===!0||e.checked===!0)&&this.chained.apply(t)}getPriority(){return 5}},ze=class extends q{constructor(e){super();this.condition=e}apply(e){if(e.conditions[this.condition])try{e.dependentConditions.push(this.condition),this.chained.apply(e)}finally{e.dependentConditions.pop()}}getPriority(){return 5}},lu=class r extends bn{constructor(){super();d(this,"applied",!1)}apply(e){this.applied=!0}clone(){let e=new r;return e.applied=this.applied,e}},hi=class extends q{constructor(e){super();d(this,"checkAppliedAction");d(this,"firstActions",[]);this.checkAppliedAction=new lu;for(let n of e)this.firstActions.push(Jh(n,this.checkAppliedAction))}apply(e){for(let n of this.firstActions)if(n.apply(e),this.checkAppliedAction.applied)break;this.checkAppliedAction.applied===this.positive()&&this.chained.apply(e),this.checkAppliedAction.applied=!1}getPriority(){return Math.max(...this.firstActions.map(e=>e instanceof q?e.getPriority():0))}positive(){return!0}relational(){return!1}},cu=class extends hi{positive(){return!1}},uu=class extends hi{constructor(e){super([]);this.selectorTexts=e}apply(e){for(let n of this.selectorTexts){let s,o;/^\s*[+~]/.test(n)?(o=e.currentElement.parentNode,s=`:scope > :nth-child(${Array.from(o.children).indexOf(e.currentElement)+1}) ${n}`):(o=e.currentElement,s=`:scope ${n}`);try{if(o.querySelector(s)){this.checkAppliedAction.apply(e);break}}catch(i){}}this.checkAppliedAction.applied&&this.chained.apply(e),this.checkAppliedAction.applied=!1}relational(){return!0}},bo=class{constructor(t,e,n){this.condition=t;this.viewConditionId=e;this.viewCondition=n}increment(t){t.increment(this.condition,this.viewCondition)}decrement(t){t.decrement(this.condition,this.viewCondition)}buildViewConditionMatcher(t){return t.buildViewConditionMatcher(this.viewConditionId)}},du=class r extends bo{constructor(t,e,n){super(t,e,n)}fresh(t){return new r(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,e){return e==0&&this.increment(t),!1}pop(t,e){return e==0?(this.decrement(t),!0):!1}},pu=class r extends bo{constructor(t,e,n){super(t,e,n)}fresh(t){return new r(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,e){return e==0?this.increment(t):e==1&&this.decrement(t),!1}pop(t,e){return e==0?(this.decrement(t),!0):(e==1&&this.increment(t),!1)}},hu=class r extends bo{constructor(e,n,s){super(e,n,s);d(this,"fired",!1)}fresh(e){return new r(this.condition,this.viewConditionId,this.buildViewConditionMatcher(e))}push(e,n){return this.fired?(this.decrement(e),!0):!1}pop(e,n){return this.fired?(this.decrement(e),!0):(n==0&&(this.fired=!0,this.increment(e)),!1)}},fu=class r extends bo{constructor(e,n,s){super(e,n,s);d(this,"fired",!1)}fresh(e){return new r(this.condition,this.viewConditionId,this.buildViewConditionMatcher(e))}push(e,n){return this.fired&&(n==-1?this.increment(e):n==0&&this.decrement(e)),!1}pop(e,n){if(this.fired){if(n==-1)return this.decrement(e),!0;n==0&&this.increment(e)}else n==0&&(this.fired=!0,this.increment(e));return!1}},gu=class{constructor(t,e){this.afterprop=t;this.element=e}fresh(t){return this}push(t,e){return!1}pop(t,e){return e==0?(t.processPseudoelementProps(this.afterprop,this.element),!0):!1}},mu=class{constructor(t){this.lang=t}fresh(t){return this}push(t,e){return!1}pop(t,e){return e==0?(t.lang=this.lang,!0):!1}},Cu=class{constructor(t){this.oldQuotes=t}fresh(t){return this}push(t,e){return!1}pop(t,e){return e==0?(t.quotes=this.oldQuotes,!0):!1}},bu=class extends Kt{constructor(e){super();this.element=e}createValueFromString(e,n){switch(n){case"url":return e?new Ue(e):new Ue("about:invalid");case"string":default:return e?new ce(e):new ce("")}}visitFunc(e){if(e.name!=="attr")return super.visitFunc(e);let n="string",s=null,o=null;if(e.values[0]instanceof K){let i=e.values[0].values;i.length>=2&&(n=i[1].stringValue()),s=i[0].stringValue()}else s=e.values[0].stringValue();return e.values.length>1?o=this.createValueFromString(e.values[1].stringValue(),n):o=this.createValueFromString(null,n),this.element&&this.element.hasAttribute(s)?this.createValueFromString(this.element.getAttribute(s),n):o}};function li(r){if(Et(r)){if(r instanceof ce)return r.stringValue();if(r instanceof K)return r.values.map(t=>li(t)).join("")}return""}var xo=class extends Kt{constructor(e,n,s){super();this.cascade=e;this.element=n;this.counterResolver=s}visitIdent(e){let n=this.cascade,s=n.quotes,o=Math.floor(s.length/2)-1;switch(e.name){case"open-quote":{let i=s[2*Math.min(o,n.quoteDepth)];return n.quoteDepth++,i}case"close-quote":return n.quoteDepth>0&&n.quoteDepth--,s[2*Math.min(o,n.quoteDepth)+1];case"no-open-quote":return n.quoteDepth++,new ce("");case"no-close-quote":return n.quoteDepth>0&&n.quoteDepth--,new ce("")}return e}format(e,n){let s=!1,o=!1,i;(i=n.match(/^upper-(.*)/))!=null?(s=!0,n=i[1]):(i=n.match(/^lower-(.*)/))!=null&&(o=!0,n=i[1]);let a="";return $h[n]?a=iC($h[n],e):Xh[n]?a=aC(Xh[n],e):jh[n]!=null?a=jh[n]:n=="decimal-leading-zero"?(a=`${e}`,a.length==1&&(a=`0${a}`)):n=="cjk-ideographic"||n=="trad-chinese-informal"?a=cC(e,lC):a=`${e}`,s?a.toUpperCase():o?a.toLowerCase():a}visitFuncCounter(e){let n=e[0].toString(),s=e.length>1?e[1].stringValue():"decimal",o=this.cascade.counters[n];if(o&&o.length){let i=o&&o.length&&o[o.length-1]||0;return new ce(this.format(i,s))}else{let i=new F(this.counterResolver.getPageCounterVal(n,a=>this.format(a||0,s)));return new K([i])}}visitFuncCounters(e){let n=e[0].toString(),s=e[1].stringValue(),o=e.length>2?e[2].stringValue():"decimal",i=this.cascade.counters[n],a=new Xe;if(i&&i.length)for(let c=0;c<i.length;c++)c>0&&a.append(s),a.append(this.format(i[c],o));let l=new F(this.counterResolver.getPageCountersVal(n,c=>{let u=[];if(c.length)for(let h=0;h<c.length;h++)u.push(this.format(c[h],o));let p=a.toString();return p.length&&u.push(p),u.length?u.join(s):this.format(0,o)}));return new K([l])}visitFuncTargetCounter(e){let n=e[0],s;n instanceof Ue?s=n.url:s=n.stringValue();let o=e[1].toString(),i=e.length>2?e[2].stringValue():"decimal",a=new F(this.counterResolver.getTargetCounterVal(s,o,l=>this.format(l||0,i)));return new K([a])}visitFuncTargetCounters(e){let n=e[0],s;n instanceof Ue?s=n.url:s=n.stringValue();let o=e[1].toString(),i=e[2].stringValue(),a=e.length>3?e[3].stringValue():"decimal",l=new F(this.counterResolver.getTargetCountersVal(s,o,c=>{let u=c.map(p=>this.format(p,a));return u.length?u.join(i):this.format(0,a)}));return new K([l])}visitFuncString(e){let n=e.length>0?e[0].stringValue():"",s=e.length>1?e[1].stringValue():"first";return new F(this.counterResolver.getNamedStringVal(n,s))}visitFuncElement(e){let n=e.length>0?e[0].stringValue():"",s=e.length>1?e[1].stringValue():"first";return new F(this.counterResolver.getRunningElementVal(n,s))}visitFuncContent(e){var o,i,a,l,c,u;let n=e.length>0?e[0].stringValue():"text",s="";switch(n){case"text":s=this.element.textContent;break;case"before":case"after":{let p=St(this.cascade.currentStyle,"_pseudos"),h=(i=(o=p==null?void 0:p[n])==null?void 0:o.content)==null?void 0:i.value;s=li(h)}break;case"first-letter":{let p=St(this.cascade.currentStyle,"_pseudos"),h=(li((l=(a=p==null?void 0:p.before)==null?void 0:a.content)==null?void 0:l.value)||this.element.textContent||li((u=(c=p==null?void 0:p.after)==null?void 0:c.content)==null?void 0:u.value)).match(Bo);s=h?h[0]:""}break}return new ce(s)}visitFuncLeader(e){let n="";if(e[0]instanceof be)switch(e[0].stringValue()){case"dotted":n=".";break;case"solid":n="_";break;case"space":n=" ";break}else e[0]instanceof ce&&(n=e[0].stringValue());return n.length==0?new ce(""):new F(new ie(null,()=>n,"viv-leader"))}visitFunc(e){switch(e.name){case"counter":if(e.values.length<=2)return this.visitFuncCounter(e.values);break;case"counters":if(e.values.length<=3)return this.visitFuncCounters(e.values);break;case"target-counter":if(e.values.length<=3)return this.visitFuncTargetCounter(e.values);break;case"target-counters":if(e.values.length<=4)return this.visitFuncTargetCounters(e.values);break;case"string":if(e.values.length<=2)return this.visitFuncString(e.values);break;case"element":if(e.values.length<=2)return this.visitFuncElement(e.values);break;case"content":if(e.values.length<=1)return this.visitFuncContent(e.values);break;case"leader":if(e.values.length<=1)return this.visitFuncLeader(e.values);break}return e}},oC=(r,t,e)=>{let n=t.filter(l=>l.after&&l.viewNode.nodeType===1&&l.viewNode.getAttribute("data-viv-leader"));for(let l of n){let y=function(Z){if(m==="rtl"){let ae="\u200F";u.textContent=(Z.startsWith(ae)?"":ae)+Z+(Z.endsWith(ae)?"":ae)}else u.textContent=Z},S=function(){let Z=e.clientLayout.getElementClientRect(p);return C.left>Z.left||C.right<Z.right||C.top>Z.top||C.bottom<Z.bottom},w=function(){let Z,ae;if(y(f),S())Z=1,ae=f.length/h.length;else{Z=f.length/h.length,ae=Z;for(let we=0;we<16;we++){let Ge=f;for(let R=0;R<1<<we;R++)Ge+=h;if(y(Ge),S()){ae+=1<<we;break}}}for(let we=0;we<16;we++){let Ge="",R=Math.floor((Z+ae)/2);for(let G=0;G<R;G++)Ge+=h;if(y(Ge),S())ae=R;else{if(Z==R)return;Z=R}}y(h)},U=function(Z){let ae=0,we=p.parentElement;for(;we&&we!==c.viewNode;)ae+=e.getComputedInsets(we)[Z],we=we.parentElement;return ae};var s=y,o=S,i=w,a=U;let c=l.parent;for(;c&&c.inline;)c=c.parent;let u=l.viewNode,p=u.parentElement,h=u.getAttribute("data-viv-leader-value"),f=u.textContent||h,{writingMode:g,direction:m,marginInlineEnd:E}=e.clientLayout.getElementComputedStyle(p);u.style.marginInlineStart="1px",y(h),p.style.display="inline-block",p.style.textIndent="0";let C=e.clientLayout.getElementClientRect(c.viewNode),x=e.clientLayout.getElementClientRect(p),N=e.parseComputedLength(E);g==="vertical-rl"||g==="vertical-lr"?(m==="rtl"?C.top+=N:C.bottom-=N,C.left=x.left,C.right=x.right,C.top=Math.min(x.top,C.top),C.bottom=Math.max(x.bottom,C.bottom)):(m==="rtl"?C.left+=N:C.right-=N,C.top=x.top,C.bottom=x.bottom,C.left=Math.min(x.left,C.left),C.right=Math.max(x.right,C.right)),w();let k=e.clientLayout.getElementClientRect(p);m=="rtl"?p.style.float="left":p.style.float="right";let I=e.clientLayout.getElementClientRect(p),Se=0;m=="rtl"?g=="vertical-rl"||g=="vertical-lr"?Se=k.top-I.top-U("top"):Se=k.left-I.left-U("left"):g=="vertical-rl"||g=="vertical-lr"?Se=I.bottom-k.bottom-U("bottom"):Se=I.right-k.right-U("right"),Se=Math.max(0,Se-.1),p.style.float="",u.style.marginInlineStart=`${Se}px`}};_e("POST_LAYOUT_BLOCK",oC);var $h={roman:[4999,1e3,"M",900,"CM",500,"D",400,"CD",100,"C",90,"XC",50,"L",40,"XL",10,"X",9,"IX",5,"V",4,"IV",1,"I"],armenian:[9999,9e3,"\u0584",8e3,"\u0583",7e3,"\u0582",6e3,"\u0581",5e3,"\u0580",4e3,"\u057F",3e3,"\u057E",2e3,"\u057D",1e3,"\u057C",900,"\u057B",800,"\u057A",700,"\u0579",600,"\u0578",500,"\u0577",400,"\u0576",300,"\u0575",200,"\u0574",100,"\u0573",90,"\u0572",80,"\u0571",70,"\u0570",60,"\u056F",50,"\u056E",40,"\u056D",30,"\u056C",20,"\u056B",10,"\u056A",9,"\u0569",8,"\u0568",7,"\u0567",6,"\u0566",5,"\u0565",4,"\u0564",3,"\u0563",2,"\u0562",1,"\u0561"],georgian:[19999,1e4,"\u10F5",9e3,"\u10F0",8e3,"\u10EF",7e3,"\u10F4",6e3,"\u10EE",5e3,"\u10ED",4e3,"\u10EC",3e3,"\u10EB",2e3,"\u10EA",1e3,"\u10E9",900,"\u10E8",800,"\u10E7",700,"\u10E6",600,"\u10E5",500,"\u10E4",400,"\u10F3",300,"\u10E2",200,"\u10E1",100,"\u10E0",90,"\u10DF",80,"\u10DE",70,"\u10DD",60,"\u10F2",50,"\u10DC",40,"\u10DB",30,"\u10DA",20,"\u10D9",10,"\u10D8",9,"\u10D7",8,"\u10F1",7,"\u10D6",6,"\u10D5",5,"\u10D4",4,"\u10D3",3,"\u10D2",2,"\u10D1",1,"\u10D0"],hebrew:[999,400,"\u05EA",300,"\u05E9",200,"\u05E8",100,"\u05E7",90,"\u05E6",80,"\u05E4",70,"\u05E2",60,"\u05E1",50,"\u05E0",40,"\u05DE",30,"\u05DC",20,"\u05DB",19,"\u05D9\u05D8",18,"\u05D9\u05D7",17,"\u05D9\u05D6",16,"\u05D8\u05D6",15,"\u05D8\u05D5",10,"\u05D9",9,"\u05D8",8,"\u05D7",7,"\u05D6",6,"\u05D5",5,"\u05D4",4,"\u05D3",3,"\u05D2",2,"\u05D1",1,"\u05D0"]},Xh={latin:"a-z",alpha:"a-z",greek:"\u03B1-\u03C1\u03C3-\u03C9",russian:"\u0430-\u0438\u043A-\u0449\u044D-\u044F"},jh={square:"\u25A0",disc:"\u2022",circle:"\u25E6",none:""};function iC(r,t){let e=r[0];if(t>e||t<=0||t!=Math.round(t))return"";let n="";for(let s=1;s<r.length;s+=2){let o=r[s],i=Math.floor(t/o);if(i>20)return"";for(t-=i*o;i>0;)n+=r[s+1],i--}return n}function rC(r){let t=[],e=0;for(;e<r.length;)if(r.substr(e+1,1)=="-"){let n=r.charCodeAt(e),s=r.charCodeAt(e+2);e+=3;for(let o=n;o<=s;o++)t.push(String.fromCharCode(o))}else t.push(r.substr(e++,1));return t}function aC(r,t){if(t<=0||t!=Math.round(t))return"";let e=rC(r),n="";do{t--;let s=t%e.length;n=e[s]+n,t=(t-s)/e.length}while(t>0);return n}var lC={formal:!1,digits:"\u96F6\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D",markers:"\u5341\u767E\u5343",negative:"\u8CA0"};function cC(r,t){if(r>9999||r<-9999)return`${r}`;if(r==0)return t.digits.charAt(0);let e=new Xe;if(r<0&&(e.append(t.negative),r=-r),r<10)e.append(t.digits.charAt(r));else if(!t.formal&&r<=19)e.append(t.markers.charAt(0)),r!=0&&e.append(t.digits.charAt(r-10));else{let n=Math.floor(r/1e3);n&&(e.append(t.digits.charAt(n)),e.append(t.markers.charAt(2)));let s=Math.floor(r/100)%10;s&&(e.append(t.digits.charAt(s)),e.append(t.markers.charAt(1)));let o=Math.floor(r/10)%10;o&&(e.append(t.digits.charAt(o)),e.append(t.markers.charAt(0)));let i=r%10;i&&e.append(t.digits.charAt(i))}return e.toString()}var Iu=1/1048576;function mo(r,t){for(let e in r)t[e]=r[e].clone()}var xu=class r{constructor(){d(this,"nsCount",0);d(this,"nsPrefix",{});d(this,"tags",{});d(this,"nstags",{});d(this,"epubtypes",{});d(this,"classes",{});d(this,"ids",{});d(this,"pagetypes",{});d(this,"order",0)}clone(){let t=new r;t.nsCount=this.nsCount;for(let e in this.nsPrefix)t.nsPrefix[e]=this.nsPrefix[e];return mo(this.tags,t.tags),mo(this.nstags,t.nstags),mo(this.epubtypes,t.epubtypes),mo(this.classes,t.classes),mo(this.ids,t.ids),mo(this.pagetypes,t.pagetypes),t.order=this.order,t}insertInTable(t,e,n){let s=t[e];s&&(n=s.mergeWith(n)),t[e]=n}createInstance(t,e,n,s){return new yu(this,t,e,n,s)}nextOrder(){return this.order+=Iu}},yu=class{constructor(t,e,n,s,o){this.context=e;this.counterListener=n;this.counterResolver=s;d(this,"code");d(this,"stack",[[],[]]);d(this,"conditions",{});d(this,"currentElement",null);d(this,"currentElementOffset",null);d(this,"currentStyle",null);d(this,"currentClassNames",null);d(this,"currentLocalName","");d(this,"currentNamespace","");d(this,"currentId","");d(this,"currentXmlId","");d(this,"currentNSTag","");d(this,"currentEpubTypes",null);d(this,"currentPageType",null);d(this,"previousPageType",null);d(this,"firstPageType",null);d(this,"isFirst",!0);d(this,"isRoot",!0);d(this,"counters",{});d(this,"counterScoping",[{}]);d(this,"quotes");d(this,"quoteDepth",0);d(this,"lang","");d(this,"siblingOrderStack",[0]);d(this,"currentSiblingOrder",0);d(this,"siblingTypeCountsStack",[{}]);d(this,"currentSiblingTypeCounts");d(this,"currentFollowingSiblingOrder",null);d(this,"followingSiblingOrderStack");d(this,"followingSiblingTypeCountsStack",[{}]);d(this,"currentFollowingSiblingTypeCounts");d(this,"viewConditions",{});d(this,"dependentConditions",[]);d(this,"elementStack");this.code=t,this.quotes=[new ce("\u201C"),new ce("\u201D"),new ce("\u2018"),new ce("\u2019")],this.currentSiblingTypeCounts=this.siblingTypeCountsStack[0],this.followingSiblingOrderStack=[this.currentFollowingSiblingOrder],this.currentFollowingSiblingTypeCounts=this.siblingTypeCountsStack[0]}pushConditionItem(t){this.stack[this.stack.length-1].push(t)}increment(t,e){this.conditions[t]=(this.conditions[t]||0)+1,e&&(this.viewConditions[t]?this.viewConditions[t].push(e):this.viewConditions[t]=[e])}decrement(t,e){this.conditions[t]--,this.viewConditions[t]&&(this.viewConditions[t]=this.viewConditions[t].filter(n=>n!==e),this.viewConditions[t].length===0&&delete this.viewConditions[t])}buildViewConditionMatcher(t){let e=null;t&&(this.currentElementOffset,e=Ns.buildViewConditionMatcher(this.currentElementOffset,t));let n=this.dependentConditions.map(s=>{let o=this.viewConditions[s];return o&&o.length>0?o.length===1?o[0]:Ns.buildAnyMatcher([].concat(o)):null}).filter(s=>s);return n.length<=0?e:e===null?n.length===1?n[0]:Ns.buildAllMatcher(n):Ns.buildAllMatcher([e].concat(n))}applyAction(t,e){let n=t[e];n&&n.apply(this)}pushRule(t,e,n){this.currentElement=null,this.currentElementOffset=null,this.currentStyle=n,this.currentNamespace="",this.currentLocalName="",this.currentId="",this.currentXmlId="",this.currentClassNames=t,this.currentNSTag="",this.currentEpubTypes=Gc,this.currentPageType=e,this.applyActions()}defineCounter(t,e){let n=this.counterScoping[this.counterScoping.length-1];n||(n={},this.counterScoping[this.counterScoping.length-1]=n),this.counters[t]?(n[t]&&this.counters[t].pop(),this.counters[t].push(e)):this.counters[t]=[e],n[t]=!0}pushCounters(t){var h,f,g,m,E,y,C;let e=b.inline,n=t.display;if(n&&(e=n.evaluate(this.context)),e===b.none){this.currentElement.setAttribute("data-viv-display-none","true"),this.counterScoping.push(null);return}else if(this.currentElement.closest("[data-viv-display-none]")){this.counterScoping.push(null);return}let s=b.inline,o=t.float;o&&(s=o.evaluate(this.context));let i=null,a=null,l=null,c=t["counter-reset"];if(c){let x=c.evaluate(this.context);x&&(i=cs(x,!0))}let u=t["counter-set"];if(u){let x=u.evaluate(this.context);x&&(l=cs(x,!1))}let p=t["counter-increment"];if(p){let x=p.evaluate(this.context);x&&(a=cs(x,!1))}if((this.currentLocalName=="ol"||this.currentLocalName=="ul")&&this.currentNamespace=="http://www.w3.org/1999/xhtml"&&(i||(i={}),i["list-item"]=((f=(h=this.currentElement)==null?void 0:h.start)!=null?f:1)-1),e===b.list_item&&(a||(a={}),a["list-item"]=(g=a["list-item"])!=null?g:1,/^\s*[-+]?\d/.test((E=(m=this.currentElement)==null?void 0:m.getAttribute("value"))!=null?E:"")&&(l||(l={}),l["list-item"]=this.currentElement.value)),((y=this.currentElement)==null?void 0:y.parentNode.nodeType)===Node.DOCUMENT_NODE&&(i||(i={}),i.footnote===void 0&&(i.footnote=0)),s===b.footnote&&(a||(a={}),a.footnote===void 0)){let x=(C=this.currentStyle["counter-increment"])==null?void 0:C.value;(!x||!(x===b.footnote||x instanceof K&&x.values.includes(b.footnote)))&&(a.footnote=1)}if(i)for(let x in i)this.defineCounter(x,i[x]);if(a)for(let x in a){this.counters[x]||this.defineCounter(x,0);let N=this.counters[x];N[N.length-1]+=a[x]}if(l)for(let x in l)if(!this.counters[x])this.defineCounter(x,l[x]);else{let N=this.counters[x];N[N.length-1]=l[x]}if(e===b.list_item){let x=this.counters["list-item"],N=x[x.length-1];t["ua-list-item-count"]=new M(new tt(N),0)}this.counterScoping.push(null)}popCounters(){let t=this.counterScoping.pop();if(t)for(let e in t){let n=this.counters[e];n&&(n.length==1?delete this.counters[e]:n.pop())}}setNamedStrings(t){let e=t["string-set"];if(!e)return;e=e.filterValue(new xo(this,this.currentElement,this.counterResolver));let n=e.value instanceof ge?e.value.values:[e.value];for(let s of n)if(s instanceof K){let o=s.values[0].stringValue(),i=s.values.slice(1).map(a=>li(a)).join("");this.counterResolver.setNamedString(o,i,this.currentElementOffset)}delete t["string-set"]}setRunningElement(t){let e=t.position;if((e==null?void 0:e.value)instanceof wt&&e.value.name==="running"){let n=e.value.values[0].stringValue();this.counterResolver.setRunningElement(n,this.currentElementOffset)}}processPseudoelementProps(t,e){this.pushCounters(t);let n=t.content;n&&(t.content=n.filterValue(new xo(this,e,this.counterResolver))),this.popCounters()}pushElement(t,e,n,s){var S,w;this.currentPageType=null,this.currentElement=e,this.currentElementOffset=s,this.currentStyle=n,this.currentNamespace=e.namespaceURI,this.currentLocalName=e.localName;let o=this.code.nsPrefix[this.currentNamespace];o?this.currentNSTag=o+this.currentLocalName:this.currentNSTag="",this.currentId=e.getAttribute("id"),this.currentXmlId=e.getAttributeNS("http://www.w3.org/XML/1998/namespace","id");let i=e.getAttribute("class");i?this.currentClassNames=i.split(/\s+/):this.currentClassNames=Gc;let a=e.getAttributeNS("http://www.idpf.org/2007/ops","type");a?this.currentEpubTypes=a.split(/\s+/):this.currentEpubTypes=Gc;let l=Oo(e);l&&(this.stack[this.stack.length-1].push(new mu(this.lang)),this.lang=l.toLowerCase());let c=this.isRoot,u=this.siblingOrderStack;this.currentSiblingOrder=++u[u.length-1],u.push(0);let p=this.siblingTypeCountsStack,h=this.currentSiblingTypeCounts=p[p.length-1],f=h[this.currentNamespace];f||(f=h[this.currentNamespace]={}),f[this.currentLocalName]=(f[this.currentLocalName]||0)+1,p.push({});let g=this.followingSiblingOrderStack;g[g.length-1]!==null?this.currentFollowingSiblingOrder=--g[g.length-1]:this.currentFollowingSiblingOrder=null,g.push(null);let m=this.followingSiblingTypeCountsStack,E=this.currentFollowingSiblingTypeCounts=m[m.length-1];E&&E[this.currentNamespace]&&E[this.currentNamespace][this.currentLocalName]--,m.push({}),this.applyActions(),this.applyVarFilter([this.currentStyle],t,e),this.applyCalcFilter(this.currentStyle,this.context),this.applyAttrFilter(e);let y=n.quotes,C=null;if(y){let k=y.evaluate(this.context);k&&(C=new Cu(this.quotes),k===b.none?this.quotes=[new ce(""),new ce("")]:k===b.auto||k===b.initial?this.quotes=[new ce("\u201C"),new ce("\u201D"),new ce("\u2018"),new ce("\u2019")]:k instanceof K&&(this.quotes=k.values))}this.pushCounters(this.currentStyle);let x=this.currentId||this.currentXmlId||e.getAttribute("name")||"";if(c||x){let k={};Object.keys(this.counters).forEach(I=>{k[I]=Array.from(this.counters[I])}),this.counterListener.countersOfId(x,k)}let N=St(this.currentStyle,"_pseudos");if(N){let k=!0;for(let I of uC){I||(k=!1);let U=N[I];U&&((I==="before"||I==="after")&&!Et((S=U.content)==null?void 0:S.value)||(I==="footnote-call"||I==="footnote-marker")&&((w=pe(this.currentStyle,"float"))==null?void 0:w.value)!==b.footnote?delete N[I]:k?this.processPseudoelementProps(U,e):this.stack[this.stack.length-2].push(new gu(U,e)))}}this.setNamedStrings(this.currentStyle),this.setRunningElement(this.currentStyle),C&&this.stack[this.stack.length-2].push(C)}applyAttrFilterInner(t,e){for(let n in e)Ts(n)&&!Ct(n)&&(e[n]=e[n].filterValue(t))}applyAttrFilter(t){let e=new bu(t),n=this.currentStyle,s=St(n,"_pseudos");for(let o in s)this.applyAttrFilterInner(e,s[o]);this.applyAttrFilterInner(e,n)}applyVarFilter(t,e,n){var l,c,u;let s=t[0],o=new wu(t,e,n),i=32,a={};for(let p in s)if(Xc(p)){let h=St(s,p);for(let f in h)this.applyVarFilter([h[f],...t],e,n)}else if(Ts(p)){let h=pe(s,p),f=h.value;for(let g=0;;g++){if(g>=i){f=O;break}let m=f.visit(o);if(o.error){f=O,o.error=!1;break}if(m===f)break;f=m}if(f!==h.value){let g=e.validatorSet,m=(l=g==null?void 0:g.shorthands[p])==null?void 0:l.clone();if(m)if(_(f)){for(let E of m.propList){let y=new M(f,h.priority),C=pe(s,E);Cn(a,E,$c(this.context,C,y))}delete s[p]}else{let E=Jt(e.scope,new Oe(f.toString(),null),"");if(E&&(E.visit(m),!m.error)){for(let y of m.propList){let C=new M((u=(c=m.values[y])!=null?c:g.defaultValues[y])!=null?u:b.initial,h.priority),x=pe(s,y);Cn(a,y,$c(this.context,x,C))}delete s[p]}}else s[p]=new M(f,h.priority)}if(a[p]){let g=pe(s,p);g&&g.value!==O&&sn(a,p,g,this.context)}}for(let p in a)s[p]=a[p]}applyCalcFilter(t,e){let n=new ca(e);for(let s in t)if(Xc(s)){let o=St(t,s);for(let i in o)this.applyCalcFilter(o[i],e)}else if(Ts(s)&&!Ct(s)){let o=pe(t,s),i=o.value.visit(n);i!==o.value&&(t[s]=new M(i,o.priority))}}applyActions(){let t;for(t=0;t<this.currentClassNames.length;t++)this.applyAction(this.code.classes,this.currentClassNames[t]);for(t=0;t<this.currentEpubTypes.length;t++)this.applyAction(this.code.epubtypes,this.currentEpubTypes[t]);this.applyAction(this.code.ids,this.currentId),this.applyAction(this.code.tags,this.currentLocalName),this.currentLocalName!=""&&this.applyAction(this.code.tags,"*"),this.applyAction(this.code.nstags,this.currentNSTag),this.currentPageType!==null&&(this.applyAction(this.code.pagetypes,this.currentPageType),this.applyAction(this.code.pagetypes,"*")),this.stack.push([]);for(let e=1;e>=-1;--e){let n=this.stack[this.stack.length-e-2];for(t=0;t<n.length;)n[t].push(this,e)?n.splice(t,1):t++}this.isFirst=!0,this.isRoot=!1}pop(){for(let t=1;t>=-1;--t){let e=this.stack[this.stack.length-t-2],n=0;for(;n<e.length;)e[n].pop(this,t)?e.splice(n,1):n++}this.stack.pop(),this.isFirst=!1}popRule(){this.pop()}popElement(t){this.siblingOrderStack.pop(),this.siblingTypeCountsStack.pop(),this.followingSiblingOrderStack.pop(),this.followingSiblingTypeCountsStack.pop(),this.pop(),this.popCounters()}},Gc=[],uC=["before","transclusion-before","footnote-call","footnote-marker","inner","first-letter","first-line","","transclusion-after","after"];var Eu=null;function ef(r){Eu=r}var xn=class extends Qt{constructor(e,n,s,o,i,a,l){super(e,n,l);this.condition=s;this.regionId=i;this.validatorSet=a;d(this,"chain",null);d(this,"specificity",0);d(this,"elementStyle",null);d(this,"conditionCount",0);d(this,"pseudoelement",null);d(this,"footnoteContent",!1);d(this,"cascade");d(this,"state");d(this,"viewConditionId",null);d(this,"insideSelectorRule");d(this,"invalid",!1);this.cascade=o?o.cascade:Eu?Eu.clone():new xu,this.state=0}insertNonPrimary(e){this.cascade.insertInTable(this.cascade.tags,"*",e)}processChain(e){let n=Jh(this.chain,e);n!==e&&n.makePrimary(this.cascade)||this.insertNonPrimary(n)}isInsideSelectorRule(e){return this.state!=0?(this.reportAndSkip(e),!0):!1}tagSelector(e,n){!n&&!e||(n&&(this.specificity+=1),n&&e?this.chain.push(new qc(e,n.toLowerCase())):n?this.chain.push(new oa(n.toLowerCase())):this.chain.push(new Qc(e)))}invalidSelector(e){V.warn(e),this.chain.push(new ze("")),this.setInvalid()}setInvalid(){this.invalid=!0;for(let e=this;e instanceof Ps;e=e.parent)e.parent.invalid=!0}classSelector(e){if(this.pseudoelement){this.invalidSelector(`::${this.pseudoelement} followed by .${e}`);return}this.specificity+=256,this.chain.push(new Yc(e))}pseudoclassSelector(e,n){if(this.pseudoelement){this.invalidSelector(`::${this.pseudoelement} followed by :${e}`);return}switch(e.toLowerCase()){case"enabled":this.chain.push(new iu);break;case"disabled":this.chain.push(new ru);break;case"checked":this.chain.push(new au);break;case"root":case"scope":this.chain.push(new nu);break;case"link":this.chain.push(new oa("a")),this.chain.push(new ia("","href"));break;case"-adapt-href-epub-type":case"href-epub-type":if(n&&n.length>=1&&typeof n[0]=="string"){let s=n[0],o=new RegExp(`(^|\\s)${an(s)}($|\\s)`),i=n[1];this.chain.push(new Zc(o,i))}else this.chain.push(new ze(""));break;case"-adapt-footnote-content":case"footnote-content":this.footnoteContent=!0;break;case"visited":case"active":case"hover":case"focus":this.chain.push(new ze(""));break;case"lang":if(n&&n.length==1&&typeof n[0]=="string"){let s=n[0];this.chain.push(new tu(new RegExp(`^${an(s.toLowerCase())}($|-)`)))}else this.chain.push(new ze(""));break;case"nth-child":case"nth-last-child":case"nth-of-type":case"nth-last-of-type":{let s=dC[e.toLowerCase()];n&&n.length==2?this.chain.push(new s(n[0],n[1])):this.chain.push(new ze(""));break}case"first-child":this.chain.push(new ra);break;case"last-child":this.chain.push(new di(0,1));break;case"first-of-type":this.chain.push(new ui(0,1));break;case"last-of-type":this.chain.push(new pi(0,1));break;case"only-child":this.chain.push(new ra),this.chain.push(new di(0,1));break;case"only-of-type":this.chain.push(new ui(0,1)),this.chain.push(new pi(0,1));break;case"empty":this.chain.push(new ou);break;case"before":case"after":case"first-line":case"first-letter":this.pseudoelementSelector(e,n);return;default:this.invalidSelector(`Unknown pseudo-class :${e}`);return}this.specificity+=256}pseudoelementSelector(e,n){switch(e){case"before":case"after":case"first-line":case"first-letter":case"footnote-call":case"footnote-marker":case"inner":case"after-if-continues":if(!this.pseudoelement)this.pseudoelement=e;else{this.invalidSelector(`Double pseudo-element ::${this.pseudoelement}::${e}`);return}break;case"first-n-lines":if(n&&n.length==1&&typeof n[0]=="number"){let s=Math.round(n[0]);if(s>0&&s==n[0]){if(!this.pseudoelement)this.pseudoelement=`first-${s}-lines`;else{this.invalidSelector(`Double pseudo-element ::${this.pseudoelement}::${e}`);return}break}}this.chain.push(new ze(""));break;case"nth-fragment":n&&n.length==2?this.viewConditionId=`NFS_${n[0]}_${n[1]}`:this.chain.push(new ze(""));break;default:this.invalidSelector(`Unknown pseudo-element ::${e}`);return}this.specificity+=1}idSelector(e){this.specificity+=65536,this.chain.push(new Kc(e))}attributeSelector(e,n,s,o){this.specificity+=256,n=n.toLowerCase(),o=o||"";let i;switch(s){case 0:i=new ia(e,n);break;case 39:i=new Jc(e,n,o);break;case 45:!o||o.match(/\s/)?i=new ze(""):i=new vs(e,n,new RegExp(`(^|\\s)${an(o)}($|\\s)`));break;case 44:i=new vs(e,n,new RegExp(`^${an(o)}($|-)`));break;case 43:o?i=new vs(e,n,new RegExp(`^${an(o)}`)):i=new ze("");break;case 42:o?i=new vs(e,n,new RegExp(`${an(o)}$`)):i=new ze("");break;case 46:o?i=new vs(e,n,new RegExp(an(o))):i=new ze("");break;case 50:if(o=="supported")i=new eu(e,n);else{this.invalidSelector(`Unsupported :: attr selector op: ${o}`);return}break;default:this.invalidSelector(`Unsupported attr selector: ${s}`);return}this.chain.push(i)}descendantSelector(){let e=`d${na++}`;this.processChain(new Co(new du(e,this.viewConditionId,null))),this.chain=[new ze(e)],this.viewConditionId=null}childSelector(){let e=`c${na++}`;this.processChain(new Co(new pu(e,this.viewConditionId,null))),this.chain=[new ze(e)],this.viewConditionId=null}adjacentSiblingSelector(){let e=`a${na++}`;this.processChain(new Co(new hu(e,this.viewConditionId,null))),this.chain=[new ze(e)],this.viewConditionId=null}followingSiblingSelector(){let e=`f${na++}`;this.processChain(new Co(new fu(e,this.viewConditionId,null))),this.chain=[new ze(e)],this.viewConditionId=null}nextSelector(){this.finishChain(),this.pseudoelement=null,this.footnoteContent=!1,this.specificity=0,this.chain=[]}startSelectorRule(){this.isInsideSelectorRule("E_CSS_UNEXPECTED_SELECTOR")||(this.state=1,this.elementStyle={},this.pseudoelement=null,this.specificity=0,this.footnoteContent=!1,this.chain=[],this.invalid=!1)}error(e,n){super.error(e,n),this.state==1&&(this.state=0),this.setInvalid()}startStylesheet(e){super.startStylesheet(e),this.state=0}startRuleBody(){this.finishChain(),super.startRuleBody(),this.state==1&&(this.state=0)}endRule(){super.endRule(),this.insideSelectorRule=0}finishChain(){this.chain&&(this.processChain(this.makeApplyRuleAction(this.specificity)),this.chain=null,this.pseudoelement=null,this.viewConditionId=null,this.footnoteContent=!1,this.specificity=0)}makeApplyRuleAction(e){let n=this.regionId;return this.footnoteContent&&(n?n="xxx-bogus-xxx":n="footnote"),new ws(this.elementStyle,e,this.pseudoelement,n,this.viewConditionId)}special(e,n){let s;this.condition?s=new ci(n,0,this.condition):s=new M(n,0),Zh(this.elementStyle,e).push(s)}property(e,n,s){this.validatorSet.validatePropertyAndHandleShorthand(e,n,s,this)}invalidPropertyValue(e,n){this.report(`E_INVALID_PROPERTY_VALUE ${e}: ${n.toString()}`)}unknownProperty(e,n){this.report(`E_INVALID_PROPERTY ${e}: ${n.toString()}`)}simpleProperty(e,n,s){e=="display"&&(n===b.oeb_page_head||n===b.oeb_page_foot)&&(this.simpleProperty("flow-options",new K([b.exclusive,b._static]),s),this.simpleProperty("flow-into",n,s),n=b.block),We("SIMPLE_PROPERTY").forEach(c=>{let p=c({name:e,value:n,important:s});e=p.name,n=p.value,s=p.important});let a=(s?this.getImportantSpecificity():this.getBaseSpecificity())+this.cascade.nextOrder(),l=this.condition?new ci(n,a,this.condition):new M(n,a);sn(this.elementStyle,e,l)}finish(){return this.cascade}startFuncWithSelector(e){let n;switch(e){case"is":n=new Ps(this);break;case"not":n=new Su(this);break;case"where":n=new Nu(this);break;case"has":n=new vu(this);break}n&&(n.startSelectorRule(),this.owner.pushHandler(n))}},dC={"nth-child":su,"nth-of-type":ui,"nth-last-child":di,"nth-last-of-type":pi},na=0,Ps=class r extends xn{constructor(e){super(e.scope,e.owner,e.condition,e,e.regionId,e.validatorSet,!1);this.parent=e;d(this,"parentChain");d(this,"chains",[]);d(this,"maxSpecificity",0);d(this,"selectorTexts",[]);this.parentChain=e.chain}nextSelector(){this.chain&&this.chains.push(this.chain),this.maxSpecificity=Math.max(this.maxSpecificity,this.specificity),this.chain=[],this.pseudoelement=null,this.viewConditionId=null,this.footnoteContent=!1,this.specificity=0}endFuncWithSelector(){this.chain&&this.chains.push(this.chain),this.chains.length>0?(this.maxSpecificity=Math.max(this.maxSpecificity,this.specificity),this.parentChain.push(this.relational()?new uu(this.selectorTexts):this.positive()?new hi(this.chains):new cu(this.chains)),this.increasingSpecificity()&&(this.parent.specificity+=this.maxSpecificity)):this.parentChain.push(new ze("")),this.owner.popHandler()}startRuleBody(){this.reportAndSkip("E_CSS_UNEXPECTED_RULE_BODY")}error(e,n){super.error(e,n),this.chain=null,this.pseudoelement=null,this.viewConditionId=null,this.footnoteContent=!1,this.specificity=0;let s=!1;for(let o=this;o instanceof r;o=o.parent)if(o.forgiving()){s=!0;break}s||this.owner.popHandler()}pushSelectorText(e){this.chain&&this.relational()&&this.selectorTexts.push(e)}positive(){return!0}increasingSpecificity(){return!0}forgiving(){return!0}relational(){return!1}},Su=class extends Ps{positive(){return!1}forgiving(){return!1}},Nu=class extends Ps{increasingSpecificity(){return!1}},vu=class extends Ps{relational(){return!0}},aa=class extends Qt{constructor(t,e){super(t,e,!1)}property(t,e,n){if(this.scope.values[t])this.error(`E_CSS_NAME_REDEFINED ${t}`,this.getCurrentToken());else{let s=t.match(/height|^(top|bottom)$/)?"vh":"vw",o=new Vt(this.scope,100,s);this.scope.defineName(t,e.toExpr(this.scope,o))}}},ks=class extends Qt{constructor(e,n,s,o,i,a){super(e,n,!1);this.condition=s;this.elementStyle=o;this.validatorSet=i;this.ruleType=a;d(this,"order");this.order=0}property(e,n,s){s?V.warn("E_IMPORTANT_NOT_ALLOWED"):this.validatorSet.validatePropertyAndHandleShorthand(e,n,s,this)}invalidPropertyValue(e,n){V.warn("E_INVALID_PROPERTY_VALUE",`${e}:`,n.toString())}unknownProperty(e,n){V.warn("E_INVALID_PROPERTY",`${e}:`,n.toString())}simpleProperty(e,n,s){let o=s?this.getImportantSpecificity():this.getBaseSpecificity();o+=this.order,this.order+=Iu;let i=this.condition?new ci(n,o,this.condition):new M(n,o);sn(this.elementStyle,e,i)}},Tu=class extends Zo{constructor(e,n){super(e);this.validatorSet=n;d(this,"elementStyle",{});d(this,"order",0)}property(e,n,s){this.validatorSet.validatePropertyAndHandleShorthand(e,n,s,this)}invalidPropertyValue(e,n){V.warn("E_INVALID_PROPERTY_VALUE",`${e}:`,n.toString())}unknownProperty(e,n){V.warn("E_INVALID_PROPERTY",`${e}:`,n.toString())}simpleProperty(e,n,s){let o=s?Ir:Rr;o+=this.order,this.order+=Iu;let i=new M(n,o);sn(this.elementStyle,e,i)}};function Vu(r,t){let e=qh(r);e&&e.forEach(n=>{n.matcher.matches()&&t(n.styles)})}function la(r,t,e){Vu(e,n=>{So(r,n,t)})}function tf(r,t,e,n){let s=new Tu(r,t),o=new Oe(n,s);try{rh(o,s,e)}catch(i){V.warn(i,"Style attribute parse error:")}return s.elementStyle}function pa(r,t,e){let n=r["writing-mode"];if(n){let s=n.evaluate(t,"writing-mode");if(s&&s!==b.inherit&&s!==b.revert&&s!==b.unset)return s===b.vertical_rl}return e}function ha(r,t,e){let n=r.direction;if(n){let s=n.evaluate(t,"direction");if(s&&s!==b.inherit&&s!==b.revert&&s!==b.unset)return s===b.rtl}return e}function fa(r,t,e,n,s){let o={};for(let i in r)Ts(i)&&(o[i]=pe(r,i));return la(o,t,r),Fu(r,e,n,(i,a)=>{So(o,a,t),la(o,t,a)}),o}function Fu(r,t,e,n){let s=St(r,"_regions");if((t||e)&&s){if(e){let o=["footnote"];t?t=t.concat(o):t=o}for(let o of t){let i=s[o];i&&n(o,i)}}}function So(r,t,e){for(let n in t)if(Ts(n)){let s=pe(t,n),o=r[n];r[n]=$c(e,o,s)}}var ga=(r,t,e,n,s,o)=>{var l,c;let i=e?n?Jm:ku:n?eC:Au,a=s?tC:nC;for(let u in r){let p=r[u];if(!p)continue;let h=(l=i[u])!=null?l:i[a[u]],f=(c=a[u])!=null?c:a[i[u]],g=h!=null?h:f,m;if(g){let E=r[g];if(E&&E.priority>p.priority||h&&f&&h!==f&&(g=f,E=r[g],E&&E.priority>p.priority))continue;m=Wh[h]?h:Wh[f]?f:u}else m=u,u.startsWith("text-align")&&(p.value===b.inside||p.value===b.outside)&&(p=new M(s===(p.value===b.inside)?b.right:b.left,p.priority));t[m]=o(u,p)}},wu=class extends Kt{constructor(e,n,s){super();this.elementStyles=e;this.styler=n;this.element=s}getVarValue(e){var s,o,i,a,l;let n=(s=this.element)!=null?s:this.styler.root;if((o=this.elementStyles)!=null&&o.length){for(let c of this.elementStyles){let u=(i=c[e])==null?void 0:i.value;if(u)return u}this.element&&(n=this.element.parentElement)}for(;n;n=n.parentElement){let c=(l=(a=this.styler.getStyle(n,!1))==null?void 0:a[e])==null?void 0:l.value;if(c)return c}return null}visitFunc(e){if(e.name!=="var")return super.visitFunc(e);let n=e.values[0]instanceof be&&e.values[0].name;if(!n||!Ct(n))return this.error=!0,O;let s=this.getVarValue(n);return s||(e.values.length<2?(this.error=!0,O):e.values.length===2?e.values[1]:new ge(e.values.slice(1)))}},ca=class extends Kt{constructor(e,n,s,o){super();this.context=e;this.resolveViewportUnit=n;this.percentRef=s;this.vertical=o}visitFunc(e){let n=super.visitFunc(e);if(e.name!=="calc")return n;let s=n.toString().replace(/^calc\b/,"-epubx-expr");if(/\d(%|em|ex|cap|ch|ic|lh|p?v[whbi]|p?vmin|p?vmax)\W|\Wvar\(\s*--/i.test(s))return n;let o=Jt(this.context.rootScope,new Oe(s,null),"");if(o instanceof F)try{let i=o.expr.evaluate(this.context);typeof i=="number"&&!isNaN(i)&&(/\d(px|in|pt|pc|cm|mm|q|rem|rlh)\W/i.test(s)?n=new P(i,"px"):/\d[a-z]/i.test(s)||(n=new tt(i)))}catch(i){V.warn(i)}return n}visitNumeric(e){return this.resolveViewportUnit&&(Al(e.unit)||Dp(e.unit))?new P(e.num*this.context.queryUnitSize(e.unit,!1,this.vertical),"px"):typeof this.percentRef=="number"&&e.unit==="%"?new P(e.num*this.percentRef/100,"px"):e}};function gi(r,t,e,n,s){try{if(t instanceof F)return t.expr instanceof ie&&(t.expr.str.startsWith("named-string-")||t.expr.str.startsWith("running-element-"))?t:ah(r,t.expr,e);if(t instanceof P||t instanceof wt||t instanceof K||t instanceof ge)return t.visit(new ca(r,!0,n,s))}catch(o){return V.warn(o),O}return t}var nf={first:!1,forceEnd:!1,allowEnd:!1,last:!1};function sf(r){let t=r instanceof Ne?r:typeof r=="string"?L(r):b.none;if(t===b.none)return nf;let e=t instanceof K?t.values:[t],n=Object.create(nf);for(let s of e)if(s instanceof be)switch(s.name){case"first":n.first=!0;break;case"force-end":n.forceEnd=!0,n.allowEnd=!1;break;case"allow-end":n.forceEnd=!1,n.allowEnd=!0;break;case"last":n.last=!0;break}return n}function of(r){return!r.first&&!r.last&&!r.forceEnd&&!r.allowEnd}var pC={trimStart:!1,spaceFirst:!1,trimEnd:!1,allowEnd:!1,trimAdjacent:!1},rf={trimStart:!1,spaceFirst:!1,trimEnd:!1,allowEnd:!0,trimAdjacent:!0},af={trimStart:!0,spaceFirst:!1,trimEnd:!0,allowEnd:!1,trimAdjacent:!0};function lf(r){let t=r instanceof Ne?r:typeof r=="string"?L(r):b.normal;if(t===b.normal)return rf;if(t===b.auto)return af;let e=t instanceof K?t.values:[t],n=Object.create(rf);for(let s of e)if(s instanceof be)switch(s.name){case"trim-both":case"trim-auto":return af;case"space-all":return pC;case"trim-start":n.trimStart=!0,n.spaceFirst=!1;break;case"space-start":n.trimStart=!1,n.spaceFirst=!1;break;case"space-first":n.trimStart=!1,n.spaceFirst=!0;break;case"trim-end":n.trimEnd=!0,n.allowEnd=!1;break;case"space-end":n.trimEnd=!1,n.allowEnd=!1;break;case"allow-end":n.trimEnd=!1,n.allowEnd=!0;break;case"trim-adjacent":n.trimAdjacent=!0;break;case"space-adjacent":n.trimAdjacent=!1;break}return n}var Bu={ideographAlpha:!1,ideographNumeric:!1},hC={ideographAlpha:!0,ideographNumeric:!0};function cf(r){let t=r instanceof Ne?r:typeof r=="string"?L(r):b.normal;if(t===b.normal||t===b.auto)return hC;if(t===b.none)return Bu;let e=t instanceof K?t.values:[t],n=Object.create(Bu);for(let s of e)if(s instanceof be)switch(s.name){case"no-autospace":return Bu;case"ideograph-alpha":n.ideographAlpha=!0;break;case"ideograph-numeric":n.ideographNumeric=!0;break}return n}function uf(r,t){return!r.ideographAlpha&&!r.ideographNumeric&&!t.trimStart&&!t.spaceFirst&&!t.trimEnd&&!t.allowEnd&&!t.trimAdjacent}function df(r){return r?(r=r.toLowerCase(),/^zh\b.*-(hant|tw|hk)\b/.test(r)?"zh-hant":/^zh\b/.test(r)?"zh-hans":/^ja\b/.test(r)?"ja":/^ko\b/.test(r)?"ko":r):null}var Ou=class{getPolyfilledInheritedProps(){return["hanging-punctuation","text-autospace","text-spacing-trim"]}preprocessSingleDocument(t){t.body&&this.preprocessForTextSpacing(t.body)}preprocessForTextSpacing(t){var n;let e=t.ownerDocument.createNodeIterator(t,NodeFilter.SHOW_TEXT);for(let s=e.nextNode();s;s=e.nextNode()){if(s.parentElement.namespaceURI!=="http://www.w3.org/1999/xhtml"||((n=s.parentElement.dataset)==null?void 0:n.mathTypeset)==="true")continue;let o=s.textContent.replace(/(?![()\[\]{}])[\p{Ps}\p{Pe}\p{Pf}\p{Pi}、。,.:;、。\u3000]\p{M}*(?=\P{M})|.(?=(?![()\[\]{}])[\p{Ps}\p{Pe}\p{Pf}\p{Pi}、。,.:;、。\u3000])|(?!\p{P})[\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF]\p{M}*(?=(?![\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF\uFF01-\uFF60])[\p{L}\p{Nd}])|(?![\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF\uFF01-\uFF60])[\p{L}\p{Nd}]\p{M}*(?=(?!\p{P})[\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF])/gsu,"$&\0").split("\0");if(o.length>1){let i=o.length-1;for(let a=0;a<i;a++)s.parentNode.insertBefore(document.createTextNode(o[a]),s);s.textContent=o[i]}}}processGeneratedContent(t,e,n,s,o,i){o=df(o);let a=cf(e),l=lf(n),c=sf(s);if(of(c)&&uf(a,l))return;this.preprocessForTextSpacing(t);let u=t.style.whiteSpace;(i?t.offsetHeight:t.offsetWidth)===0&&(t.style.whiteSpace="pre");let p=t.ownerDocument.createNodeIterator(t,NodeFilter.SHOW_TEXT),h=null,f=null;for(let g=p.nextNode();g;g=f){f=p.nextNode();let m=!h,E=!h||/\n$/.test(h.textContent),y=!f||/^\n/.test(f.textContent),C=!f;this.processTextSpacing(g,m||E,m,E,y,C,h,f,a,l,c,o,i),h=g}t.style.whiteSpace=u}postLayoutBlock(t,e){var p,h,f,g,m,E,y;let n=!t||t.fragmentIndex===1&&i(),s=n||a();function o(C){var w;if((C==null?void 0:C.nodeType)!==1)return!1;let x=C;if(x.hasAttribute(Mt))return!0;let{position:N,float:S}=(w=x.style)!=null?w:{};return N==="absolute"||N==="fixed"||S&&S!=="none"}function i(){let C=e[0];for(let x=C;;x=x.parent)if(!x||!x.inline){if((x==null?void 0:x.fragmentIndex)!==1)return!1;break}if(!C.inline)return!0;for(let x=C.viewNode.previousSibling;x;x=x.previousSibling)if(!ue(x,C.whitespace)&&!o(x))return!1;return!0}function a(){var N,S;let C=e[0],x;for(;C&&C.inline&&(x=(N=C.viewNode)==null?void 0:N.previousSibling,!(x&&(x.nodeType===3&&/^[ \t\r\n\f]*$/.test(x.textContent)&&C.whitespace!==Ze.PRESERVE&&(x=x.previousSibling),x)));)C=C.parent;for(;x;){if(x.nodeType===1){if(x.localName==="br")return!0;let w=(S=x.style)==null?void 0:S.display;if(w&&w!=="inline")return!/^(inline|ruby)\b/.test(w)}else if(x.nodeType===3){if(C.whitespace===Ze.PRESERVE){if(/\n$/.test(x.textContent))return!0}else if(C.whitespace===Ze.NEWLINE&&/\n[ \t\r\n\f]*$/.test(x.textContent))return!0}x=x.lastChild}return!1}let l=-1;for(let C=0;C<e.length;C++){let x=e[C];if(!x.after&&x.inline&&!x.display&&x.parent&&x.viewNode.parentNode&&x.viewNode.nodeType===Node.TEXT_NODE&&!ue(x.viewNode,x.whitespace)){let R=function(B){var z,X,he;if(((z=B.viewNode)==null?void 0:z.nodeType)===1)return B.viewNode.localName==="br";if(((X=B.viewNode)==null?void 0:X.nodeType)===3){if(B.whitespace===Ze.PRESERVE){if(/\n$/.test(B.viewNode.textContent))return!0}else if(B.whitespace===Ze.NEWLINE&&/\n[ \t\r\n\f]*$/.test(B.viewNode.textContent))return!0;if(((he=B.viewNode.previousElementSibling)==null?void 0:he.localName)==="br")return ue(B.viewNode,B.whitespace)}return!1},G=function(B){var z,X,he;if(((z=B.viewNode)==null?void 0:z.nodeType)===1)return B.viewNode.localName==="br";if(((X=B.viewNode)==null?void 0:X.nodeType)===3){if(B.whitespace===Ze.PRESERVE){if(/^\n/.test(B.viewNode.textContent))return!0}else if(B.whitespace===Ze.NEWLINE&&/^[ \t\r\n\f]*\n/.test(B.viewNode.textContent))return!0;if(((he=B.viewNode.nextElementSibling)==null?void 0:he.localName)==="br")return ue(B.viewNode,B.whitespace)}return!1};var c=R,u=G;let N=df((g=(h=(p=x.lang)!=null?p:x.parent.lang)!=null?h:t==null?void 0:t.lang)!=null?g:(f=t==null?void 0:t.parent)==null?void 0:f.lang),S=cf(x.inheritedProps["text-autospace"]),w=lf(x.inheritedProps["text-spacing-trim"]),k=sf(x.inheritedProps["hanging-punctuation"]);if(of(k)&&uf(S,w)||/\b(flex|grid)\b/.test(x.parent.display))continue;l<0&&(l=C);let I=null,U=null,Se=C===l,Z=C===l&&n,ae=C===l&&s,we=!1,Ge=!1;for(let B=C-1;B>=0;B--){let z=e[B];if(R(z)){ae=!0;break}if(!z.display&&z.viewNode.nodeType===Node.TEXT_NODE&&z.viewNode.textContent.length>0){I=z.viewNode;break}if(z.display&&!/^(inline|ruby)\b/.test(z.display)||((m=z.viewNode)==null?void 0:m.nodeType)===1&&(z.viewNode.localName==="br"||jt[z.viewNode.localName]))break;B===0&&(Se=!0,n&&(Z=!0,ae=!0))}for(let B=C+1;B<e.length;B++){let z=e[B];if(G(z)){we=!0;break}if(z.viewNode!==x.viewNode&&!z.display&&z.viewNode.nodeType===Node.TEXT_NODE&&z.viewNode.textContent.length>0){U=z.viewNode;break}if(z.display&&!/^(inline|ruby)\b/.test(z.display)||((E=z.viewNode)==null?void 0:E.nodeType)===1&&(z.viewNode.localName==="br"||jt[z.viewNode.localName])){B===e.length-1&&o(z.viewNode)&&(Ge=!0);break}if(B===e.length-1){we=!0,Ge=!0;for(let X=z.viewNode.nextSibling;X;X=X.nextSibling)if(!o(X)){Ge=!1;break}}}if(((y=x.parent)==null?void 0:y.display)==="inline-block"){if(!Z){let B=x.parent.viewNode.firstChild;for(;ue(B,x.whitespace);)B=B.nextSibling;x.viewNode===B&&(Z=!0)}if(!Ge){let B=x.parent.viewNode.lastChild;for(;ue(B,x.whitespace);)B=B.previousSibling;x.viewNode===B&&(Ge=!0)}}this.processTextSpacing(x.viewNode,Se,Z,ae,we,Ge,I,U,S,w,k,N,x.vertical)}}}processTextSpacing(t,e,n,s,o,i,a,l,c,u,p,h,f){let g=t.textContent,m=t.ownerDocument,E,y,C;function x(){if(e)return!0;if(!a)return!1;E||(E=m.createRange(),E.selectNode(t));let R=E.getClientRects()[0];y||(y=m.createRange(),y.selectNode(a));let G=y.getClientRects(),B=G[G.length-1];return!R||!B?!1:f?R.top<B.top+B.height-R.width||R.left+R.width<B.left+R.width/10||R.left>B.left+B.width-R.width/10:R.left<B.left+B.width-R.height||R.top>B.top+B.height-R.height/10||R.top+R.height<B.top+R.height/10}function N(){if(!l)return!1;E||(E=m.createRange(),E.selectNode(t));let R=E.getClientRects()[0];C||(C=m.createRange(),C.selectNode(l));let G=C.getClientRects()[0];return!R||!G?!1:f?R.top+R.height>G.top+R.width||R.left>G.left+G.width-R.width/10||R.left+R.width<G.left+R.width/10:R.left+R.width>G.left+R.height||R.top+R.height<G.top+R.height/10||R.top>G.top+G.height-R.height/10}let S=!1,w=!1,k=!1,I=!1,U;if(n&&p.first&&/^[\p{Ps}\p{Pf}\p{Pi}'"\u3000]\p{M}*$/u.test(g)?(U="viv-ts-open",S=!0,w=!0):i&&p.last&&/^[\p{Pe}\p{Pf}\p{Pi}'"]\p{M}*$/u.test(g)?(U="viv-ts-close",S=!0,k=!0):(p.forceEnd||p.allowEnd)&&/^[、。,.、。]\p{M}*$/u.test(g)?(U="viv-ts-close",S=!0,I=!0):(u.trimStart||u.spaceFirst||u.trimAdjacent)&&/^[‘“〝([{⦅〈〈《「『【〔〖〘〚]\p{M}*$/u.test(g)?(U="viv-ts-open",S=!0):(u.trimEnd||u.allowEnd||u.trimAdjacent)&&(/^[’”〞〟)]}⦆〉〉》」』】〕〗〙〛]\p{M}*$/u.test(g)||h==="zh-hans"&&/^[:;]\p{M}*$/u.test(g)||h!=="zh-hant"&&/^[、。,.]\p{M}*$/u.test(g))&&(U="viv-ts-close",S=!0),S){let B=function(he){let Lo=parseFloat(m.defaultView.getComputedStyle(he).fontSize)*.7;return(f?he.offsetHeight:he.offsetWidth)>Lo},X=function(){return f?R.offsetLeft:R.offsetTop};var we=B,Ge=X;if(t.parentElement.localName==="viv-ts-inner")return;let R=m.createElement(U),G=m.createElement("viv-ts-inner");R.appendChild(G),t.parentNode.insertBefore(R,t),G.appendChild(t);let z=B(G);if(z||w||k||I){if(U==="viv-ts-open"){if(w)R.className="viv-hang-first";else if(n||s)u.trimStart?R.className="viv-ts-trim":R.className="viv-ts-space";else if(!(u.trimStart||u.spaceFirst)&&x())R.className="viv-ts-space";else if(u.trimAdjacent&&a&&/[\p{Ps}\p{Pi}\p{Pe}\p{Pf}\u00B7\u2027\u30FB\u3000:;、。,.]\p{M}*$/u.test(a.textContent)&&(!/[\p{Pe}\p{Pf}]\p{M}*$/u.test(a.textContent)||a.parentElement.localName==="viv-ts-inner"&&B(a.parentElement)))R.className="viv-ts-trim";else if((u.trimStart||u.spaceFirst)&&x()){let he=X();R.className="viv-ts-auto",he===X()&&!x()&&(R.className="viv-ts-trim")}}else if(U==="viv-ts-close"){if(k)R.className=z?"viv-hang-last":"viv-hang-last viv-hang-hw";else if(i||o){let he=X();I?(R.className=z?p.allowEnd&&u.allowEnd?"viv-ts-auto":"viv-hang-end":"viv-hang-end viv-hang-hw",p.allowEnd&&he===X()&&(u.trimEnd?R.className="viv-ts-trim":u.allowEnd?(R.className="viv-hang-end",he===X()&&(R.className="")):R.className="viv-ts-space")):u.trimEnd?R.className="viv-ts-trim":u.allowEnd?(R.className="viv-ts-auto",he===X()&&(R.className="")):R.className="viv-ts-space"}else if(l&&/^[\p{Pe}\p{Pf}\u00B7\u2027\u30FB\u3000:;、。,.]/u.test(l.textContent))z&&u.trimAdjacent&&(R.className="viv-ts-trim");else if(I){let he=N(),es=he&&p.allowEnd;es||(R.className=z?"viv-hang-end":"viv-hang-end viv-hang-hw"),z?es&&u.trimEnd?R.className="viv-ts-auto":!es&&!N()?R.className="":!he&&p.allowEnd&&(u.trimEnd?(R.className="viv-ts-auto",N()||(R.className="viv-hang-end")):(R.className="viv-ts-space",N()||(u.allowEnd?(R.className="viv-ts-auto",N()||(R.className="viv-hang-end")):R.className="viv-hang-end"))):!he&&!N()&&(R.className="")}else if(u.trimEnd||u.allowEnd)if(N())u.allowEnd?R.className="viv-ts-space":R.className="viv-ts-auto";else{let he=X();R.className="viv-ts-auto",he===X()&&(R.className="")}}}}let Se=!1;function Z(R){var B;let G=(B=R==null?void 0:R.ownerDocument.defaultView)==null?void 0:B.getComputedStyle(R);return!!G&&(G.textOrientation==="upright"||G.textCombineUpright==="all"||G["-webkit-text-combine"]==="horizontal")}function ae(R,G){if(R.nodeType===1){let X=m.defaultView.getComputedStyle(R);if(parseFloat(X.marginInlineEnd)||parseFloat(X.borderInlineEndWidth)||parseFloat(X.paddingInlineEnd))return!0}let B=R.parentElement;if(B&&!B.contains(G))return ae(B,G);if(G.nodeType===1){let X=m.defaultView.getComputedStyle(G);if(parseFloat(X.marginInlineStart)||parseFloat(X.borderInlineStartWidth)||parseFloat(X.paddingInlineStart))return!0}let z=G.parentElement;return z&&!z.contains(R)?ae(R,z):!1}(c.ideographAlpha||c.ideographNumeric)&&(a&&/^(?!\p{P})[\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF]/u.test(g)&&(c.ideographAlpha&&/(?![\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF\uFF01-\uFF60])\p{L}\p{M}*$/u.test(a.textContent)||c.ideographNumeric&&/(?![\uFF01-\uFF60])\p{Nd}\p{M}*$/u.test(a.textContent))&&!(f&&Z(a.parentElement))&&!ae(a,t)&&(t.parentNode.insertBefore(m.createElement("viv-ts-thin-sp"),t),Se=!0),l&&/(?!\p{P})[\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF]\p{M}*$/u.test(g)&&(c.ideographAlpha&&/^(?![\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF\uFF01-\uFF60])\p{L}/u.test(l.textContent)||c.ideographNumeric&&/^(?![\uFF01-\uFF60])\p{Nd}/u.test(l.textContent))&&!(f&&Z(l.parentElement))&&!ae(t,l)&&(t.parentNode.insertBefore(m.createElement("viv-ts-thin-sp"),t.nextSibling),Se=!0))}registerHooks(){_e("POLYFILLED_INHERITED_PROPS",this.getPolyfilledInheritedProps.bind(this)),_e("PREPROCESS_SINGLE_DOCUMENT",this.preprocessSingleDocument.bind(this)),_e("POST_LAYOUT_BLOCK",this.postLayoutBlock.bind(this),!0)}},Du=new Ou;Du.registerHooks();function pf(r){Du.preprocessForTextSpacing(r)}function hf(r,t,e,n,s,o){Du.processGeneratedContent(r,t,e,n,s,o)}var No=new DOMParser().parseFromString('<root xmlns="http://www.pyroxy.com/ns/shadow"/>',"text/xml"),gf=["footnote-marker","first-5-lines","first-4-lines","first-3-lines","first-2-lines","first-line","first-letter","before","","after"],ma="data-adapt-pseudo";function As(r){return r.getAttribute(ma)||""}function Ci(r,t){r.setAttribute(ma,t)}var mi=class{constructor(t,e,n,s,o){this.element=t;this.style=e;this.styler=n;this.context=s;this.exprContentListener=o;d(this,"contentProcessed",{})}getStyle(t,e){let n=As(t);this.styler&&n&&n.match(/after$/)&&(this.style=this.styler.getStyle(this.element,!0),this.styler=null);let o=St(this.style,"_pseudos")[n]||{};if(n.match(/^first-/)&&!o["x-first-pseudo"]){let i=1,a;n=="first-letter"?i=0:(a=n.match(/^first-([0-9]+)-lines$/))!=null&&(i=a[1]-0),o["x-first-pseudo"]=new M(new ct(i),0)}return o}processContent(t,e,n){let s=As(t);if(!this.contentProcessed[s]){this.contentProcessed[s]=!0;let o=e.content;o&&Et(o)&&(o.visit(new dn(t,this.context,o,this.exprContentListener)),pf(t))}}};var bx=Jo.isInstanceOfAfterIfContinuesLayoutConstraint,bf=Wn.registerFragmentIndex,xx=Wn.clearFragmentIndices,Ca=class{constructor(t,e){this.sourceNode=t;this.styler=e}createElement(t,e){let s=e.viewNode.ownerDocument.createElement("div"),o=new Is(t,s,e),i=o.getColumn().pageBreakType;return o.getColumn().pageBreakType=null,o.layout(this.createNodePositionForPseudoElement(),!0).thenAsync(()=>{this.styler.contentProcessed["after-if-continues"]=!1,o.getColumn().pageBreakType=i;let a=s.firstChild;return T(a,"display","block"),v(a)})}createNodePositionForPseudoElement(){let t=No.createElementNS("http://www.w3.org/1999/xhtml","div");Ci(t,"after-if-continues");let e=this.createShadowContext(t),s={steps:[{node:t,shadowType:e.type,shadowContext:e,nodeShadow:null,shadowSibling:null}],offsetInNode:0,after:!1,preprocessedTextContent:null};return new pt(s)}createShadowContext(t){return new bs(this.sourceNode,t,null,null,null,kt.ShadowType.ROOTED,this.styler)}},Mu=class r{constructor(t,e,n){this.nodeContext=t;this.afterIfContinues=e;this.pseudoElementHeight=n;d(this,"flagmentLayoutConstraintType","AfterIfContinue")}allowLayout(t,e,n){return!(e&&!t||t&&t.overflow)}nextCandidate(t){return!1}postLayout(t,e,n,s){}finishBreak(t,e){return this.getRepetitiveElements().affectTo(t)?this.afterIfContinues.createElement(e,this.nodeContext).thenAsync(n=>(this.nodeContext.viewNode.appendChild(n),v(!0))):v(!0)}getRepetitiveElements(){return new _u(this.nodeContext,this.pseudoElementHeight)}equalsTo(t){return t instanceof r?this.afterIfContinues==t.afterIfContinues:!1}getPriorityOfFinishBreak(){return 9}},_u=class{constructor(t,e){this.nodeContext=t;this.pseudoElementHeight=e}calculateOffset(t){return this.affectTo(t)?this.pseudoElementHeight:0}calculateMinimumOffset(t){return this.calculateOffset(t)}affectTo(t){if(!t)return!1;let e=t.shadowContext?t.shadowContext.owner:t.sourceNode;if(e===this.nodeContext.sourceNode)return!!t.after;for(let n=e.parentNode;n;n=n.parentNode)if(n===this.nodeContext.sourceNode)return!0;return!1}};function xf(r,t){if(!r||!r.afterIfContinues||r.after||t.isFloatNodeContext(r))return v(r);let e=r.afterIfContinues;return e.createElement(t,r).thenAsync(n=>{let s=gC(r,t,n);return t.fragmentLayoutConstraints.push(new Mu(r,e,s)),v(r)})}function Gu(r,t){return r.thenAsync(e=>xf(e,t))}function fC(r,t){let e=A("processAfterIfContinuesOfAncestors"),n=r;return e.loop(()=>{if(n!==null){let s=xf(n,t);return n=n.parent,s.thenReturn(!0)}else return v(!1)}).then(()=>{e.finish(!0)}),e.result()}function gC(r,t,e){let n=r.viewNode;n.appendChild(e);let s=ri(e,t,r.vertical);return n.removeChild(e),s}var ba=class{constructor(t){this.constraints=t}allowLayout(t){return this.constraints.every(e=>e.allowLayout(t))}},Ls=class extends Es{constructor(e,n){super();this.checkPoints=e;this.penalty=n;d(this,"alreadyEvaluated",!1);d(this,"breakNodeContext",null)}findAcceptableBreak(e,n){return n<this.getMinBreakPenalty()?null:(this.alreadyEvaluated||(this.breakNodeContext=e.findBoxBreakPosition(this,n>0),this.alreadyEvaluated=!!this.breakNodeContext||n>0||!!e.pseudoParent),this.breakNodeContext)}getMinBreakPenalty(){return this.penalty}getNodeContext(){return this.alreadyEvaluated?this.breakNodeContext:this.checkPoints[this.checkPoints.length-1]}};var Rs=class extends uo{constructor(e,n,s,o,i){super(e);this.layoutContext=n;this.clientLayout=s;this.layoutConstraint=o;this.pageFloatLayoutContext=i;d(this,"last");d(this,"viewDocument");d(this,"flowRootFormattingContext",null);d(this,"isFloat",!1);d(this,"isFootnote",!1);d(this,"startEdge",0);d(this,"endEdge",0);d(this,"beforeEdge",0);d(this,"afterEdge",0);d(this,"footnoteEdge",0);d(this,"box",null);d(this,"chunkPositions",null);d(this,"bands",null);d(this,"overflown",!1);d(this,"breakPositions",null);d(this,"pageBreakType",null);d(this,"forceNonfitting",!0);d(this,"leftFloatEdge",0);d(this,"rightFloatEdge",0);d(this,"bottommostFloatTop",0);d(this,"stopAtOverflow",!0);d(this,"lastAfterPosition",null);d(this,"fragmentLayoutConstraints",[]);d(this,"pseudoParent",null);d(this,"nodeContextOverflowingDueToRepetitiveElements",null);d(this,"blockDistanceToBlockEndFloats",NaN);d(this,"breakAtTheEdgeBeforeFloat",null);this.last=e.lastChild,this.viewDocument=e.ownerDocument,i.setContainer(this)}getTopEdge(){return this.vertical?this.rtl?this.endEdge:this.startEdge:this.beforeEdge}getBottomEdge(){return this.vertical?this.rtl?this.startEdge:this.endEdge:this.afterEdge}getLeftEdge(){return this.vertical?this.afterEdge:this.rtl?this.endEdge:this.startEdge}getRightEdge(){return this.vertical?this.beforeEdge:this.rtl?this.startEdge:this.endEdge}isFloatNodeContext(e){return!!e.floatSide&&(!this.isFloat||!!e.parent)}stopByOverflow(e){return this.stopAtOverflow&&!!e&&e.overflow}isOverflown(e){return this.vertical?e<this.footnoteEdge:e>this.footnoteEdge}getExclusions(){let e=this.pageFloatLayoutContext.getFloatFragmentExclusions();return this.exclusions.concat(e)}openAllViews(e){let n=A("openAllViews"),s=e.steps;this.layoutContext.setViewRoot(this.element,this.isFootnote);let o=s.length-1,i=null;return n.loop(()=>{for(;o>=0;){let a=i,l=s[o];if(i=po(l,a),o===s.length-1&&!i.formattingContext&&(i.formattingContext=this.flowRootFormattingContext),o==0&&(i.offsetInNode=this.calculateOffsetInNodeForNodeContext(e),i.after=e.after,i.preprocessedTextContent=e.preprocessedTextContent,i.after))break;let c=this.layoutContext.setCurrent(i,o==0&&i.offsetInNode==0);if(o--,c.isPending())return c}return v(!1)}).then(()=>{n.finish(i)}),n.result()}calculateOffsetInNodeForNodeContext(e){return e.preprocessedTextContent?vh(e.preprocessedTextContent,e.offsetInNode):e.offsetInNode}maybePeelOff(e,n){var s,o;if(e.firstPseudo&&e.inline&&!e.after&&e.firstPseudo.count==0&&e.viewNode.nodeType!=1){let i=e.viewNode.textContent,a=i.match(Bo),l=a?a[0].length:0;if(!a&&((s=e.sourceNode)==null?void 0:s.nodeType)===3&&((o=e.sourceNode.nextSibling)==null?void 0:o.nodeType)===3&&i===e.sourceNode.textContent){let c=i+e.sourceNode.nextSibling.textContent,u=c.match(Bo);if(u){let p=u[0];l=p.length,e.sourceNode.textContent=p,e.viewNode.textContent=p,e.sourceNode.nextSibling.textContent=c.substr(l)}}return this.layoutContext.peelOff(e,l)}return v(e)}buildViewToNextBlockEdge(e,n){let s=!1,o=A("buildViewToNextBlockEdge");return o.loopWithFrame(i=>{var a;e.viewNode&&!gn(e)&&((a=e.viewNode.parentElement)==null?void 0:a.namespaceURI)==="http://www.w3.org/1999/xhtml"&&n.push(e.copy()),this.maybePeelOff(e,0).then(l=>{let c=l;c!==e&&(e=c,gn(e)||n.push(e.copy())),this.nextInTree(e).then(u=>{if(e=u,!e){i.breakLoop();return}(s||!this.layoutConstraint.allowLayout(e))&&(s=!0,e=e.modify(),e.overflow=!0),this.isFloatNodeContext(e)&&(_n(e.floatReference)||e.floatSide==="footnote")?this.layoutFloatOrFootnote(e).then(p=>{if(e=p,this.pageFloatLayoutContext.isInvalidated()&&(e=null),!e){i.breakLoop();return}i.continueLoop()}):e.inline?i.continueLoop():i.breakLoop()})})}).then(()=>{o.finish(e)}),o.result()}nextInTree(e,n){let s=this.layoutContext.nextInTree(e,n);return Gu(s,this)}buildDeepElementView(e){if(!e.viewNode)return v(e);let n=[],s=e.sourceNode,o=A("buildDeepElementView");return o.loopWithFrame(i=>{e.viewNode&&e.inline&&!gn(e)?n.push(e.copy()):(n.length>0&&this.postLayoutBlock(e,n),n=[]),this.maybePeelOff(e,0).then(a=>{let l=a;if(l!==e){let c=l;for(;c&&c.sourceNode!=s;)c=c.parent;if(c==null){e=l,i.breakLoop();return}gn(l)||n.push(l.copy())}this.nextInTree(l).then(c=>{e=c,!e||e.sourceNode==s?i.breakLoop():this.layoutConstraint.allowLayout(e)?i.continueLoop():(e=e.modify(),e.overflow=!0,this.stopAtOverflow?i.breakLoop():i.continueLoop())})})}).then(()=>{n.length>0&&this.postLayoutBlock(e,n),o.finish(e)}),o.result()}createFloat(e,n,s,o){let i=this.viewDocument.createElement("div");return this.vertical?(o>=this.height&&(o-=.1),o<1&&(o=0),T(i,"height",`${s}px`),T(i,"width",`${o}px`)):(s>=this.width&&(s-=.1),s<1&&(s=0),T(i,"width",`${s}px`),T(i,"height",`${o}px`)),T(i,"float",n),T(i,"clear",n),this.element.insertBefore(i,e),i}killFloats(){let e=this.element.firstChild;for(;e;){let n=e.nextSibling;if(e.nodeType==1){let s=e,o=s.style.cssFloat;if(o=="left"||o=="right"||o==="none")this.element.removeChild(s);else break}e=n}}createFloats(){let e=this.element.firstChild,n=this.bands,s=this.vertical?this.getTopEdge():this.getLeftEdge(),o=this.vertical?this.getBottomEdge():this.getRightEdge(),i=null;for(let a of n){let l=a.y2-a.y1;a.left=this.createFloat(e,"left",a.x1-s,l),a.right=this.createFloat(e,"right",o-a.x2,l),a.x1<o&&a.x2>s?i=a:i||T(a.right,"float","none")}if(i){let a=n[n.length-1],l=this.vertical?-this.getLeftEdge():this.getBottomEdge();i!==a&&a.y2>=l&&(this.footnoteEdge=this.vertical?-i.y2:i.y2)}}calculateEdge(e,n,s,o){let i;if(e&&fn(e.viewNode))return NaN;if(e&&e.after&&!e.inline&&(i=Un(e,this.clientLayout,0,this.vertical),!isNaN(i)))return i;e=n[s];let a=o-e.boxOffset;for(;;){if(i=Un(e,this.clientLayout,a,this.vertical),!isNaN(i))return i;if(a>0){a--;continue}if(s--,s<0)return this.beforeEdge;e=n[s],e.viewNode.nodeType!=1&&(a=e.viewNode.textContent.length)}}parseComputedLength(e){let n=e.match(/^(-?[0-9]*(\.[0-9]*)?)px$/);return n?this.clientLayout.adjustLengthValue(parseFloat(n[0])):0}getComputedMargin(e){let n=this.clientLayout.getElementComputedStyle(e),s=new Qs(0,0,0,0);return n&&(s.left=this.parseComputedLength(n.marginLeft),s.top=this.parseComputedLength(n.marginTop),s.right=this.parseComputedLength(n.marginRight),s.bottom=this.parseComputedLength(n.marginBottom)),s}getComputedPaddingBorder(e){let n=this.clientLayout.getElementComputedStyle(e),s=new Qs(0,0,0,0);return n&&(s.left=this.parseComputedLength(n.borderLeftWidth)+this.parseComputedLength(n.paddingLeft),s.top=this.parseComputedLength(n.borderTopWidth)+this.parseComputedLength(n.paddingTop),s.right=this.parseComputedLength(n.borderRightWidth)+this.parseComputedLength(n.paddingRight),s.bottom=this.parseComputedLength(n.borderBottomWidth)+this.parseComputedLength(n.paddingBottom)),s}getComputedInsets(e){let n=this.clientLayout.getElementComputedStyle(e),s=new Qs(0,0,0,0);if(n){if(n.boxSizing=="border-box")return this.getComputedMargin(e);s.left=this.parseComputedLength(n.marginLeft)+this.parseComputedLength(n.borderLeftWidth)+this.parseComputedLength(n.paddingLeft),s.top=this.parseComputedLength(n.marginTop)+this.parseComputedLength(n.borderTopWidth)+this.parseComputedLength(n.paddingTop),s.right=this.parseComputedLength(n.marginRight)+this.parseComputedLength(n.borderRightWidth)+this.parseComputedLength(n.paddingRight),s.bottom=this.parseComputedLength(n.marginBottom)+this.parseComputedLength(n.borderBottomWidth)+this.parseComputedLength(n.paddingBottom)}return s}setComputedInsets(e,n){let s=this.clientLayout.getElementComputedStyle(e);s&&(n.marginLeft=this.parseComputedLength(s.marginLeft),n.borderLeft=this.parseComputedLength(s.borderLeftWidth),n.paddingLeft=this.parseComputedLength(s.paddingLeft),n.marginTop=this.parseComputedLength(s.marginTop),n.borderTop=this.parseComputedLength(s.borderTopWidth),n.paddingTop=this.parseComputedLength(s.paddingTop),n.marginRight=this.parseComputedLength(s.marginRight),n.borderRight=this.parseComputedLength(s.borderRightWidth),n.paddingRight=this.parseComputedLength(s.paddingRight),n.marginBottom=this.parseComputedLength(s.marginBottom),n.borderBottom=this.parseComputedLength(s.borderBottomWidth),n.paddingBottom=this.parseComputedLength(s.paddingBottom))}setComputedWidthAndHeight(e,n){let s=this.clientLayout.getElementComputedStyle(e);s&&(n.width=this.parseComputedLength(s.width),n.height=this.parseComputedLength(s.height))}layoutUnbreakable(e){return this.buildDeepElementView(e)}layoutFloat(e){let n=A("layoutFloat"),s=e.viewNode,o=Rc(e.floatSide,e.vertical,e.direction,this.layoutContext.page.side);return T(s,"float","none"),T(s,"display","inline-block"),T(s,"vertical-align","top"),this.buildDeepElementView(e).then(i=>{let a=this.clientLayout.getElementClientRect(s),l=this.getComputedMargin(s),c=new He(a.left-l.left,a.top-l.top,a.right+l.right,a.bottom+l.bottom),u=this.rtl?this.endEdge:this.startEdge,p=this.rtl?this.startEdge:this.endEdge,h=e.parent;for(;h&&h.inline;)h=h.parent;if(h){let S=h.viewNode.ownerDocument.createElement("div");S.style.left="0px",S.style.top="0px",this.vertical?(S.style.bottom="0px",S.style.width="1px"):(S.style.right="0px",S.style.height="1px"),h.viewNode.appendChild(S);let w=this.clientLayout.getElementClientRect(S);u=Math.max(this.rtl?this.getEndEdge(w):this.getStartEdge(w),u),p=Math.min(this.rtl?this.getStartEdge(w):this.getEndEdge(w),p),h.viewNode.removeChild(S);let k=this.vertical?c.y2-c.y1:c.x2-c.x1;o=="left"?p=Math.max(p,u+k):u=Math.min(u,p-k),h!==e.parent&&!e.firstPseudo&&(h.viewNode.appendChild(s),s.setAttribute("data-vivliostyle-float-box-moved","true"))}let f=new He(u,this.getBoxDir()*this.beforeEdge,p,this.getBoxDir()*this.afterEdge),g=c;this.vertical&&(g=Js(c));let m=this.getBoxDir();if(g.y1<this.bottommostFloatTop*m){let S=g.y2-g.y1;g.y1=this.bottommostFloatTop*m,g.y2=g.y1+S}jp(f,this.bands,g,o),this.vertical&&(c=Er(g));let E=this.getComputedInsets(s);T(s,"width",`${c.x2-c.x1-E.left-E.right}px`),T(s,"height",`${c.y2-c.y1-E.top-E.bottom}px`),T(s,"position","absolute"),e.display,T(s,"display",e.display);let y,C=null;if(h&&(h.containingBlockForAbsolute?C=h:C=h.getContainingBlockForAbsolute()),C){let S=C.viewNode.ownerDocument.createElement("div");S.style.position="absolute",C.vertical?S.style.right="0":S.style.left="0",S.style.top="0",C.viewNode.appendChild(S),y=this.clientLayout.getElementClientRect(S),C.viewNode.removeChild(S)}else y={left:this.getLeftEdge()-this.paddingLeft,right:this.getRightEdge()+this.paddingRight,top:this.getTopEdge()-this.paddingTop};(C?C.vertical:this.vertical)?T(s,"right",`${y.right-c.x2}px`):T(s,"left",`${c.x1-y.left}px`),T(s,"top",`${c.y1-y.top}px`),e.clearSpacer&&(e.clearSpacer.parentNode.removeChild(e.clearSpacer),e.clearSpacer=null);let x=this.vertical?c.x1:c.y2,N=this.vertical?c.x2:c.y1;!this.isOverflown(x)||this.breakPositions.length==0?(this.killFloats(),f=new He(this.getLeftEdge(),this.getTopEdge(),this.getRightEdge(),this.getBottomEdge()),this.vertical&&(f=Js(f)),Yp(f,this.bands,g,null,o),this.createFloats(),o=="left"?this.leftFloatEdge=x:this.rightFloatEdge=x,this.bottommostFloatTop=N,this.updateMaxReachedAfterEdge(x),n.finish(i)):(e=e.modify(),e.overflow=!0,n.finish(e))}),n.result()}setupFloatArea(e,n,s,o,i,a){let l=this.pageFloatLayoutContext,c=l.getContainer(n),u=e.element;c.element.parentNode.appendChild(u),e.isFloat=!0,e.originX=c.originX,e.originY=c.originY,e.vertical=c.vertical,e.rtl=c.rtl,e.marginLeft=e.marginRight=e.marginTop=e.marginBottom=0,e.borderLeft=e.borderRight=e.borderTop=e.borderBottom=0,e.paddingLeft=e.paddingRight=e.paddingTop=e.paddingBottom=0,e.exclusions=(c.exclusions||[]).concat(),e.forceNonfitting=!l.hasFloatFragments(),e.innerShape=null;let p=c.getPaddingRect();e.setHorizontalPosition(p.x1-c.originX,p.x2-p.x1),e.setVerticalPosition(p.y1-c.originY,p.y2-p.y1),i.adjustPageFloatArea(e,c,this),e.init();let h=!!l.setFloatAreaDimensions(e,n,s,o,!0,!l.hasFloatFragments(),a);return h?(e.killFloats(),e.init()):c.element.parentNode.removeChild(u),h}createPageFloatArea(e,n,s,o,i){let a=this.element.ownerDocument.createElement("div");T(a,"position","absolute");let l=this.pageFloatLayoutContext.getPageFloatLayoutContext(e.floatReference),c=new pn(null,de.COLUMN,null,this.pageFloatLayoutContext.flowName,e.nodePosition,null,null),u=l.getContainer(),p=new zu(n,a,this.layoutContext.clone(),this.clientLayout,this.layoutConstraint,c,u);return c.setContainer(p),this.setupFloatArea(p,e.floatReference,n,s,o,i)?p:null}layoutSinglePageFloatFragment(e,n,s,o,i,a,l){let c=this.pageFloatLayoutContext;e=(l?l.continuations:[]).concat(e);let p=e[0].float,h=c.getPageFloatPlacementCondition(p,n,s),f=this.createPageFloatArea(p,n,a,i,h),g={floatArea:f,pageFloatFragment:null,newPosition:null};if(!f)return v(g);let m=A("layoutSinglePageFloatFragment"),E=!1,y=0;return m.loopWithFrame(C=>{if(y>=e.length){C.breakLoop();return}let x=e[y],N=new pt(x.nodePosition);f.layout(N,!0).then(S=>{g.newPosition=S,!S||o?(y++,C.continueLoop()):(E=!0,C.breakLoop())})}).then(()=>{if(!E){let C=c.setFloatAreaDimensions(f,p.floatReference,n,a,!1,o,h);if(!C)E=!0;else{let x=i.createPageFloatFragment(e,C,f,!!g.newPosition);c.addPageFloatFragment(x,!0),g.pageFloatFragment=x}}m.finish(g)}),m.result()}layoutPageFloatInner(e,n,s,o){let i=this.pageFloatLayoutContext,a=e.float;i.stashEndFloatFragments(a);function l(u,p){p?i.removePageFloatFragment(p,!0):u&&u.element.parentNode.removeChild(u.element),i.restoreStashedFragments(a.floatReference),i.deferPageFloat(e)}let c=A("layoutPageFloatInner");return this.layoutSinglePageFloatFragment([e],a.floatSide,a.clearSide,!i.hasFloatFragments(),n,s,o).then(u=>{let p=u.floatArea,h=u.pageFloatFragment,f=u.newPosition;h?this.layoutStashedPageFloats(a.floatReference,[o]).then(g=>{if(g){if(i.addPageFloatFragment(h),i.discardStashedFragments(a.floatReference),f){let m=new si(a,f.primary);i.deferPageFloat(m)}c.finish(!0)}else l(p,h),c.finish(!1)}):(l(p,h),c.finish(!1))}),c.result()}layoutStashedPageFloats(e,n){let s=this.pageFloatLayoutContext,o=s.getStashedFloatFragments(e),i=[],a=[],l=!1,c=A("layoutStashedPageFloats"),u=0;return c.loopWithFrame(p=>{if(u>=o.length){p.breakLoop();return}let h=o[u];if(n.includes(h)){u++,p.continueLoop();return}let f=new _t().findByFloat(h.continuations[0].float);this.layoutSinglePageFloatFragment(h.continuations,h.floatSide,null,!1,f,null).then(g=>{let m=g.floatArea;m&&i.push(m);let E=g.pageFloatFragment;E?(a.push(E),u++,p.continueLoop()):(l=!0,p.breakLoop())})}).then(()=>{l?(a.forEach(p=>{s.removePageFloatFragment(p,!0)}),i.forEach(p=>{let h=p.element;h&&h.parentNode&&h.parentNode.removeChild(h)})):o.forEach(p=>{let h=p.area.element;h&&h.parentNode&&h.parentNode.removeChild(h)}),c.finish(!l)}),c.result()}setFloatAnchorViewNode(e){let n=e.viewNode.parentNode,s=n.ownerDocument.createElement("span");s.setAttribute(Mt,"1"),e.floatSide==="footnote"&&this.layoutContext.applyPseudoelementStyle(e,"footnote-call",s),n.appendChild(s),n.removeChild(e.viewNode);let o=e.modify();return o.after=!0,o.viewNode=s,o}resolveFloatReferenceFromColumnSpan(e,n,s){let o=A("resolveFloatReferenceFromColumnSpan"),i=this.pageFloatLayoutContext,a=i.getPageFloatLayoutContext(de.REGION);return i.getContainer().width<a.getContainer().width&&e===de.COLUMN?n===b.auto?this.buildDeepElementView(s.copy()).then(c=>{let u=c.viewNode,p=ro(this.clientLayout,u,["min-content inline size"])["min-content inline size"],h=this.getComputedMargin(u);this.vertical?p+=h.top+h.bottom:p+=h.left+h.right,p>this.width?o.finish(de.REGION):o.finish(e)}):n===b.all?o.finish(de.REGION):o.finish(e):o.finish(e),o.result()}layoutPageFloat(e){let n=this.pageFloatLayoutContext,s=new _t().findByNodeContext(e),o,i=n.findPageFloatByNodePosition(e.toNodePosition());return i?o=v(i):o=s.createPageFloat(e,n,this),o.thenAsync(a=>{let l=xs(e,0),c=this.setFloatAnchorViewNode(e),u=s.findPageFloatFragment(a,n),p=new si(a,l);if(u&&u.hasFloat(a))return n.registerPageFloatAnchor(a,c.viewNode),v(c);if(n.isForbidden(a)||n.hasPrecedingFloatsDeferredToNext(a))return n.deferPageFloat(p),n.registerPageFloatAnchor(a,c.viewNode),v(c);if(this.nodeContextOverflowingDueToRepetitiveElements)return v(null);{let h=Un(c,this.clientLayout,0,this.vertical);return this.isOverflown(h)?v(c):this.layoutPageFloatInner(p,s,h,u).thenAsync(f=>f?v(null):(n.registerPageFloatAnchor(a,c.viewNode),v(c)))}})}processLineStyling(e,n,s){let o=A("processLineStyling"),i=s.concat([]);s.splice(0,s.length);let a=0,l=e.firstPseudo;return l.count==0&&(l=l.outer),o.loopWithFrame(c=>{if(!l){c.breakLoop();return}let u=this.findLinePositions(i),p=l.count-a;if(u.length<=p){c.breakLoop();return}let h=this.findAcceptableBreakInside(i,u[p-1],!0);if(h==null){c.breakLoop();return}this.finishBreak(h,!1,!1).then(()=>{a+=p,this.layoutContext.peelOff(h,0).then(f=>{e=f,l=e.firstPseudo,i=[],this.buildViewToNextBlockEdge(e,i).then(g=>{n=g,c.continueLoop()})})})}).then(()=>{Array.prototype.push.apply(s,i),o.finish(n)}),o.result()}isLoneImage(e){return e.length!=2&&this.breakPositions.length>0?!1:e[0].sourceNode==e[1].sourceNode&&jt[e[0].sourceNode.localName]}getTrailingMarginEdgeAdjustment(e){let n=0,s=0;for(let o=e.length-1;o>=0;o--){let i=e[o];if(!i.after||!i.viewNode||i.viewNode.nodeType!=1)break;let a=this.getComputedMargin(i.viewNode),l=this.vertical?-a.left:a.bottom;l>0?n=Math.max(n,l):s=Math.min(s,l)}return n+s}layoutBreakableBlock(e){let n=A("layoutBreakableBlock"),s=[];return this.buildViewToNextBlockEdge(e,s).then(o=>{let i=s.length-1;if(i<0){n.finish(o);return}this.postLayoutBlock(o,s);let a=this.calculateEdge(o,s,i,s[i].boxOffset),l=!1;if(!o||!fn(o.viewNode)){let u=Hn(o,this.collectElementsOffset());l=this.isOverflown(a+(this.vertical?-1:1)*u.minimum),this.isOverflown(a+(this.vertical?-1:1)*u.current)&&!this.nodeContextOverflowingDueToRepetitiveElements&&(this.nodeContextOverflowingDueToRepetitiveElements=o)}o==null&&(a+=this.getTrailingMarginEdgeAdjustment(s)),this.updateMaxReachedAfterEdge(a);let c;e.firstPseudo?c=this.processLineStyling(e,o,s):c=v(o),c.then(u=>{s.length>0&&(this.saveBoxBreakPosition(s),l&&!this.isLoneImage(s)&&u&&(u=u.modify(),u.overflow=!0)),n.finish(u)})}),n.result()}postLayoutBlock(e,n){We("POST_LAYOUT_BLOCK").forEach(o=>{o(e,n,this)})}findEndOfLine(e,n,s){let o=this.vertical?e-1:e+1,i=0,a=n[0].boxOffset,l=i,c=n.length-1,u=n[c].boxOffset,p;for(;a<u;){p=a+Math.ceil((u-a)/2),l=i;let h=c;for(;l<h;){let g=l+Math.ceil((h-l)/2);n[g].boxOffset>p?h=g-1:l=g}let f=this.calculateEdge(null,n,l,p);if(this.vertical?f<=o:f>=o){for(u=p-1;n[l].boxOffset==p;)l--;c=l}else s&&this.updateMaxReachedAfterEdge(f),a=p,i=l}return{nodeContext:n[l],index:a,checkPointIndex:l}}findAcceptableBreakInside(e,n,s){var l,c,u;let o=this.findEndOfLine(n,e,!0),i=o.nodeContext;if(o.checkPointIndex===0&&o.index===i.boxOffset)return null;let a=i.viewNode;if(a.nodeType!=1&&((l=a.parentElement)==null?void 0:l.localName)!=="viv-ts-inner"){let p=a;i=this.resolveTextNodeBreaker(i).breakTextNode(p,i,o.index,e,o.checkPointIndex,s)}else{let p=Bc(i);if(p){if(((c=this.breakPositions)==null?void 0:c[0])instanceof Ls&&(p!=null&&p.viewNode.contains(this.breakPositions[0].checkPoints[0].viewNode)))return null;for(i=p;!i.after&&i.inline&&i.parent;){let h=(u=i.viewNode)==null?void 0:u.previousSibling;for(;h&&(ue(h,i.parent.whitespace)||ys(h));)h=h.previousSibling;if(h)break;i=i.parent}}}return this.clearOverflownViewNodes(i,!1),i}resolveTextNodeBreaker(e){return We("RESOLVE_TEXT_NODE_BREAKER").reduce((s,o)=>o(e)||s,vo.instance)}getRangeBoxes(e,n){let s=[],o=e.ownerDocument.createRange(),i=!1,a=e,l=null,c=!1,u=!0;for(;u;){let p=!0;do{let h=null;a==n&&(n.nodeType===1?u=!(!n.firstChild||i):u=!1);let f=a.nodeType===1?a:null;f?i?i=!1:Jr(f)?p=!c:!f.firstChild||jt[f.localName]||/^r(uby|[bt]c?)$/.test(f.localName)||_h(this.clientLayout.getElementComputedStyle(f).display)?(p=!c,p?(f.localName==="ruby"&&a.firstChild&&(a=a.firstChild),o.setStartBefore(a),c=!0,l=a):/^r(uby|tc?)$/.test(f.localName)||(l=a),a.contains(n)&&(u=!1)):h=a.firstChild:(c||(a.parentNode==null?u=!1:(o.setStartBefore(a),c=!0)),l=a),h||(h=a.nextSibling,h||(i=!0,h=a.parentNode)),a=h}while(p&&u);if(c){o.setEndAfter(l);let h=this.clientLayout.getRangeClientRects(o);for(let f=0;f<h.length;f++)s.push(h[f]);c=!1}}return s}findLinePositions(e){let o=[],i=this.getRangeBoxes(e[0].viewNode,e[e.length-1].viewNode);i.sort(this.vertical?Lh:Ah);let a=0,l=0,c=0,u=0,p=0,h=this.getBoxDir();for(;;){if(p<i.length){let f=i[p],g=1;if(u>0){let m=Math.max(this.getBoxSize(f),1);h*this.getBeforeEdge(f)<h*a?g=h*(this.getAfterEdge(f)-a)/m:h*this.getAfterEdge(f)>h*l?g=h*(l-this.getBeforeEdge(f))/m:g=1}if(u==0||g>=.6||g>=.2&&this.getStartEdge(f)>=c-1){c=this.getEndEdge(f),this.vertical?(a=u==0?f.right:Math.max(a,f.right),l=u==0?f.left:Math.min(l,f.left)):(a=u==0?f.top:Math.min(a,f.top),l=u==0?f.bottom:Math.max(l,f.bottom)),u++,p++;continue}}if(u>0&&(o.push(l),u=0),p>=i.length)break}return o.sort(Zi),this.vertical&&o.reverse(),o}calculateClonedPaddingBorder(e){let n=0;for(let s=e;s;s=s.parent)if(!s.inline&&ms(s.viewNode)){let o=this.getComputedPaddingBorder(s.viewNode);n+=s.vertical?-o.left:o.bottom,s.display==="table"&&(n+=(s.vertical?-1:1)*s.blockBorderSpacing)}return n}getOffsetByRepetitiveElements(e){let n;return e?n=e.calculateOffset(this):n=Hn(null,this.collectElementsOffset()),n.current}findBoxBreakPosition(e,n){let s=this.element.parentNode,o=this.element.nextSibling;s.removeChild(this.element),s.insertBefore(this.element,o);let i=e.checkPoints,a=i[0];for(;a.parent&&a.inline;)a=a.parent;let l,c;n?(l=1,c=1):(l=Math.max((a.inheritedProps.widows||2)-0,1),c=Math.max((a.inheritedProps.orphans||2)-0,1));let u=this.calculateClonedPaddingBorder(a),p=this.findLinePositions(i),h=this.footnoteEdge-u,f=this.getBoxDir(),g=this.getOffsetByRepetitiveElements(e);h-=f*g;let m=this.findFirstOverflowingEdgeAndCheckPoint(i);isNaN(m.edge)&&(m.edge=f*(1/0));let E=ft(p.length,N=>{let S=p[N];return this.vertical?S<h||S<=m.edge:S>h||S>=m.edge}),y=E<=0;y&&(E=ft(p.length,N=>this.vertical?p[N]<h:p[N]>h));let C=i[i.length-1].viewNode;if((C==null?void 0:C.parentElement.localName)==="viv-ts-inner"&&(C=C.parentElement.parentElement),(E===p.length&&C.nextSibling||E>=p.length-1&&C.parentElement.querySelector(".MJXc-display"))&&(l=0),E=Math.min(p.length-l,E),E<c)return null;h=p[E-1];let x;if(y?x=m.checkPoint:x=this.findAcceptableBreakInside(e.checkPoints,h,n),x){let N=this.getAfterEdgeOfBlockContainer(x);!isNaN(N)&&f*(h-N)>0&&(h=N),this.computedBlockSize=f*(h-this.beforeEdge)+g}return x}getAfterEdgeOfBlockContainer(e){let n=e;do n=n.parent;while(n&&n.inline);return n?(n=n.copy().modify(),n.after=!0,Un(n,this.clientLayout,0,this.vertical)):NaN}findFirstOverflowingEdgeAndCheckPoint(e){let n=e.findIndex(o=>o.overflow);if(n<0)return{edge:NaN,checkPoint:null};let s=e[n];return{edge:this.calculateEdge(null,e,n,s.boxOffset),checkPoint:s}}findEdgeBreakPosition(e){return this.computedBlockSize=e.computedBlockSize+this.getOffsetByRepetitiveElements(e),e.position}finishBreak(e,n,s){e.formattingContext;let i=new zn().find(e.formattingContext).finishBreak(this,e,n,s);return i||(i=ai.finishBreak(this,e,n,s)),i}findAcceptableBreakPosition(){let e=null,n=null,s=0,o=0;do{s=o,o=Number.MAX_VALUE;for(let i=this.breakPositions.length-1;i>=0&&!n;--i){e=this.breakPositions[i],n=e.findAcceptableBreak(this,s);let a=e.getMinBreakPenalty();a>s&&(o=Math.min(o,a))}}while(o>s&&!n&&this.forceNonfitting);return{breakPosition:n?e:null,nodeContext:n}}doFinishBreak(e,n,s,o){if(this.pageFloatLayoutContext.isInvalidated()||this.pageBreakType||!n)return v(e);let i=A("doFinishBreak"),a=!1;if(!e){if(this.forceNonfitting)return V.warn("Could not find any page breaks?!!"),this.skipTailEdges(n).then(l=>{l?(l=l.modify(),l.overflow=!1,this.finishBreak(l,a,!0).then(()=>{i.finish(l)})):i.finish(l)}),i.result();e=s,a=!0,this.computedBlockSize=o}return this.finishBreak(e,a,!0).then(()=>{i.finish(e)}),i.result()}isBreakable(e){for(let n=e;n;n=n.parent)if(ys(n.viewNode))return!1;if(e.after)return!0;switch(e.sourceNode.namespaceURI){case"http://www.w3.org/2000/svg":return!1}return!e.flexContainer}zeroIndent(e){let n=e.toString();return n==""||n=="auto"||!!n.match(/^0+(.0*)?[^0-9]/)}checkOverflowAndSaveEdge(e,n){if(!e)return!1;for(let a=e;a;a=a.parent)if(ys(a.viewNode))return!1;if(fn(e.viewNode))return!1;let s=Un(e,this.clientLayout,0,this.vertical),o=Hn(e,this.collectElementsOffset()),i=this.isOverflown(s+(this.vertical?-1:1)*o.minimum);if(this.isOverflown(s+(this.vertical?-1:1)*o.current)&&!this.nodeContextOverflowingDueToRepetitiveElements)this.nodeContextOverflowingDueToRepetitiveElements=e;else if(n){let a=s+this.getTrailingMarginEdgeAdjustment(n),l=this.footnoteEdge-this.getBoxDir()*o.current;s=this.vertical?Math.min(s,Math.max(a,l)):Math.max(s,Math.min(a,l))}return this.updateMaxReachedAfterEdge(s),i}checkOverflowAndSaveEdgeAndBreakPosition(e,n,s,o){if(!e||fn(e.viewNode))return!1;let i=this.checkOverflowAndSaveEdge(e,n);return(s||!i)&&this.saveEdgeBreakPosition(e,o,i),i}applyClearance(e){if(!e.viewNode.parentNode)return!1;let n=this.getComputedMargin(e.viewNode),s=e.viewNode.ownerDocument.createElement("div");this.vertical?(s.style.bottom="0px",s.style.width="1px",s.style.marginRight=`${n.right}px`):(s.style.right="0px",s.style.height="1px",s.style.marginTop=`${n.top}px`),e.viewNode.parentNode.insertBefore(s,e.viewNode);let o=this.clientLayout.getElementClientRect(s),i=this.getBeforeEdge(o),a=this.getBoxDir(),l=e.clearSide,c=-this.getBoxDir()*(1/0);switch(l==="all"&&(c=this.pageFloatLayoutContext.getPageFloatClearEdge(l,this)),/^(top|bottom|inside|outside|(block|inline)-(start|end))$/.test(l)?Rc(l,e.vertical,e.direction,this.layoutContext.page.side):l){case"left":c=a*Math.max(c*a,this.leftFloatEdge*a);break;case"right":c=a*Math.max(c*a,this.rightFloatEdge*a);break;default:c=a*Math.max(c*a,Math.max(this.rightFloatEdge*a,this.leftFloatEdge*a))}if(i*a>=c*a)return e.viewNode.parentNode.removeChild(s),!1;{let p=Math.max(1,(c-i)*a);this.vertical?s.style.width=`${p}px`:s.style.height=`${p}px`,o=this.clientLayout.getElementClientRect(s);let h=this.getAfterEdge(o);if(!e.floatSide)if(this.vertical){let f=h+n.right-c;f>0==n.right>=0&&(f+=n.right),s.style.marginLeft=`${f}px`}else{let f=c-(h+n.top);f>0==n.top>=0&&(f+=n.top),s.style.marginBottom=`${f}px`}return e.clearSpacer=s,!0}}isBFC(e){return!!(Uh(e)||en.isInstanceOfRepetitiveElementsOwnerFormattingContext(e))}skipEdges(e,n,s){var E;let o=e.after?(E=e.parent)==null?void 0:E.formattingContext:e.formattingContext;if(o&&!this.isBFC(o))return v(e);let i=A("skipEdges"),a=!s&&n&&e&&e.after,l=s,c=null,u=[],p=[],h=!1;function f(){return!!s||!n&&De(l)&&!g()}function g(){var y;if(!c||e.floatSide)return!1;for(let C=c;C!=null&&C.parent;C=C.parent){let x=C.after?C.viewNode:(y=C.viewNode)==null?void 0:y.previousSibling;for(;x&&(ue(x,C.parent.whitespace)||ys(x));)x=x.previousSibling;if(x)return!1}return!0}let m=()=>{e=u[0]||e,e.viewNode.parentNode.removeChild(e.viewNode),this.pageBreakType=l};return i.loopWithFrame(y=>{var C;for(;e;){e.formattingContext;let x=new zn().find(e.formattingContext);do{if(!e.viewNode)break;if(e.inline&&e.viewNode.nodeType!=1){if(ue(e.viewNode,e.whitespace))break;if(!e.after){f()?m():this.checkOverflowAndSaveEdgeAndBreakPosition(c,null,!0,l)?(e=(this.stopAtOverflow&&c||e).modify(),e.overflow=!0):(e=e.modify(),e.breakBefore=l),y.breakLoop();return}}if(!e.after){if(e.floatSide&&(this.breakAtTheEdgeBeforeFloat=ao(l)?l:null),x&&x.startNonInlineElementNode(e))break;if(e.clearSide&&this.applyClearance(e)&&n&&this.breakPositions.length===0&&this.saveEdgeBreakPosition(e.copy(),l,!1),!e.inline&&!e.repeatOnBreak&&(c?Bc(c):this.breakPositions[this.breakPositions.length-1]instanceof Ls)&&this.saveEdgeBreakPosition(e.copy(),l,!1),!this.isBFC(e.formattingContext)||en.isInstanceOfRepetitiveElementsOwnerFormattingContext(e.formattingContext)||this.isFloatNodeContext(e)||e.flexContainer||!e.nodeShadow&&!e.sourceNode.firstElementChild&&ue(e.sourceNode.firstChild,e.whitespace)){u.push(e.copy()),l=Fe(l,e.breakBefore),f()?m():(this.checkOverflowAndSaveEdgeAndBreakPosition(c,null,!0,l)||!this.layoutConstraint.allowLayout(e))&&(e=(this.stopAtOverflow&&c||e).modify(),e.overflow=!0),y.breakLoop();return}}if(e.viewNode.nodeType!=1)break;let S=e.viewNode.style;if(e.after){e.floatSide&&(l=l!=null?l:this.breakAtTheEdgeBeforeFloat,this.breakAtTheEdgeBeforeFloat=null);let w=e.sourceNode;if(w.localName==="svg"||w.localName==="math"||w.getAttribute("data-math-typeset")==="true"){h=!1,c=e.copy(),p.push(c),l=Fe(null,e.breakAfter),this.checkOverflowAndSaveEdgeAndBreakPosition(c,null,!this.stopAtOverflow,l);break}if(e.inline||x&&x.afterNonInlineElementNode(e,this.stopAtOverflow))break;if(h){if(f()){m(),y.breakLoop();return}u=[],n=!1,a=!1,l=null}h=!1,c=e.copy(),p.push(c),l=Fe(l,e.breakAfter),S&&!(this.zeroIndent(S.paddingBottom)&&this.zeroIndent(S.borderBottomWidth))&&(p=[c])}else{if(u.push(e.copy()),l=Fe(l,e.breakBefore),(e.pageType!=((C=e.parent)==null?void 0:C.pageType)||!De(l))&&!this.layoutConstraint.allowLayout(e)&&(this.checkOverflowAndSaveEdgeAndBreakPosition(c,null,!this.stopAtOverflow,l),e=e.modify(),e.overflow=!0,this.stopAtOverflow)){y.breakLoop();return}let w=e.viewNode.localName;if(jt[w]){f()?m():this.checkOverflowAndSaveEdgeAndBreakPosition(c,null,!0,l)&&(e=(this.stopAtOverflow&&c||e).modify(),e.overflow=!0),y.breakLoop();return}S&&!(this.zeroIndent(S.paddingTop)&&this.zeroIndent(S.borderTopWidth))&&(a=!1,p=[]),h=!0}}while(!1);let N=this.nextInTree(e,a);if(N.isPending()){N.then(S=>{e=S,y.continueLoop()});return}else e=N.get()}this.checkOverflowAndSaveEdgeAndBreakPosition(c,p,!this.stopAtOverflow,l)?c&&this.stopAtOverflow&&(e=c.modify(),e.overflow=!0):De(l)&&(this.pageBreakType=l),y.breakLoop()}).then(()=>{c&&(this.lastAfterPosition=c.toNodePosition()),i.finish(e)}),i.result()}skipTailEdges(e){let n=e.copy(),s=A("skipEdges"),o=null,i=!1;return s.loopWithFrame(a=>{for(;e;){do{if(!e.viewNode)break;if(e.inline&&e.viewNode.nodeType!=1){if(ue(e.viewNode,e.whitespace))break;if(!e.after){De(o)&&(this.pageBreakType=o),a.breakLoop();return}}if(!e.after&&(this.isFloatNodeContext(e)||e.flexContainer)){o=Fe(o,e.breakBefore),De(o)&&(this.pageBreakType=o),a.breakLoop();return}if(e.viewNode.nodeType!=1)break;let c=e.viewNode.style;if(e.after){if(i){if(De(o)){this.pageBreakType=o,a.breakLoop();return}o=null}i=!1,o=Fe(o,e.breakAfter)}else{o=Fe(o,e.breakBefore);let u=e.viewNode.localName;if(jt[u]){De(o)&&(this.pageBreakType=o),a.breakLoop();return}if(c&&!(this.zeroIndent(c.paddingTop)&&this.zeroIndent(c.borderTopWidth))){a.breakLoop();return}}i=!0}while(!1);let l=this.layoutContext.nextInTree(e);if(l.isPending()){l.then(c=>{e=c,a.continueLoop()});return}else e=l.get()}n=null,a.breakLoop()}).then(()=>{s.finish(n)}),s.result()}layoutFloatOrFootnote(e){return _n(e.floatReference)||e.floatSide==="footnote"?this.layoutPageFloat(e):this.layoutFloat(e)}layoutNext(e,n,s){let o=A("layoutNext");return this.skipEdges(e,n,s||null).then(i=>{if(e=i,!e||this.pageBreakType||this.stopByOverflow(e))o.finish(e);else{let a=e.formattingContext;new zn().find(a).layout(e,this,n).thenFinish(o)}}),o.result()}clearOverflownViewNodes(e,n){if(e)for(let s=e.parent;e;e=s,s=s?s.parent:null){let o=(s||e).formattingContext;new zn().find(o).clearOverflownViewNodes(this,s,e,n),n=!1}}initGeom(){let e=this.element.ownerDocument.createElement("div");e.style.position="absolute",e.style.top=`${this.paddingTop}px`,e.style.right=`${this.paddingRight}px`,e.style.bottom=`${this.paddingBottom}px`,e.style.left=`${this.paddingLeft}px`,this.element.appendChild(e);let n=this.clientLayout.getElementClientRect(e);this.element.removeChild(e);let s=this.originX+this.left+this.getInsetLeft(),o=this.originY+this.top+this.getInsetTop();this.box=new He(s,o,s+this.width,o+this.height),this.startEdge=n?this.vertical?this.rtl?n.bottom:n.top:this.rtl?n.right:n.left:0,this.endEdge=n?this.vertical?this.rtl?n.top:n.bottom:this.rtl?n.left:n.right:0,this.beforeEdge=n?this.vertical?n.right:n.top:0,this.afterEdge=n?this.vertical?n.left:n.bottom:0,this.leftFloatEdge=this.beforeEdge,this.rightFloatEdge=this.beforeEdge,this.bottommostFloatTop=this.beforeEdge,this.footnoteEdge=this.afterEdge,this.bands=zp(this.box,[this.getInnerShape()],this.getExclusions(),8,this.snapHeight,this.vertical),this.createFloats()}init(){this.chunkPositions=[],T(this.element,"width",`${this.width}px`),T(this.element,"height",`${this.height}px`),this.initGeom(),this.computedBlockSize=0,this.overflown=!1,this.pageBreakType=null,this.lastAfterPosition=null}saveEdgeBreakPosition(e,n,s){e.formattingContext;let o=e.copy(),i=new zn().find(e.formattingContext),a=this.calculateClonedPaddingBorder(o),l=i.createEdgeBreakPosition(o,n,s,this.computedBlockSize+a);this.breakPositions.push(l)}saveBoxBreakPosition(e){let n=e[0].breakPenalty;if(n){let o=e[0];for(;o.parent&&o.inline;)o=o.parent;n=o.breakPenalty}let s=new Ls(e,n);this.breakPositions.push(s)}updateMaxReachedAfterEdge(e){if(!isNaN(e)){let n=this.getBoxDir()*(e-this.beforeEdge);this.computedBlockSize=Math.max(n,this.computedBlockSize)}}layout(e,n,s){if(this.chunkPositions.push(e),e.primary.after&&(this.lastAfterPosition=e.primary),this.stopAtOverflow&&this.overflown)return v(e);if(this.isFullWithPageFloats())return e.primary.after&&e.primary.steps.length===1?v(null):v(e);let o=A("layout");return this.openAllViews(e.primary).then(i=>{let a=null;if(i.viewNode)a=i.copy();else{let c=u=>{u.nodeContext.viewNode&&(a=u.nodeContext,this.layoutContext.removeEventListener("nextInTree",c))};this.layoutContext.addEventListener("nextInTree",c)}let l=new Uu(n,s);l.layout(i,this).then(c=>{this.doFinishBreak(c,l.context.overflownNodeContext,a,l.initialComputedBlockSize).then(u=>{let p=null;this.pseudoParent?p=v(null):p=this.doFinishBreakOfFragmentLayoutConstraints(u),p.then(()=>{if(this.pageFloatLayoutContext.isInvalidated()){o.finish(null);return}if(!u)o.finish(null);else{this.overflown=!0;let h=new pt(u.toNodePosition());o.finish(h)}})})})}),o.result()}isFullWithPageFloats(){return this.pageFloatLayoutContext.isColumnFullWithPageFloats(this)}getMaxBlockSizeOfPageFloats(){return this.pageFloatLayoutContext.getMaxBlockSizeOfPageFloats()}doFinishBreakOfFragmentLayoutConstraints(e){let n=A("doFinishBreakOfFragmentLayoutConstraints"),s=[].concat(this.fragmentLayoutConstraints);s.sort((i,a)=>i.getPriorityOfFinishBreak()-a.getPriorityOfFinishBreak());let o=0;return n.loop(()=>o<s.length?s[o++].finishBreak(e,this).thenReturn(!0):v(!1)).then(()=>{n.finish(!0)}),n.result()}doLayout(e,n,s){let o=A("doLayout"),i=null;return this.breakPositions=[],this.nodeContextOverflowingDueToRepetitiveElements=null,o.loopWithFrame(a=>{for(;e;){let l=!0;if(this.layoutNext(e,n,s||null).then(c=>{if(n=!1,s=null,this.nodeContextOverflowingDueToRepetitiveElements&&this.stopAtOverflow?(this.pageBreakType=null,e=this.nodeContextOverflowingDueToRepetitiveElements,e.overflow=!0):e=c,this.pageFloatLayoutContext.isInvalidated())a.breakLoop();else if(this.pageBreakType)a.breakLoop();else if(e&&this.stopByOverflow(e)){i=e;let u=this.findAcceptableBreakPosition();e=u.nodeContext,u.breakPosition&&u.breakPosition.breakPositionChosen(this),a.breakLoop()}else l?l=!1:a.continueLoop()}),l){l=!1;return}}this.computedBlockSize+=this.getOffsetByRepetitiveElements(),a.breakLoop()}).then(()=>{o.finish({nodeContext:e,overflownNodeContext:i})}),o.result()}redoLayout(){let e=this.chunkPositions,n=this.element.lastChild;for(;n!=this.last;){let l=n.previousSibling;this.element===n.parentNode&&this.layoutContext.isPseudoelement(n)||this.element.removeChild(n),n=l}this.killFloats(),this.init();let s=A("redoLayout"),o=0,i=null,a=!0;return s.loopWithFrame(l=>{if(o<e.length){let c=e[o++];this.layout(c,a).then(u=>{a=!1,u?(i=u,l.breakLoop()):l.continueLoop()});return}l.breakLoop()}).then(()=>{s.finish(i)}),s.result()}saveDistanceToBlockEndFloats(){let e=this.pageFloatLayoutContext.getBlockStartEdgeOfBlockEndFloats();e>0&&isFinite(e)&&(this.blockDistanceToBlockEndFloats=this.getBoxDir()*(e-this.beforeEdge-this.computedBlockSize))}collectElementsOffset(){let e=[];for(let n=this;n;n=n.pseudoParent)n.fragmentLayoutConstraints.forEach(s=>{if(en.isInstanceOfRepetitiveElementsOwnerLayoutConstraint(s)){let o=s.getRepetitiveElements();e.push(o)}if(Jo.isInstanceOfAfterIfContinuesLayoutConstraint(s)){let o=s.getRepetitiveElements();e.push(o)}Ot.isInstanceOfTableRowLayoutConstraint(s)&&s.getElementsOffsetsForTableCell(this).forEach(o=>{e.push(o)})});return e}},Is=class{constructor(t,e,n){d(this,"startNodeContexts",[]);d(this,"column");this.column=Object.create(t),this.column.element=e,this.column.layoutContext=t.layoutContext.clone(),this.column.stopAtOverflow=!1,this.column.flowRootFormattingContext=n.formattingContext,this.column.pseudoParent=t;let s=this.column.calculateClonedPaddingBorder(n);this.column.footnoteEdge=this.column.footnoteEdge-s;let o=this;this.column.openAllViews=function(i){return Rs.prototype.openAllViews.call(this,i).thenAsync(a=>(o.startNodeContexts.push(a.copy()),v(a)))}}layout(t,e){return this.column.layout(t,e)}findAcceptableBreakPosition(t){let e=this.column.findAcceptableBreakPosition();if(t){let n=this.startNodeContexts[0].copy(),s=new tn(n,null,n.overflow,0);if(s.findAcceptableBreak(this.column,0),!e.nodeContext)return{breakPosition:s,nodeContext:n}}return e}finishBreak(t,e,n){return this.column.finishBreak(t,e,n)}doFinishBreakOfFragmentLayoutConstraints(t){this.column.doFinishBreakOfFragmentLayoutConstraints(t)}isStartNodeContext(t){let e=this.startNodeContexts[0];return e.viewNode===t.viewNode&&e.after===t.after&&e.offsetInNode===t.offsetInNode}isLastAfterNodeContext(t){return Dt(t.toNodePosition(),this.column.lastAfterPosition)}getColumnElement(){return this.column.element}getColumn(){return this.column}},vo=class{breakTextNode(t,e,n,s,o,i){if(e.after)e.offsetInNode=t.length;else{let a=n-e.boxOffset,l=t.data;l.charCodeAt(a)==173?a=this.breakAfterSoftHyphen(t,l,a,e):a=this.breakAfterOtherCharacter(t,l,a,e),a>0&&(e=this.updateNodeContext(e,a,t))}return e}breakAfterSoftHyphen(t,e,n,s){let i=/[\u0620\u0626\u0628\u062A-\u062E\u0633-\u0647\u0649\u064A\u066E\u066F\u0678-\u0687\u069A-\u06BF\u06C1\u06C2\u06CC\u06CE\u06D0\u06D1\u06FA-\u06FC\u06FF\u0712-\u0714\u071A-\u071D\u071F-\u0727\u0729\u072B\u072D\u072E\u074E-\u0758\u075C-\u076A\u076D-\u0770\u0772\u0775-\u0777\u077A-\u077F\u07CA-\u07EA\u07FA\u0841-\u0845\u0848\u084A-\u0853\u0855\u0860\u0862-\u0865\u0868\u0883-\u0886\u0889-\u088D\u08A0-\u08A9\u08AF\u08B0\u08B3-\u08B8\u08BA-\u08C8\u1807\u180A\u1820-\u1878\u1887-\u18A8\u18AA\u200D\uA840-\uA871\u{10AC0}-\u{10AC4}\u{10AD3}-\u{10AD6}\u{10AD8}-\u{10ADC}\u{10ADE}-\u{10AE0}\u{10AEB}-\u{10AEE}\u{10B80}\u{10B82}\u{10B86}-\u{10B88}\u{10B8A}\u{10B8B}\u{10B8D}\u{10B90}\u{10BAD}\u{10BAE}\u{10D01}-\u{10D21}\u{10D23}\u{10EC3}\u{10EC4}\u{10F30}-\u{10F32}\u{10F34}-\u{10F44}\u{10F51}-\u{10F53}\u{10F70}-\u{10F73}\u{10F76}-\u{10F81}\u{10FB0}\u{10FB2}\u{10FB3}\u{10FB8}\u{10FBB}\u{10FBC}\u{10FBE}\u{10FBF}\u{10FC1}\u{10FC4}\u{10FCA}\u{1E900}-\u{1E943}]\p{Mn}*$/u.test(e.slice(0,n))?"\u200D":"";if(t.replaceData(n,e.length-n,s.breakWord?"":i+Cf(s)),i){let a=s.preprocessedTextContent[0][1];s.preprocessedTextContent[0][1]=a.slice(0,n+1)+i+a.slice(n+1)}return n+1}breakAfterOtherCharacter(t,e,n,s){let o=e.charAt(n);n++;let i=e.charAt(n);return t.replaceData(n,e.length-n,!s.breakWord&&Sl(o)&&Sl(i)?Cf(s):""),n}updateNodeContext(t,e,n){return t=t.modify(),t.offsetInNode+=e,t.breakBefore=null,t}};d(vo,"instance");vo.instance=new vo;function Cf(r){return r.hyphenateCharacter||r.parent&&r.parent.hyphenateCharacter||"-"}var Uu=class extends Gn{constructor(e,n){super();this.leadingEdge=e;d(this,"breakAfter");d(this,"initialPageBreakType",null);d(this,"initialComputedBlockSize",0);d(this,"initialOverflown",!1);d(this,"context",{overflownNodeContext:null});this.breakAfter=n||null}resolveLayoutMode(e){return new Hu(this.leadingEdge,this.breakAfter,this.context)}prepareLayout(e,n){n.fragmentLayoutConstraints=[],n.pseudoParent||zh()}clearNodes(e){super.clearNodes(e);let n=e;for(;n;){let s=n.viewNode;s&&Qr(s.parentNode,s),n=n.parent}}saveState(e,n){super.saveState(e,n),this.initialPageBreakType=n.pageBreakType,this.initialComputedBlockSize=n.computedBlockSize,this.initialOverflown=n.overflown}restoreState(e,n){super.restoreState(e,n),n.pageBreakType=this.initialPageBreakType,n.computedBlockSize=this.initialComputedBlockSize,n.overflown=this.initialOverflown}},Hu=class{constructor(t,e,n){this.leadingEdge=t;this.breakAfter=e;this.context=n}doLayout(t,e){let n=A("DefaultLayoutMode.doLayout");return fC(t,e).then(()=>{e.doLayout(t,this.leadingEdge,this.breakAfter).then(s=>{this.context.overflownNodeContext=s.overflownNodeContext,n.finish(s.nodeContext)})}),n.result()}accept(t,e){return e.pageFloatLayoutContext.isInvalidated()||e.pageBreakType||e.fragmentLayoutConstraints.length<=0?!0:e.fragmentLayoutConstraints.every(n=>n.allowLayout(t,this.context.overflownNodeContext,e))}postLayout(t,e,n,s){return s||(s=!n.fragmentLayoutConstraints.some(i=>i.nextCandidate(t))),n.fragmentLayoutConstraints.forEach(o=>{o.postLayout(s,t,e,n)}),s}},zu=class extends Rs{constructor(e,n,s,o,i,a,l){super(n,s,o,i,a);this.floatSide=e;this.parentContainer=l;d(this,"rootViewNodes",[]);d(this,"floatMargins",[]);d(this,"adjustContentRelativeSize",!0)}openAllViews(e){return super.openAllViews(e).thenAsync(n=>(n&&this.fixFloatSizeAndPosition(n),v(n)))}convertPercentageSizesToPx(e){let n=this.parentContainer.getPaddingRect(),s=n.x2-n.x1,o=n.y2-n.y1;function i(a,l){a.forEach(c=>{let u=It(e,c);if(u&&u.charAt(u.length-1)==="%"){let p=parseFloat(u),h=l*p/100;T(e,c,`${h}px`)}})}i(["width","max-width","min-width"],s),i(["height","max-height","min-height"],o),i(["margin-top","margin-right","margin-bottom","margin-left","padding-top","padding-right","padding-bottom","padding-left"],this.vertical?o:s),["margin-top","margin-right","margin-bottom","margin-left"].forEach(a=>{It(e,a)==="auto"&&T(e,a,"0")})}fixFloatSizeAndPosition(e){for(;e.parent;)e=e.parent;e.viewNode.nodeType;let n=e.viewNode;if(this.rootViewNodes.push(n),this.adjustContentRelativeSize&&this.convertPercentageSizesToPx(n),this.floatMargins.push(this.getComputedMargin(n)),this.adjustContentRelativeSize){let s=this.floatSide;if(this.parentContainer.vertical){if(s==="block-end"||s==="left"){let i=It(n,"height");i!==""&&i!=="auto"&&T(n,"margin-top","auto")}}else if(s==="block-end"||s==="bottom"){let i=It(n,"width");i!==""&&i!=="auto"&&T(n,"margin-left","auto")}}}getContentInlineSize(){return Math.max.apply(null,this.rootViewNodes.map((e,n)=>{let s=this.clientLayout.getElementClientRect(e),o=this.floatMargins[n];return this.vertical?o.top+s.height+o.bottom:o.left+s.width+o.right}))}};var Ut=class{constructor(t,e){this.parent=t;this.rootSourceNode=e;d(this,"formattingContextType","RepetitiveElementsOwner");d(this,"isRoot",!1);d(this,"repetitiveElements",null)}getName(){return"Repetitive elements owner formatting context (RepetitiveElementsOwnerFormattingContext)"}isFirstTime(t,e){return e}getParent(){return this.parent}getRepetitiveElements(){return this.repetitiveElements}getRootViewNode(t){let e=this.getRootNodeContext(t);return e?e.viewNode:null}getRootNodeContext(t){do if(!t.belongsTo(this)&&t.sourceNode===this.rootSourceNode)return t;while(t=t.parent);return null}initializeRepetitiveElements(t){if(this.repetitiveElements)return;ta.some(n=>n.root===this.rootSourceNode?(this.repetitiveElements=n.elements,!0):!1)||(this.repetitiveElements=new Wu(t,this.rootSourceNode),ta.push({root:this.rootSourceNode,elements:this.repetitiveElements}))}saveState(){}restoreState(t){}},Wu=class{constructor(t,e){this.vertical=t;this.ownerSourceNode=e;d(this,"headerSourceNode",null);d(this,"footerSourceNode",null);d(this,"headerViewNode",null);d(this,"footerViewNode",null);d(this,"headerNodePosition",null);d(this,"footerNodePosition",null);d(this,"headerHeight",0);d(this,"footerHeight",0);d(this,"isSkipHeader",!1);d(this,"isSkipFooter",!1);d(this,"enableSkippingFooter",!0);d(this,"enableSkippingHeader",!0);d(this,"doneInitialLayout",!1);d(this,"firstContentSourceNode",null);d(this,"lastContentSourceNode",null);d(this,"affectedNodeCache",[]);d(this,"afterLastContentNodeCache",[]);d(this,"allowInsert",!1);d(this,"allowInsertRepeatitiveElements")}setHeaderNodeContext(t){this.headerNodePosition||(this.headerNodePosition=xs(t,0),this.headerSourceNode=t.sourceNode,this.headerViewNode=t.viewNode)}setFooterNodeContext(t){this.footerNodePosition||(this.footerNodePosition=xs(t,0),this.footerSourceNode=t.sourceNode,this.footerViewNode=t.viewNode)}updateHeight(t){this.headerViewNode&&(this.headerHeight=ri(this.headerViewNode,t,this.vertical),this.headerViewNode=null),this.footerViewNode&&(this.footerHeight=ri(this.footerViewNode,t,this.vertical),this.footerViewNode=null)}prepareLayoutFragment(){this.isSkipHeader=this.isSkipFooter=!1,this.enableSkippingFooter=!0,this.enableSkippingHeader=!0}appendHeaderToFragment(t,e,n){return!this.headerNodePosition||this.isSkipHeader?v(!0):this.appendElementToFragment(this.headerNodePosition,t,e,n)}appendFooterToFragment(t,e,n){return!this.footerNodePosition||this.isSkipFooter?v(!0):this.appendElementToFragment(this.footerNodePosition,t,e,n)}appendElementToFragment(t,e,n,s){let o=e.viewNode.ownerDocument,i=e.viewNode,a=o.createElement("div");i.appendChild(a);let l=new Is(s,a,e),c=l.getColumn().pageBreakType;return l.getColumn().pageBreakType=null,this.allowInsertRepeatitiveElements=!0,l.layout(new pt(t),!0).thenAsync(()=>(this.allowInsertRepeatitiveElements=!1,i.removeChild(a),this.moveChildren(a,i,n),l.getColumn().pageBreakType=c,v(!0)))}moveChildren(t,e,n){if(e)for(;t.firstChild;){let s=t.firstChild;t.removeChild(s),s.setAttribute(Mt,"1"),n?e.insertBefore(s,n):e.appendChild(s)}}calculateOffset(t){let e=0;return t&&!this.affectTo(t)||((!this.isSkipFooter||t&&this.isAfterLastContent(t))&&(e+=this.footerHeight),this.isSkipHeader||(e+=this.headerHeight)),e}calculateMinimumOffset(t){let e=0;return t&&!this.affectTo(t)||(!this.enableSkippingFooter&&t&&this.isAfterLastContent(t)&&(e+=this.footerHeight),this.enableSkippingHeader||(e+=this.headerHeight)),e}isAfterLastContent(t){return this.findResultFromCache(t,this.afterLastContentNodeCache,e=>this.isAfterNodeContextOf(this.lastContentSourceNode,t,!1))}affectTo(t){return this.findResultFromCache(t,this.affectedNodeCache,e=>this.isAfterNodeContextOf(this.ownerSourceNode,t,!0))}findResultFromCache(t,e,n){let s=e.filter(o=>o.nodeContext.sourceNode===t.sourceNode&&o.nodeContext.after===t.after);if(s.length>0)return s[0].result;{let o=n(t);return e.push({nodeContext:t,result:o}),o}}isAfterNodeContextOf(t,e,n){let s=[];for(let o=t;o;o=o.parentNode){if(e.sourceNode===o)return e.after;s.push(o)}for(let o=e.sourceNode;o;o=o.parentNode){let i=s.indexOf(o);if(i>=0)return n?i===0:!1;for(let a=o;a;a=a.previousElementSibling)if(s.includes(a))return!0}return e.after}isFirstContentNode(t){return t&&this.firstContentSourceNode===t.sourceNode}isEnableToUpdateState(){return!!(!this.isSkipFooter&&this.enableSkippingFooter&&this.footerNodePosition||!this.isSkipHeader&&this.enableSkippingHeader&&this.headerNodePosition)}updateState(){!this.isSkipFooter&&this.enableSkippingFooter&&this.footerNodePosition?this.isSkipFooter=!0:!this.isSkipHeader&&this.enableSkippingHeader&&this.headerNodePosition&&(this.isSkipHeader=!0)}preventSkippingHeader(){this.isSkipHeader=!1,this.enableSkippingHeader=!1}preventSkippingFooter(){this.isSkipFooter=!1,this.enableSkippingFooter=!1}isHeaderRegistered(){return!!this.headerNodePosition}isFooterRegistered(){return!!this.footerNodePosition}isHeaderSourceNode(t){return this.headerSourceNode===t}isFooterSourceNode(t){return this.footerSourceNode===t}},bi=class{constructor(t){this.formattingContext=t}accept(t,e){return!!t}postLayout(t,e,n,s){let o=this.formattingContext.getRepetitiveElements();return o&&(n.clientLayout,o.doneInitialLayout||(o.updateHeight(n),o.doneInitialLayout=!0)),s}},xi=class{constructor(t){this.formattingContext=t}accept(t,e){return!0}postLayout(t,e,n,s){return s}},$u=class extends bi{constructor(e,n){super(e);this.processor=n}doLayout(e,n){return this.processor.doInitialLayout(e,n)}accept(e,n){return!1}},Xu=class extends xi{constructor(e,n){super(e);this.processor=n}doLayout(e,n){return!e.belongsTo(this.formattingContext)&&!e.after&&n.fragmentLayoutConstraints.unshift(new To(e)),this.processor.doLayout(e,n)}},To=class r{constructor(t){d(this,"flagmentLayoutConstraintType","RepetitiveElementsOwner");d(this,"nodeContext");let e=yn(t.formattingContext);this.nodeContext=e.getRootNodeContext(t)}allowLayout(t,e,n){let s=this.getRepetitiveElements();return!s||fn(this.nodeContext.viewNode)||!s.isEnableToUpdateState()?!0:!(e&&!t||t&&t.overflow)}nextCandidate(t){let e=this.getRepetitiveElements();return e&&e.isEnableToUpdateState()?(e.updateState(),!0):!1}postLayout(t,e,n,s){let o=this.getRepetitiveElements();o&&t&&s.stopAtOverflow&&(e==null||o.isAfterLastContent(e))&&o.preventSkippingFooter()}finishBreak(t,e){let n=yn(this.nodeContext.formattingContext),s=this.getRepetitiveElements();if(!s)return v(!0);let o=this.nodeContext;return CC(n,o,e).thenAsync(()=>bC(n,o,e).thenAsync(()=>(s.prepareLayoutFragment(),v(!0))))}getRepetitiveElements(){return yn(this.nodeContext.formattingContext).getRepetitiveElements()}equalsTo(t){return t instanceof r?yn(this.nodeContext.formattingContext)===yn(t.nodeContext.formattingContext):!1}getPriorityOfFinishBreak(){return 10}},ju=class extends Gn{constructor(e,n){super();this.formattingContext=e;this.processor=n}resolveLayoutMode(e){let n=this.formattingContext.getRepetitiveElements();return!e.belongsTo(this.formattingContext)&&!n.doneInitialLayout?new $u(this.formattingContext,this.processor):(!e.belongsTo(this.formattingContext)&&!e.after&&n&&n.preventSkippingHeader(),new Xu(this.formattingContext,this.processor))}},Yu=class extends mn{constructor(e,n){super();this.formattingContext=e;this.column=n}startNonInlineElementNode(e){let n=this.formattingContext,s=e.nodeContext,o=n.getRepetitiveElements();if(s.parent&&n.rootSourceNode===s.parent.sourceNode){switch(s.repeatOnBreak){case"header":if(o.isHeaderRegistered())s.repeatOnBreak="none";else return o.setHeaderNodeContext(s),v(!0);break;case"footer":if(o.isFooterRegistered())s.repeatOnBreak="none";else return o.setFooterNodeContext(s),v(!0);break}o.firstContentSourceNode||(o.firstContentSourceNode=s.sourceNode)}return mn.prototype.startNonInlineElementNode.call(this,e)}afterNonInlineElementNode(e){let n=this.formattingContext,s=e.nodeContext;return s.sourceNode===n.rootSourceNode&&(n.getRepetitiveElements().lastContentSourceNode=e.lastAfterNodeContext&&e.lastAfterNodeContext.sourceNode,e.break=!0),s.repeatOnBreak==="header"||s.repeatOnBreak==="footer"?v(!0):mn.prototype.afterNonInlineElementNode.call(this,e)}};var Ku=class extends nn{layout(t,e,n){if(e.isFloatNodeContext(t))return e.layoutFloatOrFootnote(t);let s=yn(t.formattingContext);return s.getRootViewNode(t)?(n&&qu(t.parent,e),t.belongsTo(s)?nn.prototype.layout.call(this,t,e,n):new ju(s,this).layout(t,e)):e.buildDeepElementView(t)}startNonInlineElementNode(t){let n=xC(t).getRepetitiveElements();return n&&!n.allowInsertRepeatitiveElements&&(n.isHeaderSourceNode(t.sourceNode)||n.isFooterSourceNode(t.sourceNode))&&t.viewNode.parentNode.removeChild(t.viewNode),!1}doInitialLayout(t,e){let n=yn(t.formattingContext),s=A("BlockLayoutProcessor.doInitialLayout");return this.layoutEntireBlock(t,e).thenFinish(s),s.result()}layoutEntireBlock(t,e){let n=yn(t.formattingContext),s=new Yu(n,e);return new Ss(s,e.layoutContext).iterate(t)}doLayout(t,e){let n=yn(t.formattingContext),s=A("doLayout"),o=e.layoutContext.nextInTree(t,!1);return Gu(o,e).then(i=>{let a=i;s.loopWithFrame(l=>{for(;a;){let c=!0;if(e.layoutNext(a,!1).then(u=>{a=u,e.pageFloatLayoutContext.isInvalidated()||e.pageBreakType||a&&e.stopByOverflow(a)||a&&a.after&&a.sourceNode==n.rootSourceNode?l.breakLoop():c?c=!1:l.continueLoop()}),c){c=!1;return}}l.breakLoop()}).then(()=>{s.finish(a)})}),s.result()}finishBreak(t,e,n,s){return nn.prototype.finishBreak.call(this,t,e,n,s)}clearOverflownViewNodes(t,e,n,s){nn.prototype.clearOverflownViewNodes(t,e,n,s)}};function mC(r,t){for(let e=r;e;e=e.parent){let n=e.formattingContext;n&&n instanceof Ut&&!e.belongsTo(n)&&t(n,e)}}function qu(r,t){r&&mC(r.after?r.parent:r,(e,n)=>{Ot.isInstanceOfTableFormattingContext(e)||t.fragmentLayoutConstraints.push(new To(n))})}function CC(r,t,e){let n=r.getRepetitiveElements();if(n){let s=r.getRootNodeContext(t);if(s.viewNode){let o=s.viewNode.firstChild;return n.appendHeaderToFragment(s,o,e)}}return v(!0)}function bC(r,t,e){let n=r.getRepetitiveElements();if(n&&!n.isSkipFooter){let s=r.getRootNodeContext(t);if(s.viewNode)return n.appendFooterToFragment(s,null,e)}return v(!0)}function xC(r){let t=r.formattingContext;return!t||!(t instanceof Ut)?null:t}function yn(r){return r instanceof Ut,r}var yC=new Ku;_e("RESOLVE_LAYOUT_PROCESSOR",r=>r instanceof Ut&&!Ot.isInstanceOfTableFormattingContext(r)?yC:null);var ya=class{constructor(t,e){this.rowIndex=t;this.sourceNode=e;d(this,"cells",[])}addCell(t){this.cells.push(t)}getMinimumHeight(){return Math.min.apply(null,this.cells.map(t=>t.height))}},Qu=class{constructor(t,e,n){this.rowIndex=t;this.columnIndex=e;d(this,"viewElement");d(this,"colSpan");d(this,"rowSpan");d(this,"height",0);d(this,"anchorSlot",null);this.viewElement=n,this.colSpan=n.colSpan||1,this.rowSpan=n.rowSpan||1}setHeight(t){this.height=t}setAnchorSlot(t){this.anchorSlot=t}},Ju=class{constructor(t,e,n){this.rowIndex=t;this.columnIndex=e;this.cell=n}},ed=class{constructor(t,e,n){this.column=t;this.cellNodeContext=n;d(this,"pseudoColumn");d(this,"empty",!1);this.pseudoColumn=new Is(t,e,n)}findAcceptableBreakPosition(){let t=this.cellNodeContext.viewNode,{verticalAlign:e,alignContent:n}=t.style;e!=="top"&&e!=="baseline"&&T(t,"vertical-align","top"),n&&n!=="normal"&&T(t,"align-content","normal");let s=this.pseudoColumn.findAcceptableBreakPosition(!0);return T(t,"vertical-align",e),n&&n!=="normal"&&T(t,"align-content",n),s}},td=class{constructor(t,e){this.viewNode=t;this.side=e}},nd=class extends tn{constructor(e,n,s,o){super(e,n,s,o);d(this,"formattingContext");d(this,"acceptableCellBreakPositions",null);d(this,"rowIndex",null);this.formattingContext=e.formattingContext}findAcceptableBreak(e,n){let s=super.findAcceptableBreak(e,n);return n<this.getMinBreakPenalty()?null:this.getAcceptableCellBreakPositions().every(i=>!!i.nodeContext)?s:null}getMinBreakPenalty(){let e=super.getMinBreakPenalty();this.getAcceptableCellBreakPositions().forEach(s=>{e+=s.breakPosition.getMinBreakPenalty()});let n=this.getCellFragments();return e+=Math.max(0,...n.map(s=>s.cellNodeContext.breakPenalty)),e}getAcceptableCellBreakPositions(){if(!this.acceptableCellBreakPositions){let e=this.formattingContext,n=this.getCellFragments();this.acceptableCellBreakPositions=n.map(s=>s.findAcceptableBreakPosition())}return this.acceptableCellBreakPositions}getRowIndex(){return this.rowIndex!=null?this.rowIndex:this.rowIndex=this.formattingContext.findRowIndexBySourceNode(this.position.sourceNode)}getCellFragments(){return this.formattingContext.getRowSpanningCellsOverflowingTheRow(this.getRowIndex()).map(this.formattingContext.getCellFragmentOfCell,this.formattingContext)}},sd=class extends Es{constructor(e,n,s){super();this.rowIndex=e;this.beforeNodeContext=n;this.formattingContext=s;d(this,"acceptableCellBreakPositions",null)}findAcceptableBreak(e,n){if(this!==e.breakPositions[0]&&n<this.getMinBreakPenalty())return null;let s=this.getCellFragments(),o=this.getAcceptableCellBreakPositions(),i=o.every(a=>!!a.nodeContext)&&o.some((a,l)=>{let c=s[l].pseudoColumn,u=a.nodeContext;return!c.isStartNodeContext(u)&&!c.isLastAfterNodeContext(u)});return this.beforeNodeContext.overflow=o.some(a=>a.nodeContext&&a.nodeContext.overflow),i?this.beforeNodeContext:null}getMinBreakPenalty(){let n=this.formattingContext.getRowByIndex(this.rowIndex),s=this.beforeNodeContext.breakPenalty,o=this.getAcceptableCellBreakPositions(),i=this.getCellFragments();s+=Math.max(0,...i.map(l=>l.cellNodeContext.breakPenalty));let a=o.some((l,c)=>l.breakPosition instanceof Ls&&i[c].cellNodeContext.sourceNode.rowSpan>1);return o.forEach((l,c)=>{let u=l.breakPosition.getMinBreakPenalty();a&&l.breakPosition instanceof tn&&l.breakPosition.overflows&&u>=3&&(i[c].column.checkOverflowAndSaveEdge(l.nodeContext,null)||(u-=3)),s+=u}),s}getAcceptableCellBreakPositions(){if(!this.acceptableCellBreakPositions){let e=this.getCellFragments();this.acceptableCellBreakPositions=e.map(n=>n.findAcceptableBreakPosition())}return this.acceptableCellBreakPositions}getCellFragments(){return this.formattingContext.getCellsFallingOnRow(this.rowIndex).map(this.formattingContext.getCellFragmentOfCell,this.formattingContext)}},Yn=class extends Ut{constructor(e,n){super(e,n);this.tableSourceNode=n;d(this,"formattingContextType","Table");d(this,"vertical",!1);d(this,"columnCount",-1);d(this,"tableWidth",0);d(this,"captions",[]);d(this,"colGroups",null);d(this,"colWidths",null);d(this,"inlineBorderSpacing",0);d(this,"rows",[]);d(this,"slots",[]);d(this,"cellFragments",[]);d(this,"lastRowViewNode",null);d(this,"cellBreakPositions",[]);d(this,"repetitiveElements",null)}getName(){return"Table formatting context (Table.TableFormattingContext)"}isFirstTime(e,n){if(!n)return n;switch(e.display){case"table-row":return this.cellBreakPositions.length===0;case"table-cell":return!this.cellBreakPositions.some(s=>s.cellNodePosition.steps[0].node===e.sourceNode);default:return n}}getParent(){return this.parent}finishFragment(){this.cellFragments=[]}addRow(e,n){this.rows[e]=n}getRowSlots(e){let n=this.slots[e];return n||(n=this.slots[e]=[]),n}addCell(e,n){let s=this.rows[e];s||(this.addRow(e,new ya(e,null)),s=this.rows[e]),s.addCell(n);let o=e+n.rowSpan,i=this.getRowSlots(e),a=0;for(;i[a];)a++;for(;e<o;e++){i=this.getRowSlots(e);for(let l=a;l<a+n.colSpan;l++){let c=i[l]=new Ju(e,l,n);n.anchorSlot||n.setAnchorSlot(c)}}}getRowByIndex(e){let n=this.rows[e];return n}findRowIndexBySourceNode(e){return this.rows.findIndex(n=>e===n.sourceNode)}addCellFragment(e,n,s){let o=this.cellFragments[e];o||(o=this.cellFragments[e]=[]),o[n]=s}getCellsFallingOnRow(e){return this.getRowSlots(e).reduce((s,o)=>o.cell!==s[s.length-1]?s.concat(o.cell):s,[])}getRowSpanningCellsOverflowingTheRow(e){return this.getCellsFallingOnRow(e).filter(n=>n.rowIndex+n.rowSpan-1>e)}getCellFragmentOfCell(e){return this.cellFragments[e.rowIndex]&&this.cellFragments[e.rowIndex][e.columnIndex]}getColumnCount(){return this.columnCount<0&&(this.columnCount=Math.max.apply(null,this.rows.map(e=>e.cells.reduce((n,s)=>n+s.colSpan,0)))),this.columnCount}updateCellSizes(e){this.rows.forEach(n=>{n.cells.forEach(s=>{let o=e.getElementClientRect(s.viewElement);s.viewElement=null,s.setHeight(this.vertical?o.width:o.height)})})}findCellFromColumn(e){if(!e)return null;let n=null,s=0,o=0;e:for(s=0;s<this.cellFragments.length;s++)if(this.cellFragments[s]){for(o=0;o<this.cellFragments[s].length;o++)if(this.cellFragments[s][o]&&e===this.cellFragments[s][o].pseudoColumn.getColumn()){n=this.rows[s].cells[o];break e}}if(!n)return null;for(;s<this.slots.length;s++)for(;o<this.slots[s].length;o++){let i=this.slots[s][o];if(i.cell===n)return{rowIndex:i.rowIndex,columnIndex:i.columnIndex}}return null}collectElementsOffsetOfUpperCells(e){let n=[];return this.slots.reduce((s,o,i)=>{if(i>=e.rowIndex)return s;let a=o[e.columnIndex]&&this.getCellFragmentOfCell(o[e.columnIndex].cell);return!a||n.includes(a)||(this.collectElementsOffsetFromColumn(a.pseudoColumn.getColumn(),s),n.push(a)),s},[])}collectElementsOffsetOfHighestColumn(){let e=[];return this.rows.forEach(n=>{n.cells.forEach((s,o)=>{e[o]||(e[o]={collected:[],elements:[]});let i=e[o],a=this.getCellFragmentOfCell(s);!a||i.collected.includes(a)||(this.collectElementsOffsetFromColumn(a.pseudoColumn.getColumn(),i.elements),i.collected.push(a))})}),[new od(e.map(n=>n.elements))]}collectElementsOffsetFromColumn(e,n){e.fragmentLayoutConstraints.forEach(s=>{if(en.isInstanceOfRepetitiveElementsOwnerLayoutConstraint(s)){let o=s.getRepetitiveElements();n.push(o)}Ot.isInstanceOfTableRowLayoutConstraint(s)&&s.getElementsOffsetsForTableCell(null).forEach(o=>{n.push(o)})})}saveState(){return[].concat(this.cellBreakPositions)}restoreState(e){this.cellBreakPositions=e}},od=class{constructor(t){this.repeatitiveElementsInColumns=t}calculateOffset(t){return this.calculateMaxOffsetOfColumn(t,e=>e.current)}calculateMinimumOffset(t){return this.calculateMaxOffsetOfColumn(t,e=>e.minimum)}calculateMaxOffsetOfColumn(t,e){let n=0;return this.repeatitiveElementsInColumns.forEach(s=>{let o=Hn(t,s);n=Math.max(n,e(o))}),n}};function At(r){return r instanceof Yn,r}function EC(r){return r==="table-row-group"||r==="table-header-group"||r==="table-footer-group"}function SC(r){return r==="table"||r==="inline-table"}function Ef(r){return EC(r)||SC(r)}function Sf(r,t,e){let n=r.nodeContext,s=n.display,o=n.parent?n.parent.display:null,i=!1;if(o==="inline-table"&&!(n.formattingContext instanceof Yn)){for(let l=n.parent;l;l=l.parent)if(l.formattingContext instanceof Yn){i=l.formattingContext===t;break}}return i||s==="table-row"&&!Ef(o)||s==="table-cell"&&o!=="table-row"&&!Ef(o)||n.formattingContext instanceof Yn&&n.formattingContext!==t?e.buildDeepElementView(n).thenAsync(l=>(r.nodeContext=l,v(!0))):null}var id=class extends mn{constructor(e,n){super();this.formattingContext=e;this.column=n;d(this,"rowIndex",-1);d(this,"columnIndex",0);d(this,"inRow",!1);d(this,"checkPoints",[]);d(this,"inHeaderOrFooter",!1)}startNonInlineElementNode(e){let n=this.formattingContext,s=Sf(e,n,this.column);if(s)return s;this.postLayoutBlockContents(e);let o=e.nodeContext,i=o.display,a=n.getRepetitiveElements();switch(i){case"table":n.inlineBorderSpacing=o.inlineBorderSpacing;break;case"table-caption":{let l=new td(o.viewNode,o.captionSide);n.captions.push(l);break}case"table-header-group":return a.isHeaderRegistered()||(this.inHeaderOrFooter=!0,a.setHeaderNodeContext(o)),v(!0);case"table-footer-group":return a.isFooterRegistered()||(this.inHeaderOrFooter=!0,a.setFooterNodeContext(o)),v(!0);case"table-row":this.inHeaderOrFooter||(this.inRow=!0,this.rowIndex++,o.sourceNode,this.columnIndex=0,n.addRow(this.rowIndex,new ya(this.rowIndex,o.sourceNode)),a.firstContentSourceNode||(a.firstContentSourceNode=o.sourceNode));break}return super.startNonInlineElementNode(e)}afterNonInlineElementNode(e){let n=this.formattingContext,s=e.nodeContext,o=s.display,i=this.column.clientLayout;if(this.postLayoutBlockContents(e),s.sourceNode===n.tableSourceNode){let a=i.getElementComputedStyle(n.getRootViewNode(s));n.tableWidth=parseFloat(a[n.vertical?"height":"width"]),n.getRepetitiveElements().lastContentSourceNode=e.lastAfterNodeContext&&e.lastAfterNodeContext.sourceNode,e.break=!0}else switch(o){case"table-header-group":case"table-footer-group":if(this.inHeaderOrFooter)return this.inHeaderOrFooter=!1,v(!0);break;case"table-row":this.inHeaderOrFooter||(n.lastRowViewNode=s.viewNode,this.inRow=!1);break;case"table-cell":if(!this.inHeaderOrFooter){this.inRow||(this.rowIndex++,this.columnIndex=0,this.inRow=!0);let a=s.viewNode;n.addCell(this.rowIndex,new Qu(this.rowIndex,this.columnIndex,a)),this.columnIndex++}break}return super.afterNonInlineElementNode(e)}startNonElementNode(e){this.registerCheckPoint(e)}afterNonElementNode(e){this.registerCheckPoint(e)}startInlineElementNode(e){this.registerCheckPoint(e)}afterInlineElementNode(e){this.registerCheckPoint(e)}registerCheckPoint(e){let n=e.nodeContext;n&&n.viewNode&&!gn(n)&&this.checkPoints.push(n.clone())}postLayoutBlockContents(e){this.checkPoints.length>0&&this.column.postLayoutBlock(e.nodeContext,this.checkPoints),this.checkPoints=[]}},Sa=class Sa extends mn{constructor(e,n){super(!0);this.formattingContext=e;this.column=n;d(this,"inRow",!1);d(this,"currentRowIndex",-1);d(this,"currentColumnIndex",0);d(this,"originalStopAtOverflow");d(this,"inHeader");d(this,"inFooter");this.originalStopAtOverflow=n.stopAtOverflow,n.stopAtOverflow=!1}resetColumn(){this.column.stopAtOverflow=this.originalStopAtOverflow}getColSpanningCellWidth(e){let n=this.formattingContext.colWidths;let s=0;for(let o=0;o<e.colSpan;o++)s+=n[e.anchorSlot.columnIndex+o];return s+=this.formattingContext.inlineBorderSpacing*(e.colSpan-1),s}layoutCell(e,n,s){let o=e.rowIndex,i=e.columnIndex,a=e.colSpan,l=n.viewNode,c=n.verticalAlign;a>1&&(T(l,"box-sizing","border-box"),T(l,this.formattingContext.vertical?"height":"width",`${this.getColSpanningCellWidth(e)}px`));let u=l.ownerDocument.createElement("div");l.appendChild(u);let p=new ed(this.column,u,n);return this.formattingContext.addCellFragment(o,i,p),s.primary.steps.length===1&&s.primary.after&&(p.empty=!0),p.pseudoColumn.layout(s,!0).thenReturn(!0)}hasBrokenCellAtSlot(e){let n=this.formattingContext.cellBreakPositions[0];return n?n.cell.anchorSlot.columnIndex===e:!1}extractRowSpanningCellBreakPositions(){let e=this.formattingContext.cellBreakPositions;if(e.length===0)return[];let n=[],s=0;do{let o=e[s],i=o.cell.rowIndex;if(i<this.currentRowIndex){let a=n[i];a||(a=n[i]=[]),a.push(o),e.splice(s,1)}else s++}while(s<e.length);return n}layoutRowSpanningCellsFromPreviousFragment(e){let n=this.formattingContext,s=this.extractRowSpanningCellBreakPositions(),o=s.reduce(h=>h+1,0);if(o===0)return v(!0);let i=this.column.layoutContext,a=e.nodeContext;a.viewNode.parentNode.removeChild(a.viewNode);let l=A("layoutRowSpanningCellsFromPreviousFragment"),c=v(!0),u=0,p=[];return s.forEach(h=>{c=c.thenAsync(()=>{let f=po(h[0].cellNodePosition.steps[1],a.parent);return i.setCurrent(f,!1).thenAsync(()=>{let g=v(!0),m=0;function E(y){for(;m<y;){if(!p.includes(m)){let C=f.viewNode.ownerDocument.createElement("td");T(C,"padding","0"),f.viewNode.appendChild(C)}m++}}return h.forEach(y=>{g=g.thenAsync(()=>{let C=y.cell;E(C.anchorSlot.columnIndex);let x=y.cellNodePosition,N=po(x.steps[0],f);return N.offsetInNode=x.offsetInNode,N.after=x.after,N.fragmentIndex=x.steps[0].fragmentIndex+1,i.setCurrent(N,!1).thenAsync(()=>{let S=y.breakChunkPosition;for(let w=0;w<C.colSpan;w++)p.push(m+w);return m+=C.colSpan,this.layoutCell(C,N,S).thenAsync(()=>(N.viewNode.rowSpan=C.rowIndex+C.rowSpan-this.currentRowIndex+o-u,v(!0)))})})}),g.thenAsync(()=>(E(n.getColumnCount()),u++,v(!0)))})})}),c.then(()=>{i.setCurrent(a,!0,e.atUnforcedBreak).then(()=>{l.finish(!0)})}),l.result()}startTableRow(e){if(this.inHeader||this.inFooter)return v(!0);let n=e.nodeContext,s=this.formattingContext;return this.currentRowIndex<0?(n.sourceNode,this.currentRowIndex=s.findRowIndexBySourceNode(n.sourceNode)):this.currentRowIndex++,this.currentColumnIndex=0,this.inRow=!0,this.layoutRowSpanningCellsFromPreviousFragment(e).thenAsync(()=>(this.registerCellFragmentIndex(),this.column.checkOverflowAndSaveEdgeAndBreakPosition(e.lastAfterNodeContext,null,!0,e.breakAtTheEdge)&&s.getRowSpanningCellsOverflowingTheRow(this.currentRowIndex-1).length===0&&(this.resetColumn(),n.overflow=!0,e.break=!0),v(!0)))}registerCellFragmentIndex(){this.formattingContext.getRowByIndex(this.currentRowIndex).cells.forEach(n=>{let s=this.formattingContext.cellBreakPositions[n.columnIndex];if(s&&s.cell.anchorSlot.columnIndex==n.anchorSlot.columnIndex){let o=s.cellNodePosition.steps[0],i=this.column.layoutContext.xmldoc.getElementOffset(o.node);bf(i,o.fragmentIndex+1,1)}})}startTableCell(e){if(this.inHeader||this.inFooter)return v(!0);let n=e.nodeContext;this.inRow||(this.currentRowIndex<0?this.currentRowIndex=0:this.currentRowIndex++,this.currentColumnIndex=0,this.inRow=!0);let s=this.formattingContext.getRowByIndex(this.currentRowIndex).cells[this.currentColumnIndex];if(!s)return e.break=!0,v(!0);let o=n.copy().modify();o.after=!0,e.nodeContext=o;let i=A("startTableCell"),a;if(this.hasBrokenCellAtSlot(s.anchorSlot.columnIndex)){let l=this.formattingContext.cellBreakPositions.shift();n.fragmentIndex=l.cellNodePosition.steps[0].fragmentIndex+1,a=v(l.breakChunkPosition)}else a=this.column.nextInTree(n,e.atUnforcedBreak).thenAsync(l=>{l.viewNode&&n.viewNode.removeChild(l.viewNode);let c=xs(l,0);return v(new pt(c))});return a.then(l=>{this.layoutCell(s,n,l).then(()=>{this.afterNonInlineElementNode(e),this.currentColumnIndex++,i.finish(!0)})}),i.result()}startNonInlineBox(e){let n=Sf(e,At(this.formattingContext),this.column);if(n)return n;let s=e.nodeContext,o=this.formattingContext.getRepetitiveElements(),i=s.display;return i==="table-header-group"&&o&&o.isHeaderSourceNode(s.sourceNode)?(this.inHeader=!0,v(!0)):i==="table-footer-group"&&o&&o.isFooterSourceNode(s.sourceNode)?(this.inFooter=!0,v(!0)):i==="table-row"?this.startTableRow(e):i==="table-cell"?this.startTableCell(e):v(!0)}endNonInlineBox(e){let n=e.nodeContext;if(n.display==="table-row"&&(this.inRow=!1,!this.inHeader&&!this.inFooter)){let o=n.copy().modify();o.after=!1;let i=new sd(this.currentRowIndex,o,this.formattingContext);this.column.breakPositions.push(i)}return v(!0)}afterNonInlineElementNode(e){let n=e.nodeContext,s=this.formattingContext.getRepetitiveElements(),o=n.display;if(o==="table-header-group"?s&&!s.allowInsertRepeatitiveElements&&s.isHeaderSourceNode(n.sourceNode)?(this.inHeader=!1,n.viewNode.parentNode.removeChild(n.viewNode)):T(n.viewNode,"display","table-row-group"):o==="table-footer-group"&&(s&&!s.allowInsertRepeatitiveElements&&s.isFooterSourceNode(n.sourceNode)?(this.inFooter=!1,n.viewNode.parentNode.removeChild(n.viewNode)):T(n.viewNode,"display","table-row-group")),o&&Sa.ignoreList[o])n.viewNode.parentNode.removeChild(n.viewNode);else if(n.sourceNode===this.formattingContext.tableSourceNode)n.overflow=this.column.checkOverflowAndSaveEdge(n,null),this.resetColumn(),e.break=!0;else return super.afterNonInlineElementNode(e);return v(!0)}};d(Sa,"ignoreList",{"table-caption":!0,"table-column-group":!0,"table-column":!0});var rd=Sa,yi=[];function NC(r){let t=yi.findIndex(n=>n.root===r),e=yi[t];return e?e.tableLayoutOption:null}function vC(r){let t=yi.findIndex(e=>e.root===r);t>=0&&yi.splice(t,1)}var Ea=class{layoutEntireTable(t,e){let n=At(t.formattingContext),s=new id(n,e);return new Ss(s,e.layoutContext).iterate(t)}getColumnWidths(t,e,n,s){let o=t.ownerDocument,i=o.createElement("tr"),a=[];for(let c=0;c<e;c++){let u=o.createElement("td");i.appendChild(u),a.push(u)}t.parentNode.insertBefore(i,t.nextSibling);let l=a.map(c=>{let u=s.getElementClientRect(c),p=n?u.height:u.width;return Math.ceil(p)});return t.parentNode.removeChild(i),l}getColGroupElements(t){let e=[],n=t.firstElementChild;for(;n;)n.localName==="colgroup"&&e.push(n),n=n.nextElementSibling;return e}normalizeAndGetColElements(t){let e=[];return t.forEach(n=>{let s=n.span;n.removeAttribute("span");let o=n.firstElementChild;for(;o;){if(o.localName==="col"){let i=o.span;for(o.removeAttribute("span"),s-=i;i-- >1;){let a=o.cloneNode(!0);n.insertBefore(a,o),e.push(a)}e.push(o)}o=o.nextElementSibling}for(;s-- >0;)o=n.ownerDocument.createElement("col"),n.appendChild(o),e.push(o)}),e}addMissingColElements(t,e,n,s){if(t.length<n){let o=s.ownerDocument.createElement("colgroup");e.push(o);for(let i=t.length;i<n;i++){let a=s.ownerDocument.createElement("col");o.appendChild(a),t.push(a)}}}normalizeColGroups(t,e,n){let s=t.vertical,o=t.lastRowViewNode;if(!o)return;t.lastRowViewNode=null;let a=o.ownerDocument.createDocumentFragment(),l=t.getColumnCount();if(!(l>0)){t.colGroups=a;return}let c=t.colWidths=this.getColumnWidths(o,l,s,n.clientLayout),u=this.getColGroupElements(e),p=this.normalizeAndGetColElements(u);this.addMissingColElements(p,u,l,e),p.forEach((h,f)=>{T(h,s?"height":"width",`${c[f]}px`)}),u.forEach(h=>{a.appendChild(h.cloneNode(!0))}),t.colGroups=a}doInitialLayout(t,e){let n=At(t.formattingContext);n.vertical=t.vertical,n.initializeRepetitiveElements(t.vertical),t.sourceNode;let s=NC(t.sourceNode);vC(t.sourceNode);let o=A("TableLayoutProcessor.doInitialLayout"),i=t.copy();return this.layoutEntireTable(t,e).then(a=>{let l=a.viewNode,c=e.clientLayout.getElementClientRect(l),u=e.vertical?c.left:c.bottom;if(u+=(e.vertical?-1:1)*Hn(t,e.collectElementsOffset()).current,!e.isOverflown(u)&&(!s||!s.calculateBreakPositionsInside)){e.breakPositions.push(new cd(i)),o.finish(a);return}this.normalizeColGroups(n,l,e),n.updateCellSizes(e.clientLayout),o.finish(null)}),o.result()}addCaptions(t,e,n){let s=t.captions;s.forEach((o,i)=>{o&&(e.insertBefore(o.viewNode,n),o.side==="top"&&(s[i]=null))})}addColGroups(t,e,n){t.colGroups&&this.getColGroupElements(e).length===0&&(e.insertBefore(t.colGroups.cloneNode(!0),n),T(e,"table-layout","fixed"),T(e,t.vertical?"height":"width",`${t.tableWidth}px`))}removeColGroups(t,e){if(t.colGroups&&e){let n=this.getColGroupElements(e);n&&n.forEach(s=>{e.removeChild(s)})}}doLayout(t,e){let n=At(t.formattingContext),s=n.getRootViewNode(t),o=s.firstChild;this.addCaptions(n,s,o),this.addColGroups(n,s,o);let i=new rd(n,e),a=new Ss(i,e.layoutContext),l=A("TableFormattingContext.doLayout");return a.iterate(t).thenFinish(l),l.result()}layout(t,e,n){let s=At(t.formattingContext);return s.getRootViewNode(t)?(n&&qu(t.parent,e),new ad(s,this).layout(t,e)):e.buildDeepElementView(t)}createEdgeBreakPosition(t,e,n,s){return new nd(t,e,n,s)}startNonInlineElementNode(t){return!1}afterNonInlineElementNode(t,e){return Zu(t),!1}finishBreak(t,e,n,s){let o=At(e.formattingContext);if(e.display==="table-row"){e.sourceNode;let i=o.findRowIndexBySourceNode(e.sourceNode);o.cellBreakPositions=[];let a;if(e.after?a=o.getRowSpanningCellsOverflowingTheRow(i):a=o.getCellsFallingOnRow(i),a.length){let l=A("TableLayoutProcessor.finishBreak"),c=0;return l.loopWithFrame(u=>{if(c===a.length){u.breakLoop();return}let p=a[c++],h=o.getCellFragmentOfCell(p),f=h.findAcceptableBreakPosition().nodeContext;let g=h.cellNodeContext,m=g.toNodePosition(),E=new pt(f.toNodePosition());o.cellBreakPositions.push({cellNodePosition:m,breakChunkPosition:E,cell:p});let y=g.viewNode;h.column.layoutContext.processFragmentedBlockEdge(h.cellNodeContext),i<p.rowIndex+p.rowSpan-1&&(y.rowSpan=i-p.rowIndex+1),h.empty?u.continueLoop():h.pseudoColumn.finishBreak(f,!1,!0).then(()=>{TC(h,o,f),u.continueLoop()})}).then(()=>{t.clearOverflownViewNodes(e,!1),t.layoutContext.processFragmentedBlockEdge(e),Zu(e),o.finishFragment(),l.finish(!0)}),l.result()}}return Zu(e),o.finishFragment(),ai.finishBreak(t,e,n,s)}clearOverflownViewNodes(t,e,n,s){nn.prototype.clearOverflownViewNodes(t,e,n,s)}};function TC(r,t,e){let n=t.getRepetitiveElements();if(!n||!(n.isHeaderRegistered()||n.isFooterRegistered()))return;let s=t.vertical,o=r.column,i=r.pseudoColumn.getColumnElement(),a=r.cellNodeContext.viewNode,l=o.clientLayout.getElementClientRect(a),c=o.getComputedPaddingBorder(a);if(s){let u=l.right-o.footnoteEdge-n.calculateOffset(e)-c.right;T(i,"max-width",`${u}px`)}else{let u=o.footnoteEdge-n.calculateOffset(e)-l.top-c.top;T(i,"max-height",`${u}px`)}}function Zu(r){let t=r.display==="table-row"?r.viewNode.parentElement:r.display==="table"?r.viewNode.querySelector("tbody"):null;if(!t)return;let e;try{e=t.querySelectorAll(":scope>tr:has(>:empty):not(:has(>:not([rowspan]:not([rowspan='1']),:empty)))")}catch(p){return}if(e.length===0)return;let n=Array.from(e).reduce((p,h)=>{let f=h.getBoundingClientRect(),g=r.vertical?f.width:f.height;return p+g},0),s=e[e.length-1],o=Array.from(t.children).indexOf(s),i=Array.from(s.children).reduce((p,h)=>{let f=h.rowSpan;return f>1&&o+f<t.childElementCount?Math.max(p,f):p},0),a=i?t.children[o+i-1]:t.lastElementChild;if(a!=t.lastElementChild&&a.querySelector(":scope>*>div>div")){for(let p=a;p&&p!==t.lastElementChild;p=p.nextElementSibling)if(p.querySelector(":scope>[rowspan]:not([rowspan='1'])")){a=p;break}}let l=a.getBoundingClientRect(),c=r.vertical?l.width:l.height,u=n+c;T(a,r.vertical?"width":"height",`${u}px`)}var ad=class extends Gn{constructor(e,n){super();this.tableFormattingContext=e;this.processor=n}resolveLayoutMode(e){let n=this.tableFormattingContext.getRepetitiveElements();return!n||!n.doneInitialLayout?new ld(this.tableFormattingContext,this.processor):(e.sourceNode===this.tableFormattingContext.tableSourceNode&&!e.after&&n&&n.preventSkippingHeader(),new dd(this.tableFormattingContext,this.processor))}clearNodes(e){super.clearNodes(e);let n=this.tableFormattingContext.getRootViewNode(e);this.processor.removeColGroups(this.tableFormattingContext,n)}restoreState(e,n){super.restoreState(e,n),this.tableFormattingContext.finishFragment()}},ld=class extends bi{constructor(e,n){super(e);this.processor=n}doLayout(e,n){return this.processor.doInitialLayout(e,n)}},cd=class extends tn{constructor(t){super(t,null,t.overflow,0)}getMinBreakPenalty(){if(!this.isEdgeUpdated)throw new Error("EdgeBreakPosition.prototype.updateEdge not called");return(this.overflows?3:0)+(this.position.parent?this.position.parent.breakPenalty:0)}breakPositionChosen(t){t.fragmentLayoutConstraints.push(new ud(this.position.sourceNode))}},ud=class r{constructor(t){this.tableRootNode=t;d(this,"flagmentLayoutConstraintType","EntireTable")}allowLayout(t,e,n){return t.overflow,!1}nextCandidate(t){return!0}postLayout(t,e,n,s){e.sourceNode,yi.push({root:e.sourceNode,tableLayoutOption:{calculateBreakPositionsInside:!0}})}finishBreak(t,e){return v(!0)}equalsTo(t){return t instanceof r&&t.tableRootNode===this.tableRootNode}getPriorityOfFinishBreak(){return 0}},dd=class extends xi{constructor(e,n){super(e);this.processor=n}doLayout(e,n){let s=this.formattingContext.getRepetitiveElements();if(s&&!s.isAfterLastContent(e)){let o=new pd(e);n.fragmentLayoutConstraints.some(i=>o.equalsTo(i))||n.fragmentLayoutConstraints.unshift(o)}return this.processor.doLayout(e,n)}},pd=class r extends To{constructor(e){super(e);d(this,"flagmentLayoutConstraintType","TableRow");d(this,"cellFragmentLayoutConstraints",[])}allowLayout(e,n,s){let o=this.getRepetitiveElements();return!o||s.pseudoParent||fn(this.nodeContext.viewNode)||!o.isEnableToUpdateState()?!0:!(n&&!e||e&&e.overflow)}nextCandidate(e){let n=At(this.nodeContext.formattingContext);return this.collectCellFragmentLayoutConstraints(e,n).some(o=>o.constraints.some(i=>i.nextCandidate(e)))?!0:super.nextCandidate(e)}postLayout(e,n,s,o){let i=At(this.nodeContext.formattingContext);if(this.cellFragmentLayoutConstraints=this.collectCellFragmentLayoutConstraints(n,i),this.cellFragmentLayoutConstraints.forEach(a=>{a.constraints.forEach(l=>{l.postLayout(e,a.breakPosition,s,o)})}),!e){let a=i.getRootViewNode(this.nodeContext);new Ea().removeColGroups(i,a),this.removeDummyRowNodes(s)}super.postLayout(e,n,s,o)}finishBreak(e,n){let s=At(this.nodeContext.formattingContext),o=A("finishBreak"),i=this.cellFragmentLayoutConstraints.reduce((l,c)=>l.concat(c.constraints.map(u=>({constraint:u,breakPosition:c.breakPosition}))),[]),a=0;return o.loop(()=>{if(a<i.length){let l=i[a++];return l.constraint.finishBreak(l.breakPosition,n).thenReturn(!0)}else return v(!1)}).then(()=>{o.finish(!0)}),o.result().thenAsync(()=>super.finishBreak(e,n))}removeDummyRowNodes(e){if(!(!e||e.display!=="table-row"||!e.viewNode))for(;e.viewNode.previousElementSibling;){let n=e.viewNode.previousElementSibling;n.parentNode&&n.parentNode.removeChild(n)}}collectCellFragmentLayoutConstraints(e,n){return this.getCellFragemnts(e,n).map(s=>({constraints:s.fragment.pseudoColumn.getColumn().fragmentLayoutConstraints,breakPosition:s.breakPosition}))}getCellFragemnts(e,n){let s=Number.MAX_VALUE;e&&e.display==="table-row"&&(e.sourceNode,s=n.findRowIndexBySourceNode(e.sourceNode)+1),s=Math.min(n.cellFragments.length,s);let o=[];for(let i=0;i<s;i++)n.cellFragments[i]&&n.cellFragments[i].forEach(a=>{a&&o.push({fragment:a,breakPosition:a.findAcceptableBreakPosition().nodeContext})});return o}getElementsOffsetsForTableCell(e){let n=At(this.nodeContext.formattingContext),s=n.findCellFromColumn(e);return s?n.collectElementsOffsetOfUpperCells(s):n.collectElementsOffsetOfHighestColumn()}equalsTo(e){return e instanceof r?At(this.nodeContext.formattingContext)===At(e.nodeContext.formattingContext):!1}},wC=new Ea;function PC(r,t,e,n,s,o){if(!t)return null;if(e===b.table){let i=r.parent;return new Yn(i?i.formattingContext:null,r.sourceNode)}return null}function kC(r){return r instanceof Yn?wC:null}_e("RESOLVE_FORMATTING_CONTEXT",PC);_e("RESOLVE_LAYOUT_PROCESSOR",kC);function Nf(r){return r.reduce((t,e)=>t+e,0)/r.length}function vf(r){let t=Nf(r);return Nf(r.map(e=>{let n=e-t;return n*n}))}var hd=class{constructor(t,e){this.layoutResult=t;this.penalty=e}};function Ei(r){return r.vertical?r.width:r.height}function Si(r,t){r.vertical?r.width=t:r.height=t}var Na=class{constructor(t,e,n){this.layoutContainer=t;this.columnGenerator=e;this.regionPageFloatLayoutContext=n;d(this,"originalContainerBlockSize");this.originalContainerBlockSize=Ei(t)}balanceColumns(t){let e=A("ColumnBalancer#balanceColumns");this.preBalance(t),this.savePageFloatLayoutContexts(t),this.layoutContainer.clear();let n=[this.createTrialResult(t)];return e.loopWithFrame(s=>{if(!this.hasNextCandidate(n)){s.breakLoop();return}this.updateCondition(n),this.columnGenerator().then(o=>{if(this.savePageFloatLayoutContexts(o),this.layoutContainer.clear(),!o){s.breakLoop();return}n.push(this.createTrialResult(o)),s.continueLoop()})}).then(()=>{let s=n.reduce((o,i)=>i.penalty<o.penalty?i:o,n[0]);this.restoreContents(s.layoutResult),this.postBalance(),e.finish(s.layoutResult)}),e.result()}createTrialResult(t){let e=this.calculatePenalty(t);return new hd(t,e)}preBalance(t){}postBalance(){Si(this.layoutContainer,this.originalContainerBlockSize)}savePageFloatLayoutContexts(t){let e=this.regionPageFloatLayoutContext.detachChildren();t&&(t.columnPageFloatLayoutContexts=e)}restoreContents(t){let e=this.layoutContainer.element;t.columns.forEach(n=>{e.appendChild(n.element)}),t.columnPageFloatLayoutContexts,this.regionPageFloatLayoutContext.attachChildren(t.columnPageFloatLayoutContexts)}},fd=1;function wf(r){let t=r[r.length-1];if(t.penalty===0)return!1;let e=r[r.length-2];if(e&&t.penalty>=e.penalty)return!1;let n=t.layoutResult.columns,s=Math.max.apply(null,n.map(i=>i.computedBlockSize)),o=Math.max.apply(null,n.map(i=>i.getMaxBlockSizeOfPageFloats()));return s>o+fd}function Pf(r,t){var o;let e=r[r.length-1].layoutResult.columns,s=Math.max.apply(null,e.map(i=>isNaN(i.blockDistanceToBlockEndFloats)?i.computedBlockSize:i.computedBlockSize-i.blockDistanceToBlockEndFloats+fd))-fd;if(s<Ei(t)?Si(t,s):Si(t,Ei(t)-1),t.vertical){let i=parseFloat((o=t.element.style)==null?void 0:o.width);t.originX=i-t.width}}var gd=class extends Na{constructor(e,n,s,o){super(s,e,n);this.columnCount=o;d(this,"originalPosition",null);d(this,"foundUpperBound",!1)}preBalance(e){let s=e.columns.reduce((o,i)=>o+i.computedBlockSize,0);Si(this.layoutContainer,s/this.columnCount),this.originalPosition=e.position}checkPosition(e){return this.originalPosition?this.originalPosition.isSamePosition(e):e===null}calculatePenalty(e){if(!this.checkPosition(e.position))return 1/0;let n=e.columns;return Tf(n)?1/0:Math.max.apply(null,n.map(s=>s.computedBlockSize))}hasNextCandidate(e){if(e.length===1)return!0;if(this.foundUpperBound)return wf(e);{let n=e[e.length-1];return this.checkPosition(n.layoutResult.position)&&!Tf(n.layoutResult.columns)?(this.foundUpperBound=!0,!0):Ei(this.layoutContainer)<this.originalContainerBlockSize}}updateCondition(e){if(this.foundUpperBound)Pf(e,this.layoutContainer);else{let n=Math.min(this.originalContainerBlockSize,Ei(this.layoutContainer)+this.originalContainerBlockSize*.1);Si(this.layoutContainer,n)}}};function Tf(r){if(r.length<=1)return!1;let t=r[r.length-1].computedBlockSize,e=r.slice(0,r.length-1),n=6;return e.every(s=>t>s.computedBlockSize+n)}var md=class extends Na{constructor(t,e,n){super(n,t,e)}calculatePenalty(t){if(t.columns.every(n=>n.computedBlockSize===0))return 1/0;let e=t.columns.filter(n=>!n.pageBreakType).map(n=>n.computedBlockSize);return vf(e)}hasNextCandidate(t){return wf(t)}updateCondition(t){Pf(t,this.layoutContainer)}};function kf(r,t,e,n,s,o,i){if(t===b.auto)return null;{let a=i.positions.length===0,l=o[o.length-1],c=!!(l&&l.pageBreakType);return a||c?new gd(e,n,s,r):t===b.balance_all?new md(e,n,s):(b.balance,null)}}var Ni=class{constructor(t,e,n){d(this,"endStuckFixed");d(this,"endFixed");d(this,"endSlipped");this.endStuckFixed=t,this.endFixed=e,this.endSlipped=n}},Cd=class{constructor(){d(this,"map",[])}getMaxFixed(){return this.map.length==0?0:this.map[this.map.length-1].endFixed}getMaxSlipped(){return this.map.length==0?0:this.map[this.map.length-1].endSlipped}addStuckRange(t){if(this.map.length==0)this.map.push(new Ni(t,t,t));else{let e=this.map[this.map.length-1],n=e.endSlipped+t-e.endFixed;e.endFixed==e.endStuckFixed?(e.endFixed=t,e.endStuckFixed=t,e.endSlipped=n):this.map.push(new Ni(t,t,n))}}addSlippedRange(t){this.map.length==0?this.map.push(new Ni(t,0,0)):this.map[this.map.length-1].endFixed=t}slippedByFixed(t){let e=ft(this.map.length,s=>t<=this.map[s].endFixed),n=this.map[e];return n.endSlipped-Math.max(0,n.endStuckFixed-t)}fixedBySlipped(t){let e=ft(this.map.length,s=>t<=this.map[s].endSlipped),n=this.map[e];return n.endStuckFixed-(n.endSlipped-t)}},bd=class r{constructor(t,e,n,s,o,i,a,l){this.context=t;this.style=e;this.offset=n;this.isRoot=s;this.flowChunk=o;this.atBlockStart=i;this.atFlowStart=a;this.isParentBoxDisplayed=l;d(this,"flowName");d(this,"isBlockValue",null);d(this,"hasBoxValue",null);d(this,"styleValues",{});d(this,"beforeBox",null);d(this,"afterBox",null);d(this,"breakBefore",null);if(this.flowName=o.flowName,this.hasBox()){let c=e._pseudos;if(c&&c.before){let u=new r(t,c.before,n,!1,o,this.isBlock(),a,!0),p=u.styleValue("content");Et(p)&&(this.beforeBox=u,this.breakBefore=u.breakBefore)}}this.breakBefore=Fe(this.getBreakValue("before"),this.breakBefore),this.atFlowStart&&De(this.breakBefore)&&(o.breakBefore=Fe(o.breakBefore,this.breakBefore))}buildAfterPseudoElementBox(t,e,n){if(this.hasBox()){let s=this.style._pseudos;if(s&&s.after){let o=new r(this.context,s.after,t,!1,this.flowChunk,e,n,!0),i=o.styleValue("content");Et(i)&&(this.afterBox=o)}}}styleValue(t,e){if(!(t in this.styleValues)){let n=this.style[t];this.styleValues[t]=n?n.evaluate(this.context,t):e||null}return this.styleValues[t]}displayValue(){return this.styleValue("display",b.inline)}isBlock(){if(this.isBlockValue===null){let t=this.displayValue(),e=this.styleValue("position"),n=this.styleValue("float");this.isBlockValue=Kr(t,e,n,this.isRoot)}return this.isBlockValue}hasBox(){return this.hasBoxValue===null&&(this.hasBoxValue=this.isParentBoxDisplayed&&this.displayValue()!==b.none&&!ii(this.styleValue("position"))),this.hasBoxValue}getBreakValue(t){let e=null;if(this.isBlock()){let n=this.styleValue(`break-${t}`);n&&(e=n.toString())}return e}},xd=class{constructor(t){this.context=t;d(this,"stack",[]);d(this,"atBlockStart",!0);d(this,"atFlowStart",!0);d(this,"atStartStack",[])}empty(){return this.stack.length===0}lastBox(){return this.stack[this.stack.length-1]}lastFlowName(){let t=this.lastBox();return t?t.flowChunk.flowName:null}isCurrentBoxDisplayed(){return this.stack.every(t=>t.displayValue()!==b.none)}push(t,e,n,s){let o=this.lastBox();s&&o&&s.flowName!==o.flowName&&this.atStartStack.push({atBlockStart:this.atBlockStart,atFlowStart:this.atFlowStart});let i=s||o.flowChunk,a=this.atFlowStart||!!s,l=this.isCurrentBoxDisplayed(),c=new bd(this.context,t,e,n,i,a||this.atBlockStart,a,l);return this.stack.push(c),this.atBlockStart=c.hasBox()?!c.beforeBox&&c.isBlock():this.atBlockStart,this.atFlowStart=c.hasBox()?!c.beforeBox&&a:this.atFlowStart,c}encounteredTextNode(t){let e=this.lastBox();if((t.nodeType===Node.TEXT_NODE||t.nodeType===Node.CDATA_SECTION_NODE)&&(this.atBlockStart||this.atFlowStart)&&e.hasBox()){let n=e.styleValue("white-space",b.normal).toString(),s=$r(n);s&&!ue(t,s)&&(this.atBlockStart=!1,this.atFlowStart=!1)}}pop(t){let e=this.stack.pop();if(e.buildAfterPseudoElementBox(t,this.atBlockStart,this.atFlowStart),this.atFlowStart&&e.afterBox){let s=e.afterBox.getBreakValue("before");e.flowChunk.breakBefore=Fe(e.flowChunk.breakBefore,s)}let n=this.lastBox();if(n)if(n.flowName===e.flowName)e.hasBox()&&(this.atBlockStart=this.atFlowStart=!1);else{let s=this.atStartStack.pop();this.atBlockStart=s.atBlockStart,this.atFlowStart=s.atFlowStart}return e}nearestBlockStartOffset(t){if(!t.atBlockStart)return t.offset;let e=this.stack.length-1,n=this.stack[e];for(n===t&&(e--,n=this.stack[e]);e>=0;){if(n.flowName!==t.flowName)return t.offset;if(!n.atBlockStart||n.isRoot)return n.offset;t=n,n=this.stack[--e]}throw new Error("No block start offset found!")}},vi=class{constructor(t,e,n,s,o,i,a,l){this.xmldoc=t;this.scope=n;this.context=s;this.primaryFlows=o;this.validatorSet=i;this.counterListener=a;d(this,"root");d(this,"cascadeHolder");d(this,"last");d(this,"rootStyle",{});d(this,"styleMap",{});d(this,"flows",{});d(this,"flowChunks",[]);d(this,"flowListener",null);d(this,"flowToReach",null);d(this,"idToReach",null);d(this,"cascade");d(this,"offsetMap");d(this,"primary",!0);d(this,"primaryStack",[]);d(this,"rootBackgroundAssigned",!1);d(this,"rootLayoutAssigned",!1);d(this,"lastOffset");d(this,"breakBeforeValues",{});d(this,"boxStack");d(this,"bodyReached",!0);this.root=t.root,this.cascadeHolder=e,this.last=this.root,this.cascade=e.createInstance(s,a,l,t.lang),this.offsetMap=new Cd;let c=t.getElementOffset(this.root);this.lastOffset=c,this.boxStack=new xd(s),this.offsetMap.addStuckRange(c);let u=this.getAttrStyle(this.root);switch(this.cascade.pushElement(this,this.root,u,c),this.postprocessTopStyle(u,!1),this.root.namespaceURI){case"http://www.w3.org/1999/xhtml":this.bodyReached=!1;break}this.primaryStack.push(!0),this.styleMap={},this.styleMap[`e${c}`]=u,this.lastOffset++,this.replayFlowElementsFromOffset(-1)}hasProp(t,e,n){let s=t[n];return s&&s.evaluate(this.context)!==e[n]}transferPropsToRoot(t,e){for(let n in e){let s=t[n];if(s)this.rootStyle[n]=s,delete t[n];else{let o=e[n];o&&(this.rootStyle[n]=new M(o,gc))}}}postprocessTopStyle(t,e){var n;if(e)for(let s of["writing-mode","direction"])t[s]&&!(e&&this.rootStyle[s])&&(this.rootStyle[s]=t[s]);else for(let s in t)Xn(s)&&(this.rootStyle[s]=t[s]);if(!this.rootBackgroundAssigned){let s=this.hasProp(t,this.validatorSet.backgroundProps,"background-color")?t["background-color"].evaluate(this.context):null,o=this.hasProp(t,this.validatorSet.backgroundProps,"background-image")?t["background-image"].evaluate(this.context):null;(s&&!_(s)||o&&!_(o))&&(this.transferPropsToRoot(t,this.validatorSet.backgroundProps),this.rootBackgroundAssigned=!0)}if(!this.rootLayoutAssigned){for(let s=0;s<Af.length;s++)if(this.hasProp(t,this.validatorSet.layoutProps,Af[s])){this.transferPropsToRoot(t,this.validatorSet.layoutProps),this.rootLayoutAssigned=!0;break}}if(!e){let s=t["font-size"],o=!0;if(s&&!_(s.value)){let l=s.evaluate(this.context);if(l instanceof P){let c=l.num;switch(l.unit){case"em":case"rem":c*=this.context.initialFontSize;break;case"ex":c*=this.context.initialFontSize*$.ex/$.em;break;case"%":c*=this.context.initialFontSize/100;break;case"lh":case"rlh":c*=this.context.initialFontSize*$.lh/$.em;break;default:{let u=$[l.unit];u&&(c*=u),o=!1}}this.context.rootFontSize=c,this.context.isRelativeRootFontSize=o}}let i=(n=this.context.rootFontSize)!=null?n:this.context.initialFontSize,a=t["line-height"];if(a&&!_(a.value)){let l=a.evaluate(this.context);if(l instanceof tt)this.context.rootLineHeight=l.num*i;else if(l instanceof P){let c=l.num;switch(l.unit){case"em":case"rem":c*=i;break;case"ex":c*=i*$.ex/$.em;break;case"%":c*=i/100;break;case"lh":case"rlh":c*=this.context.initialFontSize*$.lh/$.em;break;default:{let u=$[l.unit];u&&(c*=u)}}this.context.rootLineHeight=c}}else this.context.rootLineHeight=this.context.fontSize()*$.lh/$.em}}getTopContainerStyle(){let t=0;for(;!this.bodyReached&&(t+=5e3,this.styleUntil(t,0)!=Number.POSITIVE_INFINITY););return this.rootStyle}getAttrStyle(t){if(t.style instanceof CSSStyleDeclaration){let e=t.getAttribute("style");if(e)return tf(this.scope,this.validatorSet,this.xmldoc.url,e)}return{}}getReachedOffset(){return this.lastOffset}replayFlowElementsFromOffset(t){if(t>=this.lastOffset)return;let e=this.context,n=this.xmldoc.getElementOffset(this.root);if(t<n){let i=this.getStyle(this.root,!1);let a=pe(i,"flow-into"),l=a?a.evaluate(e,"flow-into").toString():"body",c=this.encounteredFlowElement(l,i,this.root,n);this.boxStack.empty()&&this.boxStack.push(i,n,!0,c)}let s=this.xmldoc.getNodeByOffset(t),o=this.xmldoc.getNodeOffset(s,0,!1);if(!(o>=this.lastOffset))for(;;){if(s.nodeType!=1)o+=s.textContent.length;else{let a=s,l=this.getStyle(a,!1),c=l["flow-into"];if(c){let u=c.evaluate(e,"flow-into").toString();this.encounteredFlowElement(u,l,a,o)}o++}if(o>=this.lastOffset)break;let i=s.firstChild;if(i==null){for(;i=s.nextSibling,!i;)if(s=s.parentNode,s===this.root)return}s=i}}resetFlowChunkStream(t){this.flowListener=t;for(let e=0;e<this.flowChunks.length;e++)this.flowListener.encounteredFlowChunk(this.flowChunks[e],this.flows[this.flowChunks[e].flowName])}styleUntilFlowIsReached(t){this.flowToReach=t;let e=0;for(;!(this.flowToReach==null||(e+=5e3,this.styleUntil(e,0)==Number.POSITIVE_INFINITY)););}styleUntilIdIsReached(t){if(!t)return;this.idToReach=t;let e=0;for(;!(!this.idToReach||(e+=5e3,this.styleUntil(e,0)===Number.POSITIVE_INFINITY)););this.idToReach=null}encounteredFlowElement(t,e,n,s){let o=0,i=Number.POSITIVE_INFINITY,a=!1,l=!1,c=!1,u=e["flow-options"];if(u){let E=Kp(u.evaluate(this.context,"flow-options"));a=!!E.exclusive,l=!!E.static,c=!!E.last}let p=e["flow-linger"];p&&(i=Hl(p.evaluate(this.context,"flow-linger"),Number.POSITIVE_INFINITY));let h=e["flow-priority"];h&&(o=Hl(h.evaluate(this.context,"flow-priority"),0));let f=this.breakBeforeValues[s]||null,g=this.flows[t];if(!g){let E=this.boxStack.lastFlowName();g=this.flows[t]=new _r(t,E)}let m=new Ur(t,n,s,o,i,a,l,c,f);return this.flowChunks.push(m),this.flowToReach==t&&(this.flowToReach=null),this.flowListener&&this.flowListener.encounteredFlowChunk(m,g),m}registerForcedBreakOffset(t,e,n){if(De(t)){let o=this.flows[n].forcedBreakOffsets;(o.length===0||o[o.length-1]<e)&&o.push(e)}let s=this.breakBeforeValues[e];this.breakBeforeValues[e]=Fe(s,t)}styleUntil(t,e){let n=-1,s;if(t<=this.lastOffset&&(s=this.offsetMap.slippedByFixed(t),n=s+e,n<this.offsetMap.getMaxSlipped()))return this.offsetMap.fixedBySlipped(n);if(this.last==null)return Number.POSITIVE_INFINITY;let o=this.context;for(;;){let i=this.last.firstChild;if(i==null)for(;;){if(this.last.nodeType==1){this.cascade.popElement(this.last),this.primary=this.primaryStack.pop();let a=this.boxStack.pop(this.lastOffset),l=null;if(a.afterBox){let c=a.afterBox.getBreakValue("before");this.registerForcedBreakOffset(c,a.afterBox.atBlockStart?this.boxStack.nearestBlockStartOffset(a):a.afterBox.offset,a.flowName),l=a.afterBox.getBreakValue("after")}l=Fe(l,a.getBreakValue("after")),this.registerForcedBreakOffset(l,this.lastOffset,a.flowName)}if(i=this.last.nextSibling,i)break;if(this.last=this.last.parentNode,this.last===this.root)return this.last=null,t<this.lastOffset&&(n<0&&(s=this.offsetMap.slippedByFixed(t),n=s+e),n<=this.offsetMap.getMaxSlipped())?this.offsetMap.fixedBySlipped(n):Number.POSITIVE_INFINITY}if(this.last=i,this.last.nodeType!=1)this.lastOffset+=this.last.textContent.length,this.boxStack.encounteredTextNode(this.last),this.primary?this.offsetMap.addStuckRange(this.lastOffset):this.offsetMap.addSlippedRange(this.lastOffset);else{let a=this.last,l=this.getAttrStyle(a);this.primaryStack.push(this.primary),this.cascade.pushElement(this,a,l,this.lastOffset);let c=a.getAttribute("id")||a.getAttributeNS("http://www.w3.org/XML/1998/namespace","id");c&&c===this.idToReach&&(this.idToReach=null),!this.bodyReached&&a.localName=="body"&&a.parentNode==this.root&&(this.postprocessTopStyle(l,!0),this.bodyReached=!0);let u,p=l["flow-into"];if(p){let f=p.evaluate(o,"flow-into").toString(),g=this.encounteredFlowElement(f,l,a,this.lastOffset);this.primary=!!this.primaryFlows[f],u=this.boxStack.push(l,this.lastOffset,a===this.root,g)}else u=this.boxStack.push(l,this.lastOffset,a===this.root),a===this.xmldoc.body&&(u.breakBefore=Fe(u.flowChunk.breakBefore,u.breakBefore));let h=this.boxStack.nearestBlockStartOffset(u);if(h===0){let f=l.page,g=f&&!_(f.value)&&f.value.toString();g&&g.toLowerCase()!=="auto"&&(this.cascade.firstPageType=g)}if(this.registerForcedBreakOffset(u.breakBefore,h,u.flowName),u.beforeBox){let f=u.beforeBox.getBreakValue("after");this.registerForcedBreakOffset(f,u.beforeBox.atBlockStart?h:u.offset,u.flowName)}if(this.primary&&u.displayValue()===b.none&&(this.primary=!1),this.styleMap[`e${this.lastOffset}`]=l,this.lastOffset++,this.primary?this.offsetMap.addStuckRange(this.lastOffset):this.offsetMap.addSlippedRange(this.lastOffset),this.bodyReached&&h===0)continue;if(t<this.lastOffset&&(n<0&&(s=this.offsetMap.slippedByFixed(t),n=s+e),n<=this.offsetMap.getMaxSlipped()))return this.offsetMap.fixedBySlipped(n)}}}getStyle(t,e){let n=this.xmldoc.getElementOffset(t),s=`e${n}`;return e&&(n=this.xmldoc.getNodeOffset(t,0,!0)),this.lastOffset<=n&&this.styleUntil(n,0),this.styleMap[s]}processContent(t,e,n){}},Af=["column-count","column-width","column-fill"];var Kn=class{constructor(t){this.validator=t;d(this,"success",null);d(this,"failure",null);d(this,"code",0)}isSpecial(){return this.code!=0}markAsStartGroup(){this.code=-1}isStartGroup(){return this.code==-1}markAsEndGroup(){this.code=-2}isEndGroup(){return this.code==-2}markAsStartAlternate(t){this.code=2*t+1}isStartAlternate(){return this.code>0&&this.code%2!=0}markAsEndAlternate(t){this.code=2*t+2}isEndAlternate(){return this.code>0&&this.code%2==0}getAlternate(){return Math.floor((this.code-1)/2)}},En=class{constructor(t,e){this.where=t;this.success=e;d(this,"what",-1)}};var Fs=class r{constructor(){d(this,"nodes",[]);d(this,"connections",[]);d(this,"match",[]);d(this,"nomatch",[]);d(this,"error",[]);d(this,"emptyHead",!0)}connect(t,e){for(let n=0;n<t.length;n++)this.connections[t[n]].what=e;t.splice(0,t.length)}clone(){let t=new r;for(let e=0;e<this.nodes.length;e++){let n=this.nodes[e],s=new Kn(n.validator);s.code=n.code,t.nodes.push(s)}for(let e=0;e<this.connections.length;e++){let n=this.connections[e],s=new En(n.where,n.success);s.what=n.what,t.connections.push(s)}return t.match.push(...this.match),t.nomatch.push(...this.nomatch),t.error.push(...this.error),t}addSpecialToArr(t,e,n){let s=this.nodes.length,o=new Kn(Lf);n>=0?e?o.markAsStartAlternate(n):o.markAsEndAlternate(n):e?o.markAsStartGroup():o.markAsEndGroup(),this.nodes.push(o),this.connect(t,s);let i=new En(s,!0),a=new En(s,!1);t.push(this.connections.length),this.connections.push(a),t.push(this.connections.length),this.connections.push(i)}endSpecialGroup(){let t=[this.match,this.nomatch,this.error];for(let e=0;e<t.length;e++)this.addSpecialToArr(t[e],!1,-1)}startSpecialGroup(){if(this.nodes.length)throw new Error("invalid call");this.addSpecialToArr(this.match,!0,-1)}endClause(t){this.addSpecialToArr(this.match,!1,t)}startClause(t){if(this.nodes.length)throw new Error("invalid call");let e=new Kn(Lf);e.markAsStartAlternate(t),this.nodes.push(e);let n=new En(0,!0),s=new En(0,!1);this.nomatch.push(this.connections.length),this.connections.push(s),this.match.push(this.connections.length),this.connections.push(n)}addPrimitive(t){let e=this.nodes.length;this.nodes.push(new Kn(t));let n=new En(e,!0),s=new En(e,!1);this.connect(this.match,e),this.emptyHead?(this.nomatch.push(this.connections.length),this.emptyHead=!1):this.error.push(this.connections.length),this.connections.push(s),this.match.push(this.connections.length),this.connections.push(n)}isSimple(){return this.nodes.length==1&&!this.nodes[0].isSpecial()}isPrimitive(){return this.isSimple()&&this.nodes[0].validator instanceof Ce}addGroup(t,e){if(t.nodes.length==0)return;let n=this.nodes.length;if(e==4&&n==1&&t.isPrimitive()&&this.isPrimitive()){this.nodes[0].validator=this.nodes[0].validator.combine(t.nodes[0].validator);return}for(let o=0;o<t.nodes.length;o++)this.nodes.push(t.nodes[o]);e==4?(this.emptyHead=!0,this.connect(this.nomatch,n)):this.connect(this.match,n);let s=this.connections.length;for(let o=0;o<t.connections.length;o++){let i=t.connections[o];i.where+=n,i.what>=0&&(i.what+=n),this.connections.push(i)}for(let o=0;o<t.match.length;o++)this.match.push(t.match[o]+s);if(e==3&&this.connect(this.match,n),e==2||e==3)for(let o=0;o<t.nomatch.length;o++)this.match.push(t.nomatch[o]+s);else if(this.emptyHead){for(let o=0;o<t.nomatch.length;o++)this.nomatch.push(t.nomatch[o]+s);this.emptyHead=t.emptyHead}else for(let o=0;o<t.nomatch.length;o++)this.error.push(t.nomatch[o]+s);for(let o=0;o<t.error.length;o++)this.error.push(t.error[o]+s);t.nodes=null,t.connections=null}finish(t,e){let n=this.nodes.length;this.nodes.push(t),this.nodes.push(e),this.connect(this.match,n),this.connect(this.nomatch,n+1),this.connect(this.error,n+1);for(let s of this.connections)s.success?this.nodes[s.where].success=this.nodes[s.what]:this.nodes[s.where].failure=this.nodes[s.what];for(let s=0;s<n;s++)if(this.nodes[s].failure==null||this.nodes[s].success==null)throw new Error("Invalid validator state");return this.nodes[0]}},IC=1,If=2,Vf=4,Vs=8,va=16,yd=32,Ta=64,Ff=128,Ti=256,wi=512,Ed=1024,Bf=2048,Of=4096,Df=8192,wa=class extends lt{constructor(){super()}validateForShorthand(t,e){let n=t[e].visit(this);return n?[n]:null}},Ce=class r extends wa{constructor(e,n,s){super();this.allowed=e;this.idents=n;this.units=s}visitEmpty(e){return this.allowed&IC?e:null}visitSlash(e){return this.allowed&Bf?e:null}visitStr(e){return this.allowed&If?e:null}visitIdent(e){let n=this.idents[e.name.toLowerCase()];return n||(this.allowed&Vf||this.allowed&Ta&&CSS.supports("color",e.name)?e:null)}visitNumeric(e){return e.num==0&&!(this.allowed&wi)?e.unit=="%"&&this.allowed&Ed?e:null:e.num<0&&!(this.allowed&Ti)?null:this.units[e.unit]?e:null}visitNum(e){return e.num==0?this.allowed&wi?e:null:e.num<=0&&!(this.allowed&Ti)?null:this.allowed&va?e:null}visitInt(e){if(e.num==0)return this.allowed&wi?e:null;if(e.num<=0&&!(this.allowed&Ti))return null;if(this.allowed&(yd|va))return e;let n=this.idents[`${e.num}`];return n||null}visitHexColor(e){return this.allowed&Ta&&/^([0-9A-F]{3,4}|([0-9A-F]{2}){3,4})$/i.test(e.hex)?e:null}visitURL(e){return this.allowed&Ff?e:null}visitURange(e){return this.allowed&Of?e:null}visitSpaceList(e){return null}visitCommaList(e){return null}visitFunc(e){return this.allowed&Ta&&CSS.supports("color",e.toString())||this.allowed&Df&&CSS.supports("background-image",e.toString())||e.name==="calc"&&this.allowed&(Vs|va|yd|Ti|wi|Ed)?e:null}visitExpr(e){return this.allowed&2046?e:null}combine(e){let n={},s={};for(let o in this.idents)n[o]=this.idents[o];for(let o in e.idents)n[o]=e.idents[o];for(let o in this.units)s[o]=this.units[o];for(let o in e.units)s[o]=e.units[o];return new r(this.allowed|e.allowed,n,s)}},W={},Lf=new Ce(0,W,W),Pi=class extends wa{constructor(e){super();d(this,"successTerminal");d(this,"failureTerminal");d(this,"first");this.successTerminal=new Kn(null),this.failureTerminal=new Kn(null),this.first=e.finish(this.successTerminal,this.failureTerminal)}validateList(e,n,s){let o=n?[]:e,i=this.first,a=s,l=null,c=null;for(;i!==this.successTerminal&&i!==this.failureTerminal;){if(a>=e.length){i=i.failure;continue}let u=e[a],p=u;if(i.isSpecial()){let h=!0;i.isStartGroup()?(l?l.push(c):l=[c],c=[]):i.isEndGroup()?l.length>0?c=l.pop():c=null:i.isEndAlternate()?c[i.getAlternate()]="taken":h=c[i.getAlternate()]==null,i=h?i.success:i.failure}else{if(a==0&&!n&&i.validator instanceof Bs&&this instanceof Bs){if(p=new K(e).visit(i.validator),p){a=e.length,i=i.success;continue}}else if(a==0&&!n&&i.validator instanceof ki&&this instanceof Bs){if(p=new ge(e).visit(i.validator),p){a=e.length,i=i.success;continue}}else p=u.visit(i.validator);if(!p){i=i.failure;continue}if(p!==u&&e===o){o=[];for(let h=0;h<a;h++)o[h]=e[h]}e!==o&&(o[a-s]=p),a++,i=i.success}}return i===this.successTerminal&&(n?o.length>0:a==e.length)?o:null}validateSingle(e){let n=null,s=this.first;for(;s!==this.successTerminal&&s!==this.failureTerminal;){if(!e){s=s.failure;continue}if(s.isSpecial()){s=s.success;continue}if(n=e.visit(s.validator),!n){s=s.failure;continue}e=null,s=s.success}return s===this.successTerminal?n:null}visitEmpty(e){return this.validateSingle(e)}visitSlash(e){return this.validateSingle(e)}visitStr(e){return this.validateSingle(e)}visitIdent(e){return this.validateSingle(e)}visitNumeric(e){return this.validateSingle(e)}visitNum(e){return this.validateSingle(e)}visitInt(e){return this.validateSingle(e)}visitHexColor(e){return this.validateSingle(e)}visitURL(e){return this.validateSingle(e)}visitURange(e){return this.validateSingle(e)}visitSpaceList(e){return null}visitCommaList(e){return null}visitFunc(e){return this.validateSingle(e)}visitExpr(e){return null}},Bs=class extends Pi{constructor(t){super(t)}visitSpaceList(t){let e=this.validateList(t.values,!1,0);return e===t.values?t:e?new K(e):null}visitCommaList(t){let e=this.first,n=!1;for(;e;){if(e.validator instanceof ki){n=!0;break}e=e.failure}if(n){let s=this.validateList(t.values,!1,0);return s===t.values?t:s?new ge(s):null}return null}validateForShorthand(t,e){return this.validateList(t,!0,e)}},ki=class extends Pi{constructor(t){super(t)}visitSpaceList(t){return this.validateSingle(t)}visitCommaList(t){let e=this.validateList(t.values,!1,0);return e===t.values?t:e?new ge(e):null}validateForShorthand(t,e){let n=this.first,s;for(;n!==this.failureTerminal;){if(s=n.validator.validateForShorthand(t,e),s)return s;n=n.failure}return null}},Sd=class extends Pi{constructor(e,n){super(n);this.name=e}validateSingle(e){return null}visitFunc(e){if(e.name.toLowerCase()!=this.name)return null;let n=this.validateList(e.values,!1,0);return n===e.values?e:n?new wt(e.name,n):null}},Pa=class{tryParse(t,e,n){return e}success(t,e){}},ka=class extends Pa{constructor(e,n){super();this.name=n;d(this,"validator");this.validator=e.validators[this.name]}tryParse(e,n,s){if(s.values[this.name])return n;let o=this.validator.validateForShorthand(e,n);if(o){let i=o.length,a=i>1?new K(o):o[0];return this.success(a,s),n+i}return n}success(e,n){n.values[this.name]=e}},Nd=class extends ka{constructor(e,n){super(e,n[0]);this.names=n}success(e,n){for(let s=0;s<this.names.length;s++)n.values[this.names[s]]=e}},vd=class extends Pa{constructor(e,n){super();this.nodes=e;this.slash=n}tryParse(e,n,s){let o=n;if(this.slash)if(e[n]==qs){if(++n==e.length)return o}else return o;let i=this.nodes[0].tryParse(e,n,s);if(i==n)return o;n=i;for(let a=1;a<this.nodes.length&&n<e.length&&(i=this.nodes[a].tryParse(e,n,s),i!=n);a++)n=i;return n}},Ai=class extends lt{constructor(){super(...arguments);d(this,"syntax",null);d(this,"propList",null);d(this,"error",!1);d(this,"values",{});d(this,"validatorSet",null)}setOwner(e){this.validatorSet=e}syntaxNodeForProperty(e){return new ka(this.validatorSet,e)}clone(){let e=new this.constructor;return e.syntax=this.syntax,e.propList=this.propList,e.validatorSet=this.validatorSet,e}init(e,n){this.syntax=e,this.propList=n}finish(e,n){var s,o;if(!this.error){for(let i of this.propList)n.simpleProperty(i,(o=(s=this.values[i])!=null?s:this.validatorSet.defaultValues[i])!=null?o:b.initial,e);return!0}return!1}propagateDefaultingValue(e,n,s){for(let o of this.propList)s.simpleProperty(o,e,n)}validateList(e){return this.error=!0,0}validateSingle(e){return this.validateList([e]),null}visitEmpty(e){return this.validateSingle(e)}visitStr(e){return this.validateSingle(e)}visitIdent(e){return this.validateSingle(e)}visitNumeric(e){return this.validateSingle(e)}visitNum(e){return this.validateSingle(e)}visitInt(e){return this.validateSingle(e)}visitHexColor(e){return this.validateSingle(e)}visitURL(e){return this.validateSingle(e)}visitSpaceList(e){return this.validateList(e.values),null}visitCommaList(e){return this.error=!0,null}visitFunc(e){return this.validateSingle(e)}visitExpr(e){return this.validateSingle(e)}},qn=class extends Ai{constructor(){super()}validateList(t){let e=0,n=0;for(;e<t.length;){let s=this.syntax[n].tryParse(t,e,this);if(s>e){e=s,n=0;continue}if(++n==this.syntax.length){this.error=!0;break}}return e}},Aa=class extends Ai{constructor(){super()}validateList(t){if(t.length>this.syntax.length||t.length==0)return this.error=!0,0;for(let e=0;e<this.syntax.length;e++){let n=e;for(;n>=t.length;)n=n==1?0:n-2;if(this.syntax[e].tryParse(t,n,this)!=n+1)return this.error=!0,0}return t.length}createSyntaxNode(){return new Nd(this.validatorSet,this.propList)}},Td=class extends Ai{constructor(){super()}validateList(t){let e=t.length;for(let n=0;n<t.length;n++)if(t[n]===qs){e=n;break}if(e>this.syntax.length||t.length==0)return this.error=!0,0;for(let n=0;n<this.syntax.length;n++){let s=n;for(;s>=e;)s=s==1?0:s-2;let o;if(e+1<t.length)for(o=e+n+1;o>=t.length;)o=o-(o==e+2?1:2);else o=s;let i=[t[s],t[o]];if(this.syntax[n].tryParse(i,0,this)!=2)return this.error=!0,0}return t.length}},wd=class extends qn{constructor(){super()}mergeIn(t,e){var n,s;for(let o of this.propList){let i=(s=(n=e[o])!=null?n:this.validatorSet.defaultValues[o])!=null?s:b.initial,a=t[o];a||(a=[],t[o]=a),a.push(i)}}visitCommaList(t){let e={};for(let n=0;n<t.values.length;n++)if(this.values={},t.values[n]instanceof ge?this.error=!0:(t.values[n].visit(this),this.mergeIn(e,this.values),this.values["background-color"]&&n!=t.values.length-1&&(this.error=!0)),this.error)return null;this.values={};for(let n in e)n=="background-color"?this.values[n]=e[n].pop():this.values[n]=new ge(e[n]);return null}},Pd=class extends qn{constructor(){super()}init(t,e){super.init(t,e),this.propList.push("font-family","line-height","font-size","font-stretch","font-variant-ligatures","font-variant-caps","font-variant-numeric","font-variant-east-asian")}validateList(t){let e=super.validateList(t),n=this.values["font-variant_css2"];n&&(delete this.values["font-variant_css2"],this.values["font-variant-caps"]=n);let s=this.values["font-stretch_css3"];if(s&&(delete this.values["font-stretch_css3"],this.values["font-stretch"]=s),e+2>t.length)return this.error=!0,e;this.error=!1;let o=this.validatorSet.validators;if(!t[e].visit(o["font-size"]))return this.error=!0,e;if(this.values["font-size"]=t[e++],t[e]===qs){if(e++,e+2>t.length)return this.error=!0,e;if(!t[e].visit(o["line-height"]))return this.error=!0,e;this.values["line-height"]=t[e++]}let i=e==t.length-1?t[e]:new K(t.slice(e,t.length));return i.visit(o["font-family"])?(this.values["font-family"]=i,t.length):(this.error=!0,e)}visitCommaList(t){if(t.values[0].visit(this),this.error)return null;let e=[this.values["font-family"]];for(let s=1;s<t.values.length;s++)e.push(t.values[s]);let n=new ge(e);return n.visit(this.validatorSet.validators["font-family"])?this.values["font-family"]=n:this.error=!0,null}visitIdent(t){let e=this.validatorSet.systemFonts[t.name];if(e)for(let n in e)this.values[n]=e[n];else this.error=!0;return null}},kd=class extends qn{validateList(t){if(t.length===1&&t[0]instanceof be)switch(t[0].name.toLowerCase()){case"normal":t=[this.validatorSet.defaultValues["text-autospace"],this.validatorSet.defaultValues["text-spacing-trim"]];break;case"auto":t=[b.auto,b.auto];break;case"none":t=[L("no-autospace"),L("space-all")];break}return super.validateList(t)}},VC=["unicode-bidi","direction","margin-block-start","margin-block-end","margin-inline-start","margin-inline-end","padding-block-start","padding-block-end","padding-inline-start","padding-inline-end","border-block-start-color","border-block-end-color","border-inline-start-color","border-inline-end-color","border-block-start-style","border-block-end-style","border-inline-start-style","border-inline-end-style","border-block-start-width","border-block-end-width","border-inline-start-width","border-inline-end-width","block-start","block-end","inline-start","inline-end","block-size","inline-size","max-block-size","max-inline-size","min-block-size","min-inline-size","behavior","bleed","conflicting-partitions","crop-offset","crop-marks-line-color","enabled","flow-consume","flow-from","flow-into","flow-linger","flow-options","flow-priority","font-display","font-size-adjust","font-stretch_css3","font-variant_css2","glyph-orientation-vertical","marks","min-page-height","min-page-width","repeat-on-break","required","required-partitions","ruby-align","shape-inside","snap-height","snap-width","template","text-decoration-skip","text-justify","text-zoom","unicode-range","utilization","wrap-flow"],Ad=class extends qn{constructor(){super()}init(t,e){super.init(t,e);for(let n in this.validatorSet.validators)VC.includes(n)||this.propList.push(n)}validateList(t){return this.error=!0,0}},Rf={SIMPLE:qn,INSETS:Aa,INSETS_SLASH:Td,COMMA:wd,FONT:Pd,TEXT_SPACING:kd,ALL:Ad},Ld=class{constructor(){d(this,"validators",{});d(this,"prefixes",{});d(this,"defaultValues",{});d(this,"namedValidators",{});d(this,"systemFonts",{});d(this,"shorthands",{});d(this,"layoutProps",{});d(this,"backgroundProps",{})}addReplacement(t,e){let n;if(e.type==3)n=new P(e.num,e.text);else if(e.type==7)n=new Ks(e.text);else if(e.type==1)n=L(e.text);else throw new Error("unexpected replacement");if(t.isPrimitive()){let o=t.nodes[0].validator.idents;for(let i in o)o[i]=n;return t}throw new Error("unexpected replacement")}newGroup(t,e){let n=new Fs;if(t=="||"){for(let o=0;o<e.length;o++){let i=new Fs;i.startClause(o),i.addGroup(e[o],1),i.endClause(o),n.addGroup(i,o==0?1:4)}let s=new Fs;return s.startSpecialGroup(),s.addGroup(n,3),s.endSpecialGroup(),s}else{let s;switch(t){case" ":s=1;break;case"|":case"||":s=4;break;default:throw new Error("unexpected op")}for(let o=0;o<e.length;o++)n.addGroup(e[o],o==0?1:s);return n}}addCounts(t,e,n){let s=new Fs;for(let o=0;o<e;o++)s.addGroup(t.clone(),1);if(n==Number.POSITIVE_INFINITY)s.addGroup(t,3);else for(let o=e;o<n;o++)s.addGroup(t.clone(),2);return s}primitive(t){let e=new Fs;return e.addPrimitive(t),e}newFunc(t,e){let n;switch(t){case"COMMA":n=new ki(e);break;case"SPACE":n=new Bs(e);break;default:n=new Sd(t.toLowerCase(),e);break}return this.primitive(n)}initBuiltInValidators(){this.namedValidators.COLOR=this.primitive(new Ce(Ta,W,W)),this.namedValidators.IMAGE_FUNCTION=this.primitive(new Ce(Df,W,W)),this.namedValidators.POS_INT=this.primitive(new Ce(yd,W,W)),this.namedValidators.POS_NUM=this.primitive(new Ce(va,W,W)),this.namedValidators.POS_PERCENTAGE=this.primitive(new Ce(Vs,W,{"%":O})),this.namedValidators.NEGATIVE=this.primitive(new Ce(Ti,W,W)),this.namedValidators.ZERO=this.primitive(new Ce(wi,W,W)),this.namedValidators.ZERO_PERCENTAGE=this.primitive(new Ce(Ed,W,W)),this.namedValidators.POS_LENGTH=this.primitive(new Ce(Vs,W,{em:O,ex:O,ch:O,rem:O,lh:O,rlh:O,vw:O,vh:O,vi:O,vb:O,vmin:O,vmax:O,pvw:O,pvh:O,pvi:O,pvb:O,pvmin:O,pvmax:O,cm:O,mm:O,in:O,px:O,pt:O,pc:O,q:O})),this.namedValidators.POS_ANGLE=this.primitive(new Ce(Vs,W,{deg:O,grad:O,rad:O,turn:O})),this.namedValidators.POS_TIME=this.primitive(new Ce(Vs,W,{s:O,ms:O})),this.namedValidators.FREQUENCY=this.primitive(new Ce(Vs,W,{Hz:O,kHz:O})),this.namedValidators.RESOLUTION=this.primitive(new Ce(Vs,W,{dpi:O,dpcm:O,dppx:O})),this.namedValidators.URI=this.primitive(new Ce(Ff,W,W)),this.namedValidators.URANGE=this.primitive(new Ce(Of,W,W)),this.namedValidators.IDENT=this.primitive(new Ce(Vf,W,W)),this.namedValidators.STRING=this.primitive(new Ce(If,W,W)),this.namedValidators.SLASH=this.primitive(new Ce(Bf,W,W));let t={"font-family":L("sans-serif")};this.systemFonts.caption=t,this.systemFonts.icon=t,this.systemFonts.menu=t,this.systemFonts["message-box"]=t,this.systemFonts["small-caption"]=t,this.systemFonts["status-bar"]=t}isBuiltIn(t){return!!t.match(/^[A-Z_0-9]+$/)}readNameAndPrefixes(t,e){let n=t.token();if(n.type==0)return null;let s={"":!0};if(n.type==14){do{if(t.consume(),n=t.token(),n.type!=1)throw new Error("Prefix name expected");s[n.text]=!0,t.consume(),n=t.token()}while(n.type==16);if(n.type!=15)throw new Error("']' expected");t.consume(),n=t.token()}if(n.type!=1)throw new Error("Property name expected");if(e==2?n.text=="SHORTHANDS":n.text=="DEFAULTS")return t.consume(),null;let o=n.text;if(t.consume(),e!=2){if(t.token().type!=39)throw new Error("'=' expected");this.isBuiltIn(o)||(this.prefixes[o]=s)}else if(t.token().type!=18)throw new Error("':' expected");return o}parseValidators(t){for(;;){let e=this.readNameAndPrefixes(t,1);if(!e)return;let n=[],s=[],o="",i,a=!0,l=()=>{if(n.length==0)throw new Error("No values");return n.length==1?n[0]:this.newGroup(o,n)},c=p=>{if(a)throw new Error(`'${p}': unexpected`);if(o&&o!=p)throw new Error(`mixed operators: '${p}' and '${o}'`);o=p,a=!0},u=null;for(;!u;){t.consume();let p=t.token();switch(p.type){case 1:if(a||c(" "),this.isBuiltIn(p.text)){let h=this.namedValidators[p.text];if(!h)throw new Error(`'${p.text}' unexpected`);n.push(h.clone())}else{let h={};h[p.text.toLowerCase()]=L(p.text),n.push(this.primitive(new Ce(0,h,W)))}a=!1;break;case 5:{let h={};h[`${p.num}`]=new ct(p.num),n.push(this.primitive(new Ce(0,h,W))),a=!1;break}case 34:c("|");break;case 25:c("||");break;case 14:a||c(" "),s.push({vals:n,op:o,b:"["}),o="",n=[],a=!0;break;case 6:a||c(" "),s.push({vals:n,op:o,b:"(",fn:p.text}),o="",n=[],a=!0;break;case 15:{i=l();let h=s.pop();if(h.b!="[")throw new Error("']' unexpected");n=h.vals,n.push(i),o=h.op,a=!1;break}case 11:{i=l();let h=s.pop();if(h.b!="(")throw new Error("')' unexpected");n=h.vals,n.push(this.newFunc(h.fn,i)),o=h.op,a=!1;break}case 18:if(a)throw new Error("':' unexpected");t.consume(),n.push(this.addReplacement(n.pop(),t.token()));break;case 22:if(a)throw new Error("'?' unexpected");n.push(this.addCounts(n.pop(),0,1));break;case 36:if(a)throw new Error("'*' unexpected");n.push(this.addCounts(n.pop(),0,Number.POSITIVE_INFINITY));break;case 23:if(a)throw new Error("'+' unexpected");n.push(this.addCounts(n.pop(),1,Number.POSITIVE_INFINITY));break;case 12:{if(t.consume(),p=t.token(),p.type!=5)throw new Error("<int> expected");let h=p.num,f=h;if(t.consume(),p=t.token(),p.type==16){if(t.consume(),p=t.token(),p.type!=5)throw new Error("<int> expected");f=p.num,t.consume(),p=t.token()}if(p.type!=13)throw new Error("'}' expected");n.push(this.addCounts(n.pop(),h,f));break}case 17:if(u=l(),s.length>0)throw new Error(`unclosed '${s.pop().b}'`);break;default:throw new Error("unexpected token")}}t.consume(),this.isBuiltIn(e)?this.namedValidators[e]=u:u.isSimple()?this.validators[e]=u.nodes[0].validator:this.validators[e]=new Bs(u)}}parseDefaults(t){for(;;){let e=this.readNameAndPrefixes(t,2);if(!e)return;let n=[];for(;;){t.consume();let s=t.token();if(s.type==17){t.consume();break}switch(s.type){case 1:n.push(L(s.text));break;case 4:n.push(new tt(s.num));break;case 5:n.push(new ct(s.num));break;case 3:n.push(new P(s.num,s.text));break;default:throw new Error("unexpected token")}}this.defaultValues[e]=n.length>1?new K(n):n[0]}}parseShorthands(t){for(;;){let e=this.readNameAndPrefixes(t,3);if(!e)return;let n=t.nthToken(1),s;n.type==1&&Rf[n.text]?(s=new Rf[n.text],t.consume()):s=new qn,s.setOwner(this);let o=!1,i=[],a=!1,l=[],c=[];for(;!o;)switch(t.consume(),n=t.token(),n.type){case 1:if(this.validators[n.text])i.push(s.syntaxNodeForProperty(n.text)),n.text.includes("_")||c.push(n.text);else if(this.shorthands[n.text]instanceof Aa){let u=this.shorthands[n.text];i.push(u.createSyntaxNode()),c.push(...u.propList)}else throw new Error(`'${n.text}' is neither a simple property nor an inset shorthand`);break;case 19:if(i.length>0||a)throw new Error("unexpected slash");a=!0;break;case 14:l.push({slash:a,syntax:i}),i=[],a=!1;break;case 15:{let u=new vd(i,a),p=l.pop();i=p.syntax,a=p.slash,i.push(u);break}case 17:o=!0,t.consume();break;default:throw new Error("unexpected token")}s.init(i,c),this.shorthands[e]=s}}parse(t){let e=new Oe(t,null);this.parseValidators(e),this.parseDefaults(e),this.parseShorthands(e),this.backgroundProps=this.makePropSet(["background"]),this.layoutProps=this.makePropSet(["margin","border","padding","columns","column-gap","column-rule","column-fill"])}makePropSet(t){var n;let e={};for(let s of t){let o=this.shorthands[s],i=o?o.propList:[s];for(let a of i)e[a]=(n=this.defaultValues[a])!=null?n:b.initial}return e}validatePropertyAndHandleShorthand(t,e,n,s){if(Ct(t)||s.ruleType==="font-face"||FC(e)){s.simpleProperty(t,e,n);return}let o="",i=t;t=t.toLowerCase();let a=t.match(/^-([a-z]+)-([-a-z0-9]+)$/);a&&(o=a[1],t=a[2]);let l=this.prefixes[t];if(!l||!l[o]){CSS.supports(i,e.toString())?s.simpleProperty(i,e,n):o&&!yl.includes(`-${o}-`)||s.unknownProperty(i,e);return}let c=this.validators[t];if(c){let u=_(e)||e.isExpr()?e:e.visit(c);u?s.simpleProperty(t,u,n):!o&&CSS.supports(t,e.toString())?s.simpleProperty(t,e,n):s.invalidPropertyValue(i,e)}else{let u=this.shorthands[t].clone();_(e)?u.propagateDefaultingValue(e,n,s):(e.visit(u),u.finish(n,s)||s.invalidPropertyValue(i,e))}}};function Id(){let r=new Ld;return r.initBuiltInValidators(),r.parse(lc),r}var Rd=class extends lt{constructor(){super(...arguments);d(this,"varFound",!1)}visitFunc(e){return e.name==="var"?this.varFound=!0:this.varFound||this.visitValues(e.values),null}};function FC(r){let t=new Rd;return r.visit(t),t.varFound}var Ux=`OTTO${new Date().valueOf()}`;function Vd(r){return Object.keys(r).filter(t=>!["src","font-family","font-display"].includes(t)).sort()}function OC(r){let t=new Xe;for(let e of Vd(r))t.append(`${e}:${r[e].toString()};`);return t.toString()}function _f(r,t){let e={};for(let n in r)e[n]=pe(r,n).evaluate(t,n);return e}var Li=class{constructor(t){this.properties=t;d(this,"fontTraitKey");d(this,"src");d(this,"blobURLs",[]);d(this,"blobs",[]);d(this,"family");this.fontTraitKey=OC(this.properties),this.src=this.properties.src?this.properties.src.toString():null;let e=this.properties["font-family"];this.family=e?e.stringValue():null}traitsEqual(t){return this.fontTraitKey==t.fontTraitKey}makeAtRule(t,e){let n=new Xe;n.append(`@font-face {
|
|
1512
|
+
`;function gs(r,t,e){let n=A("fetchFromURL"),s={method:e||"GET",mode:"cors"},o=n.suspend(),i={status:0,statusText:"",url:r,contentType:null,responseText:null,responseXML:null,responseBlob:null};return fetch(r,s).then(a=>{var l;return i.status=a.status,i.url=a.url,i.statusText=a.statusText,i.contentType=(l=a.headers.get("Content-Type"))==null?void 0:l.replace(/;.*$/,"").toLowerCase(),a.ok?t==="blob"?a.blob():t==="arraybuffer"?a.arrayBuffer():t==="json"?a.json():/\/aozorabunko\/[^/]+\/cards\/[^/]+\/files\/[^/.]+\.html$/.test(r)?(i.contentType="text/html",a.arrayBuffer().then(c=>new TextDecoder("Shift_JIS").decode(c))):(/^data:,(<|%3c)/i.test(r)&&(i.contentType="text/html"),a.text()):a.text()}).then(a=>{t==="blob"&&a instanceof Blob?i.responseBlob=a:t==="arraybuffer"&&a instanceof ArrayBuffer?i.responseBlob=Nc([a]):t==="json"?i.responseText=JSON.stringify(a):typeof a=="string"&&(i.responseText=a),o.schedule(i)}).catch(a=>{V.warn(a,`Error fetching ${r}`),o.schedule(i)}),n.result()}function Nc(r,t){let e=t||"application/octet-stream";return new Blob(r,{type:e})}function fh(r){let t=A("readBlob"),e=new FileReader,n=t.suspend(e);return e.addEventListener("load",()=>{n.schedule(e.result)},!1),e.readAsArrayBuffer(r),t.result()}function gh(r){return URL.createObjectURL(r)}var fs=class{constructor(t,e){this.parser=t;this.type=e;p(this,"resources",{});p(this,"fetchers",{})}load(t,e,n){t=Pt(t);let s=this.resources[t];return typeof s!="undefined"?v(s):this.fetch(t,e,n).get()}fetchInner(t,e,n){let s=A("fetch"),o=t.endsWith("?viv-toc-box");o&&(t=t.replace("?viv-toc-box",""));let i=J("user-agent.xml",Xt),a=!o&&t===i;return a&&(t=`data:application/xml,${encodeURIComponent(bc)}`),gs(t,this.type).then(l=>{if(l.status>=400&&e)throw new Error((n||`Failed to fetch required resource: ${t}`)+` (${l.status}${l.statusText?" "+l.statusText:""})`);o?(t+="?viv-toc-box",l.url+="?viv-toc-box"):a&&(l.url=t=i),this.parser(l,this).then(c=>{delete this.fetchers[t],this.resources[t]=c,s.finish(c)})}),s.result()}fetch(t,e,n){if(t=Pt(t),this.resources[t])return null;let o=this.fetchers[t];return o||(o=new Qt(()=>this.fetchInner(t,e,n),`Fetch ${t}`),this.fetchers[t]=o,o.start()),o}get(t){return this.resources[Pt(t)]}delete(t){delete this.resources[Pt(t)]}};function Bm(r,t){let e=r.responseText;return v(e?$s(e):null)}function mh(){return new fs(Bm,"text")}function Fn(r,t,e){let n=new Qt(()=>{let s=A("loadElement"),o=s.suspend(r),i=!1,a=l=>{i||(i=!0,o.schedule(l?l.type:"timeout"))};return r.addEventListener("load",a,!1),r.addEventListener("error",a,!1),r.addEventListener("abort",a,!1),r.namespaceURI=="http://www.w3.org/2000/svg"?(t&&r.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",t),setTimeout(a,300)):r.localName==="script"?setTimeout(a,3e3):t&&(r.src=t,e&&(r.alt=e)),s.result()},`loadElement ${t||r.localName}`);return n.start(),n}var Ch=0,Om=16777216,vc=33554432,Mr=50331648,_r=67108864,Dm=83886080,Mm=100663296;var ei=class{constructor(t){this.scope=t;p(this,"flavor");this.flavor="Author"}getCurrentToken(){return null}getScope(){return this.scope}error(t,e){}startStylesheet(t){this.flavor=t}tagSelector(t,e){}classSelector(t){}pseudoclassSelector(t,e){}pseudoelementSelector(t,e){}idSelector(t){}attributeSelector(t,e,n,s){}descendantSelector(){}childSelector(){}adjacentSiblingSelector(){}followingSiblingSelector(){}nextSelector(){}startSelectorRule(){}startFontFaceRule(){}startFootnoteRule(t){}startViewportRule(){}startDefineRule(){}startRegionRule(){}startPageRule(){}startPageMarginBoxRule(t){}startWhenRule(t){}startMediaRule(t){this.startWhenRule(t)}startFlowRule(t){}startPageTemplateRule(){}startPageMasterRule(t,e,n){}startPartitionRule(t,e,n){}startPartitionGroupRule(t,e,n){}startRuleBody(){}property(t,e,n){}endRule(){}startFuncWithSelector(t){}endFuncWithSelector(){}pushSelectorText(t){}getImportantSpecificity(){switch(this.flavor){case"UA":return Ch;case"User":return Mm;default:return Dm}}getBaseSpecificity(){switch(this.flavor){case"UA":return Ch;case"User":return Om;default:return vc}}},Br=class extends ei{constructor(){super(null);p(this,"stack",[]);p(this,"tokenizer",null);p(this,"slave",null)}pushHandler(e){this.stack.push(this.slave),this.slave=e}popHandler(){this.slave=this.stack.pop()}getCurrentToken(){return this.tokenizer?this.tokenizer.token():null}getScope(){return this.slave.getScope()}error(e,n){this.slave.error(e,n)}errorMsg(e,n){var s;V.warn(e,(s=n==null?void 0:n.toString())!=null?s:"")}startStylesheet(e){super.startStylesheet(e),this.stack.length>0&&(this.slave=this.stack[0],this.stack=[]),this.slave.startStylesheet(e)}tagSelector(e,n){this.slave.tagSelector(e,n)}classSelector(e){this.slave.classSelector(e)}pseudoclassSelector(e,n){this.slave.pseudoclassSelector(e,n)}pseudoelementSelector(e,n){this.slave.pseudoelementSelector(e,n)}idSelector(e){this.slave.idSelector(e)}attributeSelector(e,n,s,o){this.slave.attributeSelector(e,n,s,o)}descendantSelector(){this.slave.descendantSelector()}childSelector(){this.slave.childSelector()}adjacentSiblingSelector(){this.slave.adjacentSiblingSelector()}followingSiblingSelector(){this.slave.followingSiblingSelector()}nextSelector(){this.slave.nextSelector()}startSelectorRule(){this.slave.startSelectorRule()}startFontFaceRule(){this.slave.startFontFaceRule()}startFootnoteRule(e){this.slave.startFootnoteRule(e)}startViewportRule(){this.slave.startViewportRule()}startDefineRule(){this.slave.startDefineRule()}startRegionRule(){this.slave.startRegionRule()}startPageRule(){this.slave.startPageRule()}startPageMarginBoxRule(e){this.slave.startPageMarginBoxRule(e)}startWhenRule(e){this.slave.startWhenRule(e)}startFlowRule(e){this.slave.startFlowRule(e)}startPageTemplateRule(){this.slave.startPageTemplateRule()}startPageMasterRule(e,n,s){this.slave.startPageMasterRule(e,n,s)}startPartitionRule(e,n,s){this.slave.startPartitionRule(e,n,s)}startPartitionGroupRule(e,n,s){this.slave.startPartitionGroupRule(e,n,s)}startRuleBody(){this.slave.startRuleBody()}property(e,n,s){this.slave.property(e,n,s)}endRule(){this.slave.endRule()}startFuncWithSelector(e){this.slave.startFuncWithSelector(e)}endFuncWithSelector(){this.slave.endFuncWithSelector()}pushSelectorText(e){this.slave.pushSelectorText(e)}},Or=class extends ei{constructor(e,n,s){super(e);this.owner=n;this.topLevel=s;p(this,"depth",0);n&&(this.flavor=n.flavor)}getCurrentToken(){var e;return(e=this.owner)==null?void 0:e.getCurrentToken()}error(e,n){var s;(s=this.owner)==null||s.errorMsg(e,n)}startRuleBody(){this.depth++}endRule(){--this.depth==0&&!this.topLevel&&this.owner.popHandler()}},Jt=class extends Or{constructor(t,e,n){super(t,e,n)}report(t){this.error(t,this.getCurrentToken())}reportAndSkip(t){this.report(t),this.owner.pushHandler(new Or(this.scope,this.owner,!1))}startSelectorRule(){this.reportAndSkip("E_CSS_UNEXPECTED_SELECTOR")}startFontFaceRule(){this.reportAndSkip("E_CSS_UNEXPECTED_FONT_FACE")}startFootnoteRule(t){this.reportAndSkip("E_CSS_UNEXPECTED_FOOTNOTE")}startViewportRule(){this.reportAndSkip("E_CSS_UNEXPECTED_VIEWPORT")}startDefineRule(){this.reportAndSkip("E_CSS_UNEXPECTED_DEFINE")}startRegionRule(){this.reportAndSkip("E_CSS_UNEXPECTED_REGION")}startPageRule(){this.reportAndSkip("E_CSS_UNEXPECTED_PAGE")}startWhenRule(t){this.reportAndSkip("E_CSS_UNEXPECTED_WHEN")}startFlowRule(t){this.reportAndSkip("E_CSS_UNEXPECTED_FLOW")}startPageTemplateRule(){this.reportAndSkip("E_CSS_UNEXPECTED_PAGE_TEMPLATE")}startPageMasterRule(t,e,n){this.reportAndSkip("E_CSS_UNEXPECTED_PAGE_MASTER")}startPartitionRule(t,e,n){this.reportAndSkip("E_CSS_UNEXPECTED_PARTITION")}startPartitionGroupRule(t,e,n){this.reportAndSkip("E_CSS_UNEXPECTED_PARTITION_GROUP")}startFuncWithSelector(t){this.reportAndSkip("E_CSS_UNEXPECTED_SELECTOR_FUNC")}endFuncWithSelector(){this.reportAndSkip("E_CSS_UNEXPECTED_END_SELECTOR_FUNC")}property(t,e,n){this.error("E_CSS_UNEXPECTED_PROPERTY",this.getCurrentToken())}},me=[],Dr=[],re=[],Ee=[],At=[],dt=[],ye=[],Pe=[],se=[],Re=[],Ke=[],Le=[],xe=[];var lo=55,co=56,Fr=57;me[1]=28,me[36]=29,me[7]=29,me[9]=29,me[14]=29,me[18]=29,me[50]=29,me[20]=30,me[13]=27,me[0]=200,Dr[1]=46,Dr[0]=200,dt[1]=2,dt[36]=4,dt[7]=6,dt[9]=8,dt[14]=10,dt[18]=14,dt[50]=42,re[37]=11,re[23]=12,re[35]=56,re[1]=1,re[36]=3,re[7]=5,re[9]=7,re[14]=9,re[12]=13,re[18]=55,re[50]=58,re[16]=41,Ee[37]=11,Ee[23]=12,Ee[35]=56,Ee[1]=1,Ee[36]=3,Ee[7]=5,Ee[9]=7,Ee[14]=9,Ee[18]=55,At[1]=2,At[36]=4,At[7]=6,At[9]=8,At[18]=14,At[50]=42,At[14]=10,At[12]=13,ye[1]=15,ye[7]=16,ye[4]=17,ye[5]=18,ye[3]=19,ye[2]=20,ye[8]=21,ye[27]=57,ye[16]=22,ye[19]=23,ye[6]=24,ye[11]=25,ye[17]=26,ye[13]=48,ye[31]=47,ye[23]=54,ye[0]=44,Pe[1]=31,Pe[4]=32,Pe[5]=32,Pe[3]=33,Pe[2]=34,Pe[10]=40,Pe[6]=38,Pe[31]=36,Pe[24]=36,Pe[32]=35,se[1]=45,se[16]=37,se[37]=37,se[38]=37,se[47]=37,se[48]=37,se[39]=37,se[49]=37,se[41]=37,se[26]=37,se[25]=37,se[23]=37,se[24]=37,se[19]=37,se[21]=37,se[36]=37,se[18]=37,se[22]=37,se[11]=39,se[12]=43,se[17]=49,Re[0]=200,Re[12]=50,Re[13]=51,Re[14]=50,Re[15]=51,Re[10]=50,Re[11]=51,Re[17]=53,Ke[0]=200,Ke[12]=50,Ke[13]=52,Ke[14]=50,Ke[15]=51,Ke[10]=50,Ke[11]=51,Ke[17]=53,Le[0]=200,Le[12]=50,Le[13]=51,Le[14]=50,Le[15]=51,Le[10]=50,Le[11]=51,xe[11]=0,xe[16]=0,xe[22]=1,xe[18]=1,xe[26]=2,xe[25]=2,xe[38]=3,xe[37]=3,xe[48]=3,xe[47]=3,xe[39]=3,xe[49]=3,xe[41]=3,xe[23]=4,xe[24]=4,xe[36]=5,xe[19]=5,xe[21]=5,xe[0]=6,xe[lo]=2,xe[co]=2;var Bn=class{constructor(t,e,n,s){this.actions=t;this.tokenizer=e;this.handler=n;this.baseURL=s;p(this,"valStack",[]);p(this,"namespacePrefixToURI",{});p(this,"defaultNamespaceURI",null);p(this,"propName",null);p(this,"propImportant",!1);p(this,"exprContext");p(this,"result",null);p(this,"importReady",!1);p(this,"importURL",null);p(this,"importCondition",null);p(this,"errorBrackets",[]);p(this,"ruleStack",[]);p(this,"regionRule",!1);p(this,"pageRule",!1);p(this,"inStyleDeclaration",!1);this.exprContext=2}extractVals(t,e){let n=[],s=this.valStack;for(;e<s.length&&(n.push(s[e++]),e!==s.length);){if(s[e++]!==t)throw new Error("Unexpected state");e===s.length&&n.push(O)}return n}valStackReduce(t,e){let n=this.valStack,s=n.length,o=0,i;do if(i=n[--s],t===")"&&i instanceof Ln){if(i.text===")")o++;else if(i.text==="("){if(o===0)return null;o--}}while(typeof i!="undefined"&&typeof i!="string");let a=n.length-(s+1);if(a>1&&n.splice(s+1,a,new q(n.slice(s+1,n.length))),t==",")return null;s++;do i=n[--s];while(typeof i!="undefined"&&(typeof i!="string"||i==","));if(a=n.length-(s+1),i=="("){t!=")"&&e.type!==0&&(this.handler.error("E_CSS_MISMATCHED_C_PAR",e),this.actions=Ke);let c=new kt(n[s-1],this.extractVals(",",s+1));if(n.splice(s-1,a+2,c),c.name==="var"){let u=c.values[0]instanceof be&&c.values[0].name;(!xt(u)||u===this.propName)&&(this.handler.error(`E_CSS_INVALID_VAR ${c.toString()}`,e),this.actions=Ke)}return c}if(t!=";"||s>=0)return this.handler.error("E_CSS_UNEXPECTED_VAL_END",e),this.actions=Ke,null;if(a>1)return new ge(this.extractVals(",",s+1));let l=n[0];return l instanceof Se?l:l?new Ln(l.toString()):O}exprError(t,e){this.actions=this.propName?Ke:Re,V.warn(t,e.toString())}exprStackReduce(t,e){let n=this.valStack,s=this.handler,o=n.pop(),i;for(;;){let a=n.pop();if(t==11){let l=[o];for(;a==16;)l.unshift(n.pop()),a=n.pop();if(typeof a=="string"){if(a=="{"){for(;l.length>=2;){let c=l.shift(),u=l.shift(),d=new fr(s.getScope(),c,u);l.unshift(d)}return n.push(new B(l[0])),!0}else if(a=="("){let c=n.pop(),u=n.pop();o=new un(s.getScope(),jo(u,c),l),t=0;continue}}if(a==10){o.isMediaName()&&(o=new Xo(s.getScope(),o,null)),t=0;continue}}else if(typeof a=="string"){n.push(a);break}if(a<0)if(a==-31)o=new Ct(s.getScope(),o);else if(a==-24)o=new qt(s.getScope(),o);else if(a==-Fr)o=new pr(s.getScope(),o);else return this.exprError("F_UNEXPECTED_STATE",e),!1;else{if(xe[t]>xe[a]){n.push(a);break}switch(i=n.pop(),a){case 26:o=new Ys(s.getScope(),i,o);break;case lo:o=new hr(s.getScope(),i,o);break;case co:o=new gr(s.getScope(),i,o);break;case 25:o=new qs(s.getScope(),i,o);break;case 38:o=new mr(s.getScope(),i,o);break;case 37:o=new br(s.getScope(),i,o);break;case 48:o=new Cr(s.getScope(),i,o);break;case 47:o=new ls(s.getScope(),i,o);break;case 39:case 49:o=new An(s.getScope(),i,o);break;case 41:o=new xr(s.getScope(),i,o);break;case 23:o=new zo(s.getScope(),i,o);break;case 24:o=new Go(s.getScope(),i,o);break;case 36:o=new cs(s.getScope(),i,o);break;case 19:o=new Wo(s.getScope(),i,o);break;case 21:o=new Ks(s.getScope(),i,o);break;case 18:if(n.length>1)switch(n[n.length-1]){case 22:n.pop(),o=new yr(s.getScope(),n.pop(),i,o);break;case 10:if(i.isMediaName())o=new Xo(s.getScope(),i,o);else return this.exprError("E_CSS_MEDIA_TEST",e),!1;break}else return this.exprError("E_CSS_EXPR_COND",e),!1;break;case 22:if(t!=18)return this.exprError("E_CSS_EXPR_COND",e),!1;case 10:return n.push(i),n.push(a),n.push(o),!1;default:return this.exprError("F_UNEXPECTED_STATE",e),!1}}}return n.push(o),!1}readSupportsTest(t){let e=t.type===6,n=this.tokenizer,s,o;if(e)o=t.text,s=t.position+o.length+1;else if(t.type===10){let h=n.nthToken(1),f=n.nthToken(2);if(h.type===1&&f.type===18)n.consume(),n.consume(),o=h.text,s=f.position+1;else{if(h.type===10||h.type===6||h.type===1&&h.text.toLowerCase()==="not"&&(f.type===10||f.type===6))return null;s=t.position+1}}else return null;let i=0,a,l=0;for(;i>=0;)switch(n.consume(),a=n.token(),a.type){case 11:i--;break;case 10:case 6:i++;break;case 16:i===0&&l++;break;case 0:return this.exprError("E_CSS_UNEXPECTED_EOF",a),null}n.consume();let c=a.position,u=e&&o==="selector"&&l>0?"":n.input.substring(s,c).trim();return new Er(this.handler.getScope(),o,u,e)}readPseudoParams(){let t=[];for(;;){let e=this.tokenizer.token();switch(e.type){case 1:t.push(e.text);break;case 23:t.push("+");break;case 4:case 5:t.push(e.num);break;default:return t}this.tokenizer.consume()}}readNthPseudoParams(){let t=!1,e=this.tokenizer.token();if(e.type===23)t=!0,this.tokenizer.consume(),e=this.tokenizer.token();else if(e.type===1&&(e.text==="even"||e.text==="odd"))return this.tokenizer.consume(),[2,e.text==="odd"?1:0];switch(e.type){case 3:if(t&&e.num<0)return null;case 1:if(t&&e.text.charAt(0)==="-")return null;if(e.text==="n"||e.text==="-n"){if(t&&e.precededBySpace)return null;let n=e.text==="-n"?-1:1;e.type===3&&(n=e.num);let s=0;this.tokenizer.consume(),e=this.tokenizer.token();let o=e.type===24,i=e.type===23||o;if(i&&(this.tokenizer.consume(),e=this.tokenizer.token()),e.type===5){if(s=e.num,1/s===-1/0){if(s=0,i)return null}else if(s<0){if(i)return null}else if(s>=0&&!i)return null;this.tokenizer.consume()}else if(i)return null;return[n,o&&s>0?-s:s]}else if(e.text==="n-"||e.text==="-n-"){if(t&&e.precededBySpace)return null;let n=e.text==="-n-"?-1:1;if(e.type===3&&(n=e.num),this.tokenizer.consume(),e=this.tokenizer.token(),e.type===5)return e.num<0||1/e.num===-1/0?null:(this.tokenizer.consume(),[n,e.num])}else{let n=e.text.match(/^n(-[0-9]+)$/);if(n)return t&&e.precededBySpace?null:(this.tokenizer.consume(),[e.type===3?e.num:1,parseInt(n[1],10)]);if(n=e.text.match(/^-n(-[0-9]+)$/),n)return this.tokenizer.consume(),[-1,parseInt(n[1],10)]}return null;case 5:return t&&(e.precededBySpace||e.num<0)?null:(this.tokenizer.consume(),[0,e.num])}return null}makeCondition(t,e){let n=this.handler.getScope();if(!n)return null;if(e=e||n._true,t){let s=t.split(/\s+/);for(let o of s)switch(o){case"vertical":e=tt(n,e,new Ct(n,new ee(n,"pref-horizontal")));break;case"horizontal":e=tt(n,e,new ee(n,"pref-horizontal"));break;case"day":e=tt(n,e,new Ct(n,new ee(n,"pref-night-mode")));break;case"night":e=tt(n,e,new ee(n,"pref-night-mode"));break;default:e=n._false}}return e===n._true?null:new B(e)}isInsidePropertyOnlyRule(){switch(this.ruleStack[this.ruleStack.length-1]){case"[selector]":case"font-face":case"-epubx-flow":case"-epubx-viewport":case"-epubx-define":case"-adapt-footnote-area":return!0}return!1}runParser(t,e,n,s,o,i){let a=this.handler,l=this.tokenizer,c=this.valStack,u,d,h,f,g,m,y,E=null;for(n&&(this.inStyleDeclaration=!0),s&&(this.exprContext=2,this.valStack.push("{"));t>0;--t){if(u=l.token(),o&&E===null&&(E=u.position-1,l.input[E]==="("&&E++),this.actions===ye&&this.errorBrackets.length>0&&(u.type===this.errorBrackets[this.errorBrackets.length-1]||u.type===17||u.type===31)){if(u.type===this.errorBrackets[this.errorBrackets.length-1]&&(this.errorBrackets.pop(),u.type===11&&this.valStackReduce(")",u))){l.consume();continue}c.push(new Ln(u.toString())),l.consume();continue}switch(this.actions[u.type]){case 28:if(!this.inStyleDeclaration||l.nthToken(1).type!=18){this.isInsidePropertyOnlyRule()?(a.error("E_CSS_COLON_EXPECTED",l.nthToken(1)),this.actions=Ke):(this.actions=dt,a.startSelectorRule());continue}this.propName=u.text,this.propImportant=!1,l.consume(),l.consume(),this.actions=ye,c.splice(0,c.length);continue;case 46:if(l.nthToken(1).type!=18){this.actions=Ke,a.error("E_CSS_COLON_EXPECTED",l.nthToken(1));continue}this.propName=u.text,this.propImportant=!1,l.consume(),l.consume(),this.actions=ye,c.splice(0,c.length);continue;case 29:this.actions=dt,a.startSelectorRule();continue;case 1:if(!u.precededBySpace){this.actions=Le,a.error("E_CSS_SPACE_EXPECTED",u);continue}a.descendantSelector();case 2:if(l.nthToken(1).type==34)if(l.consume(),l.consume(),h=this.namespacePrefixToURI[u.text],h!=null)switch(u=l.token(),u.type){case 1:a.tagSelector(h,u.text),o?this.actions=Ee:this.actions=re,l.consume();break;case 36:a.tagSelector(h,null),o?this.actions=Ee:this.actions=re,l.consume();break;default:this.actions=Re,a.error("E_CSS_NAMESPACE",u)}else this.actions=Re,a.error("E_CSS_UNDECLARED_PREFIX",u);else a.tagSelector(this.defaultNamespaceURI,u.text),o?this.actions=Ee:this.actions=re,l.consume();continue;case 3:if(!u.precededBySpace){this.actions=Le,a.error("E_CSS_SPACE_EXPECTED",u);continue}a.descendantSelector();case 4:if(l.nthToken(1).type==34)switch(l.consume(),l.consume(),u=l.token(),u.type){case 1:a.tagSelector(null,u.text),o?this.actions=Ee:this.actions=re,l.consume();break;case 36:a.tagSelector(null,null),o?this.actions=Ee:this.actions=re,l.consume();break;default:this.actions=Re,a.error("E_CSS_NAMESPACE",u)}else a.tagSelector(this.defaultNamespaceURI,null),o?this.actions=Ee:this.actions=re,l.consume();continue;case 5:u.precededBySpace&&a.descendantSelector();case 6:if(!u.text){a.error("E_CSS_SYNTAX",u),l.consume();continue}a.idSelector(u.text),o?this.actions=Ee:this.actions=re,l.consume();continue;case 7:u.precededBySpace&&a.descendantSelector();case 8:a.classSelector(u.text),o?this.actions=Ee:this.actions=re,l.consume();continue;case 55:u.precededBySpace&&a.descendantSelector();case 14:l.consume(),u=l.token();e:switch(u.type){case 1:a.pseudoclassSelector(u.text,null),l.consume(),o?this.actions=Ee:this.actions=re;continue;case 6:switch(f=u.text,l.consume(),f){case"is":case"not":case"where":case"has":this.actions=dt,a.startFuncWithSelector(f),this.runParser(Number.POSITIVE_INFINITY,!1,!1,!1,!0,f==="has")?this.actions=re:this.actions=Le;continue;case"lang":case"href-epub-type":if(u=l.token(),u.type===1){y=[u.text],l.consume(),f==="href-epub-type"&&l.token().type===16&&(l.consume(),u=l.token(),u.type===1&&(y.push(u.text),l.consume()));break}else break e;case"nth-child":case"nth-of-type":case"nth-last-child":case"nth-last-of-type":case"nth":if(y=this.readNthPseudoParams(),y)break;break e;default:y=this.readPseudoParams()}if(u=l.token(),u.type==11){a.pseudoclassSelector(f,y),l.consume(),o?this.actions=Ee:this.actions=re;continue}break}a.error("E_CSS_PSEUDOCLASS_SYNTAX",u),this.actions=Re;continue;case 58:u.precededBySpace&&a.descendantSelector();case 42:switch(l.consume(),u=l.token(),u.type){case 1:a.pseudoelementSelector(u.text,null),o?this.actions=Ee:this.actions=re,l.consume();continue;case 6:if(f=u.text,l.consume(),f=="nth-fragment"){if(y=this.readNthPseudoParams(),y===null)break}else y=this.readPseudoParams();if(u=l.token(),u.type==11){a.pseudoelementSelector(f,y),o?this.actions=Ee:this.actions=re,l.consume();continue}break}a.error("E_CSS_PSEUDOELEM_SYNTAX",u),this.actions=Re;continue;case 9:u.precededBySpace&&a.descendantSelector();case 10:if(l.consume(),u=l.token(),u.type==1)f=u.text,l.consume();else if(u.type==36)f=null,l.consume();else if(u.type==34)f="";else{this.actions=Le,a.error("E_CSS_ATTR",u),l.consume();continue}if(u=l.token(),u.type==34){if(h=f&&this.namespacePrefixToURI[f],h===void 0){this.actions=Le,a.error("E_CSS_UNDECLARED_PREFIX",u),l.consume();continue}if(l.consume(),u=l.token(),u.type!=1){this.actions=Le,a.error("E_CSS_ATTR_NAME_EXPECTED",u);continue}f=u.text,l.consume(),u=l.token()}else h="";switch(u.type){case 39:case 45:case 44:case 43:case 42:case 46:case 50:g=u.type,l.consume(),u=l.token();break;case 15:a.attributeSelector(h,f,0,null),o?this.actions=Ee:this.actions=re,l.consume();continue;default:this.actions=Le,a.error("E_CSS_ATTR_OP_EXPECTED",u);continue}switch(u.type){case 1:case 2:a.attributeSelector(h,f,g,u.text),l.consume(),u=l.token();break;default:this.actions=Le,a.error("E_CSS_ATTR_VAL_EXPECTED",u);continue}if(u.type!=15){this.actions=Le,a.error("E_CSS_ATTR",u);continue}o?this.actions=Ee:this.actions=re,l.consume();continue;case 11:a.childSelector(),this.actions=At,l.consume();continue;case 12:a.adjacentSiblingSelector(),this.actions=At,l.consume();continue;case 56:a.followingSiblingSelector(),this.actions=At,l.consume();continue;case 13:this.regionRule?(this.ruleStack.push("-epubx-region"),this.regionRule=!1):this.pageRule?(this.ruleStack.push("page"),this.pageRule=!1,this.inStyleDeclaration=!0):(this.ruleStack.push("[selector]"),this.inStyleDeclaration=!0),a.startRuleBody(),this.actions=me,l.consume();continue;case 41:a.nextSelector(),this.actions=dt,l.consume();continue;case 15:c.push(L(u.text)),l.consume();continue;case 16:g=parseInt(u.text,16),c.push(new Js(u.text)),l.consume();continue;case 17:c.push(new nt(u.num)),l.consume();continue;case 18:c.push(new ut(u.num)),l.consume();continue;case 19:c.push(new P(u.num,u.text)),l.consume();continue;case 20:c.push(new ce(u.text)),l.consume();continue;case 21:c.push(new Oe(J(u.text,this.baseURL))),l.consume();continue;case 57:c.push(new qo(u.text)),l.consume();continue;case 22:this.valStackReduce(",",u),c.push(","),l.consume();continue;case 23:c.push(eo),l.consume();continue;case 24:f=u.text.toLowerCase(),f=="-epubx-expr"||f=="env"?(this.actions=Pe,this.exprContext=0,c.push("{")):(c.push(f),c.push("("),this.errorBrackets.length>0&&this.errorBrackets.push(11)),l.consume();continue;case 25:this.valStackReduce(")",u),l.consume();continue;case 47:if(l.consume(),u=l.token(),d=l.nthToken(1),u.type==1&&u.text.toLowerCase()=="important"&&(d.type==17||d.type==0||d.type==13)){l.consume(),this.propImportant=!0;continue}this.exprError("E_CSS_SYNTAX",u);continue;case 54:switch(d=l.nthToken(1),d.type){case 4:case 3:case 5:if(!d.precededBySpace){l.consume();continue}}c.push(new Ln("+")),l.consume();continue;case 26:l.consume();case 48:m=this.valStackReduce(";",u),m&&this.propName&&a.property(this.propName,m,this.propImportant),this.actions=n?Dr:me;continue;case 44:for(l.consume();c.length>0;){let C=c.length;if(m=this.valStackReduce(";",u),!m||c.length===C)break}return e?(this.result=m,!0):(this.propName&&m&&a.property(this.propName,m,this.propImportant),!0);case 31:if(d=l.nthToken(1),d.type==9)l.nthToken(2).type==10&&!l.nthToken(2).precededBySpace?(c.push(u.text,d.text,"("),l.consume()):(c.push(new ee(a.getScope(),jo(u.text,d.text))),this.actions=se),l.consume();else{if(this.exprContext==2||this.exprContext==3)u.text.toLowerCase()=="not"?(l.consume(),c.push(new $o(a.getScope(),!0,d.text))):(u.text.toLowerCase()=="only"&&(l.consume(),u=d),c.push(new $o(a.getScope(),!1,u.text)));else if(this.exprContext===4&&u.text.toLowerCase()==="not"&&c[c.length-1]!==lo&&c[c.length-1]!==co&&(d.type===10||d.type===6)){c.push(-Fr),l.consume();continue}else c.push(new ee(a.getScope(),u.text));this.actions=se}l.consume();continue;case 38:if(this.exprContext===4){c.push(this.readSupportsTest(u)),this.actions=se;continue}c.push(null,u.text,"("),l.consume();continue;case 32:c.push(new ie(a.getScope(),u.num)),l.consume(),this.actions=se;continue;case 33:f=u.text,f=="%"&&(this.propName&&this.propName.match(/height|^(top|bottom)$/)?f="vh":f="vw"),c.push(new Ft(a.getScope(),u.num,f)),l.consume(),this.actions=se;continue;case 34:c.push(new ie(a.getScope(),u.text)),l.consume(),this.actions=se;continue;case 35:l.consume(),u=l.token(),u.type!=5||u.precededBySpace?this.exprError("E_CSS_SYNTAX",u):(c.push(new Zs(a.getScope(),u.num)),l.consume(),this.actions=se);continue;case 36:c.push(-u.type),l.consume();continue;case 37:this.actions=Pe,this.exprStackReduce(u.type,u),c.push(u.type),l.consume();continue;case 45:u.text.toLowerCase()==="and"&&c[c.length-2]!==co&&c[c.length-2]!==-Fr?(this.actions=Pe,this.exprStackReduce(lo,u),c.push(lo),l.consume()):u.text.toLowerCase()==="or"&&c[c.length-2]!==lo&&c[c.length-2]!==-Fr?(this.actions=Pe,this.exprStackReduce(co,u),c.push(co),l.consume()):this.exprError("E_CSS_SYNTAX",u);continue;case 39:this.exprStackReduce(u.type,u)&&(this.actions=ye),l.consume();continue;case 43:this.exprStackReduce(11,u)&&(this.propName||this.exprContext==3?this.exprError("E_CSS_UNEXPECTED_BRC",u):(this.exprContext==1?a.startWhenRule(c.pop()):a.startMediaRule(c.pop()),this.ruleStack.push("media"),a.startRuleBody(),this.actions=me)),l.consume();continue;case 49:if(this.exprStackReduce(11,u))return this.propName||this.exprContext!=3?(this.exprError("E_CSS_UNEXPECTED_SEMICOL",u),this.actions=me,l.consume(),!1):(this.importCondition=c.pop(),this.importReady=!0,this.actions=me,l.consume(),!1);l.consume();continue;case 40:if(this.exprContext===4){let C=this.readSupportsTest(u);if(C){c.push(C),this.actions=se;continue}}c.push(u.type),l.consume();continue;case 27:if(this.actions=me,l.consume(),a.endRule(),this.inStyleDeclaration=!1,this.ruleStack.length)switch(this.ruleStack.pop(),this.ruleStack[this.ruleStack.length-1]){case"page":case"-epubx-page-master":case"-epubx-partition-group":this.inStyleDeclaration=!0}continue;case 30:switch(f=u.text.toLowerCase(),f){case"import":if(l.consume(),u=l.token(),u.type==2||u.type==8){if(this.importURL=u.text,l.consume(),u=l.token(),u.type==17||u.type==0)return this.importReady=!0,l.consume(),!1;this.propName=null,this.exprContext=3,this.actions=Pe,c.push("{");continue}a.error("E_CSS_IMPORT_SYNTAX",u),this.actions=Re;continue;case"namespace":switch(l.consume(),u=l.token(),u.type){case 1:if(f=u.text,l.consume(),u=l.token(),(u.type==2||u.type==8)&&l.nthToken(1).type==17){this.namespacePrefixToURI[f]=u.text,l.consume(),l.consume();continue}break;case 2:case 8:if(l.nthToken(1).type==17){this.defaultNamespaceURI=u.text,l.consume(),l.consume();continue}break}a.error("E_CSS_NAMESPACE_SYNTAX",u),this.actions=Re;continue;case"charset":if(l.consume(),u=l.token(),u.type==2&&l.nthToken(1).type==17){f=u.text.toLowerCase(),f!="utf-8"&&f!="utf-16"&&a.error(`E_CSS_UNEXPECTED_CHARSET ${f}`,u),l.consume(),l.consume();continue}a.error("E_CSS_CHARSET_SYNTAX",u),this.actions=Re;continue;case"font-face":case"-epubx-page-template":case"-epubx-define":case"-epubx-viewport":if(l.nthToken(1).type==12){switch(l.consume(),l.consume(),f){case"font-face":a.startFontFaceRule(),this.inStyleDeclaration=!0;break;case"-epubx-page-template":a.startPageTemplateRule();break;case"-epubx-define":a.startDefineRule(),this.inStyleDeclaration=!0;break;case"-epubx-viewport":a.startViewportRule(),this.inStyleDeclaration=!0;break}this.ruleStack.push(f),a.startRuleBody();continue}break;case"-adapt-footnote-area":switch(l.consume(),u=l.token(),u.type){case 12:l.consume(),a.startFootnoteRule(null),this.ruleStack.push(f),a.startRuleBody(),this.inStyleDeclaration=!0;continue;case 50:if(l.consume(),u=l.token(),u.type==1&&l.nthToken(1).type==12){f=u.text,l.consume(),l.consume(),a.startFootnoteRule(f),this.ruleStack.push("-adapt-footnote-area"),a.startRuleBody(),this.inStyleDeclaration=!0;continue}break}break;case"-epubx-region":l.consume(),a.startRegionRule(),this.regionRule=!0,this.actions=dt;continue;case"page":l.consume(),a.startPageRule(),this.pageRule=!0,this.actions=At;continue;case"top-left-corner":case"top-left":case"top-center":case"top-right":case"top-right-corner":case"right-top":case"right-middle":case"right-bottom":case"bottom-right-corner":case"bottom-right":case"bottom-center":case"bottom-left":case"bottom-left-corner":case"left-bottom":case"left-middle":case"left-top":if(l.consume(),u=l.token(),u.type==12){l.consume(),a.startPageMarginBoxRule(f),this.ruleStack.push(f),a.startRuleBody(),this.inStyleDeclaration=!0;continue}break;case"-epubx-when":l.consume(),this.propName=null,this.exprContext=1,this.actions=Pe,c.push("{");continue;case"media":l.consume(),this.propName=null,this.exprContext=2,this.actions=Pe,c.push("{");continue;case"supports":l.consume(),this.propName=null,this.exprContext=4,this.actions=Pe,c.push("{");continue;case"-epubx-flow":if(l.nthToken(1).type==1&&l.nthToken(2).type==12){a.startFlowRule(l.nthToken(1).text),l.consume(),l.consume(),l.consume(),this.ruleStack.push(f),a.startRuleBody(),this.inStyleDeclaration=!0;continue}break;case"-epubx-page-master":case"-epubx-partition":case"-epubx-partition-group":{l.consume(),u=l.token();let C=null,x=null,N=[];for(u.type==1&&(C=u.text,l.consume(),u=l.token()),u.type==18&&l.nthToken(1).type==1&&(x=l.nthToken(1).text,l.consume(),l.consume(),u=l.token());u.type==6&&u.text.toLowerCase()=="class"&&l.nthToken(1).type==1&&l.nthToken(2).type==11;)N.push(l.nthToken(1).text),l.consume(),l.consume(),l.consume(),u=l.token();if(u.type==12){switch(l.consume(),f){case"-epubx-page-master":a.startPageMasterRule(C,x,N);break;case"-epubx-partition":a.startPartitionRule(C,x,N);break;case"-epubx-partition-group":a.startPartitionGroupRule(C,x,N);break}this.ruleStack.push(f),a.startRuleBody(),this.inStyleDeclaration=!0;continue}break}case"":a.error(`E_CSS_UNEXPECTED_AT${f}`,u),this.actions=Le;continue;default:a.error(`E_CSS_AT_UNKNOWN ${f}`,u),this.actions=Re;continue}a.error(`E_CSS_AT_SYNTAX ${f}`,u),this.actions=Re;continue;case 50:this.errorBrackets.push(u.type+1),l.consume();continue;case 52:if(this.errorBrackets.length==0){this.actions=me;continue}case 51:if(o&&this.errorBrackets.length==0&&u.type==11)return l.consume(),a.endFuncWithSelector(),!0;this.errorBrackets.length>0&&this.errorBrackets[this.errorBrackets.length-1]==u.type&&this.errorBrackets.pop(),this.errorBrackets.length==0&&u.type==13&&(this.actions=me),l.consume();continue;case 53:this.errorBrackets.length==0&&(this.actions=me),l.consume();continue;case 200:return!0;default:if(s)return this.exprStackReduce(11,u)?(this.result=c.pop(),!0):!1;if(o){switch(u.type){case 16:case 11:if(this.actions===dt)a.error("E_CSS_SYNTAX",u);else{let C=l.input.substring(E,u.position);a.pushSelectorText(C),E=u.position+1}if(u.type===16){a.nextSelector(),this.actions=dt,l.consume();continue}else return a.endFuncWithSelector(),l.consume(),!0;case 37:case 23:case 35:if(i){this.actions=re;continue}break;case 12:case 14:case 10:this.errorBrackets.push(u.type+1);break}a.error("E_CSS_SYNTAX",u),l.consume(),this.actions=Le;continue}if(this.actions!==Re&&this.actions!==Le&&this.actions!==Ke){if(u.type==54)a.error("E_CSS_SYNTAX",u);else if(this.actions===ye){switch(u.type){case 10:case 12:case 14:this.errorBrackets.push(u.type+1);break}c.push(new Ln(u.toString())),l.consume();continue}else if(u.type===12&&this.actions==Pe&&c.length>0){a.startMediaRule(c.pop()),this.ruleStack.push("media"),a.startRuleBody(),this.actions=me,l.consume();continue}else{if(u.type===17&&this.actions==Pe)return this.actions=me,l.consume(),!1;a.error("E_CSS_SYNTAX",u)}this.isInsidePropertyOnlyRule()?this.actions=Ke:this.actions=Le;continue}l.consume();continue}}return!1}},ti=class extends ei{constructor(e){super(null);this.scope=e}error(e,n){V.warn(e,n.toString())}getScope(){return this.scope}};function _m(r,t,e,n,s){let o=A("parseStylesheet"),i=new Bn(me,r,t,e),a=null;return s&&(a=Um(new De(s,t),t,e)),a=i.makeCondition(n,a&&a.toExpr()),a&&(t.startMediaRule(a),t.startRuleBody()),o.loop(()=>{for(;!i.runParser(100,!1,!1,!1,!1);){if(i.importReady){let c=J(i.importURL,e);i.importCondition&&(t.startMediaRule(i.importCondition),t.startRuleBody());let u=A("parseStylesheet.import");return Tc(c,t,null,null).then(()=>{i.importCondition&&t.endRule(),i.importReady=!1,i.importURL=null,i.importCondition=null,u.finish(!0)}),u.result()}let l=o.timeSlice();if(l.isPending)return l}return v(!1)}).then(()=>{a&&t.endRule(),o.finish(!0)}),o.result()}function Ur(r,t,e,n,s){return pn("parseStylesheetFromText",o=>{let i=new De(r,t);_m(i,t,e,n,s).thenFinish(o)},(o,i)=>{V.warn(i,`Failed to parse stylesheet text: ${r}`),o.finish(!1)})}function Tc(r,t,e,n){return pn("parseStylesheetFromURL",s=>{gs(r).then(o=>{o.responseText?Ur(o.responseText,t,r,e,n).then(i=>{i||V.warn(`Failed to parse stylesheet from ${r}`),s.finish(!0)}):s.finish(!0)})},(s,o)=>{V.warn(o,"Exception while fetching and parsing:",r),s.finish(!0)})}function en(r,t,e){let n=new Bn(ye,t,new ti(r),e);return n.runParser(Number.POSITIVE_INFINITY,!0,!1,!1,!1),n.result}function xh(r,t,e){new Bn(Dr,r,t,e).runParser(Number.POSITIVE_INFINITY,!1,!0,!1,!1)}function Um(r,t,e){let n=new Bn(Pe,r,t,e);return n.runParser(Number.POSITIVE_INFINITY,!1,!1,!0,!1),n.result}var Hm={"z-index":!0,"column-count":!0,"flow-linger":!0,opacity:!0,page:!0,"flow-priority":!0,utilization:!0};function zm(r){return!!Hm[r]}function yh(r,t,e){if(t instanceof Z&&t.str==="viv-leader")return new B(t);let n=t.evaluate(r);switch(typeof n){case"number":return zm(e)?n==Math.round(n)?new ut(n):new nt(n):new P(n,"px");case"string":return n?en(t.scope,new De(n,null),""):O;case"boolean":return n?b._true:b._false;case"undefined":return O}throw new Error("E_UNEXPECTED")}function Eh(r,t){let e={};return Object.keys(r).forEach(n=>{let s=e[n]={},o=r[n];Object.keys(o).forEach(i=>{s[i]=o[i].map(a=>{let l=t?a.logical:a.physical,c=t?a.physical:a.logical;return{regexp:new RegExp(`(-?)${l}(-?)`),to:`$1${c}$2`}})})}),e}function Sh(r,t,e,n){let s=n[t];if(!s)throw new Error(`unknown writing-mode: ${t}`);let o=s[e||"ltr"];if(!o)throw new Error(`unknown direction: ${e}`);for(let i of o){let a=r.replace(i.regexp,i.to);if(a!==r)return a}return r}var Nh={"horizontal-tb":{ltr:[{logical:"inline-start",physical:"left"},{logical:"inline-end",physical:"right"},{logical:"block-start",physical:"top"},{logical:"block-end",physical:"bottom"},{logical:"inline-size",physical:"width"},{logical:"block-size",physical:"height"}],rtl:[{logical:"inline-start",physical:"right"},{logical:"inline-end",physical:"left"},{logical:"block-start",physical:"top"},{logical:"block-end",physical:"bottom"},{logical:"inline-size",physical:"width"},{logical:"block-size",physical:"height"}]},"vertical-rl":{ltr:[{logical:"inline-start",physical:"top"},{logical:"inline-end",physical:"bottom"},{logical:"block-start",physical:"right"},{logical:"block-end",physical:"left"},{logical:"inline-size",physical:"height"},{logical:"block-size",physical:"width"}],rtl:[{logical:"inline-start",physical:"bottom"},{logical:"inline-end",physical:"top"},{logical:"block-start",physical:"right"},{logical:"block-end",physical:"left"},{logical:"inline-size",physical:"height"},{logical:"block-size",physical:"width"}]},"vertical-lr":{ltr:[{logical:"inline-start",physical:"top"},{logical:"inline-end",physical:"bottom"},{logical:"block-start",physical:"left"},{logical:"block-end",physical:"right"},{logical:"inline-size",physical:"height"},{logical:"block-size",physical:"width"}],rtl:[{logical:"inline-start",physical:"bottom"},{logical:"inline-end",physical:"top"},{logical:"block-start",physical:"left"},{logical:"block-end",physical:"right"},{logical:"inline-size",physical:"height"},{logical:"block-size",physical:"width"}]}},Gm=Eh(Nh,!0);function wc(r,t,e){return Sh(r,t,e||null,Gm)}var Wm=Eh(Nh,!1);function Pc(r,t,e){return Sh(r,t,e||null,Wm)}var $m={"horizontal-tb":[{logical:"line-left",physical:"left"},{logical:"line-right",physical:"right"},{logical:"over",physical:"top"},{logical:"under",physical:"bottom"}],"vertical-rl":[{logical:"line-left",physical:"top"},{logical:"line-right",physical:"bottom"},{logical:"over",physical:"right"},{logical:"under",physical:"left"}],"vertical-lr":[{logical:"line-left",physical:"top"},{logical:"line-right",physical:"bottom"},{logical:"over",physical:"right"},{logical:"under",physical:"left"}]};function vh(r,t){let e=$m[t];if(!e)throw new Error(`unknown writing-mode: ${t}`);for(let n=0;n<e.length;n++)if(e[n].physical===r)return e[n].logical;return r}function uo(r,t,e){var h;let n=t,s={width:n.style.width,height:n.style.height};function o(f){return r.getElementComputedStyle(t).getPropertyValue(f)}let a=o("writing-mode")!=="horizontal-tb",l=a?"height":"width",c=a?"width":"height";function u(f,g){n.style[f]=g;let m=o(f);return n.style[f]=s[f],m}let d={};for(let f of e){let g;switch(f){case"max-content inline size":g=u(l,"max-content");break;case"min-content inline size":g=u(l,"min-content");break;case"fit-content inline size":g=u(l,"fit-content");break;case"max-content block size":g=u(c,"max-content");break;case"min-content block size":g=u(c,"min-content");break;case"fit-content block size":g=u(c,"fit-content");break;case"max-content width":g=u("width","max-content");break;case"max-content height":g=u("height","max-content");break;case"min-content width":g=u("width","min-content");break;case"min-content height":g=u("height","min-content");break;case"fit-content width":g=u("width","fit-content");break;case"fit-content height":g=u("height","fit-content");break}g==="0px"&&t.childNodes.length===1&&((h=t.firstElementChild)==null?void 0:h.localName)==="img"&&!t.firstElementChild.complete&&(g="1px"),d[f]=parseFloat(g)}return d}function bs(r){var t,e;return((t=r==null?void 0:r.style)==null?void 0:t["box-decoration-break"])==="clone"||((e=r==null?void 0:r.style)==null?void 0:e["-webkit-box-decoration-break"])==="clone"}function Ac(r){let t=r.getAttribute("data-viv-box-break");return t?t.split(" "):[]}function Lc(r,t){r.setAttribute("data-viv-box-break",t.join(" "))}function pt(r,t){let e=Ac(r);e.includes(t)||(e.push(t),Lc(r,e))}function jm(r){let t=r.getAttribute("data-viv-margin-discard");return t?t.split(" "):[]}function Ym(r,t){r.setAttribute("data-viv-margin-discard",t.join(" "))}function Hr(r,t){let e=jm(r);e.includes(t)||(e.push(t),Ym(r,e))}function qm(r){let t=r.name,e=r.value;switch(t){case"page-break-before":case"page-break-after":case"page-break-inside":return{name:t.replace(/^page-/,""),value:e===b.always?b.page:e,important:r.important};default:return r}}var zr={page:!0,left:!0,right:!0,recto:!0,verso:!0,column:!0,region:!0};function Ie(r){return!!zr[r]}var Km={left:!0,right:!0,recto:!0,verso:!0};function On(r){return!!Km[r]}var Zm={avoid:!0,"avoid-page":!0,"avoid-column":!0,"avoid-region":!0};function po(r){return!!Zm[r]}function Ve(r,t){if(r)if(t){if(On(t))return t;if(On(r))return r;{let e=Ie(r),n=Ie(t);if(e&&n)switch(t){case"column":return r;case"region":return r==="column"?t:r;default:return t}else return n?t:e?r:po(t)?t:po(r)?r:t}}else return r;else return t}function Rc(r){return Ie(r)?r:"auto"}Ue("SIMPLE_PROPERTY",qm);var ho=zg(Bh());function Oh(r,t){return(0,ho.default)(r,t,0)}function Bc(r){return r.reduce((t,e)=>e[0]===ho.default.DELETE?t:t+e[1],"")}function Dh(r,t){return _h(r,t,1)}function Mh(r,t){return _h(r,t,-1)}function _h(r,t,e){let n=0,s=0;return r.some(o=>{for(let i=0;i<o[1].length;i++){switch(o[0]*e){case ho.default.INSERT:n++;break;case ho.default.DELETE:n--,s++;break;case ho.default.EQUAL:s++;break}if(s>t)return!0}return!1}),Math.max(Math.min(t,s-1)+n,0)}var $r;(t=>{function r(e){return e&&e.formattingContextType==="Block"}t.isInstanceOfBlockFormattingContext=r})($r||($r={}));var Dn;(t=>{let r;(i=>(i.INLINE="inline",i.COLUMN="column",i.REGION="region",i.PAGE="page"))(r=t.FloatReference||(t.FloatReference={}))})(Dn||(Dn={}));var si;(t=>{function r(e){return e&&e.flagmentLayoutConstraintType=="AfterIfContinue"}t.isInstanceOfAfterIfContinuesLayoutConstraint=r})(si||(si={}));var tn;(e=>{function r(n){return n?n.formattingContextType==="RepetitiveElementsOwner"||Dt.isInstanceOfTableFormattingContext(n):!1}e.isInstanceOfRepetitiveElementsOwnerFormattingContext=r;function t(n){return n?n.flagmentLayoutConstraintType==="RepetitiveElementsOwner"||Dt.isInstanceOfTableRowLayoutConstraint(n):!1}e.isInstanceOfRepetitiveElementsOwnerLayoutConstraint=t})(tn||(tn={}));var Dt;(e=>{function r(n){return n&&n.formattingContextType==="Table"}e.isInstanceOfTableFormattingContext=r;function t(n){return n&&n.flagmentLayoutConstraintType==="TableRow"}e.isInstanceOfTableRowLayoutConstraint=t})(Dt||(Dt={}));var Lt;(e=>{let r;(i=>(i[i.IGNORE=0]="IGNORE",i[i.NEWLINE=1]="NEWLINE",i[i.PRESERVE=2]="PRESERVE"))(r=e.Whitespace||(e.Whitespace={}));let t;(a=>(a[a.NONE=0]="NONE",a[a.CONTENT=1]="CONTENT",a[a.ROOTLESS=2]="ROOTLESS",a[a.ROOTED=3]="ROOTED"))(t=e.ShadowType||(e.ShadowType={}))})(Lt||(Lt={}));var Uh={transform:!0,"transform-origin":!0},Hh={top:!0,bottom:!0,left:!0,right:!0},_n=class{constructor(t,e,n){this.target=t;this.name=e;this.value=n}},aC={show:function(r){r.style.visibility="visible"},hide:function(r){r.style.visibility="hidden"},play:function(r){r.currentTime=0,r.play()},pause:function(r){r.pause()},resume:function(r){r.play()},mute:function(r){r.muted=!0},unmute:function(r){r.muted=!1}};function lC(r,t){let e=aC[t];return e?()=>{for(let n=0;n<r.length;n++)try{e(r[n])}catch(s){}}:null}var Mn=class Mn extends wn{constructor(e,n){super();this.container=e;this.bleedBox=n;p(this,"pageAreaElement",null);p(this,"delayedItems",[]);p(this,"hrefHandler");p(this,"elementsById",{});p(this,"dimensions",{width:0,height:0});p(this,"isFirstPage",!1);p(this,"isLastPage",!1);p(this,"isBlankPage",!1);p(this,"isAutoPageWidth",!0);p(this,"isAutoPageHeight",!0);p(this,"spineIndex",0);p(this,"position",null);p(this,"offset",-1);p(this,"side",null);p(this,"fetchers",[]);p(this,"marginBoxes",{top:{},bottom:{},left:{},right:{}});p(this,"pageType",null);this.hrefHandler=s=>{let o=s.currentTarget,i=o.getAttribute("href")||o.getAttributeNS("http://www.w3.org/1999/xlink","href");if(i){let a={type:"hyperlink",target:null,currentTarget:null,anchorElement:o,href:i,preventDefault(){s.preventDefault()}};this.dispatchEvent(a)}}}setAutoPageWidth(e){this.isAutoPageWidth=e,e?this.container.setAttribute(Mn.AUTO_PAGE_WIDTH_ATTRIBUTE,"true"):this.container.removeAttribute(Mn.AUTO_PAGE_WIDTH_ATTRIBUTE)}setAutoPageHeight(e){this.isAutoPageHeight=e,e?this.container.setAttribute(Mn.AUTO_PAGE_HEIGHT_ATTRIBUTE,"true"):this.container.removeAttribute(Mn.AUTO_PAGE_HEIGHT_ATTRIBUTE)}registerElementWithId(e,n){let s=this.elementsById[n];s?s.push(e):this.elementsById[n]=[e]}finish(e,n){Object.keys(this.elementsById).forEach(i=>{let a=this.elementsById[i];for(let l=0;l<a.length;)this.container.contains(a[l])?l++:a.splice(l,1);a.length===0&&delete this.elementsById[i]});let s=this.delayedItems;for(let i=0;i<s.length;i++){let a=s[i];a.target===this.container&&a.name==="transform"&&!this.isAutoPageWidth&&!this.isAutoPageHeight||T(a.target,a.name,a.value.toString())}let o=n.getElementClientRect(this.container);this.dimensions.width=o.width,this.dimensions.height=o.height;for(let i=0;i<e.length;i++){let a=e[i],l=this.elementsById[a.ref],c=this.elementsById[a.observer];if(l&&c){let u=lC(l,a.action);if(u)for(let d=0;d<c.length;d++)c[d].addEventListener(a.event,u,!1)}}}};p(Mn,"AUTO_PAGE_WIDTH_ATTRIBUTE","data-vivliostyle-auto-page-width"),p(Mn,"AUTO_PAGE_HEIGHT_ATTRIBUTE","data-vivliostyle-auto-page-height");var fo=Mn,_t="data-adapt-spec",Ze=Lt.Whitespace;function Qr(r){switch(r){case"normal":case"nowrap":return Ze.IGNORE;case"pre-line":return Ze.NEWLINE;case"pre":case"pre-wrap":case"break-spaces":return Ze.PRESERVE;default:return null}}function ue(r,t){if(!r)return!0;if(r.nodeType==1)return!1;let e=r.textContent;switch(t){case Ze.PRESERVE:return e.length==0;case Ze.NEWLINE:return!!e.match(/^[ \t]*$/);case Ze.IGNORE:default:return!!e.match(/^[ \t\r\n\f]*$/)}}var Xr=class{constructor(t,e){this.flowName=t;this.parentFlowName=e;p(this,"forcedBreakOffsets",[]);p(this,"formattingContext",null)}},jr=class{constructor(t,e,n,s,o,i,a,l,c){this.flowName=t;this.element=e;this.startOffset=n;this.priority=s;this.linger=o;this.exclusive=i;this.repeated=a;this.last=l;this.breakBefore=c;p(this,"startPage",-1)}isBetter(t){return this.exclusive?!t.exclusive||this.priority>t.priority?!0:this.last:!1}};function zh(r,t){return r.top-t.top}function Gh(r,t){return t.right-r.right}function Wh(r,t){var e,n;return r===t?!0:!r||!t?!1:(r.node===t.node||!!r.shadowContext&&!!t.shadowContext&&r.shadowType===Lt.ShadowType.ROOTLESS&&t.shadowType===Lt.ShadowType.ROOTLESS&&((e=r.node)==null?void 0:e.outerHTML)===((n=t.node)==null?void 0:n.outerHTML))&&r.shadowType===t.shadowType&&Dc(r.shadowContext,t.shadowContext)&&Dc(r.nodeShadow,t.nodeShadow)&&Wh(r.shadowSibling,t.shadowSibling)}function Mt(r,t){if(r===t)return!0;if(!r||!t||r.offsetInNode!==t.offsetInNode||r.after!==t.after||r.steps.length!==t.steps.length)return!1;for(let e=0;e<r.steps.length;e++)if(!Wh(r.steps[e],t.steps[e]))return!1;return!0}function $h(r){return{steps:[{node:r,shadowType:St.NONE,shadowContext:null,nodeShadow:null,shadowSibling:null,formattingContext:null,fragmentIndex:0}],offsetInNode:0,after:!1,preprocessedTextContent:null}}function Es(r,t){return{steps:[{node:r.sourceNode,shadowType:St.NONE,shadowContext:r.shadowContext,nodeShadow:null,shadowSibling:null,formattingContext:null,fragmentIndex:t!=null?t:r.fragmentIndex}],offsetInNode:0,after:!1,preprocessedTextContent:r.preprocessedTextContent}}function mo(r,t){let e=new Un(r.node,t,0);return e.shadowType=r.shadowType,e.shadowContext=r.shadowContext,e.nodeShadow=r.nodeShadow,e.shadowSibling=r.shadowSibling?mo(r.shadowSibling,t.copy()):null,e.formattingContext=r.formattingContext,e.fragmentIndex=r.fragmentIndex+1,e}var St=Lt.ShadowType,ys=class{constructor(t,e,n,s,o,i,a){this.owner=t;this.root=e;this.xmldoc=n;this.parentShadow=s;this.type=i;this.styler=a;p(this,"subShadow",null);o&&(o.subShadow=this)}equals(t){return t?this.owner===t.owner&&this.xmldoc===t.xmldoc&&this.type===t.type&&Dc(this.parentShadow,t.parentShadow):!1}};function Dc(r,t){return r===t||!!r&&!!t&&r.equals(t)}var Yr=class{constructor(t,e){this.outer=t;this.count=e}},Un=class r{constructor(t,e,n){this.sourceNode=t;this.parent=e;this.boxOffset=n;p(this,"offsetInNode",0);p(this,"after",!1);p(this,"shadowType");p(this,"shadowContext");p(this,"nodeShadow",null);p(this,"shadowSibling",null);p(this,"shared",!1);p(this,"inline",!0);p(this,"overflow",!1);p(this,"breakPenalty");p(this,"display",null);p(this,"floatReference");p(this,"floatSide",null);p(this,"clearSide",null);p(this,"floatMinWrapBlock",null);p(this,"columnSpan",null);p(this,"verticalAlign","baseline");p(this,"captionSide","top");p(this,"inlineBorderSpacing",0);p(this,"blockBorderSpacing",0);p(this,"flexContainer",!1);p(this,"whitespace");p(this,"hyphenateCharacter");p(this,"breakWord");p(this,"establishesBFC",!1);p(this,"containingBlockForAbsolute",!1);p(this,"breakBefore",null);p(this,"breakAfter",null);p(this,"viewNode",null);p(this,"clearSpacer",null);p(this,"inheritedProps");p(this,"vertical");p(this,"direction");p(this,"firstPseudo");p(this,"lang",null);p(this,"preprocessedTextContent",null);p(this,"formattingContext");p(this,"repeatOnBreak",null);p(this,"pluginProps",{});p(this,"fragmentIndex",1);p(this,"afterIfContinues",null);p(this,"footnotePolicy",null);p(this,"pageType");this.shadowType=St.NONE,this.shadowContext=e?e.shadowContext:null,this.breakPenalty=e?e.breakPenalty:0,this.floatReference=Dn.FloatReference.INLINE,this.whitespace=e?e.whitespace:Ze.IGNORE,this.hyphenateCharacter=e?e.hyphenateCharacter:null,this.breakWord=e?e.breakWord:!1,this.inheritedProps=e?e.inheritedProps:{},this.vertical=e?e.vertical:!1,this.direction=e?e.direction:"ltr",this.firstPseudo=e?e.firstPseudo:null,this.formattingContext=e?e.formattingContext:null,this.pageType=e?e.pageType:null}resetView(){this.inline=!0,this.breakPenalty=this.parent?this.parent.breakPenalty:0,this.viewNode=null,this.clearSpacer=null,this.offsetInNode=0,this.after=!1,this.display=null,this.floatReference=Dn.FloatReference.INLINE,this.floatSide=null,this.clearSide=null,this.floatMinWrapBlock=null,this.columnSpan=null,this.verticalAlign="baseline",this.flexContainer=!1,this.whitespace=this.parent?this.parent.whitespace:Ze.IGNORE,this.hyphenateCharacter=this.parent?this.parent.hyphenateCharacter:null,this.breakWord=this.parent?this.parent.breakWord:!1,this.breakBefore=null,this.breakAfter=null,this.nodeShadow=null,this.establishesBFC=!1,this.containingBlockForAbsolute=!1,this.vertical=this.parent?this.parent.vertical:!1,this.nodeShadow=null,this.preprocessedTextContent=null,this.formattingContext=this.parent?this.parent.formattingContext:null,this.repeatOnBreak=null,this.pluginProps={},this.fragmentIndex=1,this.afterIfContinues=null,this.footnotePolicy=null}cloneItem(){let t=new r(this.sourceNode,this.parent,this.boxOffset);return t.offsetInNode=this.offsetInNode,t.after=this.after,t.nodeShadow=this.nodeShadow,t.shadowType=this.shadowType,t.shadowContext=this.shadowContext,t.shadowSibling=this.shadowSibling,t.inline=this.inline,t.breakPenalty=this.breakPenalty,t.display=this.display,t.floatReference=this.floatReference,t.floatSide=this.floatSide,t.clearSide=this.clearSide,t.floatMinWrapBlock=this.floatMinWrapBlock,t.columnSpan=this.columnSpan,t.verticalAlign=this.verticalAlign,t.captionSide=this.captionSide,t.inlineBorderSpacing=this.inlineBorderSpacing,t.blockBorderSpacing=this.blockBorderSpacing,t.establishesBFC=this.establishesBFC,t.containingBlockForAbsolute=this.containingBlockForAbsolute,t.flexContainer=this.flexContainer,t.whitespace=this.whitespace,t.hyphenateCharacter=this.hyphenateCharacter,t.breakWord=this.breakWord,t.breakBefore=this.breakBefore,t.breakAfter=this.breakAfter,t.viewNode=this.viewNode,t.clearSpacer=this.clearSpacer,t.firstPseudo=this.firstPseudo,t.vertical=this.vertical,t.overflow=this.overflow,t.preprocessedTextContent=this.preprocessedTextContent,t.formattingContext=this.formattingContext,t.repeatOnBreak=this.repeatOnBreak,t.pluginProps=Object.create(this.pluginProps),t.fragmentIndex=this.fragmentIndex,t.afterIfContinues=this.afterIfContinues,t.footnotePolicy=this.footnotePolicy,t}modify(){return this.shared?this.cloneItem():this}copy(){let t=this;do{if(t.shared)break;t.shared=!0,t=t.parent}while(t);return this}clone(){let t=this.cloneItem(),e=t,n;for(;(n=e.parent)!=null;)n=n.cloneItem(),e.parent=n,e=n;return t}toNodePositionStep(){var t;return{node:this.sourceNode,shadowType:this.shadowType,shadowContext:this.shadowContext,nodeShadow:this.nodeShadow,shadowSibling:this.shadowSibling?this.shadowSibling.toNodePositionStep():null,formattingContext:this.formattingContext,fragmentIndex:((t=this.viewNode)==null?void 0:t.parentNode)===null?0:this.fragmentIndex}}toNodePosition(){var s,o,i;let t=this,e=[];t.shadowType===Lt.ShadowType.ROOTLESS&&(t.floatReference!==Dn.FloatReference.INLINE||t.floatSide==="footnote")&&((i=(o=(s=t.shadowContext)==null?void 0:s.styler)==null?void 0:o.style)!=null&&i._pseudos)&&(t=t.parent);do(!t.firstPseudo||!t.parent||t.parent.firstPseudo===t.firstPseudo)&&e.push(t.toNodePositionStep()),t=t.parent;while(t);let n=this.preprocessedTextContent?Mh(this.preprocessedTextContent,this.offsetInNode):this.offsetInNode;return{steps:e,offsetInNode:n,after:this.after,preprocessedTextContent:this.preprocessedTextContent}}isInsideBFC(){let t=this.parent;for(;t;){if(t.establishesBFC)return!0;t=t.parent}return!1}getContainingBlockForAbsolute(){let t=this.parent;for(;t;){if(t.containingBlockForAbsolute)return t;t=t.parent}return null}belongsTo(t){return this.formattingContext===t&&!!this.parent&&this.parent.formattingContext===t}},ht=class r{constructor(t){this.primary=t;p(this,"floats",null)}clone(){let t=new r(this.primary);if(this.floats){t.floats=[];for(let e=0;e<this.floats.length;++e)t.floats[e]=this.floats[e]}return t}isSamePosition(t){if(!t)return!1;if(this===t)return!0;if(!Mt(this.primary,t.primary))return!1;if(this.floats){if(!t.floats||this.floats.length!==t.floats.length)return!1;for(let e=0;e<this.floats.length;e++)if(!Mt(this.floats[e],t.floats[e]))return!1}else if(t.floats)return!1;return!0}},qr=class r{constructor(t,e){this.chunkPosition=t;this.flowChunk=e}clone(){return new r(this.chunkPosition.clone(),this.flowChunk)}isSamePosition(t){return!!t&&(this===t||this.chunkPosition.isSamePosition(t.chunkPosition))}},Kr=class r{constructor(){p(this,"positions",[]);p(this,"startBreakType",null);p(this,"breakAfter",null)}clone(){let t=new r,e=this.positions,n=t.positions;for(let s=0;s<e.length;s++)n[s]=e[s].clone();return t.startBreakType=this.startBreakType,t.breakAfter=this.breakAfter,t}isSamePosition(t){if(this===t)return!0;if(!t||this.positions.length!==t.positions.length)return!1;for(let e=0;e<this.positions.length;e++)if(!this.positions[e].isSamePosition(t.positions[e]))return!1;return!0}hasContent(t){return this.positions.length>0&&this.positions[0].flowChunk.startOffset<=t}},Zr=class r{constructor(){p(this,"page",0);p(this,"flows",{});p(this,"flowPositions",{});p(this,"isBlankPage",!1);p(this,"highestSeenOffset",0);p(this,"highestSeenNode");p(this,"lookupPositionOffset")}clone(){let t=new r;t.page=this.page,t.isBlankPage=this.isBlankPage,t.highestSeenNode=this.highestSeenNode,t.highestSeenOffset=this.highestSeenOffset,t.lookupPositionOffset=this.lookupPositionOffset,t.flows=this.flows;for(let e in this.flowPositions)t.flowPositions[e]=this.flowPositions[e].clone();return t}isSamePosition(t){if(this===t)return!0;if(!t||this.page!==t.page)return!1;let e=Object.keys(this.flowPositions),n=Object.keys(t.flowPositions);if(e.length!==n.length)return!1;for(let s of e)if(!this.flowPositions[s].isSamePosition(t.flowPositions[s]))return!1;return!0}hasContent(t,e){let n=this.flowPositions[t];return n?n.hasContent(e):!1}startSideOfFlow(t){var n;let e=(n=this.flowPositions[t])==null?void 0:n.startBreakType;return e&&On(e)?e:"any"}firstFlowChunkOfFlow(t){let e=this.flowPositions[t];if(!e)return null;let n=e.positions[0];return n?n.flowChunk:null}},go=class{constructor(t){this.element=t;p(this,"left",0);p(this,"top",0);p(this,"marginLeft",0);p(this,"marginRight",0);p(this,"marginTop",0);p(this,"marginBottom",0);p(this,"borderLeft",0);p(this,"borderRight",0);p(this,"borderTop",0);p(this,"borderBottom",0);p(this,"paddingLeft",0);p(this,"paddingRight",0);p(this,"paddingTop",0);p(this,"paddingBottom",0);p(this,"width",0);p(this,"height",0);p(this,"originX",0);p(this,"originY",0);p(this,"exclusions",null);p(this,"innerShape",null);p(this,"computedBlockSize",0);p(this,"snapWidth",0);p(this,"snapHeight",0);p(this,"snapOffsetX",0);p(this,"snapOffsetY",0);p(this,"vertical",!1);p(this,"rtl",!1);p(this,"borderBoxSizing",!1)}getInsetTop(){return this.marginTop+(this.borderBoxSizing?0:this.borderTop+this.paddingTop)}getInsetBottom(){return this.marginBottom+(this.borderBoxSizing?0:this.borderBottom+this.paddingBottom)}getInsetLeft(){return this.marginLeft+(this.borderBoxSizing?0:this.borderLeft+this.paddingLeft)}getInsetRight(){return this.marginRight+(this.borderBoxSizing?0:this.borderRight+this.paddingRight)}getInsetBefore(){return this.vertical?this.getInsetRight():this.getInsetTop()}getInsetAfter(){return this.vertical?this.getInsetLeft():this.getInsetBottom()}getInsetStart(){return this.vertical?this.getInsetTop():this.getInsetLeft()}getInsetEnd(){return this.vertical?this.getInsetBottom():this.getInsetRight()}getBeforeEdge(t){return this.vertical?t.right:t.top}getAfterEdge(t){return this.vertical?t.left:t.bottom}getStartEdge(t){return this.vertical?this.rtl?t.bottom:t.top:this.rtl?t.right:t.left}getEndEdge(t){return this.vertical?this.rtl?t.top:t.bottom:this.rtl?t.left:t.right}getInlineSize(t){return this.vertical?t.bottom-t.top:t.right-t.left}getBoxSize(t){return this.vertical?t.right-t.left:t.bottom-t.top}getBoxDir(){return this.vertical?-1:1}getInlineDir(){return this.rtl?-1:1}copyFrom(t){this.element=t.element,this.left=t.left,this.top=t.top,this.marginLeft=t.marginLeft,this.marginRight=t.marginRight,this.marginTop=t.marginTop,this.marginBottom=t.marginBottom,this.borderLeft=t.borderLeft,this.borderRight=t.borderRight,this.borderTop=t.borderTop,this.borderBottom=t.borderBottom,this.paddingLeft=t.paddingLeft,this.paddingRight=t.paddingRight,this.paddingTop=t.paddingTop,this.paddingBottom=t.paddingBottom,this.width=t.width,this.height=t.height,this.originX=t.originX,this.originY=t.originY,this.innerShape=t.innerShape,this.exclusions=t.exclusions,this.computedBlockSize=t.computedBlockSize,this.snapWidth=t.snapWidth,this.snapHeight=t.snapHeight,this.vertical=t.vertical,this.rtl=t.rtl,this.borderBoxSizing=t.borderBoxSizing}setVerticalPosition(t,e){this.top=t,this.height=e,T(this.element,"top",`${t}px`),T(this.element,"height",`${e}px`)}setHorizontalPosition(t,e){this.left=t,this.width=e,T(this.element,"left",`${t}px`),T(this.element,"width",`${e}px`)}setBlockPosition(t,e){if(this.vertical){let n=e+this.marginLeft+this.marginRight+(this.borderBoxSizing?0:this.paddingLeft+this.paddingRight+this.borderLeft+this.borderRight);this.setHorizontalPosition(t+n*this.getBoxDir(),e)}else this.setVerticalPosition(t,e)}setInlinePosition(t,e){if(this.vertical)if(this.rtl){let n=e+this.marginTop+this.marginBottom+(this.borderBoxSizing?0:this.paddingTop+this.paddingBottom+this.borderTop+this.borderBottom);this.setVerticalPosition(t+n*this.getInlineDir(),e)}else this.setVerticalPosition(t,e);else if(this.rtl){let n=e+this.marginLeft+this.marginRight+(this.borderBoxSizing?0:this.paddingLeft+this.paddingRight+this.borderLeft+this.borderRight);this.setHorizontalPosition(t+n*this.getInlineDir(),e)}else this.setHorizontalPosition(t,e)}clear(){let t=this.element,e;for(;e=t.lastChild;)t.removeChild(e)}getInnerShape(){let t=this.getInnerRect();return this.innerShape?this.innerShape.withOffset(t.x1,t.y1):Ko(t.x1,t.y1,t.x2,t.y2)}getInnerRect(){let t=this.originX+this.left+this.getInsetLeft(),e=this.originY+this.top+this.getInsetTop();return new He(t,e,t+this.width,e+this.height)}getPaddingRect(){let t=this.originX+this.left+this.marginLeft+this.borderLeft,e=this.originY+this.top+this.marginTop+this.borderTop,n=this.paddingLeft+this.width+this.paddingRight,s=this.paddingTop+this.height+this.paddingBottom;return new He(t,e,t+n,e+s)}getOuterShape(t,e){let n=this.getOuterRect();return Rr(t,n.x1,n.y1,n.x2-n.x1,n.y2-n.y1,e)}getOuterRect(){let t=this.originX+this.left,e=this.originY+this.top,n=this.getInsetLeft()+this.width+this.getInsetRight(),s=this.getInsetTop()+this.height+this.getInsetBottom();return new He(t,e,t+n,e+s)}},hn=class extends ct{constructor(e,n,s,o){super();this.elem=e;this.context=n;this.rootContentValue=s;this.exprContentListener=o}visitStrInner(e,n){var s;if(!n){if(((s=this.elem.lastChild)==null?void 0:s.nodeType)===3){this.elem.lastChild.textContent+=e;return}n=this.elem.ownerDocument.createTextNode(e)}this.elem.appendChild(n)}visitStr(e){return this.visitStrInner(e.str),null}visitURL(e){if(this.rootContentValue.url)this.elem.setAttribute("src",e.url);else{let n=this.elem.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml","img");n.setAttribute("src",e.url),this.elem.appendChild(n)}return null}visitSpaceList(e){return this.visitValues(e.values),null}visitExpr(e){let n=e.toExpr(),s=n.evaluate(this.context);if(typeof s=="string"){n instanceof ee&&(s=en(n.scope,new De(s,null),"").stringValue()),this.elem.ownerDocument;let o=this.exprContentListener(n,s,this.elem.ownerDocument);!o&&s&&n instanceof Z&&n.str.startsWith("running-element-")&&(s=""),this.visitStrInner(s,o)}return null}};function Nt(r){return r!=null&&r!==O&&r!==b.normal&&r!==b.none&&!U(r)}var ae=Dn.FloatReference;function jh(r){switch(r){case"inline":return ae.INLINE;case"column":return ae.COLUMN;case"region":return ae.REGION;case"page":return ae.PAGE;default:throw new Error(`Unknown float-reference: ${r}`)}}function Hn(r){switch(r){case ae.INLINE:return!1;case ae.COLUMN:case ae.REGION:case ae.PAGE:return!0;default:throw new Error(`Unknown float-reference: ${r}`)}}function Uc(r,t,e,n){let s=t?"vertical-rl":"horizontal-tb";if((r==="top"||r==="bottom")&&(r=Pc(r,s,e)),r==="block-start"&&(r="inline-start"),r==="block-end"&&(r="inline-end"),r==="inline-start"||r==="inline-end"){let o=wc(r,s,e),i=vh(o,s);i==="line-left"?r="left":i==="line-right"&&(r="right")}else r==="inside"?r=n==="left"?"right":"left":r==="outside"&&(r=n==="left"?"left":"right");return r!=="left"&&r!=="right"&&(V.warn(`Invalid float value: ${r}. Fallback to left.`),r="left"),r}var ii=class{constructor(t,e,n,s,o,i){this.nodePosition=t;this.floatReference=e;this.floatSide=n;this.clearSide=s;this.flowName=o;this.floatMinWrapBlock=i;p(this,"order",null);p(this,"id",null)}getOrder(){if(this.order===null)throw new Error("The page float is not yet added");return this.order}getId(){if(!this.id)throw new Error("The page float is not yet added");return this.id}isAllowedOnContext(t){return t.isAnchorAlreadyAppeared(this.getId())}isAllowedToPrecede(t){return!1}},Mc=class{constructor(){p(this,"floats",[]);p(this,"nextPageFloatIndex",0)}nextOrder(){return this.nextPageFloatIndex++}createPageFloatId(t){return`pf${t}`}addPageFloat(t){if(this.floats.findIndex(n=>Mt(n.nodePosition,t.nodePosition))>=0)throw new Error("A page float with the same source node is already registered");{let n=t.order=this.nextOrder();t.id=this.createPageFloatId(n),this.floats.push(t)}}findPageFloatByNodePosition(t){let e=this.floats.findIndex(n=>Mt(n.nodePosition,t));return e>=0?this.floats[e]:null}findPageFloatById(t){let e=this.floats.findIndex(n=>n.id===t);return e>=0?this.floats[e]:null}},ri=class{constructor(t,e,n,s,o,i){this.floatReference=t;this.floatSide=e;this.clearSide=n;this.continuations=s;this.area=o;this.continues=i}hasFloat(t){return this.continuations.some(e=>e.float===t)}findNotAllowedFloat(t){for(let e=this.continuations.length-1;e>=0;e--){let n=this.continuations[e].float;if(!n.isAllowedOnContext(t))return n}return null}getOuterShape(){return this.area.getOuterShape(null,null)}getOuterRect(){return this.area.getOuterRect()}getOrder(){let t=this.continuations.map(e=>e.float);return Math.min.apply(null,t.map(e=>e.getOrder()))}shouldBeStashedBefore(t){return this.getOrder()<t.getOrder()}addContinuations(t){t.forEach(e=>{this.continuations.push(e)})}getFlowName(){let t=this.continuations[0].float.flowName;return this.continuations.every(e=>e.float.flowName===t),t}},ai=class{constructor(t,e){this.float=t;this.nodePosition=e}equals(t){return t?this===t?!0:this.float===t.float&&Mt(this.nodePosition,t.nodePosition):!1}},fn=class{constructor(t,e,n,s,o,i,a){this.parent=t;this.floatReference=e;this.container=n;this.flowName=s;this.generatingNodePosition=o;p(this,"children",[]);p(this,"writingMode");p(this,"direction");p(this,"invalidated",!1);p(this,"floatStore");p(this,"forbiddenFloats",[]);p(this,"floatFragments",[]);p(this,"stashedFloatFragments",[]);p(this,"floatAnchors",{});p(this,"floatsDeferredToNext",[]);p(this,"floatsDeferredFromPrevious");p(this,"layoutConstraints",[]);p(this,"locked",!1);t&&t.children.push(this),this.writingMode=i||t&&t.writingMode||b.horizontal_tb,this.direction=a||t&&t.direction||b.ltr,this.floatStore=t?t.floatStore:new Mc;let l=this.getPreviousSibling();this.floatsDeferredFromPrevious=l?[].concat(l.floatsDeferredToNext):[]}getParent(t){if(!this.parent)throw new Error(`No PageFloatLayoutContext for ${t}`);return this.parent}getPreviousSiblingOf(t,e,n,s){let o=this.children.indexOf(t);o<0&&(o=this.children.length);for(let i=o-1;i>=0;i--){let a=this.children[i];if(a.floatReference===e&&a.flowName===n&&Mt(a.generatingNodePosition,s))return a;if(a=a.getPreviousSiblingOf(null,e,n,s),a)return a}return null}getPreviousSibling(){let t=this,e=this.parent,n;for(;e;){if(n=e.getPreviousSiblingOf(t,this.floatReference,this.flowName,this.generatingNodePosition),n)return n;t=e,e=e.parent}return null}getContainer(t){return!t||t===this.floatReference?this.container:this.getParent(t).getContainer(t)}setContainer(t){this.container=t,this.reattachFloatFragments()}addPageFloat(t){this.floatStore.addPageFloat(t)}getPageFloatLayoutContext(t){return t===this.floatReference?this:this.getParent(t).getPageFloatLayoutContext(t)}findPageFloatByNodePosition(t){return this.floatStore.findPageFloatByNodePosition(t)}forbid(t){let e=t.getId(),n=t.floatReference;n===this.floatReference?this.forbiddenFloats.includes(e)||(this.forbiddenFloats.push(e),new Ut().findByFloat(t).forbid(t,this)):this.getParent(n).forbid(t)}isForbidden(t){let e=t.getId(),n=t.floatReference;return n===this.floatReference?this.forbiddenFloats.includes(e):this.getParent(n).isForbidden(t)}addPageFloatFragment(t,e){let n=t.floatReference;n!==this.floatReference?this.getParent(n).addPageFloatFragment(t,e):this.floatFragments.includes(t)||(this.floatFragments.push(t),this.floatFragments.sort((s,o)=>s.getOrder()-o.getOrder())),e||this.invalidate()}removePageFloatFragment(t,e){let n=t.floatReference;if(n!==this.floatReference)this.getParent(n).removePageFloatFragment(t,e);else{let s=this.floatFragments.indexOf(t);if(s>=0){let o=this.floatFragments.splice(s,1)[0],i=o.area&&o.area.element;i&&i.parentNode&&i.parentNode.removeChild(i),e||this.invalidate()}}}findPageFloatFragment(t){if(t.floatReference!==this.floatReference)return this.getParent(t.floatReference).findPageFloatFragment(t);let e=this.floatFragments.findIndex(n=>n.hasFloat(t));return e>=0?this.floatFragments[e]:null}hasFloatFragments(t){return this.floatFragments.length>0&&(!t||this.floatFragments.some(t))?!0:this.parent?this.parent.hasFloatFragments(t):!1}hasContinuingFloatFragmentsInFlow(t){return this.hasFloatFragments(e=>e.continues&&e.getFlowName()===t)}registerPageFloatAnchor(t,e){this.floatAnchors[t.getId()]=e}collectPageFloatAnchors(){let t=Object.assign({},this.floatAnchors);return this.children.reduce((e,n)=>Object.assign(e,n.collectPageFloatAnchors()),t)}isAnchorAlreadyAppeared(t){if(this.getDeferredPageFloatContinuations().some(o=>o.float.getId()===t))return!0;let s=this.collectPageFloatAnchors()[t];return s&&this.container&&this.container.element?this.container.element.contains(s):!1}deferPageFloat(t){let e=t.float;if(e.floatReference===this.floatReference){let n=this.floatsDeferredToNext.findIndex(s=>s.float===e);n>=0?this.floatsDeferredToNext.splice(n,1,t):this.floatsDeferredToNext.push(t)}else this.getParent(e.floatReference).deferPageFloat(t)}hasPrecedingFloatsDeferredToNext(t,e){if(!e&&t.floatReference!==this.floatReference)return this.getParent(t.floatReference).hasPrecedingFloatsDeferredToNext(t,!1);let n=t.getOrder();return this.floatsDeferredToNext.some(o=>o.float.getOrder()<n&&!t.isAllowedToPrecede(o.float))?!0:this.parent?this.parent.hasPrecedingFloatsDeferredToNext(t,!0):!1}getLastFollowingFloatInFragments(t){let e=t.getOrder(),n=null;if(this.floatFragments.forEach(s=>{s.continuations.forEach(o=>{let i=o.float,a=i.getOrder();a>e&&(!n||a>n.getOrder())&&(n=i)})}),this.parent){let s=this.parent.getLastFollowingFloatInFragments(t);s&&(!n||s.getOrder()>n.getOrder())&&(n=s)}return n}getDeferredPageFloatContinuations(t){t=t||this.flowName;let e=this.floatsDeferredFromPrevious.filter(n=>!t||n.float.flowName===t);return this.parent&&(e=this.parent.getDeferredPageFloatContinuations(t).concat(e)),e.sort((n,s)=>n.float.getOrder()-s.float.getOrder())}getPageFloatContinuationsDeferredToNext(t){t=t||this.flowName;let e=this.floatsDeferredToNext.filter(n=>!t||n.float.flowName===t);return this.parent?this.parent.getPageFloatContinuationsDeferredToNext(t).concat(e):e}getFloatsDeferredToNextInChildContexts(){let t=[],e=[];for(let n=this.children.length-1;n>=0;n--){let s=this.children[n];e.includes(s.flowName)||(e.push(s.flowName),t=t.concat(s.floatsDeferredToNext.map(o=>o.float)),t=t.concat(s.getFloatsDeferredToNextInChildContexts()))}return t}checkAndForbidNotAllowedFloat(){if(this.checkAndForbidFloatFollowingDeferredFloat())return!0;for(let t=this.floatFragments.length-1;t>=0;t--){let e=this.floatFragments[t],n=e.findNotAllowedFloat(this);if(n)return this.locked?this.invalidate():(this.removePageFloatFragment(e),this.forbid(n),this.removeEndFloatFragments(e.floatSide)),!0}return this.floatReference===ae.REGION&&this.parent.locked?this.parent.checkAndForbidNotAllowedFloat():!1}checkAndForbidFloatFollowingDeferredFloat(){let t=this.getFloatsDeferredToNextInChildContexts(),e=this.floatFragments.reduce((n,s)=>n.concat(s.continuations.map(o=>o.float)),[]);e.sort((n,s)=>s.getOrder()-n.getOrder());for(let n of e){let s=n.getOrder();if(t.some(o=>!n.isAllowedToPrecede(o)&&s>o.getOrder())){if(this.locked)this.invalidate();else{this.forbid(n);let o=this.findPageFloatFragment(n);this.removePageFloatFragment(o)}return!0}}return!1}finish(){if(!this.checkAndForbidNotAllowedFloat()){for(let t=this.floatsDeferredToNext.length-1;t>=0;t--)if(!this.floatsDeferredToNext[t].float.isAllowedOnContext(this)){if(this.locked){this.invalidate();return}this.floatsDeferredToNext.splice(t,1)}this.floatsDeferredFromPrevious.forEach(t=>{this.floatsDeferredToNext.findIndex(e=>t.equals(e))>=0||this.floatFragments.some(e=>e.hasFloat(t.float))||this.floatsDeferredToNext.push(t)})}}hasSameContainerAs(t){return!!this.container&&!!t.container&&this.container.element===t.container.element}invalidate(){this.invalidated=!0,!this.locked&&(this.container&&(this.children.forEach(t=>{this.hasSameContainerAs(t)&&t.floatFragments.forEach(e=>{let n=e.area.element;n&&n.parentNode&&n.parentNode.removeChild(n)})}),this.container.clear()),this.children.forEach(t=>{t.layoutConstraints.splice(0)}),this.children.splice(0),Object.keys(this.floatAnchors).forEach(t=>{delete this.floatAnchors[t]}))}detachChildren(){let t=this.children.splice(0);return t.forEach(e=>{e.floatFragments.forEach(n=>{let s=n.area.element;s&&s.parentNode&&s.parentNode.removeChild(s)})}),t}attachChildren(t){t.forEach(e=>{this.children.push(e),e.reattachFloatFragments()})}isInvalidated(){return this.invalidated||!!this.parent&&this.parent.isInvalidated()}validate(){this.invalidated=!1}toLogical(t){let e=this.writingMode.toString(),n=this.direction.toString();if(t==="inside"||t==="outside"){let s=!!this.container.element.closest("[data-vivliostyle-page-side='left']");t=t==="inside"?s?"right":"left":s?"left":"right"}return Pc(t,e,n)}toPhysical(t){let e=this.writingMode.toString(),n=this.direction.toString();return wc(t,e,n)}toLogicalFloatSides(t){let e=t.split(" "),n=[];for(let a of e){let l=this.toLogical(a);n.includes(l)||n.push(l)}let s=[],o=!1,i=!1;for(let a=0;a<n.length;a++){let l=n[a];l.includes("block")?o||(n.slice(a+1).some(c=>c.includes("block"))?(s.push("snap-block"),o=!0):s.push(l)):l.includes("inline")&&(i||(n.slice(a+1).some(c=>c.includes("inline"))?(s.push("snap-inline"),i=!0):s.push(l)))}return s}removeEndFloatFragments(t){let e=this.toLogicalFloatSides(t)[0];if(e==="block-end"||e==="inline-end"){let n=0;for(;n<this.floatFragments.length;){let s=this.floatFragments[n];this.toLogicalFloatSides(s.floatSide)[0]===e?this.removePageFloatFragment(s):n++}}}stashEndFloatFragments(t){let e=t.floatReference;if(e!==this.floatReference){this.getParent(e).stashEndFloatFragments(t);return}let n=this.toLogicalFloatSides(t.floatSide)[0];if(n==="block-end"||n==="snap-block"||n==="inline-end"||n==="snap-inline"){let s=0;for(;s<this.floatFragments.length;){let o=this.floatFragments[s],i=this.toLogicalFloatSides(o.floatSide)[0];(i===n||n==="snap-block"&&i==="block-end"||n==="snap-inline"&&i==="inline-end")&&o.shouldBeStashedBefore(t)?(this.stashedFloatFragments.push(o),this.floatFragments.splice(s,1)):s++}}}restoreStashedFragments(t){if(t!==this.floatReference){this.getParent(t).restoreStashedFragments(t);return}this.stashedFloatFragments.forEach(e=>{this.addPageFloatFragment(e,!0)}),this.stashedFloatFragments.splice(0)}discardStashedFragments(t){if(t!==this.floatReference){this.getParent(t).discardStashedFragments(t);return}this.stashedFloatFragments.splice(0)}getStashedFloatFragments(t){return t===this.floatReference?this.stashedFloatFragments.concat().sort((e,n)=>n.getOrder()-e.getOrder()):this.getParent(t).getStashedFloatFragments(t)}getLimitValue(t,e,n,s,o){this.container;let i=this.toLogical(t),a=this.toPhysical(t),l=e&&this.toLogical(e),c=e&&this.toPhysical(e),u=this.getLimitValueInner(i,l,n,s,o);if(this.parent&&this.parent.container){let d=this.parent.getLimitValue(a,c,n,s,o);switch(a){case"top":return Math.max(u,d);case"left":return Math.max(u,d);case"bottom":return Math.min(u,d);case"right":return Math.min(u,d);default:}}return u}getLimitValueInner(t,e,n,s,o){this.container;let i=this.getLimitValuesInner(n,s,o,t,e);switch(t){case"block-start":return this.container.vertical?i.right:i.top;case"block-end":return this.container.vertical?i.left:i.bottom;case"inline-start":return this.container.vertical?this.container.rtl?i.bottom:i.top:this.container.rtl?i.right:i.left;case"inline-end":return this.container.vertical?this.container.rtl?i.top:i.bottom:this.container.rtl?i.left:i.right;default:throw new Error(`Unknown logical side: ${t}`)}}getLimitValuesInner(t,e,n,s,o){this.container;let i=this.container.originX,a=this.container.originY,l=this.container.getPaddingRect(),c={top:l.y1-a,left:l.x1-i,bottom:l.y2-a,right:l.x2-i,floatMinWrapBlockStart:0,floatMinWrapBlockEnd:0};function u(h,f,g){return h.unit==="%"?g*h.num/100:t.convertLengthToPx(h,f,e)}let d=this.floatFragments;return d.length>0&&(c=d.reduce((h,f)=>{if(n&&!n(f,this))return h;let[g,m]=this.toLogicalFloatSides(f.floatSide);if(m&&(s&&m.includes("block")===s.includes("block")&&m!==s||o&&m.includes("block")===o.includes("block")&&m!==o))return h;let y=f.area,E=f.continuations[0].float.floatMinWrapBlock,C=h.top,x=h.left,N=h.bottom,S=h.right,w=h.floatMinWrapBlockStart,k=h.floatMinWrapBlockEnd;switch(g){case"inline-start":y.vertical?C=Math.max(C,y.top+y.height):x=Math.max(x,y.left+y.width);break;case"block-start":y.vertical?(E&&y.left<S&&(w=u(E,y.rootViewNodes[0],l.x2-l.x1)),S=Math.min(S,y.left)):(E&&y.top+y.height>C&&(w=u(E,y.rootViewNodes[0],l.y2-l.y1)),C=Math.max(C,y.top+y.height));break;case"inline-end":y.vertical?N=Math.min(N,y.top):S=Math.min(S,y.left);break;case"block-end":y.vertical?(E&&y.left+y.width>x&&(k=u(E,y.rootViewNodes[0],l.x2-l.x1)),x=Math.max(x,y.left+y.width)):(E&&y.top<N&&(k=u(E,y.rootViewNodes[0],l.y2-l.y1)),N=Math.min(N,y.top));break;default:throw new Error(`Unknown logical float side: ${g}`)}return{top:C,left:x,bottom:N,right:S,floatMinWrapBlockStart:w,floatMinWrapBlockEnd:k}},c)),c.left+=i,c.right+=i,c.top+=a,c.bottom+=a,c}setFloatAreaDimensions(t,e,n,s,o,i,a){if(e!==this.floatReference)return this.getParent(e).setFloatAreaDimensions(t,e,n,s,o,i,a);let l=this.toLogicalFloatSides(n);if(l[0]==="snap-block"){if(!a["block-start"]&&!a["block-end"])return null}else if(l[0].includes("block")&&!a[l[0]])return null;t.clientLayout;let c=l.find(w=>w.includes("inline")&&a[w==="inline-start"?"inline-end":"inline-start"]),u=l.find(w=>w.includes("block")),d=this.getLimitValue("block-start",c,t.layoutContext,t.clientLayout),h=this.getLimitValue("block-end",c,t.layoutContext,t.clientLayout),f=this.getLimitValue("inline-start",u,t.layoutContext,t.clientLayout),g=this.getLimitValue("inline-end",u,t.layoutContext,t.clientLayout),m=t.vertical?t.originX:t.originY,y=t.vertical?t.originY:t.originX;d=t.vertical?Math.min(d,t.left+t.getInsetLeft()+t.width+t.getInsetRight()+m):Math.max(d,t.top+m),h=t.vertical?Math.max(h,t.left+m):Math.min(h,t.top+t.getInsetTop()+t.height+t.getInsetBottom()+m);function E(w,k){let R=w(t.bands,k);return R?(t.vertical&&(R=kr(R)),d=t.vertical?Math.min(d,R.x2):Math.max(d,R.y1),h=t.vertical?Math.max(h,R.x1):Math.min(h,R.y2),!0):i}let C,x,N,S;if(o){let w=t.vertical?so(new He(h,f,d,g)):new He(f,d,g,h);if((l[0]==="block-start"||l[0]==="snap-block"||l[0]==="inline-start"||l[0]==="snap-inline")&&!E(sh,w)||(l[0]==="block-end"||l[0]==="snap-block"||l[0]==="inline-end"||l[0]==="snap-inline")&&!E(oh,w)||(N=(h-d)*t.getBoxDir(),C=N-t.getInsetBefore()-t.getInsetAfter(),S=(g-f)*t.getInlineDir(),x=S-t.getInsetStart()-t.getInsetEnd(),!i&&(C<=0||x<=0)))return null}else{C=t.computedBlockSize,N=C+t.getInsetBefore()+t.getInsetAfter();let w=(h-d)*t.getBoxDir();if(l[0]==="snap-block"){if(s===null)l[0]="block-start";else{let R=this.container.getPaddingRect(),G=this.container.getBoxDir()*(s-(this.container.vertical?R.x2:R.y1)),de=this.container.getBoxDir()*((this.container.vertical?R.x1:R.y2)-s-N);G<=de?l[0]="block-start":l[0]="block-end"}if(!a[l[0]])if(a["block-end"])l[0]="block-end";else return null}else if(l[0]==="snap-inline")if(s===null)l[0]="inline-start";else if(a["inline-start"])l[0]="inline-start";else if(a["inline-end"])l[0]="inline-end";else return null;if(!i&&w<N)return null;l[0]==="inline-start"||l[0]==="inline-end"||l[1]?x=uo(t.clientLayout,t.element,["fit-content inline size"])["fit-content inline size"]:t.adjustContentRelativeSize?x=t.getContentInlineSize():x=t.vertical?t.height:t.width,S=x+t.getInsetStart()+t.getInsetEnd();let k=(g-f)*t.getInlineDir();if(!i&&k<S)return null}return d-=m,h-=m,f-=y,g-=y,l.some(w=>w==="inline-start"||w==="snap-inline")||l.length===1&&(l[0]==="block-start"||l[0]==="snap-block")?t.setInlinePosition(f,x):(l.some(w=>w==="inline-end")||l.length===1&&l[0]==="block-end")&&t.setInlinePosition(g-S*t.getInlineDir(),x),l.some(w=>w==="block-start"||w==="snap-block")||l.length===1&&(l[0]==="inline-start"||l[0]==="snap-inline")?t.setBlockPosition(d,C):(l.some(w=>w==="block-end")||l.length===1&&l[0]==="inline-end")&&t.setBlockPosition(h-N*t.getBoxDir(),C),l.join(" ")}getFloatFragmentExclusions(){let t=this.floatFragments.map(e=>e.getOuterShape());return this.parent?this.parent.getFloatFragmentExclusions().concat(t):t}reattachFloatFragments(){let t=this.container.element&&this.container.element.parentNode;t&&this.floatFragments.forEach(e=>{t.appendChild(e.area.element)})}getMaxReachedAfterEdge(){let t=this.getContainer().vertical;return this.floatFragments.reduce((e,n)=>{let s=n.getOuterRect();return t?Math.min(e,s.x1):Math.max(e,s.y2)},t?1/0:0)}getBlockStartEdgeOfBlockEndFloats(){let t=this.getContainer().vertical;return this.floatFragments.filter(e=>e.floatSide==="block-end").reduce((e,n)=>{let s=n.getOuterRect();return t?Math.max(e,s.x2):Math.min(e,s.y1)},t?0:1/0)}getPageFloatClearEdge(t,e){function n(d){return h=>d.isAnchorAlreadyAppeared(h.float.getId())}function s(d,h){return t==="inline-start"&&(d.floatSide.includes("inline-end")||d.floatSide==="block-end")||t==="inline-end"&&(d.floatSide.includes("inline-start")||d.floatSide==="block-start")?!1:d.continuations.some(n(h))}let o=e.getPaddingRect(),i=e.vertical?o.x1:o.y2,a=this;for(;a;){if(a.floatsDeferredToNext.some(n(a)))return i;a=a.parent}function l(d){return d.floatFragments.some(h=>s(h,d))||d.children.some(h=>l(h))}if(t==="column"||t==="region"||t==="page"){for(a=this;a;a=a.parent)if(a.floatReference===t){if(l(a))return i;break}}e.clientLayout;let c=this.getLimitValue("block-start",null,e.layoutContext,e.clientLayout,s);return this.getLimitValue("block-end",null,e.layoutContext,e.clientLayout,s)*e.getBoxDir()<i*e.getBoxDir()?i:c}getPageFloatPlacementCondition(t,e,n){if(t.floatReference!==this.floatReference)return this.getParent(t.floatReference).getPageFloatPlacementCondition(t,e,n);let s={"block-start":!0,"block-end":!0,"inline-start":!0,"inline-end":!0};if(!n)return s;let o=this.toLogicalFloatSides(e)[0],i=this.toLogical(n),a;i==="all"?a=["block-start","block-end","inline-start","inline-end"]:i==="both"?a=["inline-start","inline-end"]:i==="same"?o==="snap-block"?a=["block-start","block-end"]:a=[o]:a=[i];let l=t.getOrder();function c(h){return f=>(!h||f.floatSide.includes(h))&&f.getOrder()<l}function u(h,f){return h.children.some(g=>g.floatFragments.some(c(f))||u(g,f))}function d(h,f){let g=h.parent;return!!g&&(g.floatFragments.some(c(f))||d(g,f))}if(n==="column"||n==="region"||n==="page"){for(let h=this;h;h=h.parent)if(h.floatReference===n){(h.floatFragments.some(c(null))||u(h,null))&&(s["block-start"]=!1,s["block-end"]=!1,s["inline-start"]=!1,s["inline-end"]=!1);break}return s}return a.forEach(h=>{switch(h){case"block-start":s[h]=!u(this,h);break;case"block-end":s[h]=!d(this,h);break;case"inline-start":case"inline-end":s[h]=!this.floatFragments.some(c(h));break;default:throw new Error(`Unexpected side: ${h}`)}}),s}getLayoutConstraints(){return(this.parent?this.parent.getLayoutConstraints():[]).concat(this.layoutConstraints)}addLayoutConstraint(t,e){e===this.floatReference?this.layoutConstraints.push(t):this.getParent(e).addLayoutConstraint(t,e)}isColumnFullWithPageFloats(t){let e=t.layoutContext,n=t.clientLayout;let s=this,o=null;for(;s&&s.container;){let l=s.getLimitValuesInner(e,n);o?t.vertical?(l.right<o.right&&(o.right=l.right,o.floatMinWrapBlockStart=l.floatMinWrapBlockStart),l.left>o.left&&(o.left=l.left,o.floatMinWrapBlockEnd=l.floatMinWrapBlockEnd)):(l.top>o.top&&(o.top=l.top,o.floatMinWrapBlockStart=l.floatMinWrapBlockStart),l.bottom<o.bottom&&(o.bottom=l.bottom,o.floatMinWrapBlockEnd=l.floatMinWrapBlockEnd)):o=l,s=s.parent}let i=Math.max(o.floatMinWrapBlockStart,o.floatMinWrapBlockEnd);return(t.vertical?o.right-o.left:o.bottom-o.top)<=i}getMaxBlockSizeOfPageFloats(){let t=this.getContainer().vertical;return this.floatFragments.length?Math.max.apply(null,this.floatFragments.map(e=>{let n=e.area;return t?n.width:n.height})):0}lock(){this.locked=!0}unlock(){this.locked=!1}isLocked(){return this.locked}},oi=[],Ut=class{static register(t){oi.push(t)}findByNodeContext(t){for(let e=oi.length-1;e>=0;e--){let n=oi[e];if(n.appliesToNodeContext(t))return n}throw new Error(`No PageFloatLayoutStrategy found for ${t}`)}findByFloat(t){for(let e=oi.length-1;e>=0;e--){let n=oi[e];if(n.appliesToFloat(t))return n}throw new Error(`No PageFloatLayoutStrategy found for ${t}`)}},_c=class{appliesToNodeContext(t){return Hn(t.floatReference)}appliesToFloat(t){return!0}createPageFloat(t,e,n){let s=t.floatReference;t.floatSide;let o=t.floatSide,i=t.toNodePosition();return n.resolveFloatReferenceFromColumnSpan(s,t.columnSpan,t).thenAsync(a=>{s=a,e.flowName;let l=new ii(i,s,o,t.clearSide,e.flowName,t.floatMinWrapBlock);return e.addPageFloat(l),v(l)})}createPageFloatFragment(t,e,n,s,o){let i=t[0].float;return new ri(i.floatReference,e,n,t,s,o)}findPageFloatFragment(t,e){return e.findPageFloatFragment(t)}adjustPageFloatArea(t,e,n){}forbid(t,e){}};Ut.register(new _c);var uC=ri,li=class r extends ii{constructor(e,n,s,o,i){super(e,n,"block-end",null,s,i);this.footnotePolicy=o}isAllowedToPrecede(e){return!(e instanceof r)}},ea=class extends uC{constructor(t,e,n,s){super(t,"block-end",null,e,n,s)}getOrder(){return 1/0}shouldBeStashedBefore(t){return t instanceof li?!0:this.getOrder()<t.getOrder()}},Hc=class{constructor(t){this.footnote=t}allowLayout(t){let e=t.toNodePosition();return!Mt(e,this.footnote.nodePosition)}},zc=class{appliesToNodeContext(t){return t.floatSide==="footnote"}appliesToFloat(t){return t instanceof li}createPageFloat(t,e,n){let s=ae.REGION,o=e.getPageFloatLayoutContext(s);e.getPageFloatLayoutContext(ae.PAGE).hasSameContainerAs(o)&&(s=ae.PAGE);let a=t.toNodePosition();e.flowName;let l=new li(a,s,e.flowName,t.footnotePolicy,t.floatMinWrapBlock);return e.addPageFloat(l),v(l)}createPageFloatFragment(t,e,n,s,o){let i=t[0].float;return new ea(i.floatReference,t,s,o)}findPageFloatFragment(t,e){let s=e.getPageFloatLayoutContext(t.floatReference).floatFragments.filter(o=>o instanceof ea);return s.length<=1,s[0]||null}adjustPageFloatArea(t,e,n){t.isFootnote=!0,t.adjustContentRelativeSize=!1;let s=t.element;t.vertical=n.layoutContext.applyFootnoteStyle(e.vertical,n.layoutContext.nodeContext&&n.layoutContext.nodeContext.direction==="rtl",s),t.convertPercentageSizesToPx(s),n.setComputedInsets(s,t),n.setComputedWidthAndHeight(s,t)}forbid(t,e){let n=t;switch(n.footnotePolicy){case b.line:{let s=new Hc(n);e.addLayoutConstraint(s,n.floatReference);break}}}};Ut.register(new zc);var dC="data-vivliostyle-flow-root";function qh(r){return r.getAttribute(dC)==="true"}function Yh(r){let t=(r==null?void 0:r.toString())||"block",e;switch(t){case"inline-flex":e="flex";break;case"inline-grid":e="grid";break;case"inline-table":e="table";break;case"inline":case"table-row-group":case"table-column":case"table-column-group":case"table-header-group":case"table-footer-group":case"table-row":case"table-cell":case"table-caption":case"inline-block":e="block";break;default:e=t}return L(e)}function ta(r){return r===b.absolute||r===b.fixed}function ci(r){return r instanceof kt&&r.name==="running"}function Gc(r,t,e,n){return r===b.none||(ta(t)?(e=b.none,r=Yh(r)):(e&&e!==b.none&&!U(e)||n)&&(r=Yh(r))),{display:r,position:t,float:e}}function na(r,t,e,n){return Gc(r,t,e,n).display===b.block}function gn(r){switch(r.toString()){case"inline":case"inline-block":case"inline-list-item":case"inline-flex":case"inline-grid":case"ruby":case"inline-table":return!0;default:return!1}}function sa(r){switch(r.toString()){case"ruby-base":case"ruby-text":case"ruby-base-container":case"ruby-text-container":return!0;default:return!1}}function Kh(r,t,e,n,s,o,i){return s=s||o||b.horizontal_tb,!!i||!!e&&e!==b.none&&!U(e)||ta(t)||r===b.inline_block||r===b.table_cell||r===b.table_caption||r==b.flex||r==b.grid||r==b.flow_root||(r===b.block||r===b.list_item)&&!!n&&n!==b.visible&&n!==b.clip&&!U(n)||!!o&&s!==o}function Zh(r){return r===b.relative||r===b.absolute||r===b.fixed}var Ss=1e5;function Qh(r){T(r.element,"column-count","1"),T(r.element,"column-width",`${r.vertical?r.height:r.width}px`),T(r.element,"column-gap",`${Ss-(r.vertical?r.height:r.width)}px`),T(r.element,"column-fill","auto")}function Co(r,t){let e=t?r.bottom:Math.max(Math.abs(r.left),Math.abs(r.right));return Math.round(e/Ss)}function Wc(r,t){let e=Co(r,t);if(e===0)return 0;let n=t?r.top:Math.min(Math.abs(r.left),Math.abs(r.right)),s=Math.round(n/Ss),o=e*Ss,i=s*Ss;return t?(r.top-=i,r.bottom-=o,r.right-=i,r.left-=o):r.left<-Ss/2?(r.right+=i,r.left+=o,r.top+=i,r.bottom+=o):(r.left-=i,r.right-=o,r.top+=i,r.bottom+=o),r.width=r.right-r.left,r.height=r.bottom-r.top,s}function $c(r,t){for(let e=0;e<r.length;e++)Wc(r[e],t)}function bo(r,t,e){var o;let n=r.getElementClientRect(t),s=Wc(n,e);if(s===1){let i=r.getElementComputedStyle(t);if(i.display==="table-cell"||t.className==="-vivliostyle-table-cell-container"&&((o=t.parentElement)!=null&&o.parentElement)&&(i=r.getElementComputedStyle(t.parentElement.parentElement)).display==="table-cell"){let a=t.closest("[data-vivliostyle-column]"),l=e?"width":"height",c=a&&parseFloat(gt(a,l));if(c){let u=c,d=s,h=parseFloat(i.paddingBlockEnd),f=parseFloat(i.borderBlockEndWidth),g=Math.ceil(h+f);for(;g-- >0&&d===s&&--u>0;){T(a,l,`${u}px`);let m=r.getElementClientRect(t);if(d=Wc(m,e),d<s||d===s&&(e?m.right>n.right:m.top<n.top))return a.setAttribute("data-vivliostyle-column-height-adjusted","true"),m}T(a,l,`${c}px`)}}}return n}function Jh(r,t){var e,n;if(r.nodeType===1){let s=r;((e=s.style)==null?void 0:e.breakAfter)==="column"&&(s.style.breakAfter="")}if(t.nodeType===1){let s=t;((n=s.style)==null?void 0:n.breakBefore)==="column"&&(s.style.breakBefore="")}}function Xc(r){for(let t=r.nodeType===1?r:r.parentElement;t;t=t.parentElement){let e=t.style;if(!e||t.hasAttribute("data-vivliostyle-column"))break;if(!isNaN(parseFloat(e.columnCount))||!isNaN(parseFloat(e.columnWidth)))return t;if(e.position==="absolute")break}return null}function ef(r){var C;if(r.nodeType!==1)return;let t=r,e=t.style,n=(e==null?void 0:e.breakBefore)==="column",s=t.previousElementSibling,o=s&&((C=s.style)==null?void 0:C.breakAfter)==="column";if(!n&&!o)return;let i=Xc(t);if(!i)return;let a=i.ownerDocument.defaultView.getComputedStyle(i),{writingMode:l,direction:c,columnGap:u,fontSize:d}=a,h=l==="vertical-rl"||l==="vertical-lr",f=c==="rtl",g=(parseFloat(u)||parseFloat(d)||16)/2,m=i.getBoundingClientRect(),y=t.getBoundingClientRect();(h?y.top>m.bottom+g:f?y.right<m.left-g:y.left>m.right+g)&&(n&&(e.breakBefore=""),o&&s&&(s.style.breakAfter=""),e.marginBlockStart=`${Ss}px`)}function zn(r,t,e,n){let s=r.viewNode;if(!s)return NaN;let o=s.nodeType===1?s:s.parentElement;if(o&&o.namespaceURI==="http://www.w3.org/1999/xhtml"){let i=o.style;if(o.localName==="br"||o.localName==="wbr"||i&&gn(i.display)&&/^([\d\.]|super|(text-)?top)/.test(i.verticalAlign))return NaN}if(s===o){if(r.after||!r.inline){if(r.after&&!r.inline&&o.querySelector("ruby")){let a=o.parentNode,l=o.nextSibling;a.removeChild(o),a.insertBefore(o,l)}let i=bo(t,o,n);if(i.left===0&&i.top===0&&i.right===0&&i.bottom===0)return NaN;if(i.right>=i.left&&i.bottom>=i.top)return r.after?n?i.left:i.bottom:n?i.right:i.top}return NaN}else{let i=NaN,a=s.ownerDocument.createRange(),l=s.textContent.length;if(!l)return NaN;r.after&&(e+=l),e>=l&&(e=l-1),a.setStart(s,e),a.setEnd(s,e+1);let c=t.getRangeClientRects(a);return $c(c,n),c=c.filter(u=>u.right>u.left&&u.bottom>u.top),c.length?(n?i=Math.min.apply(null,c.map(u=>u.left)):i=Math.max.apply(null,c.map(u=>u.bottom)),i):NaN}}function ui(r,t,e){let n=t.clientLayout.getElementClientRect(r),s=t.getComputedMargin(r);return e?n.width+s.left+s.right:n.height+s.top+s.bottom}function mn(r){for(;r;){if(r.parentNode===r.ownerDocument)return!1;r=r.parentNode}return!0}function ia(r,t){var e;if(r)for(let n=r.lastChild,s=n;n!==t;n=s)s=n.previousSibling,!(n.nodeType===1&&n.hasAttribute("data-vivliostyle-float-box-moved")&&((e=t.style)==null?void 0:e.display)==="inline")&&r.removeChild(n)}function ra(r){return!!r.getAttribute(_t)}function Ns(r){var n;if((r==null?void 0:r.nodeType)!==1)return!1;let t=r;if(ra(t))return!0;let e=(n=t.style)==null?void 0:n.position;return e==="absolute"||e==="fixed"}function Cn(r){let t=r==null?void 0:r.viewNode;return(t==null?void 0:t.nodeType)===1&&ra(t)}function tf(r){return r!=="inline"&&(gn(r)||sa(r))}function jc(r){var t;for(let e=r.parent;e;e=e.parent)if((e.display!=="inline"||e.vertical!==((t=e.parent)==null?void 0:t.vertical))&&gn(e.display))return e;return null}var Ts=class{calculateOffset(t){return Gn(this.getNodeContext(),t.collectElementsOffset())}breakPositionChosen(t){}getNodeContext(){return null}};function Gn(r,t){return{current:t.reduce((e,n)=>e+n.calculateOffset(r),0),minimum:t.reduce((e,n)=>e+n.calculateMinimumOffset(r),0)}}var nn=class extends Ts{constructor(e,n,s,o){super();this.position=e;this.breakOnEdge=n;this.overflows=s;this.computedBlockSize=o;p(this,"overflowIfRepetitiveElementsDropped");p(this,"isEdgeUpdated",!1);p(this,"edge",0);this.overflowIfRepetitiveElementsDropped=s}findAcceptableBreak(e,n){return this.updateOverflows(e),n<this.getMinBreakPenalty()?null:e.findEdgeBreakPosition(this)}getMinBreakPenalty(){if(!this.isEdgeUpdated)throw new Error("EdgeBreakPosition.prototype.updateEdge not called");let e=this.isFirstContentOfRepetitiveElementsOwner()&&!this.overflowIfRepetitiveElementsDropped;return(po(this.breakOnEdge)?1:0)+(this.overflows&&!e?3:0)+(this.position.parent?this.position.parent.breakPenalty:0)}updateEdge(e){var s;let n=e.calculateClonedPaddingBorder(this.position);if(this.edge=zn(this.position,e.clientLayout,0,e.vertical)+n,!this.position.after&&!this.position.inline){let o=e.parseComputedLength(e.clientLayout.getElementComputedStyle(this.position.viewNode).marginBlockStart);this.edge-=(e.vertical?-1:1)*o}else if(this.position.after&&((s=this.position.shadowContext)==null?void 0:s.root.id)==="table-cell"){let o=e.element.parentElement,i=o==null?void 0:o.closest("table, [style*='display: table;']");if(i){let a=i.style.borderCollapse==="collapse",l=0,c=0;for(let u=o;u;u=u.parentElement){let d=e.clientLayout.getElementComputedStyle(u);if((u===o||u===i&&!a)&&(l+=e.parseComputedLength(d.paddingBlockEnd)),u===i&&!a&&(l+=e.parseComputedLength(d.borderSpacing.replace(/^\S+ (\S+)$/,"$1"))),a?c=Math.max(c,e.parseComputedLength(d.borderBlockEndWidth)):(u===o||u===i)&&(c+=e.parseComputedLength(d.borderBlockEndWidth)),u===i)break}this.edge+=(e.vertical?-1:1)*(l+c)}}this.isEdgeUpdated=!0}updateOverflows(e){this.isEdgeUpdated||this.updateEdge(e);let n=this.edge,s=this.calculateOffset(e);this.overflowIfRepetitiveElementsDropped=e.isOverflown(n+(e.vertical?-1:1)*s.minimum),this.overflows=this.position.overflow=e.isOverflown(n+(e.vertical?-1:1)*s.current)}getNodeContext(){return this.position}isFirstContentOfRepetitiveElementsOwner(){let e=this.getNodeContext();if(!e||!e.parent)return!1;let{formattingContext:n}=e.parent;if(!tn.isInstanceOfRepetitiveElementsOwnerFormattingContext(n))return!1;let s=n.getRepetitiveElements();return s?s.isFirstContentNode(e):!1}};var Wn=class{find(t){let e=Ge("RESOLVE_LAYOUT_PROCESSOR");for(let n=0;n<e.length;n++){let s=e[n](t);if(s)return s}throw new Error(`No processor found for a formatting context: ${t.getName()}`)}},sn=class{layout(t,e,n){return e.isFloatNodeContext(t)?e.layoutFloatOrFootnote(t):e.isBreakable(t)?e.layoutBreakableBlock(t):e.layoutUnbreakable(t)}createEdgeBreakPosition(t,e,n,s){return new nn(t.copy(),e,n,s)}startNonInlineElementNode(t){return!1}afterNonInlineElementNode(t,e){return!1}clearOverflownViewNodes(t,e,n,s){var a;if(!n.viewNode||!n.viewNode.parentNode||n.shadowType===Lt.ShadowType.ROOTLESS&&Cn(n))return;let o=n.viewNode;((a=o.parentElement)==null?void 0:a.localName)==="viv-ts-inner"&&(o=o.parentElement.parentElement);let i=o.parentNode;ia(i,o),s&&i.removeChild(o)}finishBreak(t,e,n,s){let o=n||e.viewNode!=null&&e.viewNode.nodeType==1&&!e.after;return t.clearOverflownViewNodes(e,o),s&&t.layoutContext.processFragmentedBlockEdge(e),v(!0)}},xo=class{constructor(t){this.parent=t;p(this,"formattingContextType","Block")}getName(){return"Block formatting context (BlockFormattingContext)"}isFirstTime(t,e){return e}getParent(){return this.parent}saveState(){}restoreState(t){}},di=new sn,nf=$r.isInstanceOfBlockFormattingContext;Ue("RESOLVE_FORMATTING_CONTEXT",(r,t,e,n,s,o)=>{let i=r.parent;return!i&&r.formattingContext||i&&r.formattingContext!==i.formattingContext?null:r.establishesBFC||!r.formattingContext&&na(e,n,s,o)?new xo(i?i.formattingContext:null):null});Ue("RESOLVE_LAYOUT_PROCESSOR",r=>r instanceof xo?di:null);var $n=class{constructor(){p(this,"initialBreakPositions",null);p(this,"initialStateOfFormattingContext",null);p(this,"initialPosition");p(this,"initialFragmentLayoutConstraints")}layout(t,e){return this.prepareLayout(t,e),this.tryLayout(t,e)}tryLayout(t,e){let n=A("AbstractLayoutRetryer.tryLayout");this.saveState(t,e);let s=this.resolveLayoutMode(t);return s.doLayout(t,e).then(o=>{let i=s.accept(o,e);i=s.postLayout(o,this.initialPosition,e,i),i?n.finish(o):(this.initialPosition,this.clearNodes(this.initialPosition),this.restoreState(t,e),this.tryLayout(this.initialPosition,e).thenFinish(n))}),n.result()}prepareLayout(t,e){}clearNodes(t){let e=t.viewNode||t.parent.viewNode,n;for(;n=e.lastChild;)e.removeChild(n);let s;for(;s=e.nextSibling;)s.parentNode.removeChild(s)}saveState(t,e){this.initialPosition=t.copy(),this.initialBreakPositions=[].concat(e.breakPositions),this.initialFragmentLayoutConstraints=[].concat(e.fragmentLayoutConstraints),t.formattingContext&&(this.initialStateOfFormattingContext=t.formattingContext.saveState())}restoreState(t,e){e.breakPositions=this.initialBreakPositions,e.fragmentLayoutConstraints=this.initialFragmentLayoutConstraints,t.formattingContext&&t.formattingContext.restoreState(this.initialStateOfFormattingContext)}};var Kc=class{initialState(t){return{nodeContext:t,atUnforcedBreak:!1,break:!1}}startNonDisplayableNode(t){}afterNonDisplayableNode(t){}startIgnoredTextNode(t){}afterIgnoredTextNode(t){}startNonElementNode(t){}afterNonElementNode(t){}startInlineElementNode(t){}afterInlineElementNode(t){}startNonInlineElementNode(t){}afterNonInlineElementNode(t){}finish(t){}},ws=class{constructor(t,e){this.strategy=t;this.layoutContext=e}iterate(t){let e=this.strategy,n=e.initialState(t),s=A("LayoutIterator");return s.loopWithFrame(o=>{let i;for(;n.nodeContext;){n.nodeContext.viewNode?n.nodeContext.viewNode.nodeType!==1?ue(n.nodeContext.viewNode,n.nodeContext.whitespace)?n.nodeContext.after?i=e.afterIgnoredTextNode(n):i=e.startIgnoredTextNode(n):n.nodeContext.after?i=e.afterNonElementNode(n):i=e.startNonElementNode(n):n.nodeContext.inline?n.nodeContext.after?i=e.afterInlineElementNode(n):i=e.startInlineElementNode(n):n.nodeContext.after?i=e.afterNonInlineElementNode(n):i=e.startNonInlineElementNode(n):n.nodeContext.after?i=e.afterNonDisplayableNode(n):i=e.startNonDisplayableNode(n);let l=(i&&i.isPending()?i:v(!0)).thenAsync(()=>n.break?v(null):this.layoutContext.nextInTree(n.nodeContext,n.atUnforcedBreak));if(l.isPending()){l.then(c=>{n.break?o.breakLoop():(n.nodeContext=c,o.continueLoop())});return}else if(n.break){o.breakLoop();return}else n.nodeContext=l.get()}e.finish(n),o.breakLoop()}).then(()=>{s.finish(n.nodeContext)}),s.result()}},bn=class extends Kc{constructor(e){super();this.leadingEdge=e}startNonInlineBox(e){}endEmptyNonInlineBox(e){}endNonInlineBox(e){}initialState(e){return{nodeContext:e,atUnforcedBreak:!!this.leadingEdge&&e.after,break:!1,leadingEdge:this.leadingEdge,breakAtTheEdge:null,onStartEdges:!1,leadingEdgeContexts:[],lastAfterNodeContext:null}}processForcedBreak(e,n){let s=!e.leadingEdge&&Ie(e.breakAtTheEdge);if(s){let o=e.nodeContext=e.leadingEdgeContexts[0]||e.nodeContext;o.viewNode.parentNode.removeChild(o.viewNode),n.pageBreakType=e.breakAtTheEdge}return s}saveEdgeAndProcessOverflow(e,n){let s=n.checkOverflowAndSaveEdgeAndBreakPosition(e.lastAfterNodeContext,null,!0,e.breakAtTheEdge);return s&&(e.nodeContext=(e.lastAfterNodeContext||e.nodeContext).modify(),e.nodeContext.overflow=!0),s}processLayoutConstraint(e,n,s){let o=e.nodeContext,i=!n.allowLayout(o);return i&&(s.checkOverflowAndSaveEdgeAndBreakPosition(e.lastAfterNodeContext,null,!1,e.breakAtTheEdge),o=e.nodeContext=o.modify(),o.overflow=!0),i}startNonElementNode(e){e.onStartEdges=!1}startNonInlineElementNode(e){return e.leadingEdgeContexts.push(e.nodeContext.copy()),e.breakAtTheEdge=Ve(e.breakAtTheEdge,e.nodeContext.breakBefore),e.onStartEdges=!0,this.startNonInlineBox(e)}afterNonInlineElementNode(e){let n,s;return e.onStartEdges?(n=this.endEmptyNonInlineBox(e),s=n&&n.isPending()?n:v(!0),s=s.thenAsync(()=>(e.break||(e.leadingEdgeContexts=[],e.leadingEdge=!1,e.atUnforcedBreak=!1,e.breakAtTheEdge=null),v(!0)))):(n=this.endNonInlineBox(e),s=n&&n.isPending()?n:v(!0)),s.thenAsync(()=>(e.break||(e.onStartEdges=!1,e.lastAfterNodeContext=e.nodeContext.copy(),e.breakAtTheEdge=Ve(e.breakAtTheEdge,e.nodeContext.breakAfter)),v(!0)))}};var la=[];function of(){la=[]}function Jc(r,t,e){return r-=e,t===0?r===0:r%t===0&&r/t>=0}var Zc=class{constructor(t){this.matchers=t}matches(){return this.matchers.some(t=>t.matches())}},Qc=class{constructor(t){this.matchers=t}matches(){return this.matchers.every(t=>t.matches())}},yo=class yo{constructor(t,e,n){this.elementOffset=t;this.a=e;this.b=n}static registerFragmentIndex(t,e,n){let s=yo.fragmentIndices;(!s[t]||s[t].priority<=n)&&(s[t]={fragmentIndex:e,priority:n})}static clearFragmentIndices(){yo.fragmentIndices={}}matches(){let t=yo.fragmentIndices[this.elementOffset];return t!=null&&t.fragmentIndex!=null&&Jc(t.fragmentIndex,this.a,this.b)}};p(yo,"fragmentIndices",{});var Xn=yo,Ps=class{static buildViewConditionMatcher(t,e){let n=e.split("_");return n[0]=="NFS"?new Xn(t,parseInt(n[1],10),parseInt(n[2],10)):(`${e}`,null)}static buildAllMatcher(t){return new Qc(t)}static buildAnyMatcher(t){return new Zc(t)}};var _u={"border-collapse":!0,"border-spacing":!0,"caption-side":!0,"clip-rule":!0,color:!0,"color-interpolation":!0,"color-rendering":!0,cursor:!0,direction:!0,"empty-cells":!0,fill:!0,"fill-opacity":!0,"fill-rule":!0,"font-kerning":!0,"font-size":!0,"font-size-adjust":!0,"font-family":!0,"font-feature-settings":!0,"font-style":!0,"font-stretch":!0,"font-variant-ligatures":!0,"font-variant-caps":!0,"font-variant-numeric":!0,"font-variant-east-asian":!0,"font-weight":!0,"glyph-orientation-vertical":!0,"hanging-punctuation":!0,hyphens:!0,"hyphenate-character":!0,"hyphenate-limit-chars":!0,"hyphenate-limit-last":!0,"image-rendering":!0,"image-resolution":!0,"letter-spacing":!0,"line-break":!0,"line-height":!0,"list-style-image":!0,"list-style-position":!0,"list-style-type":!0,marker:!0,"marker-end":!0,"marker-mid":!0,"marker-start":!0,orphans:!0,"overflow-wrap":!0,"paint-order":!0,"pointer-events":!0,quotes:!0,"ruby-align":!0,"ruby-position":!0,"shape-rendering":!0,stroke:!0,"stroke-dasharray":!0,"stroke-dashoffset":!0,"stroke-linecap":!0,"stroke-linejoin":!0,"stroke-miterlimit":!0,"stroke-opacity":!0,"stroke-width":!0,"tab-size":!0,"text-align":!0,"text-align-last":!0,"text-anchor":!0,"text-autospace":!0,"text-decoration-skip":!0,"text-decoration-skip-ink":!0,"text-emphasis-color":!0,"text-emphasis-position":!0,"text-emphasis-style":!0,"text-fill-color":!0,"text-combine-upright":!0,"text-indent":!0,"text-justify":!0,"text-orientation":!0,"text-rendering":!0,"text-shadow":!0,"text-size-adjust":!0,"text-spacing-trim":!0,"text-stroke-color":!0,"text-stroke-width":!0,"text-transform":!0,"text-underline-offset":!0,"text-underline-position":!0,"text-wrap":!0,"text-wrap-mode":!0,"text-wrap-style":!0,visibility:!0,"white-space":!0,widows:!0,"word-break":!0,"word-spacing":!0,"writing-mode":!0},pC=["image-resolution","orphans","widows"];function df(){return Ge("POLYFILLED_INHERITED_PROPS").reduce((t,e)=>t.concat(e()),[].concat(pC))}var hC={"http://www.idpf.org/2007/ops":!0,"http://www.w3.org/1999/xhtml":!0,"http://www.w3.org/2000/svg":!0,"http://www.w3.org/1998/Math/MathML":!0},nu=["margin-%","padding-%","border-%-width","border-%-style","border-%-color","%"],fC=["max-%","min-%","%"],af=(()=>{let r=["left","right","top","bottom"],t={width:!0,height:!0,"max-width":!0,"max-height":!0,"min-width":!0,"min-height":!0};for(let e=0;e<nu.length;e++)for(let n=0;n<r.length;n++){let s=nu[e].replace("%",r[n]);t[s]=!0}return t})();function To(r,t){let e={};for(let n of nu)for(let s in r){let o=n.replace("%",s),i=n.replace("%",r[s]);e[o]=i,e[i]=o}for(let n of fC)for(let s in t){let o=n.replace("%",s),i=n.replace("%",t[s]);e[o]=i,e[i]=o}return e}var Uu=To({"block-start":"right","block-end":"left","inline-start":"top","inline-end":"bottom"},{"block-size":"width","inline-size":"height"}),Hu=To({"block-start":"top","block-end":"bottom","inline-start":"left","inline-end":"right"},{"block-size":"height","inline-size":"width"}),gC=To({"block-start":"right","block-end":"left","inline-start":"bottom","inline-end":"top"},{"block-size":"width","inline-size":"height"}),mC=To({"block-start":"top","block-end":"bottom","inline-start":"right","inline-end":"left"},{"block-size":"height","inline-size":"width"}),CC=To({inside:"right",outside:"left"},{}),bC=To({inside:"left",outside:"right"},{}),H=class r{constructor(t,e){this.value=t;this.priority=e}getBaseValue(){return this}filterValue(t){let e=this.value.visit(t);return e===this.value?this:new r(e,this.priority)}increaseSpecificity(t){return t==0?this:new r(this.value,this.priority+t)}evaluate(t,e,n,s){return e&&xt(e)?this.value:xi(t,this.value,e,n,s)}isEnabled(t){return!0}},hi=class r extends H{constructor(e,n,s){super(e,n);this.condition=s}getBaseValue(){return new H(this.value,this.priority)}filterValue(e){let n=this.value.visit(e);return n===this.value?this:new r(n,this.priority,this.condition)}increaseSpecificity(e){return e==0?this:new r(this.value,this.priority+e,this.condition)}isEnabled(e){try{return!!this.condition.evaluate(e)}catch(n){V.warn(n)}return!1}};function su(r,t,e){return(!t||e.priority>=t.priority)&&e.isEnabled(r)?e.getBaseValue():t}function on(r,t,e,n){if(r)if(!e)delete r[t];else{let s=r[t];(!s||e.priority>=s.priority)&&(n?e.isEnabled(n)&&(r[t]=e.getBaseValue()):r[t]=e)}}var pf={"region-id":!0,"fragment-selector-id":!0};function xC(r){return!!pf[r]}function ou(r){return r.charAt(0)==="_"&&r!=="_viewConditionalStyles"}function As(r){return r.charAt(0)!=="_"&&!pf[r]}function Yn(r){return!!_u[r]||xt(r)}function pe(r,t){return r[t]}function xn(r,t,e){e?r[t]=e:delete r[t]}function vt(r,t){return r[t]}function wo(r,t){let e=r[t];return e||(e={},r[t]=e),e}var hf=r=>{let t=r._viewConditionalStyles;return t||(t=[],r._viewConditionalStyles=t),t};function zu(r,t){return r[t]}function ff(r,t){let e=r[t];return e||(e=[],r[t]=e),e}function bi(r,t,e,n,s,o,i){var l,c;if([{id:s,styleKey:"_pseudos"},{id:o,styleKey:"_regions"}].forEach(u=>{if(u.id){let d=wo(t,u.styleKey);t=d[u.id],t||(t={},d[u.id]=t)}}),i){let u=hf(t);t={},u.push({styles:t,matcher:i})}for(let u in e)if(!ou(u))if(xC(u)){let d=zu(e,u),h=ff(t,u);Array.prototype.push.apply(h,d)}else{let d=pe(e,u);if(!d.isEnabled(r))continue;let h=d.increaseSpecificity(n);on(t,u,h,r);let f=(c=(l=r.style)==null?void 0:l.validatorSet.shorthands[u])==null?void 0:c.propList;if(f)for(let g of f){let m=new H(O,h.priority);on(t,g,m,r)}}}function gf(r,t){let e={};for(let n=0;n<t.length;n++)bi(r,e,t[n],0,null,null,null);return e}function mf(r,t){if(r.length>0){r.sort((n,s)=>s.getPriority()-n.getPriority());let e=null;for(let n=r.length-1;n>=0;n--)e=r[n],e.chained=t,t=e;return e}return t}var ua=class extends Kt{constructor(e,n){super();this.props=e;this.context=n;p(this,"propName","")}setPropName(e){this.propName=e}getFontSize(){let e=pe(this.props,"font-size");if(!e.value.isNumeric())return Y.em;let n=e.value;if(!jp(n.unit))throw new Error("Unexpected state");return n.num*Y[n.unit]}visitNumeric(e){return this.context,this.propName==="font-size"?Gu(e,this.getFontSize(),this.context):e.unit==="em"||e.unit==="ex"||e.unit==="rem"||e.unit==="lh"||e.unit==="rlh"?Ca(e,this.getFontSize(),this.context):e}visitExpr(e){return this.propName=="font-size"?xi(this.context,e,this.propName).visit(this):e}};function Ca(r,t,e){let n=r.unit,s=r.num;if(n==="em"||n==="ex"){let o=Y[n]/Y.em;return new P(s*o*t,"px")}else return n==="rem"?new P(s*e.fontSize(),"px"):n==="rlh"?new P(s*e.rootLineHeight,"px"):r}function Gu(r,t,e){r=Ca(r,t,e);let n=r.unit,s=r.num;return n==="px"?r:n==="%"?new P(s/100*t,"px"):new P(s*e.queryUnitSize(n,!1),"px")}var yn=class{apply(t){}mergeWith(t){return new iu([this,t])}clone(){return this}},So=class extends yn{constructor(e){super();this.conditionItem=e}apply(e){e.pushConditionItem(this.conditionItem.fresh(e))}},iu=class r extends yn{constructor(e){super();this.list=e}apply(e){for(let n=0;n<this.list.length;n++)this.list[n].apply(e)}mergeWith(e){return this.list.push(e),this}clone(){return new r([].concat(this.list))}},Ls=class extends yn{constructor(e,n,s,o,i){super();this.style=e;this.specificity=n;this.pseudoelement=s;this.regionId=o;this.viewConditionId=i}apply(e){bi(e.context,e.currentStyle,this.style,this.specificity,this.pseudoelement,this.regionId,e.buildViewConditionMatcher(this.viewConditionId))}},Q=class extends yn{constructor(){super();p(this,"chained",null)}apply(e){this.chained.apply(e)}getPriority(){return 0}makePrimary(e){return!1}},ru=class extends Q{constructor(e){super();this.className=e}apply(e){e.currentClassNames.includes(this.className)&&this.chained.apply(e)}getPriority(){return 10}makePrimary(e){return this.chained&&e.insertInTable(e.classes,this.className,this.chained),!0}},au=class extends Q{constructor(e){super();this.id=e}apply(e){(e.currentId==this.id||e.currentXmlId==this.id)&&this.chained.apply(e)}getPriority(){return 11}makePrimary(e){return this.chained&&e.insertInTable(e.ids,this.id,this.chained),!0}},da=class extends Q{constructor(e){super();this.localName=e}apply(e){e.currentLocalName==this.localName&&this.chained.apply(e)}getPriority(){return 8}makePrimary(e){return this.chained&&e.insertInTable(e.tags,this.localName,this.chained),!0}},lu=class extends Q{constructor(e,n){super();this.ns=e;this.localName=n}apply(e){e.currentLocalName==this.localName&&e.currentNamespace==this.ns&&this.chained.apply(e)}getPriority(){return 8}makePrimary(e){if(this.chained){let n=e.nsPrefix[this.ns];n||(n=`ns${e.nsCount++}:`,e.nsPrefix[this.ns]=n);let s=n+this.localName;e.insertInTable(e.nstags,s,this.chained)}return!0}},cu=class extends Q{constructor(e,n){super();this.epubTypePatt=e;this.targetLocalName=n}apply(e){let n=e.currentElement;if(n instanceof HTMLAnchorElement&&n.hash&&n.href==n.baseURI.replace(/#.*$/,"")+n.hash){let s=n.hash.substring(1),o=n.ownerDocument.getElementById(s);if(o&&(!this.targetLocalName||o.localName==this.targetLocalName)){let i=o.getAttributeNS("http://www.idpf.org/2007/ops","type")||o.getAttribute("epub:type");i&&i.match(this.epubTypePatt)&&this.chained.apply(e)}}}},uu=class extends Q{constructor(e){super();this.ns=e}apply(e){e.currentNamespace==this.ns&&this.chained.apply(e)}};function ba(r,t,e,n){if(!r)return!1;if(t!==null)return n(r,t,e);for(let s of r.getAttributeNames())if((s===e||s.endsWith(`:${e}`))&&n(r,s===e?"":r.lookupNamespaceURI(s.split(":")[0]),e))return!0;return!1}var pa=class extends Q{constructor(e,n){super();this.ns=e;this.name=n}apply(e){ba(e.currentElement,this.ns,this.name,(n,s,o)=>n.hasAttributeNS(s,o))&&this.chained.apply(e)}},du=class extends Q{constructor(e,n,s){super();this.ns=e;this.name=n;this.value=s}apply(e){ba(e.currentElement,this.ns,this.name,(n,s,o)=>n.getAttributeNS(s,o)==this.value)&&this.chained.apply(e)}getPriority(){return this.name=="type"&&this.ns=="http://www.idpf.org/2007/ops"?9:0}makePrimary(e){return this.name=="type"&&this.ns=="http://www.idpf.org/2007/ops"?(this.chained&&e.insertInTable(e.epubtypes,this.value,this.chained),!0):!1}},pu=class extends Q{constructor(e,n){super();this.ns=e;this.name=n}apply(e){ba(e.currentElement,this.ns,this.name,(n,s,o)=>!!hC[n.getAttributeNS(s,o)])&&this.chained.apply(e)}getPriority(){return 0}makePrimary(e){return!1}},ks=class extends Q{constructor(e,n,s){super();this.ns=e;this.name=n;this.regexp=s}apply(e){ba(e.currentElement,this.ns,this.name,(n,s,o)=>{var i;return!!((i=n.getAttributeNS(s,o))!=null&&i.match(this.regexp))})&&this.chained.apply(e)}},hu=class extends Q{constructor(e){super();this.langRegExp=e}apply(e){e.lang.match(this.langRegExp)&&this.chained.apply(e)}},ha=class extends Q{constructor(){super()}apply(t){t.isFirst&&this.chained.apply(t)}getPriority(){return 6}},fu=class extends Q{constructor(){super()}apply(t){t.isRoot&&this.chained.apply(t)}getPriority(){return 12}},jn=class extends Q{constructor(e,n){super();this.a=e;this.b=n}matchANPlusB(e){return Jc(e,this.a,this.b)}},gu=class extends jn{constructor(t,e){super(t,e)}apply(t){this.matchANPlusB(t.currentSiblingOrder)&&this.chained.apply(t)}getPriority(){return 5}},fi=class extends jn{constructor(t,e){super(t,e)}apply(t){let e=t.currentSiblingTypeCounts[t.currentNamespace][t.currentLocalName];this.matchANPlusB(e)&&this.chained.apply(t)}getPriority(){return 5}},gi=class extends jn{constructor(t,e){super(t,e)}apply(t){let e=t.currentFollowingSiblingOrder;e===null&&(e=t.currentFollowingSiblingOrder=t.currentElement.parentNode.childElementCount-t.currentSiblingOrder+1),this.matchANPlusB(e)&&this.chained.apply(t)}getPriority(){return 4}},mi=class extends jn{constructor(t,e){super(t,e)}apply(t){let e=t.currentFollowingSiblingTypeCounts;if(!e[t.currentNamespace]){let n=t.currentElement;do{let s=n.namespaceURI,o=n.localName,i=e[s];i||(i=e[s]={}),i[o]=(i[o]||0)+1}while(n=n.nextElementSibling)}this.matchANPlusB(e[t.currentNamespace][t.currentLocalName])&&this.chained.apply(t)}getPriority(){return 4}},mu=class extends Q{constructor(){super()}apply(t){let e=t.currentElement.firstChild;for(;e;){switch(e.nodeType){case Node.ELEMENT_NODE:return;case Node.TEXT_NODE:if(e.length>0)return}e=e.nextSibling}this.chained.apply(t)}getPriority(){return 4}},Cu=class extends Q{constructor(){super()}apply(t){t.currentElement.disabled===!1&&this.chained.apply(t)}getPriority(){return 5}},bu=class extends Q{constructor(){super()}apply(t){t.currentElement.disabled===!0&&this.chained.apply(t)}getPriority(){return 5}},xu=class extends Q{constructor(){super()}apply(t){let e=t.currentElement;(e.selected===!0||e.checked===!0)&&this.chained.apply(t)}getPriority(){return 5}},ze=class extends Q{constructor(e){super();this.condition=e}apply(e){if(e.conditions[this.condition])try{e.dependentConditions.push(this.condition),this.chained.apply(e)}finally{e.dependentConditions.pop()}}getPriority(){return 5}},yu=class r extends yn{constructor(){super();p(this,"applied",!1)}apply(e){this.applied=!0}clone(){let e=new r;return e.applied=this.applied,e}},Ci=class extends Q{constructor(e){super();p(this,"checkAppliedAction");p(this,"firstActions",[]);this.checkAppliedAction=new yu;for(let n of e)this.firstActions.push(mf(n,this.checkAppliedAction))}apply(e){for(let n of this.firstActions)if(n.apply(e),this.checkAppliedAction.applied)break;this.checkAppliedAction.applied===this.positive()&&this.chained.apply(e),this.checkAppliedAction.applied=!1}getPriority(){return Math.max(...this.firstActions.map(e=>e instanceof Q?e.getPriority():0))}positive(){return!0}relational(){return!1}},Eu=class extends Ci{positive(){return!1}},Su=class extends Ci{constructor(e){super([]);this.selectorTexts=e}apply(e){for(let n of this.selectorTexts){let s,o;/^\s*[+~]/.test(n)?(o=e.currentElement.parentNode,s=`:scope > :nth-child(${Array.from(o.children).indexOf(e.currentElement)+1}) ${n}`):(o=e.currentElement,s=`:scope ${n}`);try{if(o.querySelector(s)){this.checkAppliedAction.apply(e);break}}catch(i){}}this.checkAppliedAction.applied&&this.chained.apply(e),this.checkAppliedAction.applied=!1}relational(){return!0}},No=class{constructor(t,e,n){this.condition=t;this.viewConditionId=e;this.viewCondition=n}increment(t){t.increment(this.condition,this.viewCondition)}decrement(t){t.decrement(this.condition,this.viewCondition)}buildViewConditionMatcher(t){return t.buildViewConditionMatcher(this.viewConditionId)}},Nu=class r extends No{constructor(t,e,n){super(t,e,n)}fresh(t){return new r(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,e){return e==0&&this.increment(t),!1}pop(t,e){return e==0?(this.decrement(t),!0):!1}},vu=class r extends No{constructor(t,e,n){super(t,e,n)}fresh(t){return new r(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,e){return e==0?this.increment(t):e==1&&this.decrement(t),!1}pop(t,e){return e==0?(this.decrement(t),!0):(e==1&&this.increment(t),!1)}},Tu=class r extends No{constructor(e,n,s){super(e,n,s);p(this,"fired",!1)}fresh(e){return new r(this.condition,this.viewConditionId,this.buildViewConditionMatcher(e))}push(e,n){return this.fired?(this.decrement(e),!0):!1}pop(e,n){return this.fired?(this.decrement(e),!0):(n==0&&(this.fired=!0,this.increment(e)),!1)}},wu=class r extends No{constructor(e,n,s){super(e,n,s);p(this,"fired",!1)}fresh(e){return new r(this.condition,this.viewConditionId,this.buildViewConditionMatcher(e))}push(e,n){return this.fired&&(n==-1?this.increment(e):n==0&&this.decrement(e)),!1}pop(e,n){if(this.fired){if(n==-1)return this.decrement(e),!0;n==0&&this.increment(e)}else n==0&&(this.fired=!0,this.increment(e));return!1}},Pu=class{constructor(t,e){this.afterprop=t;this.element=e}fresh(t){return this}push(t,e){return!1}pop(t,e){return e==0?(t.processPseudoelementProps(this.afterprop,this.element),!0):!1}},ku=class{constructor(t){this.lang=t}fresh(t){return this}push(t,e){return!1}pop(t,e){return e==0?(t.lang=this.lang,!0):!1}},Au=class{constructor(t){this.oldQuotes=t}fresh(t){return this}push(t,e){return!1}pop(t,e){return e==0?(t.quotes=this.oldQuotes,!0):!1}},Lu=class extends Kt{constructor(e){super();this.element=e}createValueFromString(e,n){switch(n){case"url":return e?new Oe(e):new Oe("about:invalid");case"string":default:return e?new ce(e):new ce("")}}visitFunc(e){if(e.name!=="attr")return super.visitFunc(e);let n="string",s=null,o=null;if(e.values[0]instanceof q){let i=e.values[0].values;i.length>=2&&(n=i[1].stringValue()),s=i[0].stringValue()}else s=e.values[0].stringValue();return e.values.length>1?o=this.createValueFromString(e.values[1].stringValue(),n):o=this.createValueFromString(null,n),this.element&&this.element.hasAttribute(s)?this.createValueFromString(this.element.getAttribute(s),n):o}};function pi(r){if(Nt(r)){if(r instanceof ce)return r.stringValue();if(r instanceof q)return r.values.map(t=>pi(t)).join("")}return""}var vo=class extends Kt{constructor(e,n,s){super();this.cascade=e;this.element=n;this.counterResolver=s}visitIdent(e){let n=this.cascade,s=n.quotes,o=Math.floor(s.length/2)-1;switch(e.name){case"open-quote":{let i=s[2*Math.min(o,n.quoteDepth)];return n.quoteDepth++,i}case"close-quote":return n.quoteDepth>0&&n.quoteDepth--,s[2*Math.min(o,n.quoteDepth)+1];case"no-open-quote":return n.quoteDepth++,new ce("");case"no-close-quote":return n.quoteDepth>0&&n.quoteDepth--,new ce("")}return e}format(e,n){let s=!1,o=!1,i;(i=n.match(/^upper-(.*)/))!=null?(s=!0,n=i[1]):(i=n.match(/^lower-(.*)/))!=null&&(o=!0,n=i[1]);let a="";return lf[n]?a=EC(lf[n],e):cf[n]?a=NC(cf[n],e):uf[n]!=null?a=uf[n]:n=="decimal-leading-zero"?(a=`${e}`,a.length==1&&(a=`0${a}`)):n=="cjk-ideographic"||n=="trad-chinese-informal"?a=TC(e,vC):a=`${e}`,s?a.toUpperCase():o?a.toLowerCase():a}visitFuncCounter(e){let n=e[0].toString(),s=e.length>1?e[1].stringValue():"decimal",o=this.cascade.counters[n];if(o&&o.length){let i=o&&o.length&&o[o.length-1]||0;return new ce(this.format(i,s))}else{let i=new B(this.counterResolver.getPageCounterVal(n,a=>this.format(a||0,s)));return new q([i])}}visitFuncCounters(e){let n=e[0].toString(),s=e[1].stringValue(),o=e.length>2?e[2].stringValue():"decimal",i=this.cascade.counters[n],a=new $e;if(i&&i.length)for(let c=0;c<i.length;c++)c>0&&a.append(s),a.append(this.format(i[c],o));let l=new B(this.counterResolver.getPageCountersVal(n,c=>{let u=[];if(c.length)for(let h=0;h<c.length;h++)u.push(this.format(c[h],o));let d=a.toString();return d.length&&u.push(d),u.length?u.join(s):this.format(0,o)}));return new q([l])}visitFuncTargetCounter(e){let n=e[0],s;n instanceof Oe?s=n.url:s=n.stringValue();let o=e[1].toString(),i=e.length>2?e[2].stringValue():"decimal",a=new B(this.counterResolver.getTargetCounterVal(s,o,l=>this.format(l||0,i)));return new q([a])}visitFuncTargetCounters(e){let n=e[0],s;n instanceof Oe?s=n.url:s=n.stringValue();let o=e[1].toString(),i=e[2].stringValue(),a=e.length>3?e[3].stringValue():"decimal",l=new B(this.counterResolver.getTargetCountersVal(s,o,c=>{let u=c.map(d=>this.format(d,a));return u.length?u.join(i):this.format(0,a)}));return new q([l])}visitFuncTargetText(e){let n=e[0],s;n instanceof Oe?s=n.url:s=n.stringValue();let o=e.length>1?e[1].stringValue():"content",i=new B(this.counterResolver.getTargetTextVal(s,o));return new q([i])}visitFuncString(e){let n=e.length>0?e[0].stringValue():"",s=e.length>1?e[1].stringValue():"first";return new B(this.counterResolver.getNamedStringVal(n,s))}visitFuncElement(e){let n=e.length>0?e[0].stringValue():"",s=e.length>1?e[1].stringValue():"first";return new B(this.counterResolver.getRunningElementVal(n,s))}visitFuncContent(e){var o,i,a,l,c,u;let n=e.length>0?e[0].stringValue():"text",s="";switch(n){case"text":s=this.element.textContent;break;case"before":case"after":{let d=vt(this.cascade.currentStyle,"_pseudos"),h=(i=(o=d==null?void 0:d[n])==null?void 0:o.content)==null?void 0:i.value;s=pi(h)}break;case"first-letter":{let d=vt(this.cascade.currentStyle,"_pseudos"),h=(pi((l=(a=d==null?void 0:d.before)==null?void 0:a.content)==null?void 0:l.value)||this.element.textContent||pi((u=(c=d==null?void 0:d.after)==null?void 0:c.content)==null?void 0:u.value)).match(is);s=h?h[0]:""}break}return new ce(s)}visitFuncLeader(e){let n="";if(e[0]instanceof be)switch(e[0].stringValue()){case"dotted":n=".";break;case"solid":n="_";break;case"space":n=" ";break}else e[0]instanceof ce&&(n=e[0].stringValue());return n.length==0?new ce(""):new B(new Z(null,()=>n,"viv-leader"))}visitFunc(e){switch(e.name){case"counter":if(e.values.length<=2)return this.visitFuncCounter(e.values);break;case"counters":if(e.values.length<=3)return this.visitFuncCounters(e.values);break;case"target-counter":if(e.values.length<=3)return this.visitFuncTargetCounter(e.values);break;case"target-counters":if(e.values.length<=4)return this.visitFuncTargetCounters(e.values);break;case"target-text":if(e.values.length>=1&&e.values.length<=2)return this.visitFuncTargetText(e.values);break;case"string":if(e.values.length<=2)return this.visitFuncString(e.values);break;case"element":if(e.values.length<=2)return this.visitFuncElement(e.values);break;case"content":if(e.values.length<=1)return this.visitFuncContent(e.values);break;case"leader":if(e.values.length<=1)return this.visitFuncLeader(e.values);break}return e}},yC=(r,t,e)=>{let n=t.filter(l=>l.after&&l.viewNode.nodeType===1&&l.viewNode.getAttribute("data-viv-leader"));for(let l of n){let E=function($){m==="rtl"?u.textContent=($.startsWith("\u200F")?"":"\u200F")+$+($.endsWith("\u200F")?"":"\u200F"):u.textContent=$},G=function(){let $=e.clientLayout.getElementClientRect(d);return C.left>$.left||C.right<$.right||C.top>$.top||C.bottom<$.bottom},de=function(){let $,I;if(E(f),G())$=1,I=f.length/h.length;else{$=f.length/h.length,I=$;for(let M=0;M<16;M++){let F=f;for(let _=0;_<1<<M;_++)F+=h;if(E(F),G()){I+=1<<M;break}}}for(let M=0;M<16;M++){let F="",_=Math.floor(($+I)/2);for(let W=0;W<_;W++)F+=h;if(E(F),G())I=_;else{if($==_)return;$=_}}E(h)},_e=function($){let I=0,M=d.parentElement;for(;M&&M!==c.viewNode;)I+=e.getComputedInsets(M)[$],M=M.parentElement;return I};var s=E,o=G,i=de,a=_e;let c=l.parent;for(;c&&c.inline;)c=c.parent;let u=l.viewNode,d=u.parentElement,h=u.getAttribute("data-viv-leader-value"),f=u.textContent||h,{writingMode:g,direction:m,marginInlineEnd:y}=e.clientLayout.getElementComputedStyle(d);u.style.marginInlineStart="1px",E(h),d.style.display="inline-block",d.style.textIndent="0";let C=e.clientLayout.getElementClientRect(c.viewNode),x=e.clientLayout.getElementClientRect(d),N=e.parseComputedLength(y),S=0,w=[],k=null,R=d.parentElement.nextSibling;for(;R;){if(R.nodeType!==1){R=R.nextSibling;continue}let $=R,I=e.clientLayout.getElementComputedStyle($),M=I.display,F=I.float,_=I.position;if(F!=="none"||_==="absolute"||_==="fixed"){R=R.nextSibling;continue}if(M==="inline"||M==="inline-block"||M==="inline-flex"||M==="inline-grid"||M==="inline-table")w.push($),k=$;else if(M==="block"||M==="flex"||M==="grid"||M==="table"||M==="list-item")break;R=R.nextSibling}if(w.length>0&&d.parentElement){let $=e.clientLayout.getElementClientRect(d.parentElement),I=e.clientLayout.getElementClientRect(k);g==="vertical-rl"||g==="vertical-lr"?S=I.bottom-$.bottom:S=I.right-$.right}g==="vertical-rl"||g==="vertical-lr"?(m==="rtl"?C.top+=N:C.bottom-=N,C.left=x.left,C.right=x.right,C.top=Math.min(x.top,C.top),C.bottom=Math.max(x.bottom,C.bottom),S>0&&(m==="rtl"?C.top+=S:C.bottom-=S)):(m==="rtl"?C.left+=N:C.right-=N,C.top=x.top,C.bottom=x.bottom,C.left=Math.min(x.left,C.left),C.right=Math.max(x.right,C.right),S>0&&(m==="rtl"?C.left+=S:C.right-=S)),de();let Xe=e.clientLayout.getElementClientRect(d);m=="rtl"?d.style.float="left":d.style.float="right";let Je=e.clientLayout.getElementClientRect(d),Fe=0;m=="rtl"?g=="vertical-rl"||g=="vertical-lr"?Fe=Xe.top-Je.top-_e("top"):Fe=Xe.left-Je.left-_e("left"):g=="vertical-rl"||g=="vertical-lr"?Fe=Je.bottom-Xe.bottom-_e("bottom"):Fe=Je.right-Xe.right-_e("right"),Fe-=S,Fe=Math.max(0,Fe-.1),d.style.float="",u.style.marginInlineStart=`${Fe}px`}};Ue("POST_LAYOUT_BLOCK",yC);var lf={roman:[4999,1e3,"M",900,"CM",500,"D",400,"CD",100,"C",90,"XC",50,"L",40,"XL",10,"X",9,"IX",5,"V",4,"IV",1,"I"],armenian:[9999,9e3,"\u0584",8e3,"\u0583",7e3,"\u0582",6e3,"\u0581",5e3,"\u0580",4e3,"\u057F",3e3,"\u057E",2e3,"\u057D",1e3,"\u057C",900,"\u057B",800,"\u057A",700,"\u0579",600,"\u0578",500,"\u0577",400,"\u0576",300,"\u0575",200,"\u0574",100,"\u0573",90,"\u0572",80,"\u0571",70,"\u0570",60,"\u056F",50,"\u056E",40,"\u056D",30,"\u056C",20,"\u056B",10,"\u056A",9,"\u0569",8,"\u0568",7,"\u0567",6,"\u0566",5,"\u0565",4,"\u0564",3,"\u0563",2,"\u0562",1,"\u0561"],georgian:[19999,1e4,"\u10F5",9e3,"\u10F0",8e3,"\u10EF",7e3,"\u10F4",6e3,"\u10EE",5e3,"\u10ED",4e3,"\u10EC",3e3,"\u10EB",2e3,"\u10EA",1e3,"\u10E9",900,"\u10E8",800,"\u10E7",700,"\u10E6",600,"\u10E5",500,"\u10E4",400,"\u10F3",300,"\u10E2",200,"\u10E1",100,"\u10E0",90,"\u10DF",80,"\u10DE",70,"\u10DD",60,"\u10F2",50,"\u10DC",40,"\u10DB",30,"\u10DA",20,"\u10D9",10,"\u10D8",9,"\u10D7",8,"\u10F1",7,"\u10D6",6,"\u10D5",5,"\u10D4",4,"\u10D3",3,"\u10D2",2,"\u10D1",1,"\u10D0"],hebrew:[999,400,"\u05EA",300,"\u05E9",200,"\u05E8",100,"\u05E7",90,"\u05E6",80,"\u05E4",70,"\u05E2",60,"\u05E1",50,"\u05E0",40,"\u05DE",30,"\u05DC",20,"\u05DB",19,"\u05D9\u05D8",18,"\u05D9\u05D7",17,"\u05D9\u05D6",16,"\u05D8\u05D6",15,"\u05D8\u05D5",10,"\u05D9",9,"\u05D8",8,"\u05D7",7,"\u05D6",6,"\u05D5",5,"\u05D4",4,"\u05D3",3,"\u05D2",2,"\u05D1",1,"\u05D0"]},cf={latin:"a-z",alpha:"a-z",greek:"\u03B1-\u03C1\u03C3-\u03C9",russian:"\u0430-\u0438\u043A-\u0449\u044D-\u044F"},uf={square:"\u25A0",disc:"\u2022",circle:"\u25E6",none:""};function EC(r,t){let e=r[0];if(t>e||t<=0||t!=Math.round(t))return"";let n="";for(let s=1;s<r.length;s+=2){let o=r[s],i=Math.floor(t/o);if(i>20)return"";for(t-=i*o;i>0;)n+=r[s+1],i--}return n}function SC(r){let t=[],e=0;for(;e<r.length;)if(r.substr(e+1,1)=="-"){let n=r.charCodeAt(e),s=r.charCodeAt(e+2);e+=3;for(let o=n;o<=s;o++)t.push(String.fromCharCode(o))}else t.push(r.substr(e++,1));return t}function NC(r,t){if(t<=0||t!=Math.round(t))return"";let e=SC(r),n="";do{t--;let s=t%e.length;n=e[s]+n,t=(t-s)/e.length}while(t>0);return n}var vC={formal:!1,digits:"\u96F6\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D",markers:"\u5341\u767E\u5343",negative:"\u8CA0"};function TC(r,t){if(r>9999||r<-9999)return`${r}`;if(r==0)return t.digits.charAt(0);let e=new $e;if(r<0&&(e.append(t.negative),r=-r),r<10)e.append(t.digits.charAt(r));else if(!t.formal&&r<=19)e.append(t.markers.charAt(0)),r!=0&&e.append(t.digits.charAt(r-10));else{let n=Math.floor(r/1e3);n&&(e.append(t.digits.charAt(n)),e.append(t.markers.charAt(2)));let s=Math.floor(r/100)%10;s&&(e.append(t.digits.charAt(s)),e.append(t.markers.charAt(1)));let o=Math.floor(r/10)%10;o&&(e.append(t.digits.charAt(o)),e.append(t.markers.charAt(0)));let i=r%10;i&&e.append(t.digits.charAt(i))}return e.toString()}var Wu=1/1048576;function Eo(r,t){for(let e in r)t[e]=r[e].clone()}var Ru=class r{constructor(){p(this,"nsCount",0);p(this,"nsPrefix",{});p(this,"tags",{});p(this,"nstags",{});p(this,"epubtypes",{});p(this,"classes",{});p(this,"ids",{});p(this,"pagetypes",{});p(this,"order",0)}clone(){let t=new r;t.nsCount=this.nsCount;for(let e in this.nsPrefix)t.nsPrefix[e]=this.nsPrefix[e];return Eo(this.tags,t.tags),Eo(this.nstags,t.nstags),Eo(this.epubtypes,t.epubtypes),Eo(this.classes,t.classes),Eo(this.ids,t.ids),Eo(this.pagetypes,t.pagetypes),t.order=this.order,t}insertInTable(t,e,n){let s=t[e];s&&(n=s.mergeWith(n)),t[e]=n}createInstance(t,e,n,s){return new Iu(this,t,e,n,s)}nextOrder(){return this.order+=Wu}},Iu=class{constructor(t,e,n,s,o){this.context=e;this.counterListener=n;this.counterResolver=s;p(this,"code");p(this,"stack",[[],[]]);p(this,"conditions",{});p(this,"currentElement",null);p(this,"currentElementOffset",null);p(this,"currentStyle",null);p(this,"currentClassNames",null);p(this,"currentLocalName","");p(this,"currentNamespace","");p(this,"currentId","");p(this,"currentXmlId","");p(this,"currentNSTag","");p(this,"currentEpubTypes",null);p(this,"currentPageType",null);p(this,"previousPageType",null);p(this,"firstPageType",null);p(this,"isFirst",!0);p(this,"isRoot",!0);p(this,"counters",{});p(this,"counterScoping",[{}]);p(this,"quotes");p(this,"quoteDepth",0);p(this,"lang","");p(this,"siblingOrderStack",[0]);p(this,"currentSiblingOrder",0);p(this,"siblingTypeCountsStack",[{}]);p(this,"currentSiblingTypeCounts");p(this,"currentFollowingSiblingOrder",null);p(this,"followingSiblingOrderStack");p(this,"followingSiblingTypeCountsStack",[{}]);p(this,"currentFollowingSiblingTypeCounts");p(this,"viewConditions",{});p(this,"dependentConditions",[]);p(this,"elementStack");this.code=t,this.quotes=[new ce("\u201C"),new ce("\u201D"),new ce("\u2018"),new ce("\u2019")],this.currentSiblingTypeCounts=this.siblingTypeCountsStack[0],this.followingSiblingOrderStack=[this.currentFollowingSiblingOrder],this.currentFollowingSiblingTypeCounts=this.siblingTypeCountsStack[0]}pushConditionItem(t){this.stack[this.stack.length-1].push(t)}increment(t,e){this.conditions[t]=(this.conditions[t]||0)+1,e&&(this.viewConditions[t]?this.viewConditions[t].push(e):this.viewConditions[t]=[e])}decrement(t,e){this.conditions[t]--,this.viewConditions[t]&&(this.viewConditions[t]=this.viewConditions[t].filter(n=>n!==e),this.viewConditions[t].length===0&&delete this.viewConditions[t])}buildViewConditionMatcher(t){let e=null;t&&(this.currentElementOffset,e=Ps.buildViewConditionMatcher(this.currentElementOffset,t));let n=this.dependentConditions.map(s=>{let o=this.viewConditions[s];return o&&o.length>0?o.length===1?o[0]:Ps.buildAnyMatcher([].concat(o)):null}).filter(s=>s);return n.length<=0?e:e===null?n.length===1?n[0]:Ps.buildAllMatcher(n):Ps.buildAllMatcher([e].concat(n))}applyAction(t,e){let n=t[e];n&&n.apply(this)}pushRule(t,e,n){this.currentElement=null,this.currentElementOffset=null,this.currentStyle=n,this.currentNamespace="",this.currentLocalName="",this.currentId="",this.currentXmlId="",this.currentClassNames=t,this.currentNSTag="",this.currentEpubTypes=tu,this.currentPageType=e,this.applyActions()}defineCounter(t,e){let n=this.counterScoping[this.counterScoping.length-1];n||(n={},this.counterScoping[this.counterScoping.length-1]=n),this.counters[t]?(n[t]&&this.counters[t].pop(),this.counters[t].push(e)):this.counters[t]=[e],n[t]=!0}pushCounters(t){var h,f,g,m,y,E,C;let e=b.inline,n=t.display;if(n&&(e=n.evaluate(this.context)),e===b.none){this.currentElement.setAttribute("data-viv-display-none","true"),this.counterScoping.push(null);return}else if(this.currentElement.closest("[data-viv-display-none]")){this.counterScoping.push(null);return}let s=b.inline,o=t.float;o&&(s=o.evaluate(this.context));let i=null,a=null,l=null,c=t["counter-reset"];if(c){let x=c.evaluate(this.context);x&&(i=ds(x,!0))}let u=t["counter-set"];if(u){let x=u.evaluate(this.context);x&&(l=ds(x,!1))}let d=t["counter-increment"];if(d){let x=d.evaluate(this.context);x&&(a=ds(x,!1))}if((this.currentLocalName=="ol"||this.currentLocalName=="ul")&&this.currentNamespace=="http://www.w3.org/1999/xhtml"&&(i||(i={}),i["list-item"]=((f=(h=this.currentElement)==null?void 0:h.start)!=null?f:1)-1),e===b.list_item&&(a||(a={}),a["list-item"]=(g=a["list-item"])!=null?g:1,/^\s*[-+]?\d/.test((y=(m=this.currentElement)==null?void 0:m.getAttribute("value"))!=null?y:"")&&(l||(l={}),l["list-item"]=this.currentElement.value)),((E=this.currentElement)==null?void 0:E.parentNode.nodeType)===Node.DOCUMENT_NODE&&(i||(i={}),i.footnote===void 0&&(i.footnote=0)),s===b.footnote&&(a||(a={}),a.footnote===void 0)){let x=(C=this.currentStyle["counter-increment"])==null?void 0:C.value;(!x||!(x===b.footnote||x instanceof q&&x.values.includes(b.footnote)))&&(a.footnote=1)}if(i)for(let x in i)this.defineCounter(x,i[x]);if(a)for(let x in a){this.counters[x]||this.defineCounter(x,0);let N=this.counters[x];N[N.length-1]+=a[x]}if(l)for(let x in l)if(!this.counters[x])this.defineCounter(x,l[x]);else{let N=this.counters[x];N[N.length-1]=l[x]}if(e===b.list_item){let x=this.counters["list-item"],N=x[x.length-1];t["ua-list-item-count"]=new H(new nt(N),0)}this.counterScoping.push(null)}popCounters(){let t=this.counterScoping.pop();if(t)for(let e in t){let n=this.counters[e];n&&(n.length==1?delete this.counters[e]:n.pop())}}setNamedStrings(t){let e=t["string-set"];if(!e)return;e=e.filterValue(new vo(this,this.currentElement,this.counterResolver));let n=e.value instanceof ge?e.value.values:[e.value];for(let s of n)if(s instanceof q){let o=s.values[0].stringValue(),i=s.values.slice(1).map(a=>pi(a)).join("");this.counterResolver.setNamedString(o,i,this.currentElementOffset)}delete t["string-set"]}setRunningElement(t){let e=t.position;if((e==null?void 0:e.value)instanceof kt&&e.value.name==="running"){let n=e.value.values[0].stringValue();this.counterResolver.setRunningElement(n,this.currentElementOffset)}}processPseudoelementProps(t,e){this.pushCounters(t);let n=t.content;n&&(t.content=n.filterValue(new vo(this,e,this.counterResolver))),this.popCounters()}pushElement(t,e,n,s){var S,w;this.currentPageType=null,this.currentElement=e,this.currentElementOffset=s,this.currentStyle=n,this.currentNamespace=e.namespaceURI,this.currentLocalName=e.localName;let o=this.code.nsPrefix[this.currentNamespace];o?this.currentNSTag=o+this.currentLocalName:this.currentNSTag="",this.currentId=e.getAttribute("id"),this.currentXmlId=e.getAttributeNS("http://www.w3.org/XML/1998/namespace","id");let i=e.getAttribute("class");i?this.currentClassNames=i.split(/\s+/):this.currentClassNames=tu;let a=e.getAttributeNS("http://www.idpf.org/2007/ops","type");a?this.currentEpubTypes=a.split(/\s+/):this.currentEpubTypes=tu;let l=_o(e);l&&(this.stack[this.stack.length-1].push(new ku(this.lang)),this.lang=l.toLowerCase());let c=this.isRoot,u=this.siblingOrderStack;this.currentSiblingOrder=++u[u.length-1],u.push(0);let d=this.siblingTypeCountsStack,h=this.currentSiblingTypeCounts=d[d.length-1],f=h[this.currentNamespace];f||(f=h[this.currentNamespace]={}),f[this.currentLocalName]=(f[this.currentLocalName]||0)+1,d.push({});let g=this.followingSiblingOrderStack;g[g.length-1]!==null?this.currentFollowingSiblingOrder=--g[g.length-1]:this.currentFollowingSiblingOrder=null,g.push(null);let m=this.followingSiblingTypeCountsStack,y=this.currentFollowingSiblingTypeCounts=m[m.length-1];y&&y[this.currentNamespace]&&y[this.currentNamespace][this.currentLocalName]--,m.push({}),this.applyActions(),this.applyVarFilter([this.currentStyle],t,e),this.applyCalcFilter(this.currentStyle,this.context),this.applyAttrFilter(e);let E=n.quotes,C=null;if(E){let k=E.evaluate(this.context);k&&(C=new Au(this.quotes),k===b.none?this.quotes=[new ce(""),new ce("")]:k===b.auto||k===b.initial?this.quotes=[new ce("\u201C"),new ce("\u201D"),new ce("\u2018"),new ce("\u2019")]:k instanceof q&&(this.quotes=k.values))}this.pushCounters(this.currentStyle);let x=this.currentId||this.currentXmlId||e.getAttribute("name")||"";if(c||x){let k={};Object.keys(this.counters).forEach(R=>{k[R]=Array.from(this.counters[R])}),this.counterListener.countersOfId(x,k)}let N=vt(this.currentStyle,"_pseudos");if(N){let k=!0;for(let R of wC){R||(k=!1);let G=N[R];G&&((R==="before"||R==="after")&&!Nt((S=G.content)==null?void 0:S.value)||(R==="footnote-call"||R==="footnote-marker")&&((w=pe(this.currentStyle,"float"))==null?void 0:w.value)!==b.footnote?delete N[R]:k?this.processPseudoelementProps(G,e):this.stack[this.stack.length-2].push(new Pu(G,e)))}}this.setNamedStrings(this.currentStyle),this.setRunningElement(this.currentStyle),C&&this.stack[this.stack.length-2].push(C)}applyAttrFilterInner(t,e){for(let n in e)As(n)&&!xt(n)&&(e[n]=e[n].filterValue(t))}applyAttrFilter(t){let e=new Lu(t),n=this.currentStyle,s=vt(n,"_pseudos");for(let o in s)this.applyAttrFilterInner(e,s[o]);this.applyAttrFilterInner(e,n)}applyVarFilter(t,e,n){var l,c,u;let s=t[0],o=new Mu(t,e,n),i=32,a={};for(let d in s)if(ou(d)){let h=vt(s,d);for(let f in h)this.applyVarFilter([h[f],...t],e,n)}else if(As(d)){let h=pe(s,d),f=h.value;for(let g=0;;g++){if(g>=i){f=O;break}let m=f.visit(o);if(o.error){f=O,o.error=!1;break}if(m===f)break;f=m}if(f!==h.value){let g=e.validatorSet,m=(l=g==null?void 0:g.shorthands[d])==null?void 0:l.clone();if(m)if(U(f)){for(let y of m.propList){let E=new H(f,h.priority),C=pe(s,y);xn(a,y,su(this.context,C,E))}delete s[d]}else{let y=en(e.scope,new De(f.toString(),null),"");if(y&&(y.visit(m),!m.error)){for(let E of m.propList){let C=new H((u=(c=m.values[E])!=null?c:g.defaultValues[E])!=null?u:b.initial,h.priority),x=pe(s,E);xn(a,E,su(this.context,x,C))}delete s[d]}}else s[d]=new H(f,h.priority)}if(a[d]){let g=pe(s,d);g&&g.value!==O&&on(a,d,g,this.context)}}for(let d in a)s[d]=a[d]}applyCalcFilter(t,e){let n=new ma(e);for(let s in t)if(ou(s)){let o=vt(t,s);for(let i in o)this.applyCalcFilter(o[i],e)}else if(As(s)&&!xt(s)){let o=pe(t,s),i=o.value.visit(n);i!==o.value&&(t[s]=new H(i,o.priority))}}applyActions(){let t;for(t=0;t<this.currentClassNames.length;t++)this.applyAction(this.code.classes,this.currentClassNames[t]);for(t=0;t<this.currentEpubTypes.length;t++)this.applyAction(this.code.epubtypes,this.currentEpubTypes[t]);this.applyAction(this.code.ids,this.currentId),this.applyAction(this.code.tags,this.currentLocalName),this.currentLocalName!=""&&this.applyAction(this.code.tags,"*"),this.applyAction(this.code.nstags,this.currentNSTag),this.currentPageType!==null&&(this.applyAction(this.code.pagetypes,this.currentPageType),this.applyAction(this.code.pagetypes,"*")),this.stack.push([]);for(let e=1;e>=-1;--e){let n=this.stack[this.stack.length-e-2];for(t=0;t<n.length;)n[t].push(this,e)?n.splice(t,1):t++}this.isFirst=!0,this.isRoot=!1}pop(){for(let t=1;t>=-1;--t){let e=this.stack[this.stack.length-t-2],n=0;for(;n<e.length;)e[n].pop(this,t)?e.splice(n,1):n++}this.stack.pop(),this.isFirst=!1}popRule(){this.pop()}popElement(t){this.siblingOrderStack.pop(),this.siblingTypeCountsStack.pop(),this.followingSiblingOrderStack.pop(),this.followingSiblingTypeCountsStack.pop(),this.pop(),this.popCounters()}},tu=[],wC=["before","transclusion-before","footnote-call","footnote-marker","inner","first-letter","first-line","","transclusion-after","after"];var Vu=null;function Cf(r){Vu=r}var En=class extends Jt{constructor(e,n,s,o,i,a,l){super(e,n,l);this.condition=s;this.regionId=i;this.validatorSet=a;p(this,"chain",null);p(this,"specificity",0);p(this,"elementStyle",null);p(this,"conditionCount",0);p(this,"pseudoelement",null);p(this,"footnoteContent",!1);p(this,"cascade");p(this,"state");p(this,"viewConditionId",null);p(this,"insideSelectorRule");p(this,"invalid",!1);this.cascade=o?o.cascade:Vu?Vu.clone():new Ru,this.state=0}insertNonPrimary(e){this.cascade.insertInTable(this.cascade.tags,"*",e)}processChain(e){let n=mf(this.chain,e);n!==e&&n.makePrimary(this.cascade)||this.insertNonPrimary(n)}isInsideSelectorRule(e){return this.state!=0?(this.reportAndSkip(e),!0):!1}tagSelector(e,n){!n&&!e||(n&&(this.specificity+=1),n&&e?this.chain.push(new lu(e,n.toLowerCase())):n?this.chain.push(new da(n.toLowerCase())):this.chain.push(new uu(e)))}invalidSelector(e){V.warn(e),this.chain.push(new ze("")),this.setInvalid()}setInvalid(){this.invalid=!0;for(let e=this;e instanceof Rs;e=e.parent)e.parent.invalid=!0}classSelector(e){if(this.pseudoelement){this.invalidSelector(`::${this.pseudoelement} followed by .${e}`);return}this.specificity+=256,this.chain.push(new ru(e))}pseudoclassSelector(e,n){if(this.pseudoelement){this.invalidSelector(`::${this.pseudoelement} followed by :${e}`);return}switch(e.toLowerCase()){case"enabled":this.chain.push(new Cu);break;case"disabled":this.chain.push(new bu);break;case"checked":this.chain.push(new xu);break;case"root":case"scope":this.chain.push(new fu);break;case"link":this.chain.push(new da("a")),this.chain.push(new pa("","href"));break;case"-adapt-href-epub-type":case"href-epub-type":if(n&&n.length>=1&&typeof n[0]=="string"){let s=n[0],o=new RegExp(`(^|\\s)${cn(s)}($|\\s)`),i=n[1];this.chain.push(new cu(o,i))}else this.chain.push(new ze(""));break;case"-adapt-footnote-content":case"footnote-content":this.footnoteContent=!0;break;case"visited":case"active":case"hover":case"focus":this.chain.push(new ze(""));break;case"lang":if(n&&n.length==1&&typeof n[0]=="string"){let s=n[0];this.chain.push(new hu(new RegExp(`^${cn(s.toLowerCase())}($|-)`)))}else this.chain.push(new ze(""));break;case"nth-child":case"nth-last-child":case"nth-of-type":case"nth-last-of-type":{let s=PC[e.toLowerCase()];n&&n.length==2?this.chain.push(new s(n[0],n[1])):this.chain.push(new ze(""));break}case"first-child":this.chain.push(new ha);break;case"last-child":this.chain.push(new gi(0,1));break;case"first-of-type":this.chain.push(new fi(0,1));break;case"last-of-type":this.chain.push(new mi(0,1));break;case"only-child":this.chain.push(new ha),this.chain.push(new gi(0,1));break;case"only-of-type":this.chain.push(new fi(0,1)),this.chain.push(new mi(0,1));break;case"empty":this.chain.push(new mu);break;case"before":case"after":case"first-line":case"first-letter":this.pseudoelementSelector(e,n);return;default:this.invalidSelector(`Unknown pseudo-class :${e}`);return}this.specificity+=256}pseudoelementSelector(e,n){switch(e){case"before":case"after":case"first-line":case"first-letter":case"footnote-call":case"footnote-marker":case"inner":case"after-if-continues":if(!this.pseudoelement)this.pseudoelement=e;else{this.invalidSelector(`Double pseudo-element ::${this.pseudoelement}::${e}`);return}break;case"first-n-lines":if(n&&n.length==1&&typeof n[0]=="number"){let s=Math.round(n[0]);if(s>0&&s==n[0]){if(!this.pseudoelement)this.pseudoelement=`first-${s}-lines`;else{this.invalidSelector(`Double pseudo-element ::${this.pseudoelement}::${e}`);return}break}}this.chain.push(new ze(""));break;case"nth-fragment":n&&n.length==2?this.viewConditionId=`NFS_${n[0]}_${n[1]}`:this.chain.push(new ze(""));break;default:this.invalidSelector(`Unknown pseudo-element ::${e}`);return}this.specificity+=1}idSelector(e){this.specificity+=65536,this.chain.push(new au(e))}attributeSelector(e,n,s,o){this.specificity+=256,n=n.toLowerCase(),o=o||"";let i;switch(s){case 0:i=new pa(e,n);break;case 39:i=new du(e,n,o);break;case 45:!o||o.match(/\s/)?i=new ze(""):i=new ks(e,n,new RegExp(`(^|\\s)${cn(o)}($|\\s)`));break;case 44:i=new ks(e,n,new RegExp(`^${cn(o)}($|-)`));break;case 43:o?i=new ks(e,n,new RegExp(`^${cn(o)}`)):i=new ze("");break;case 42:o?i=new ks(e,n,new RegExp(`${cn(o)}$`)):i=new ze("");break;case 46:o?i=new ks(e,n,new RegExp(cn(o))):i=new ze("");break;case 50:if(o=="supported")i=new pu(e,n);else{this.invalidSelector(`Unsupported :: attr selector op: ${o}`);return}break;default:this.invalidSelector(`Unsupported attr selector: ${s}`);return}this.chain.push(i)}descendantSelector(){let e=`d${ca++}`;this.processChain(new So(new Nu(e,this.viewConditionId,null))),this.chain=[new ze(e)],this.viewConditionId=null}childSelector(){let e=`c${ca++}`;this.processChain(new So(new vu(e,this.viewConditionId,null))),this.chain=[new ze(e)],this.viewConditionId=null}adjacentSiblingSelector(){let e=`a${ca++}`;this.processChain(new So(new Tu(e,this.viewConditionId,null))),this.chain=[new ze(e)],this.viewConditionId=null}followingSiblingSelector(){let e=`f${ca++}`;this.processChain(new So(new wu(e,this.viewConditionId,null))),this.chain=[new ze(e)],this.viewConditionId=null}nextSelector(){this.finishChain(),this.pseudoelement=null,this.footnoteContent=!1,this.specificity=0,this.chain=[]}startSelectorRule(){this.isInsideSelectorRule("E_CSS_UNEXPECTED_SELECTOR")||(this.state=1,this.elementStyle={},this.pseudoelement=null,this.specificity=0,this.footnoteContent=!1,this.chain=[],this.invalid=!1)}error(e,n){super.error(e,n),this.state==1&&(this.state=0),this.setInvalid()}startStylesheet(e){super.startStylesheet(e),this.state=0}startRuleBody(){this.finishChain(),super.startRuleBody(),this.state==1&&(this.state=0)}endRule(){super.endRule(),this.insideSelectorRule=0}finishChain(){this.chain&&(this.processChain(this.makeApplyRuleAction(this.specificity)),this.chain=null,this.pseudoelement=null,this.viewConditionId=null,this.footnoteContent=!1,this.specificity=0)}makeApplyRuleAction(e){let n=this.regionId;return this.footnoteContent&&(n?n="xxx-bogus-xxx":n="footnote"),new Ls(this.elementStyle,e,this.pseudoelement,n,this.viewConditionId)}special(e,n){let s;this.condition?s=new hi(n,0,this.condition):s=new H(n,0),ff(this.elementStyle,e).push(s)}property(e,n,s){this.validatorSet.validatePropertyAndHandleShorthand(e,n,s,this)}invalidPropertyValue(e,n){this.report(`E_INVALID_PROPERTY_VALUE ${e}: ${n.toString()}`)}unknownProperty(e,n){this.report(`E_INVALID_PROPERTY ${e}: ${n.toString()}`)}simpleProperty(e,n,s){e=="display"&&(n===b.oeb_page_head||n===b.oeb_page_foot)&&(this.simpleProperty("flow-options",new q([b.exclusive,b._static]),s),this.simpleProperty("flow-into",n,s),n=b.block),Ge("SIMPLE_PROPERTY").forEach(c=>{let d=c({name:e,value:n,important:s});e=d.name,n=d.value,s=d.important});let a=(s?this.getImportantSpecificity():this.getBaseSpecificity())+this.cascade.nextOrder(),l=this.condition?new hi(n,a,this.condition):new H(n,a);on(this.elementStyle,e,l)}finish(){return this.cascade}startFuncWithSelector(e){let n;switch(e){case"is":n=new Rs(this);break;case"not":n=new Fu(this);break;case"where":n=new Bu(this);break;case"has":n=new Ou(this);break}n&&(n.startSelectorRule(),this.owner.pushHandler(n))}},PC={"nth-child":gu,"nth-of-type":fi,"nth-last-child":gi,"nth-last-of-type":mi},ca=0,Rs=class r extends En{constructor(e){super(e.scope,e.owner,e.condition,e,e.regionId,e.validatorSet,!1);this.parent=e;p(this,"parentChain");p(this,"chains",[]);p(this,"maxSpecificity",0);p(this,"selectorTexts",[]);this.parentChain=e.chain}nextSelector(){this.chain&&this.chains.push(this.chain),this.maxSpecificity=Math.max(this.maxSpecificity,this.specificity),this.chain=[],this.pseudoelement=null,this.viewConditionId=null,this.footnoteContent=!1,this.specificity=0}endFuncWithSelector(){this.chain&&this.chains.push(this.chain),this.chains.length>0?(this.maxSpecificity=Math.max(this.maxSpecificity,this.specificity),this.parentChain.push(this.relational()?new Su(this.selectorTexts):this.positive()?new Ci(this.chains):new Eu(this.chains)),this.increasingSpecificity()&&(this.parent.specificity+=this.maxSpecificity)):this.parentChain.push(new ze("")),this.owner.popHandler()}startRuleBody(){this.reportAndSkip("E_CSS_UNEXPECTED_RULE_BODY")}error(e,n){super.error(e,n),this.chain=null,this.pseudoelement=null,this.viewConditionId=null,this.footnoteContent=!1,this.specificity=0;let s=!1;for(let o=this;o instanceof r;o=o.parent)if(o.forgiving()){s=!0;break}s||this.owner.popHandler()}pushSelectorText(e){this.chain&&this.relational()&&this.selectorTexts.push(e)}positive(){return!0}increasingSpecificity(){return!0}forgiving(){return!0}relational(){return!1}},Fu=class extends Rs{positive(){return!1}forgiving(){return!1}},Bu=class extends Rs{increasingSpecificity(){return!1}},Ou=class extends Rs{relational(){return!0}},fa=class extends Jt{constructor(t,e){super(t,e,!1)}property(t,e,n){if(this.scope.values[t])this.error(`E_CSS_NAME_REDEFINED ${t}`,this.getCurrentToken());else{let s=t.match(/height|^(top|bottom)$/)?"vh":"vw",o=new Ft(this.scope,100,s);this.scope.defineName(t,e.toExpr(this.scope,o))}}},Is=class extends Jt{constructor(e,n,s,o,i,a){super(e,n,!1);this.condition=s;this.elementStyle=o;this.validatorSet=i;this.ruleType=a;p(this,"order");this.order=0}property(e,n,s){s?V.warn("E_IMPORTANT_NOT_ALLOWED"):this.validatorSet.validatePropertyAndHandleShorthand(e,n,s,this)}invalidPropertyValue(e,n){V.warn("E_INVALID_PROPERTY_VALUE",`${e}:`,n.toString())}unknownProperty(e,n){V.warn("E_INVALID_PROPERTY",`${e}:`,n.toString())}simpleProperty(e,n,s){let o=s?this.getImportantSpecificity():this.getBaseSpecificity();o+=this.order,this.order+=Wu;let i=this.condition?new hi(n,o,this.condition):new H(n,o);on(this.elementStyle,e,i)}},Du=class extends ti{constructor(e,n){super(e);this.validatorSet=n;p(this,"elementStyle",{});p(this,"order",0)}property(e,n,s){this.validatorSet.validatePropertyAndHandleShorthand(e,n,s,this)}invalidPropertyValue(e,n){V.warn("E_INVALID_PROPERTY_VALUE",`${e}:`,n.toString())}unknownProperty(e,n){V.warn("E_INVALID_PROPERTY",`${e}:`,n.toString())}simpleProperty(e,n,s){let o=s?_r:Mr;o+=this.order,this.order+=Wu;let i=new H(n,o);on(this.elementStyle,e,i)}};function $u(r,t){let e=hf(r);e&&e.forEach(n=>{n.matcher.matches()&&t(n.styles)})}function ga(r,t,e){$u(e,n=>{Po(r,n,t)})}function bf(r,t,e,n){let s=new Du(r,t),o=new De(n,s);try{xh(o,s,e)}catch(i){V.warn(i,"Style attribute parse error:")}return s.elementStyle}function xa(r,t,e){let n=r["writing-mode"];if(n){let s=n.evaluate(t,"writing-mode");if(s&&s!==b.inherit&&s!==b.revert&&s!==b.unset)return s===b.vertical_rl}return e}function ya(r,t,e){let n=r.direction;if(n){let s=n.evaluate(t,"direction");if(s&&s!==b.inherit&&s!==b.revert&&s!==b.unset)return s===b.rtl}return e}function Ea(r,t,e,n,s){let o={};for(let i in r)As(i)&&(o[i]=pe(r,i));return ga(o,t,r),Xu(r,e,n,(i,a)=>{Po(o,a,t),ga(o,t,a)}),o}function Xu(r,t,e,n){let s=vt(r,"_regions");if((t||e)&&s){if(e){let o=["footnote"];t?t=t.concat(o):t=o}for(let o of t){let i=s[o];i&&n(o,i)}}}function Po(r,t,e){for(let n in t)if(As(n)){let s=pe(t,n),o=r[n];r[n]=su(e,o,s)}}var Sa=(r,t,e,n,s,o)=>{var l,c;let i=e?n?gC:Uu:n?mC:Hu,a=s?CC:bC;for(let u in r){let d=r[u];if(!d)continue;let h=(l=i[u])!=null?l:i[a[u]],f=(c=a[u])!=null?c:a[i[u]],g=h!=null?h:f,m;if(g){let y=r[g];if(y&&y.priority>d.priority||h&&f&&h!==f&&(g=f,y=r[g],y&&y.priority>d.priority))continue;m=af[h]?h:af[f]?f:u}else m=u,u.startsWith("text-align")&&(d.value===b.inside||d.value===b.outside)&&(d=new H(s===(d.value===b.inside)?b.right:b.left,d.priority));t[m]=o(u,d)}},Mu=class extends Kt{constructor(e,n,s){super();this.elementStyles=e;this.styler=n;this.element=s}getVarValue(e){var s,o,i,a,l;let n=(s=this.element)!=null?s:this.styler.root;if((o=this.elementStyles)!=null&&o.length){for(let c of this.elementStyles){let u=(i=c[e])==null?void 0:i.value;if(u)return u}this.element&&(n=this.element.parentElement)}for(;n;n=n.parentElement){let c=(l=(a=this.styler.getStyle(n,!1))==null?void 0:a[e])==null?void 0:l.value;if(c)return c}return null}visitFunc(e){if(e.name!=="var")return super.visitFunc(e);let n=e.values[0]instanceof be&&e.values[0].name;if(!n||!xt(n))return this.error=!0,O;let s=this.getVarValue(n);return s||(e.values.length<2?(this.error=!0,O):e.values.length===2?e.values[1]:new ge(e.values.slice(1)))}},ma=class extends Kt{constructor(e,n,s,o){super();this.context=e;this.resolveViewportUnit=n;this.percentRef=s;this.vertical=o}visitFunc(e){let n=super.visitFunc(e);if(e.name!=="calc")return n;let s=n.toString().replace(/^calc\b/,"-epubx-expr");if(/\d(%|em|ex|cap|ch|ic|lh|p?v[whbi]|p?vmin|p?vmax)\W|\Wvar\(\s*--/i.test(s))return n;let o=en(this.context.rootScope,new De(s,null),"");if(o instanceof B)try{let i=o.expr.evaluate(this.context);typeof i=="number"&&!isNaN(i)&&(/\d(px|in|pt|pc|cm|mm|q|rem|rlh)\W/i.test(s)?n=new P(i,"px"):/\d[a-z]/i.test(s)||(n=new nt(i)))}catch(i){V.warn(i)}return n}visitNumeric(e){return this.resolveViewportUnit&&(Dl(e.unit)||qp(e.unit))?new P(e.num*this.context.queryUnitSize(e.unit,!1,this.vertical),"px"):typeof this.percentRef=="number"&&e.unit==="%"?new P(e.num*this.percentRef/100,"px"):e}};function xi(r,t,e,n,s){try{if(t instanceof B)return t.expr instanceof Z&&(t.expr.str.startsWith("named-string-")||t.expr.str.startsWith("running-element-"))?t:yh(r,t.expr,e);if(t instanceof P||t instanceof kt||t instanceof q||t instanceof ge)return t.visit(new ma(r,!0,n,s))}catch(o){return V.warn(o),O}return t}var xf={first:!1,forceEnd:!1,allowEnd:!1,last:!1};function yf(r){let t=r instanceof Se?r:typeof r=="string"?L(r):b.none;if(t===b.none)return xf;let e=t instanceof q?t.values:[t],n=Object.create(xf);for(let s of e)if(s instanceof be)switch(s.name){case"first":n.first=!0;break;case"force-end":n.forceEnd=!0,n.allowEnd=!1;break;case"allow-end":n.forceEnd=!1,n.allowEnd=!0;break;case"last":n.last=!0;break}return n}function Ef(r){return!r.first&&!r.last&&!r.forceEnd&&!r.allowEnd}var kC={trimStart:!1,spaceFirst:!1,trimEnd:!1,allowEnd:!1,trimAdjacent:!1},Sf={trimStart:!1,spaceFirst:!1,trimEnd:!1,allowEnd:!0,trimAdjacent:!0},Nf={trimStart:!0,spaceFirst:!1,trimEnd:!0,allowEnd:!1,trimAdjacent:!0};function vf(r){let t=r instanceof Se?r:typeof r=="string"?L(r):b.normal;if(t===b.normal)return Sf;if(t===b.auto)return Nf;let e=t instanceof q?t.values:[t],n=Object.create(Sf);for(let s of e)if(s instanceof be)switch(s.name){case"trim-both":case"trim-auto":return Nf;case"space-all":return kC;case"trim-start":n.trimStart=!0,n.spaceFirst=!1;break;case"space-start":n.trimStart=!1,n.spaceFirst=!1;break;case"space-first":n.trimStart=!1,n.spaceFirst=!0;break;case"trim-end":n.trimEnd=!0,n.allowEnd=!1;break;case"space-end":n.trimEnd=!1,n.allowEnd=!1;break;case"allow-end":n.trimEnd=!1,n.allowEnd=!0;break;case"trim-adjacent":n.trimAdjacent=!0;break;case"space-adjacent":n.trimAdjacent=!1;break}return n}var ju={ideographAlpha:!1,ideographNumeric:!1},AC={ideographAlpha:!0,ideographNumeric:!0};function Tf(r){let t=r instanceof Se?r:typeof r=="string"?L(r):b.normal;if(t===b.normal||t===b.auto)return AC;if(t===b.none)return ju;let e=t instanceof q?t.values:[t],n=Object.create(ju);for(let s of e)if(s instanceof be)switch(s.name){case"no-autospace":return ju;case"ideograph-alpha":n.ideographAlpha=!0;break;case"ideograph-numeric":n.ideographNumeric=!0;break}return n}function wf(r,t){return!r.ideographAlpha&&!r.ideographNumeric&&!t.trimStart&&!t.spaceFirst&&!t.trimEnd&&!t.allowEnd&&!t.trimAdjacent}function Pf(r){return r?(r=r.toLowerCase(),/^zh\b.*-(hant|tw|hk)\b/.test(r)?"zh-hant":/^zh\b/.test(r)?"zh-hans":/^ja\b/.test(r)?"ja":/^ko\b/.test(r)?"ko":r):null}var Yu=class{getPolyfilledInheritedProps(){return["hanging-punctuation","text-autospace","text-spacing-trim"]}preprocessSingleDocument(t){t.body&&this.preprocessForTextSpacing(t.body)}preprocessForTextSpacing(t){var n;let e=t.ownerDocument.createNodeIterator(t,NodeFilter.SHOW_TEXT);for(let s=e.nextNode();s;s=e.nextNode()){if(s.parentElement.namespaceURI!=="http://www.w3.org/1999/xhtml"||((n=s.parentElement.dataset)==null?void 0:n.mathTypeset)==="true")continue;let o=s.textContent.replace(/(?![()\[\]{}])[\p{Ps}\p{Pe}\p{Pf}\p{Pi}、。,.:;、。\u3000]\p{M}*(?=\P{M})|.(?=(?![()\[\]{}])[\p{Ps}\p{Pe}\p{Pf}\p{Pi}、。,.:;、。\u3000])|(?!\p{P})[\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF]\p{M}*(?=(?![\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF\uFF01-\uFF60])[\p{L}\p{Nd}])|(?![\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF\uFF01-\uFF60])[\p{L}\p{Nd}]\p{M}*(?=(?!\p{P})[\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF])/gsu,"$&\0").split("\0");if(o.length>1){let i=o.length-1;for(let a=0;a<i;a++)s.parentNode.insertBefore(document.createTextNode(o[a]),s);s.textContent=o[i]}}}processGeneratedContent(t,e,n,s,o,i){o=Pf(o);let a=Tf(e),l=vf(n),c=yf(s);if(Ef(c)&&wf(a,l))return;this.preprocessForTextSpacing(t);let u=t.style.whiteSpace;(i?t.offsetHeight:t.offsetWidth)===0&&(t.style.whiteSpace="pre");let d=t.ownerDocument.createNodeIterator(t,NodeFilter.SHOW_TEXT),h=null,f=null;for(let g=d.nextNode();g;g=f){f=d.nextNode();let m=!h,y=!h||/\n$/.test(h.textContent),E=!f||/^\n/.test(f.textContent),C=!f;this.processTextSpacing(g,m||y,m,y,E,C,h,f,a,l,c,o,i),h=g}t.style.whiteSpace=u}postLayoutBlock(t,e){var d,h,f,g,m,y,E;let n=!t||t.fragmentIndex===1&&i(),s=n||a();function o(C){var w;if((C==null?void 0:C.nodeType)!==1)return!1;let x=C;if(x.hasAttribute(_t))return!0;let{position:N,float:S}=(w=x.style)!=null?w:{};return N==="absolute"||N==="fixed"||S&&S!=="none"}function i(){let C=e[0];for(let x=C;;x=x.parent)if(!x||!x.inline){if((x==null?void 0:x.fragmentIndex)!==1)return!1;break}if(!C.inline)return!0;for(let x=C.viewNode.previousSibling;x;x=x.previousSibling)if(!ue(x,C.whitespace)&&!o(x))return!1;return!0}function a(){var N,S;let C=e[0],x;for(;C&&C.inline&&(x=(N=C.viewNode)==null?void 0:N.previousSibling,!(x&&(x.nodeType===3&&/^[ \t\r\n\f]*$/.test(x.textContent)&&C.whitespace!==Ze.PRESERVE&&(x=x.previousSibling),x)));)C=C.parent;for(;x;){if(x.nodeType===1){if(x.localName==="br")return!0;let w=(S=x.style)==null?void 0:S.display;if(w&&w!=="inline")return!/^(inline|ruby)\b/.test(w)}else if(x.nodeType===3){if(C.whitespace===Ze.PRESERVE){if(/\n$/.test(x.textContent))return!0}else if(C.whitespace===Ze.NEWLINE&&/\n[ \t\r\n\f]*$/.test(x.textContent))return!0}x=x.lastChild}return!1}let l=-1;for(let C=0;C<e.length;C++){let x=e[C];if(!x.after&&x.inline&&!x.display&&x.parent&&x.viewNode.parentNode&&x.viewNode.nodeType===Node.TEXT_NODE&&!ue(x.viewNode,x.whitespace)){let $=function(F){var _,W,he;if(((_=F.viewNode)==null?void 0:_.nodeType)===1)return F.viewNode.localName==="br";if(((W=F.viewNode)==null?void 0:W.nodeType)===3){if(F.whitespace===Ze.PRESERVE){if(/\n$/.test(F.viewNode.textContent))return!0}else if(F.whitespace===Ze.NEWLINE&&/\n[ \t\r\n\f]*$/.test(F.viewNode.textContent))return!0;if(((he=F.viewNode.previousElementSibling)==null?void 0:he.localName)==="br")return ue(F.viewNode,F.whitespace)}return!1},I=function(F){var _,W,he;if(((_=F.viewNode)==null?void 0:_.nodeType)===1)return F.viewNode.localName==="br";if(((W=F.viewNode)==null?void 0:W.nodeType)===3){if(F.whitespace===Ze.PRESERVE){if(/^\n/.test(F.viewNode.textContent))return!0}else if(F.whitespace===Ze.NEWLINE&&/^[ \t\r\n\f]*\n/.test(F.viewNode.textContent))return!0;if(((he=F.viewNode.nextElementSibling)==null?void 0:he.localName)==="br")return ue(F.viewNode,F.whitespace)}return!1};var c=$,u=I;let N=Pf((g=(h=(d=x.lang)!=null?d:x.parent.lang)!=null?h:t==null?void 0:t.lang)!=null?g:(f=t==null?void 0:t.parent)==null?void 0:f.lang),S=Tf(x.inheritedProps["text-autospace"]),w=vf(x.inheritedProps["text-spacing-trim"]),k=yf(x.inheritedProps["hanging-punctuation"]);if(Ef(k)&&wf(S,w)||/\b(flex|grid)\b/.test(x.parent.display))continue;l<0&&(l=C);let R=null,G=null,de=C===l,Xe=C===l&&n,Je=C===l&&s,_e=!1,Fe=!1;for(let F=C-1;F>=0;F--){let _=e[F];if($(_)){Je=!0;break}if(!_.display&&_.viewNode.nodeType===Node.TEXT_NODE&&_.viewNode.textContent.length>0){R=_.viewNode;break}if(_.display&&!/^(inline|ruby)\b/.test(_.display)||((m=_.viewNode)==null?void 0:m.nodeType)===1&&(_.viewNode.localName==="br"||Yt[_.viewNode.localName]))break;F===0&&(de=!0,n&&(Xe=!0,Je=!0))}for(let F=C+1;F<e.length;F++){let _=e[F];if(I(_)){_e=!0;break}if(_.viewNode!==x.viewNode&&!_.display&&_.viewNode.nodeType===Node.TEXT_NODE&&_.viewNode.textContent.length>0){G=_.viewNode;break}if(_.display&&!/^(inline|ruby)\b/.test(_.display)||((y=_.viewNode)==null?void 0:y.nodeType)===1&&(_.viewNode.localName==="br"||Yt[_.viewNode.localName])){F===e.length-1&&o(_.viewNode)&&(Fe=!0);break}if(F===e.length-1){_e=!0,Fe=!0;for(let W=_.viewNode.nextSibling;W;W=W.nextSibling)if(!o(W)){Fe=!1;break}}}if(((E=x.parent)==null?void 0:E.display)==="inline-block"){if(!Xe){let F=x.parent.viewNode.firstChild;for(;ue(F,x.whitespace);)F=F.nextSibling;x.viewNode===F&&(Xe=!0)}if(!Fe){let F=x.parent.viewNode.lastChild;for(;ue(F,x.whitespace);)F=F.previousSibling;x.viewNode===F&&(Fe=!0)}}if(this.processTextSpacing(x.viewNode,de,Xe,Je,_e,Fe,R,G,S,w,k,N,x.vertical)>0)break}}}processTextSpacing(t,e,n,s,o,i,a,l,c,u,d,h,f){let g=t.textContent,m=t.ownerDocument,y=0,E,C,x;function N(){if(e)return!0;if(!a)return!1;E||(E=m.createRange(),E.selectNode(t));let I=E.getClientRects()[0];C||(C=m.createRange(),C.selectNode(a));let M=C.getClientRects(),F=M[M.length-1];return!I||!F?!1:(y||(y=Co(F,f)),f?I.top<F.top+F.height-I.width||I.left+I.width<F.left+I.width/10||I.left>F.left+F.width-I.width/10:I.left<F.left+F.width-I.height||I.top>F.top+F.height-I.height/10||I.top+I.height<F.top+I.height/10)}function S(){if(!l)return!1;E||(E=m.createRange(),E.selectNode(t));let I=E.getClientRects()[0];y||(y=Co(I,f)),x||(x=m.createRange(),x.selectNode(l));let M=x.getClientRects()[0];return!I||!M?!1:f?I.top+I.height>M.top+I.width||I.left>M.left+M.width-I.width/10||I.left+I.width<M.left+I.width/10:I.left+I.width>M.left+I.height||I.top+I.height<M.top+I.height/10||I.top>M.top+M.height-I.height/10}let w=!1,k=!1,R=!1,G=!1,de;if(n&&d.first&&/^[\p{Ps}\p{Pf}\p{Pi}'"\u3000]\p{M}*$/u.test(g)?(de="viv-ts-open",w=!0,k=!0):i&&d.last&&/^[\p{Pe}\p{Pf}\p{Pi}'"]\p{M}*$/u.test(g)?(de="viv-ts-close",w=!0,R=!0):(d.forceEnd||d.allowEnd)&&/^[、。,.、。]\p{M}*$/u.test(g)?(de="viv-ts-close",w=!0,G=!0):(u.trimStart||u.spaceFirst||u.trimAdjacent)&&/^[‘“〝([{⦅〈〈《「『【〔〖〘〚]\p{M}*$/u.test(g)?(de="viv-ts-open",w=!0):(u.trimEnd||u.allowEnd||u.trimAdjacent)&&(/^[’”〞〟)]}⦆〉〉》」』】〕〗〙〛]\p{M}*$/u.test(g)||h==="zh-hans"&&/^[:;]\p{M}*$/u.test(g)||h!=="zh-hant"&&/^[、。,.]\p{M}*$/u.test(g))&&(de="viv-ts-close",w=!0),w){let F=function(he){let Ki=parseFloat(m.defaultView.getComputedStyle(he).fontSize)*.7;return(f?he.offsetHeight:he.offsetWidth)>Ki},W=function(){return f?I.offsetLeft:I.offsetTop};var Fe=F,$=W;if(t.parentElement.localName==="viv-ts-inner")return 0;let I=m.createElement(de),M=m.createElement("viv-ts-inner");I.appendChild(M),t.parentNode.insertBefore(I,t),M.appendChild(t);let _=F(M);if(_||k||R||G){if(de==="viv-ts-open"){if(k)I.className="viv-hang-first";else if(n||s)u.trimStart?I.className="viv-ts-trim":I.className="viv-ts-space";else if(!(u.trimStart||u.spaceFirst)&&N())I.className="viv-ts-space";else if(u.trimAdjacent&&a&&/[\p{Ps}\p{Pi}\p{Pe}\p{Pf}\u00B7\u2027\u30FB\u3000:;、。,.]\p{M}*$/u.test(a.textContent)&&(!/[\p{Pe}\p{Pf}]\p{M}*$/u.test(a.textContent)||a.parentElement.localName==="viv-ts-inner"&&F(a.parentElement)))I.className="viv-ts-trim";else if((u.trimStart||u.spaceFirst)&&N()){let he=W();I.className="viv-ts-auto",he===W()&&!N()&&(I.className="viv-ts-trim")}}else if(de==="viv-ts-close"){if(R)I.className=_?"viv-hang-last":"viv-hang-last viv-hang-hw";else if(i||o){let he=W();G?(I.className=_?d.allowEnd&&u.allowEnd?"viv-ts-auto":"viv-hang-end":"viv-hang-end viv-hang-hw",d.allowEnd&&he===W()&&(u.trimEnd?I.className="viv-ts-trim":u.allowEnd?(I.className="viv-hang-end",he===W()&&(I.className="")):I.className="viv-ts-space")):u.trimEnd?I.className="viv-ts-trim":u.allowEnd?(I.className="viv-ts-auto",he===W()&&(I.className="")):I.className="viv-ts-space"}else if(l&&/^[\p{Pe}\p{Pf}\u00B7\u2027\u30FB\u3000:;、。,.]/u.test(l.textContent))_&&u.trimAdjacent&&(I.className="viv-ts-trim");else if(G){let he=S(),Tn=he&&d.allowEnd;Tn||(I.className=_?"viv-hang-end":"viv-hang-end viv-hang-hw"),_?Tn&&u.trimEnd?I.className="viv-ts-auto":!Tn&&!S()?I.className="":!he&&d.allowEnd&&(u.trimEnd?(I.className="viv-ts-auto",S()||(I.className="viv-hang-end")):(I.className="viv-ts-space",S()||(u.allowEnd?(I.className="viv-ts-auto",S()||(I.className="viv-hang-end")):I.className="viv-hang-end"))):!he&&!S()&&(I.className="")}else if(u.trimEnd||u.allowEnd)if(S())u.allowEnd?I.className="viv-ts-space":I.className="viv-ts-auto";else{let he=W();I.className="viv-ts-auto",he===W()&&(I.className="")}}}}let Xe=!1;function Je(I){var F;let M=(F=I==null?void 0:I.ownerDocument.defaultView)==null?void 0:F.getComputedStyle(I);return!!M&&(M.textOrientation==="upright"||M.textCombineUpright==="all"||M["-webkit-text-combine"]==="horizontal")}function _e(I,M){if(I.nodeType===1){let W=m.defaultView.getComputedStyle(I);if(parseFloat(W.marginInlineEnd)||parseFloat(W.borderInlineEndWidth)||parseFloat(W.paddingInlineEnd))return!0}let F=I.parentElement;if(F&&!F.contains(M))return _e(F,M);if(M.nodeType===1){let W=m.defaultView.getComputedStyle(M);if(parseFloat(W.marginInlineStart)||parseFloat(W.borderInlineStartWidth)||parseFloat(W.paddingInlineStart))return!0}let _=M.parentElement;return _&&!_.contains(I)?_e(I,_):!1}return(c.ideographAlpha||c.ideographNumeric)&&(a&&/^(?!\p{P})[\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF]/u.test(g)&&(c.ideographAlpha&&/(?![\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF\uFF01-\uFF60])\p{L}\p{M}*$/u.test(a.textContent)||c.ideographNumeric&&/(?![\uFF01-\uFF60])\p{Nd}\p{M}*$/u.test(a.textContent))&&!(f&&Je(a.parentElement))&&!_e(a,t)&&(t.parentNode.insertBefore(m.createElement("viv-ts-thin-sp"),t),Xe=!0),l&&/(?!\p{P})[\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF]\p{M}*$/u.test(g)&&(c.ideographAlpha&&/^(?![\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF\uFF01-\uFF60])\p{L}/u.test(l.textContent)||c.ideographNumeric&&/^(?![\uFF01-\uFF60])\p{Nd}/u.test(l.textContent))&&!(f&&Je(l.parentElement))&&!_e(t,l)&&(t.parentNode.insertBefore(m.createElement("viv-ts-thin-sp"),t.nextSibling),Xe=!0)),y}registerHooks(){Ue("POLYFILLED_INHERITED_PROPS",this.getPolyfilledInheritedProps.bind(this)),Ue("PREPROCESS_SINGLE_DOCUMENT",this.preprocessSingleDocument.bind(this)),Ue("POST_LAYOUT_BLOCK",this.postLayoutBlock.bind(this),!0)}},qu=new Yu;qu.registerHooks();function kf(r){qu.preprocessForTextSpacing(r)}function Af(r,t,e,n,s,o){qu.processGeneratedContent(r,t,e,n,s,o)}var ko=new DOMParser().parseFromString('<root xmlns="http://www.pyroxy.com/ns/shadow"/>',"text/xml"),Rf=["footnote-marker","first-5-lines","first-4-lines","first-3-lines","first-2-lines","first-line","first-letter","before","","after"],Na="data-adapt-pseudo";function Vs(r){return r.getAttribute(Na)||""}function Ei(r,t){r.setAttribute(Na,t)}var yi=class{constructor(t,e,n,s,o){this.element=t;this.style=e;this.styler=n;this.context=s;this.exprContentListener=o;p(this,"contentProcessed",{})}getStyle(t,e){let n=Vs(t);this.styler&&n&&n.match(/after$/)&&(this.style=this.styler.getStyle(this.element,!0),this.styler=null);let o=vt(this.style,"_pseudos")[n]||{};if(n.match(/^first-/)&&!o["x-first-pseudo"]){let i=1,a;n=="first-letter"?i=0:(a=n.match(/^first-([0-9]+)-lines$/))!=null&&(i=a[1]-0),o["x-first-pseudo"]=new H(new ut(i),0)}return o}processContent(t,e,n){let s=Vs(t);if(!this.contentProcessed[s]){this.contentProcessed[s]=!0;let o=e.content;o&&Nt(o)&&(o.visit(new hn(t,this.context,o,this.exprContentListener)),kf(t))}}};var Fx=si.isInstanceOfAfterIfContinuesLayoutConstraint,Ff=Xn.registerFragmentIndex,Bx=Xn.clearFragmentIndices,va=class{constructor(t,e){this.sourceNode=t;this.styler=e}createElement(t,e){let s=e.viewNode.ownerDocument.createElement("div"),o=new Os(t,s,e),i=o.getColumn().pageBreakType;return o.getColumn().pageBreakType=null,o.layout(this.createNodePositionForPseudoElement(),!0).thenAsync(()=>{this.styler.contentProcessed["after-if-continues"]=!1,o.getColumn().pageBreakType=i;let a=s.firstChild;return T(a,"display","block"),v(a)})}createNodePositionForPseudoElement(){let t=ko.createElementNS("http://www.w3.org/1999/xhtml","div");Ei(t,"after-if-continues");let e=this.createShadowContext(t),s={steps:[{node:t,shadowType:e.type,shadowContext:e,nodeShadow:null,shadowSibling:null}],offsetInNode:0,after:!1,preprocessedTextContent:null};return new ht(s)}createShadowContext(t){return new ys(this.sourceNode,t,null,null,null,Lt.ShadowType.ROOTED,this.styler)}},Ku=class r{constructor(t,e,n){this.nodeContext=t;this.afterIfContinues=e;this.pseudoElementHeight=n;p(this,"flagmentLayoutConstraintType","AfterIfContinue")}allowLayout(t,e,n){return!(e&&!t||t&&t.overflow)}nextCandidate(t){return!1}postLayout(t,e,n,s){}finishBreak(t,e){return this.getRepetitiveElements().affectTo(t)?this.afterIfContinues.createElement(e,this.nodeContext).thenAsync(n=>(this.nodeContext.viewNode.appendChild(n),v(!0))):v(!0)}getRepetitiveElements(){return new Zu(this.nodeContext,this.pseudoElementHeight)}equalsTo(t){return t instanceof r?this.afterIfContinues==t.afterIfContinues:!1}getPriorityOfFinishBreak(){return 9}},Zu=class{constructor(t,e){this.nodeContext=t;this.pseudoElementHeight=e}calculateOffset(t){return this.affectTo(t)?this.pseudoElementHeight:0}calculateMinimumOffset(t){return this.calculateOffset(t)}affectTo(t){if(!t)return!1;let e=t.shadowContext?t.shadowContext.owner:t.sourceNode;if(e===this.nodeContext.sourceNode)return!!t.after;for(let n=e.parentNode;n;n=n.parentNode)if(n===this.nodeContext.sourceNode)return!0;return!1}};function Bf(r,t){if(!r||!r.afterIfContinues||r.after||t.isFloatNodeContext(r))return v(r);let e=r.afterIfContinues;return e.createElement(t,r).thenAsync(n=>{let s=RC(r,t,n);return t.fragmentLayoutConstraints.push(new Ku(r,e,s)),v(r)})}function td(r,t){return r.thenAsync(e=>Bf(e,t))}function LC(r,t){let e=A("processAfterIfContinuesOfAncestors"),n=r;return e.loop(()=>{if(n!==null){let s=Bf(n,t);return n=n.parent,s.thenReturn(!0)}else return v(!1)}).then(()=>{e.finish(!0)}),e.result()}function RC(r,t,e){let n=r.viewNode;n.appendChild(e);let s=ui(e,t,r.vertical);return n.removeChild(e),s}var Ta=class{constructor(t){this.constraints=t}allowLayout(t){return this.constraints.every(e=>e.allowLayout(t))}},Fs=class extends Ts{constructor(e,n){super();this.checkPoints=e;this.penalty=n;p(this,"alreadyEvaluated",!1);p(this,"breakNodeContext",null)}findAcceptableBreak(e,n){return n<this.getMinBreakPenalty()?null:(this.alreadyEvaluated||(this.breakNodeContext=e.findBoxBreakPosition(this,n>0),this.alreadyEvaluated=!!this.breakNodeContext||n>0||!!e.pseudoParent),this.breakNodeContext)}getMinBreakPenalty(){return this.penalty}getNodeContext(){return this.alreadyEvaluated?this.breakNodeContext:this.checkPoints[this.checkPoints.length-1]}};var Bs=class extends go{constructor(e,n,s,o,i){super(e);this.layoutContext=n;this.clientLayout=s;this.layoutConstraint=o;this.pageFloatLayoutContext=i;p(this,"last");p(this,"viewDocument");p(this,"flowRootFormattingContext",null);p(this,"isFloat",!1);p(this,"isFootnote",!1);p(this,"startEdge",0);p(this,"endEdge",0);p(this,"beforeEdge",0);p(this,"afterEdge",0);p(this,"footnoteEdge",0);p(this,"box",null);p(this,"chunkPositions",null);p(this,"bands",null);p(this,"overflown",!1);p(this,"breakPositions",null);p(this,"pageBreakType",null);p(this,"forceNonfitting",!0);p(this,"leftFloatEdge",0);p(this,"rightFloatEdge",0);p(this,"bottommostFloatTop",0);p(this,"stopAtOverflow",!0);p(this,"lastAfterPosition",null);p(this,"fragmentLayoutConstraints",[]);p(this,"pseudoParent",null);p(this,"nodeContextOverflowingDueToRepetitiveElements",null);p(this,"blockDistanceToBlockEndFloats",NaN);p(this,"breakAtTheEdgeBeforeFloat",null);e.setAttribute("data-vivliostyle-column","true"),this.last=e.lastChild,this.viewDocument=e.ownerDocument,i.setContainer(this)}getTopEdge(){return this.vertical?this.rtl?this.endEdge:this.startEdge:this.beforeEdge}getBottomEdge(){return this.vertical?this.rtl?this.startEdge:this.endEdge:this.afterEdge}getLeftEdge(){return this.vertical?this.afterEdge:this.rtl?this.endEdge:this.startEdge}getRightEdge(){return this.vertical?this.beforeEdge:this.rtl?this.startEdge:this.endEdge}isFloatNodeContext(e){return!!e.floatSide&&(!this.isFloat||!!e.parent)}stopByOverflow(e){return this.stopAtOverflow&&!!e&&e.overflow}isOverflown(e){return this.vertical?e<this.footnoteEdge:e>this.footnoteEdge}getExclusions(){let e=this.pageFloatLayoutContext.getFloatFragmentExclusions();return this.exclusions.concat(e)}openAllViews(e){let n=A("openAllViews"),s=e.steps;this.layoutContext.setViewRoot(this.element,this.isFootnote);let o=s.length-1,i=null;return n.loop(()=>{for(;o>=0;){let a=i,l=s[o];if(i=mo(l,a),o===s.length-1&&!i.formattingContext&&(i.formattingContext=this.flowRootFormattingContext),o==0&&(i.offsetInNode=this.calculateOffsetInNodeForNodeContext(e),i.after=e.after,i.preprocessedTextContent=e.preprocessedTextContent,i.after))break;let c=this.layoutContext.setCurrent(i,o==0&&i.offsetInNode==0);if(o--,c.isPending())return c}return v(!1)}).then(()=>{n.finish(i)}),n.result()}calculateOffsetInNodeForNodeContext(e){return e.preprocessedTextContent?Dh(e.preprocessedTextContent,e.offsetInNode):e.offsetInNode}maybePeelOff(e,n){var s,o;if(e.firstPseudo&&e.inline&&!e.after&&e.firstPseudo.count==0&&e.viewNode.nodeType!=1){let i=e.viewNode.textContent,a=i.match(is),l=a?a[0].length:0;if(!a&&((s=e.sourceNode)==null?void 0:s.nodeType)===3&&((o=e.sourceNode.nextSibling)==null?void 0:o.nodeType)===3&&i===e.sourceNode.textContent){let c=i+e.sourceNode.nextSibling.textContent,u=c.match(is);if(u){let d=u[0];l=d.length,e.sourceNode.textContent=d,e.viewNode.textContent=d,e.sourceNode.nextSibling.textContent=c.substr(l)}}return this.layoutContext.peelOff(e,l)}return v(e)}buildViewToNextBlockEdge(e,n){let s=!1,o=A("buildViewToNextBlockEdge");return o.loopWithFrame(i=>{var a;if(e.viewNode&&!Cn(e)&&((a=e.viewNode.parentElement)==null?void 0:a.namespaceURI)==="http://www.w3.org/1999/xhtml"&&(n.push(e.copy()),n.length>1e3)){let c=e.viewNode.nodeType===1?e.viewNode:e.viewNode.parentElement,u=this.clientLayout.getElementClientRect(c);if(Co(u,this.vertical)>=2){i.breakLoop();return}}this.maybePeelOff(e,0).then(l=>{let c=l;c!==e&&(e=c,Cn(e)||n.push(e.copy())),this.nextInTree(e).then(u=>{if(e=u,!e){i.breakLoop();return}(s||!this.layoutConstraint.allowLayout(e))&&(s=!0,e=e.modify(),e.overflow=!0),this.isFloatNodeContext(e)&&(Hn(e.floatReference)||e.floatSide==="footnote")?this.layoutFloatOrFootnote(e).then(d=>{if(e=d,this.pageFloatLayoutContext.isInvalidated()&&(e=null),!e){i.breakLoop();return}i.continueLoop()}):e.inline?i.continueLoop():i.breakLoop()})})}).then(()=>{o.finish(e)}),o.result()}nextInTree(e,n){let s=this.layoutContext.nextInTree(e,n);return td(s,this)}buildDeepElementView(e){if(!e.viewNode)return v(e);let n=[],s=e.sourceNode,o=A("buildDeepElementView");return o.loopWithFrame(i=>{e.viewNode&&e.inline&&!Cn(e)?n.push(e.copy()):(n.length>0&&this.postLayoutBlock(e,n),n=[]),this.maybePeelOff(e,0).then(a=>{let l=a;if(l!==e){let c=l;for(;c&&c.sourceNode!=s;)c=c.parent;if(c==null){e=l,i.breakLoop();return}Cn(l)||n.push(l.copy())}this.nextInTree(l).then(c=>{e=c,!e||e.sourceNode==s?i.breakLoop():this.layoutConstraint.allowLayout(e)?i.continueLoop():(e=e.modify(),e.overflow=!0,this.stopAtOverflow?i.breakLoop():i.continueLoop())})})}).then(()=>{n.length>0&&this.postLayoutBlock(e,n),o.finish(e)}),o.result()}createFloat(e,n,s,o){let i=this.viewDocument.createElement("div");return this.vertical?(o>=this.height&&(o-=.1),o<1&&(o=0),T(i,"height",`${s}px`),T(i,"width",`${o}px`)):(s>=this.width&&(s-=.1),s<1&&(s=0),T(i,"width",`${s}px`),T(i,"height",`${o}px`)),T(i,"float",n),T(i,"clear",n),this.element.insertBefore(i,e),i}killFloats(){let e=this.element.firstChild;for(;e;){let n=e.nextSibling;if(e.nodeType==1){let s=e,o=s.style.cssFloat;if(o=="left"||o=="right"||o==="none")this.element.removeChild(s);else break}e=n}}createFloats(){let e=this.element.firstChild,n=this.bands,s=this.vertical?this.getTopEdge():this.getLeftEdge(),o=this.vertical?this.getBottomEdge():this.getRightEdge(),i=null;for(let a of n){let l=a.y2-a.y1;a.left=this.createFloat(e,"left",a.x1-s,l),a.right=this.createFloat(e,"right",o-a.x2,l),a.x1<o&&a.x2>s?i=a:i||T(a.right,"float","none")}if(i){let a=n[n.length-1],l=this.vertical?-this.getLeftEdge():this.getBottomEdge();i!==a&&a.y2>=l&&(this.footnoteEdge=this.vertical?-i.y2:i.y2)}}calculateEdge(e,n,s,o){let i;if(e&&mn(e.viewNode))return NaN;if(e&&e.after&&!e.inline&&(i=zn(e,this.clientLayout,0,this.vertical),!isNaN(i)))return i;e=n[s];let a=o-e.boxOffset;for(;;){if(i=zn(e,this.clientLayout,a,this.vertical),!isNaN(i))return i;if(a>0){a--;continue}if(s--,s<0)return this.beforeEdge;e=n[s],e.viewNode.nodeType!=1&&(a=e.viewNode.textContent.length)}}parseComputedLength(e){let n=e.match(/^(-?[0-9]*(\.[0-9]*)?)px$/);return n?this.clientLayout.adjustLengthValue(parseFloat(n[0])):0}getComputedMargin(e){let n=this.clientLayout.getElementComputedStyle(e),s=new no(0,0,0,0);return n&&(s.left=this.parseComputedLength(n.marginLeft),s.top=this.parseComputedLength(n.marginTop),s.right=this.parseComputedLength(n.marginRight),s.bottom=this.parseComputedLength(n.marginBottom)),s}getComputedPaddingBorder(e){let n=this.clientLayout.getElementComputedStyle(e),s=new no(0,0,0,0);return n&&(s.left=this.parseComputedLength(n.borderLeftWidth)+this.parseComputedLength(n.paddingLeft),s.top=this.parseComputedLength(n.borderTopWidth)+this.parseComputedLength(n.paddingTop),s.right=this.parseComputedLength(n.borderRightWidth)+this.parseComputedLength(n.paddingRight),s.bottom=this.parseComputedLength(n.borderBottomWidth)+this.parseComputedLength(n.paddingBottom)),s}getComputedInsets(e){let n=this.clientLayout.getElementComputedStyle(e),s=new no(0,0,0,0);if(n){if(n.boxSizing=="border-box")return this.getComputedMargin(e);s.left=this.parseComputedLength(n.marginLeft)+this.parseComputedLength(n.borderLeftWidth)+this.parseComputedLength(n.paddingLeft),s.top=this.parseComputedLength(n.marginTop)+this.parseComputedLength(n.borderTopWidth)+this.parseComputedLength(n.paddingTop),s.right=this.parseComputedLength(n.marginRight)+this.parseComputedLength(n.borderRightWidth)+this.parseComputedLength(n.paddingRight),s.bottom=this.parseComputedLength(n.marginBottom)+this.parseComputedLength(n.borderBottomWidth)+this.parseComputedLength(n.paddingBottom)}return s}setComputedInsets(e,n){let s=this.clientLayout.getElementComputedStyle(e);s&&(n.marginLeft=this.parseComputedLength(s.marginLeft),n.borderLeft=this.parseComputedLength(s.borderLeftWidth),n.paddingLeft=this.parseComputedLength(s.paddingLeft),n.marginTop=this.parseComputedLength(s.marginTop),n.borderTop=this.parseComputedLength(s.borderTopWidth),n.paddingTop=this.parseComputedLength(s.paddingTop),n.marginRight=this.parseComputedLength(s.marginRight),n.borderRight=this.parseComputedLength(s.borderRightWidth),n.paddingRight=this.parseComputedLength(s.paddingRight),n.marginBottom=this.parseComputedLength(s.marginBottom),n.borderBottom=this.parseComputedLength(s.borderBottomWidth),n.paddingBottom=this.parseComputedLength(s.paddingBottom))}setComputedWidthAndHeight(e,n){let s=this.clientLayout.getElementComputedStyle(e);s&&(n.width=this.parseComputedLength(s.width),n.height=this.parseComputedLength(s.height))}layoutUnbreakable(e){return this.buildDeepElementView(e)}layoutFloat(e){let n=A("layoutFloat"),s=e.viewNode,o=Uc(e.floatSide,e.vertical,e.direction,this.layoutContext.page.side);return T(s,"float","none"),T(s,"display","inline-block"),T(s,"vertical-align","top"),this.buildDeepElementView(e).then(i=>{let a=this.clientLayout.getElementClientRect(s),l=this.getComputedMargin(s),c=new He(a.left-l.left,a.top-l.top,a.right+l.right,a.bottom+l.bottom),u=this.rtl?this.endEdge:this.startEdge,d=this.rtl?this.startEdge:this.endEdge,h=e.parent;for(;h&&h.inline;)h=h.parent;if(h){let S=h.viewNode.ownerDocument.createElement("div");S.style.left="0px",S.style.top="0px",this.vertical?(S.style.bottom="0px",S.style.width="1px"):(S.style.right="0px",S.style.height="1px"),h.viewNode.appendChild(S);let w=this.clientLayout.getElementClientRect(S);u=Math.max(this.rtl?this.getEndEdge(w):this.getStartEdge(w),u),d=Math.min(this.rtl?this.getStartEdge(w):this.getEndEdge(w),d),h.viewNode.removeChild(S);let k=this.vertical?c.y2-c.y1:c.x2-c.x1;o=="left"?d=Math.max(d,u+k):u=Math.min(u,d-k),h!==e.parent&&!e.firstPseudo&&(h.viewNode.appendChild(s),s.setAttribute("data-vivliostyle-float-box-moved","true"))}let f=new He(u,this.getBoxDir()*this.beforeEdge,d,this.getBoxDir()*this.afterEdge),g=c;this.vertical&&(g=so(c));let m=this.getBoxDir();if(g.y1<this.bottommostFloatTop*m){let S=g.y2-g.y1;g.y1=this.bottommostFloatTop*m,g.y2=g.y1+S}ih(f,this.bands,g,o),this.vertical&&(c=kr(g));let y=this.getComputedInsets(s);T(s,"width",`${c.x2-c.x1-y.left-y.right}px`),T(s,"height",`${c.y2-c.y1-y.top-y.bottom}px`),T(s,"position","absolute"),e.display,T(s,"display",e.display);let E,C=null;if(h&&(h.containingBlockForAbsolute?C=h:C=h.getContainingBlockForAbsolute()),C){let S=C.viewNode.ownerDocument.createElement("div");S.style.position="absolute",C.vertical?S.style.right="0":S.style.left="0",S.style.top="0",C.viewNode.appendChild(S),E=this.clientLayout.getElementClientRect(S),C.viewNode.removeChild(S)}else E={left:this.getLeftEdge()-this.paddingLeft,right:this.getRightEdge()+this.paddingRight,top:this.getTopEdge()-this.paddingTop};(C?C.vertical:this.vertical)?T(s,"right",`${E.right-c.x2}px`):T(s,"left",`${c.x1-E.left}px`),T(s,"top",`${c.y1-E.top}px`),e.clearSpacer&&(e.clearSpacer.parentNode.removeChild(e.clearSpacer),e.clearSpacer=null);let x=this.vertical?c.x1:c.y2,N=this.vertical?c.x2:c.y1;!this.isOverflown(x)||this.breakPositions.length==0?(this.killFloats(),f=new He(this.getLeftEdge(),this.getTopEdge(),this.getRightEdge(),this.getBottomEdge()),this.vertical&&(f=so(f)),rh(f,this.bands,g,null,o),this.createFloats(),o=="left"?this.leftFloatEdge=x:this.rightFloatEdge=x,this.bottommostFloatTop=N,this.updateMaxReachedAfterEdge(x),n.finish(i)):(e=e.modify(),e.overflow=!0,n.finish(e))}),n.result()}setupFloatArea(e,n,s,o,i,a){let l=this.pageFloatLayoutContext,c=l.getContainer(n),u=e.element;c.element.parentNode.appendChild(u),e.isFloat=!0,e.originX=c.originX,e.originY=c.originY,e.vertical=c.vertical,e.rtl=c.rtl,e.marginLeft=e.marginRight=e.marginTop=e.marginBottom=0,e.borderLeft=e.borderRight=e.borderTop=e.borderBottom=0,e.paddingLeft=e.paddingRight=e.paddingTop=e.paddingBottom=0,e.exclusions=(c.exclusions||[]).concat(),e.forceNonfitting=!l.hasFloatFragments(),e.innerShape=null;let d=c.getPaddingRect();e.setHorizontalPosition(d.x1-c.originX,d.x2-d.x1),e.setVerticalPosition(d.y1-c.originY,d.y2-d.y1),i.adjustPageFloatArea(e,c,this),e.init();let h=!!l.setFloatAreaDimensions(e,n,s,o,!0,!l.hasFloatFragments(),a);return h?(e.killFloats(),e.init()):c.element.parentNode.removeChild(u),h}createPageFloatArea(e,n,s,o,i){let a=this.element.ownerDocument.createElement("div");T(a,"position","absolute");let l=this.pageFloatLayoutContext.getPageFloatLayoutContext(e.floatReference),c=new fn(null,ae.COLUMN,null,this.pageFloatLayoutContext.flowName,e.nodePosition,null,null),u=l.getContainer(),d=new ed(n,a,this.layoutContext.clone(),this.clientLayout,this.layoutConstraint,c,u);return c.setContainer(d),this.setupFloatArea(d,e.floatReference,n,s,o,i)?d:null}layoutSinglePageFloatFragment(e,n,s,o,i,a,l){let c=this.pageFloatLayoutContext;e=(l?l.continuations:[]).concat(e);let d=e[0].float,h=c.getPageFloatPlacementCondition(d,n,s),f=this.createPageFloatArea(d,n,a,i,h),g={floatArea:f,pageFloatFragment:null,newPosition:null};if(!f)return v(g);let m=A("layoutSinglePageFloatFragment"),y=!1,E=0;return m.loopWithFrame(C=>{if(E>=e.length){C.breakLoop();return}let x=e[E],N=new ht(x.nodePosition);f.layout(N,!0).then(S=>{g.newPosition=S,!S||o?(E++,C.continueLoop()):(y=!0,C.breakLoop())})}).then(()=>{if(!y){let C=c.setFloatAreaDimensions(f,d.floatReference,n,a,!1,o,h);if(!C)y=!0;else{let x=i.createPageFloatFragment(e,C,s,f,!!g.newPosition);c.addPageFloatFragment(x,!0),g.pageFloatFragment=x}}m.finish(g)}),m.result()}layoutPageFloatInner(e,n,s,o){let i=this.pageFloatLayoutContext,a=e.float;i.stashEndFloatFragments(a);function l(u,d){d?i.removePageFloatFragment(d,!0):u&&u.element.parentNode.removeChild(u.element),i.restoreStashedFragments(a.floatReference),i.deferPageFloat(e)}let c=A("layoutPageFloatInner");return this.layoutSinglePageFloatFragment([e],a.floatSide,a.clearSide,!i.hasFloatFragments(),n,s,o).then(u=>{let d=u.floatArea,h=u.pageFloatFragment,f=u.newPosition;h?this.layoutStashedPageFloats(a.floatReference,[o]).then(g=>{if(g){if(i.addPageFloatFragment(h),i.discardStashedFragments(a.floatReference),f){let m=new ai(a,f.primary);i.deferPageFloat(m)}c.finish(!0)}else l(d,h),c.finish(!1)}):(l(d,h),c.finish(!1))}),c.result()}layoutStashedPageFloats(e,n){let s=this.pageFloatLayoutContext,o=s.getStashedFloatFragments(e),i=[],a=[],l=!1,c=A("layoutStashedPageFloats"),u=0;return c.loopWithFrame(d=>{if(u>=o.length){d.breakLoop();return}let h=o[u];if(n.includes(h)){u++,d.continueLoop();return}let f=new Ut().findByFloat(h.continuations[0].float);this.layoutSinglePageFloatFragment(h.continuations,h.floatSide,h.clearSide,!1,f,null).then(g=>{let m=g.floatArea;m&&i.push(m);let y=g.pageFloatFragment;y?(a.push(y),u++,d.continueLoop()):(l=!0,d.breakLoop())})}).then(()=>{l?(a.forEach(d=>{s.removePageFloatFragment(d,!0)}),i.forEach(d=>{let h=d.element;h&&h.parentNode&&h.parentNode.removeChild(h)})):o.forEach(d=>{let h=d.area.element;h&&h.parentNode&&h.parentNode.removeChild(h)}),c.finish(!l)}),c.result()}setFloatAnchorViewNode(e){let n=e.viewNode.parentNode,s=n.ownerDocument.createElement("span");s.setAttribute(_t,"1"),e.floatSide==="footnote"&&this.layoutContext.applyPseudoelementStyle(e,"footnote-call",s),n.appendChild(s),n.removeChild(e.viewNode);let o=e.modify();return o.after=!0,o.viewNode=s,o}resolveFloatReferenceFromColumnSpan(e,n,s){let o=A("resolveFloatReferenceFromColumnSpan"),i=this.pageFloatLayoutContext,a=i.getPageFloatLayoutContext(ae.REGION);return i.getContainer().width<a.getContainer().width&&e===ae.COLUMN?n===b.auto?this.buildDeepElementView(s.copy()).then(c=>{let u=c.viewNode,d=uo(this.clientLayout,u,["min-content inline size"])["min-content inline size"],h=this.getComputedMargin(u);this.vertical?d+=h.top+h.bottom:d+=h.left+h.right,d>this.width?o.finish(ae.REGION):o.finish(e)}):n===b.all?o.finish(ae.REGION):o.finish(e):o.finish(e),o.result()}layoutPageFloat(e){let n=this.pageFloatLayoutContext,s=new Ut().findByNodeContext(e),o,i=n.findPageFloatByNodePosition(e.toNodePosition());return i?o=v(i):o=s.createPageFloat(e,n,this),o.thenAsync(a=>{let l=Es(e,0),c=this.setFloatAnchorViewNode(e),u=s.findPageFloatFragment(a,n),d=new ai(a,l);if(u&&u.hasFloat(a))return n.registerPageFloatAnchor(a,c.viewNode),v(c);if(n.isForbidden(a)||n.hasPrecedingFloatsDeferredToNext(a))return n.deferPageFloat(d),n.registerPageFloatAnchor(a,c.viewNode),v(c);if(this.nodeContextOverflowingDueToRepetitiveElements)return v(null);{let h=zn(c,this.clientLayout,0,this.vertical);return this.isOverflown(h)?v(c):this.layoutPageFloatInner(d,s,h,u).thenAsync(f=>f?v(null):(n.registerPageFloatAnchor(a,c.viewNode),v(c)))}})}processLineStyling(e,n,s){let o=A("processLineStyling"),i=s.concat([]);s.splice(0,s.length);let a=0,l=e.firstPseudo;return l.count==0&&(l=l.outer),o.loopWithFrame(c=>{if(!l){c.breakLoop();return}let u=this.findLinePositions(i),d=l.count-a;if(u.length<=d){c.breakLoop();return}let h=this.findAcceptableBreakInside(i,u[d-1],!0);if(h==null){c.breakLoop();return}this.finishBreak(h,!1,!1).then(()=>{a+=d,this.layoutContext.peelOff(h,0).then(f=>{e=f,l=e.firstPseudo,i=[],this.buildViewToNextBlockEdge(e,i).then(g=>{n=g,c.continueLoop()})})})}).then(()=>{Array.prototype.push.apply(s,i),o.finish(n)}),o.result()}isLoneImage(e){return e.length!=2&&this.breakPositions.length>0?!1:e[0].sourceNode==e[1].sourceNode&&Yt[e[0].sourceNode.localName]}getTrailingMarginEdgeAdjustment(e){let n=0,s=0;for(let o=e.length-1;o>=0;o--){let i=e[o];if(!i.after||!i.viewNode||i.viewNode.nodeType!=1)break;let a=this.getComputedMargin(i.viewNode),l=this.vertical?-a.left:a.bottom;l>0?n=Math.max(n,l):s=Math.min(s,l)}return n+s}layoutBreakableBlock(e){let n=A("layoutBreakableBlock"),s=[];return this.buildViewToNextBlockEdge(e,s).then(o=>{let i=s.length-1;if(i<0){n.finish(o);return}this.postLayoutBlock(o,s);let a=this.calculateEdge(o,s,i,s[i].boxOffset),l=!1;if(!o||!mn(o.viewNode)){let u=Gn(o,this.collectElementsOffset());l=this.isOverflown(a+(this.vertical?-1:1)*u.minimum),this.isOverflown(a+(this.vertical?-1:1)*u.current)&&!this.nodeContextOverflowingDueToRepetitiveElements&&(this.nodeContextOverflowingDueToRepetitiveElements=o)}o==null&&(a+=this.getTrailingMarginEdgeAdjustment(s)),this.updateMaxReachedAfterEdge(a);let c;e.firstPseudo?c=this.processLineStyling(e,o,s):c=v(o),c.then(u=>{s.length>0&&(this.saveBoxBreakPosition(s),l&&!this.isLoneImage(s)&&u&&(u=u.modify(),u.overflow=!0)),n.finish(u)})}),n.result()}postLayoutBlock(e,n){Ge("POST_LAYOUT_BLOCK").forEach(o=>{o(e,n,this)})}findEndOfLine(e,n,s){let o=this.vertical?e-1:e+1,i=0,a=n[0].boxOffset,l=i,c=n.length-1,u=n[c].boxOffset,d;for(;a<u;){d=a+Math.ceil((u-a)/2),l=i;let h=c;for(;l<h;){let g=l+Math.ceil((h-l)/2);n[g].boxOffset>d?h=g-1:l=g}let f=this.calculateEdge(null,n,l,d);if(this.vertical?f<=o:f>=o){for(u=d-1;n[l].boxOffset==d;)l--;c=l}else s&&this.updateMaxReachedAfterEdge(f),a=d,i=l}return{nodeContext:n[l],index:a,checkPointIndex:l}}findAcceptableBreakInside(e,n,s){var l,c,u;let o=this.findEndOfLine(n,e,!0),i=o.nodeContext;if(o.checkPointIndex===0&&o.index===i.boxOffset)return null;let a=i.viewNode;if(a.nodeType!=1&&((l=a.parentElement)==null?void 0:l.localName)!=="viv-ts-inner"){let d=a;i=this.resolveTextNodeBreaker(i).breakTextNode(d,i,o.index,e,o.checkPointIndex,s)}else{let d=jc(i);if(d){if(((c=this.breakPositions)==null?void 0:c[0])instanceof Fs&&(d!=null&&d.viewNode.contains(this.breakPositions[0].checkPoints[0].viewNode)))return null;for(i=d;!i.after&&i.inline&&i.parent;){let h=(u=i.viewNode)==null?void 0:u.previousSibling;for(;h&&(ue(h,i.parent.whitespace)||Ns(h));)h=h.previousSibling;if(h)break;i=i.parent}}}return this.clearOverflownViewNodes(i,!1),i}resolveTextNodeBreaker(e){return Ge("RESOLVE_TEXT_NODE_BREAKER").reduce((s,o)=>o(e)||s,Ao.instance)}getRangeBoxes(e,n){let s=[],o=e.ownerDocument.createRange(),i=!1,a=e,l=null,c=!1,u=!0;for(;u;){let d=!0;do{let h=null;a==n&&(n.nodeType===1?u=!(!n.firstChild||i):u=!1);let f=a.nodeType===1?a:null;f?i?i=!1:ra(f)?d=!c:!f.firstChild||Yt[f.localName]||/^r(uby|[bt]c?)$/.test(f.localName)||tf(this.clientLayout.getElementComputedStyle(f).display)?(d=!c,d?(f.localName==="ruby"&&a.firstChild&&(a=a.firstChild),o.setStartBefore(a),c=!0,l=a):/^r(uby|tc?)$/.test(f.localName)||(l=a),a.contains(n)&&(u=!1)):h=a.firstChild:(c||(a.parentNode==null?u=!1:(o.setStartBefore(a),c=!0)),l=a),h||(h=a.nextSibling,h||(i=!0,h=a.parentNode)),a=h}while(d&&u);if(c){o.setEndAfter(l);let h=this.clientLayout.getRangeClientRects(o);$c(h,this.vertical);for(let f=0;f<h.length;f++)s.push(h[f]);c=!1}}return s}findLinePositions(e){let o=[],i=this.getRangeBoxes(e[0].viewNode,e[e.length-1].viewNode);i.sort(this.vertical?Gh:zh);let a=0,l=0,c=0,u=0,d=0,h=this.getBoxDir();for(;;){if(d<i.length){let f=i[d],g=1;if(u>0){let m=Math.max(this.getBoxSize(f),1);h*this.getBeforeEdge(f)<h*a?g=h*(this.getAfterEdge(f)-a)/m:h*this.getAfterEdge(f)>h*l?g=h*(l-this.getBeforeEdge(f))/m:g=1}if(u==0||g>=.6||g>=.2&&this.getStartEdge(f)>=c-1){c=this.getEndEdge(f),this.vertical?(a=u==0?f.right:Math.max(a,f.right),l=u==0?f.left:Math.min(l,f.left)):(a=u==0?f.top:Math.min(a,f.top),l=u==0?f.bottom:Math.max(l,f.bottom)),u++,d++;continue}}if(u>0&&(o.push(l),u=0),d>=i.length)break}return o.sort(or),this.vertical&&o.reverse(),o}calculateClonedPaddingBorder(e){let n=0;for(let s=e;s;s=s.parent)if(!s.inline&&bs(s.viewNode)){let o=this.getComputedPaddingBorder(s.viewNode);n+=s.vertical?-o.left:o.bottom,s.display==="table"&&(n+=(s.vertical?-1:1)*s.blockBorderSpacing)}return n}getOffsetByRepetitiveElements(e){let n;return e?n=e.calculateOffset(this):n=Gn(null,this.collectElementsOffset()),n.current}findBoxBreakPosition(e,n){let s=this.element.parentNode,o=this.element.nextSibling;s.removeChild(this.element),s.insertBefore(this.element,o);let i=e.checkPoints,a=i[0];for(;a.parent&&a.inline;)a=a.parent;let l,c;n?(l=1,c=1):(l=Math.max((a.inheritedProps.widows||2)-0,1),c=Math.max((a.inheritedProps.orphans||2)-0,1));let u=this.calculateClonedPaddingBorder(a),d=this.findLinePositions(i),h=this.footnoteEdge-u,f=this.getBoxDir(),g=this.getOffsetByRepetitiveElements(e);h-=f*g;let m=this.findFirstOverflowingEdgeAndCheckPoint(i);isNaN(m.edge)&&(m.edge=f*(1/0));let y=mt(d.length,N=>{let S=d[N];return this.vertical?S<h||S<=m.edge:S>h||S>=m.edge}),E=y<=0;E&&(y=mt(d.length,N=>this.vertical?d[N]<h:d[N]>h));let C=i[i.length-1].viewNode;if((C==null?void 0:C.parentElement.localName)==="viv-ts-inner"&&(C=C.parentElement.parentElement),(y===d.length&&C.nextSibling||y>=d.length-1&&C.parentElement.querySelector(".MJXc-display"))&&(l=0),y=Math.min(d.length-l,y),y<c)return null;h=d[y-1];let x;if(E?x=m.checkPoint:x=this.findAcceptableBreakInside(e.checkPoints,h,n),x){let N=this.getAfterEdgeOfBlockContainer(x);!isNaN(N)&&f*(h-N)>0&&(h=N),this.computedBlockSize=f*(h-this.beforeEdge)+g}return x}getAfterEdgeOfBlockContainer(e){let n=e;do n=n.parent;while(n&&n.inline);return n?(n=n.copy().modify(),n.after=!0,zn(n,this.clientLayout,0,this.vertical)):NaN}findFirstOverflowingEdgeAndCheckPoint(e){let n=e.findIndex(o=>o.overflow);if(n<0)return{edge:NaN,checkPoint:null};let s=e[n];return{edge:this.calculateEdge(null,e,n,s.boxOffset),checkPoint:s}}findEdgeBreakPosition(e){return this.computedBlockSize=e.computedBlockSize+this.getOffsetByRepetitiveElements(e),e.position}finishBreak(e,n,s){e.formattingContext;let i=new Wn().find(e.formattingContext).finishBreak(this,e,n,s);return i||(i=di.finishBreak(this,e,n,s)),i}findAcceptableBreakPosition(){let e=null,n=null,s=0,o=0;do{s=o,o=Number.MAX_VALUE;for(let i=this.breakPositions.length-1;i>=0&&!n;--i){e=this.breakPositions[i],n=e.findAcceptableBreak(this,s);let a=e.getMinBreakPenalty();a>s&&(o=Math.min(o,a))}}while(o>s&&!n&&this.forceNonfitting);return{breakPosition:n?e:null,nodeContext:n}}doFinishBreak(e,n,s,o){if(this.pageFloatLayoutContext.isInvalidated()||this.pageBreakType||!n)return v(e);let i=A("doFinishBreak"),a=!1;if(!e){if(this.forceNonfitting)return V.warn("Could not find any page breaks?!!"),this.skipTailEdges(n).then(l=>{l?(l=l.modify(),l.overflow=!1,this.finishBreak(l,a,!0).then(()=>{i.finish(l)})):i.finish(l)}),i.result();e=s,a=!0,this.computedBlockSize=o}return this.finishBreak(e,a,!0).then(()=>{i.finish(e)}),i.result()}isBreakable(e){for(let n=e;n;n=n.parent)if(Ns(n.viewNode))return!1;if(e.after)return!0;switch(e.sourceNode.namespaceURI){case"http://www.w3.org/2000/svg":return!1}return!e.flexContainer}zeroIndent(e){let n=e.toString();return n==""||n=="auto"||!!n.match(/^0+(.0*)?[^0-9]/)}checkOverflowAndSaveEdge(e,n){if(!e)return!1;for(let a=e;a;a=a.parent)if(Ns(a.viewNode))return!1;if(mn(e.viewNode))return!1;let s=zn(e,this.clientLayout,0,this.vertical),o=Gn(e,this.collectElementsOffset()),i=this.isOverflown(s+(this.vertical?-1:1)*o.minimum);if(this.isOverflown(s+(this.vertical?-1:1)*o.current)&&!this.nodeContextOverflowingDueToRepetitiveElements)this.nodeContextOverflowingDueToRepetitiveElements=e;else if(n){let a=s+this.getTrailingMarginEdgeAdjustment(n),l=this.footnoteEdge-this.getBoxDir()*o.current;s=this.vertical?Math.min(s,Math.max(a,l)):Math.max(s,Math.min(a,l))}return this.updateMaxReachedAfterEdge(s),i}checkOverflowAndSaveEdgeAndBreakPosition(e,n,s,o){if(!e||mn(e.viewNode))return!1;let i=this.checkOverflowAndSaveEdge(e,n);return(s||!i)&&this.saveEdgeBreakPosition(e,o,i),i}applyClearance(e){if(!e.viewNode.parentNode||e.floatReference!==ae.INLINE)return!1;let n=this.getComputedMargin(e.viewNode),s=e.viewNode.ownerDocument.createElement("div");this.vertical?(s.style.bottom="0px",s.style.width="1px",s.style.marginRight=`${n.right}px`):(s.style.right="0px",s.style.height="1px",s.style.marginTop=`${n.top}px`),e.viewNode.parentNode.insertBefore(s,e.viewNode);let o=this.clientLayout.getElementClientRect(s),i=this.getBeforeEdge(o),a=this.getBoxDir(),l=e.clearSide==="same"?e.floatSide:e.clearSide,c=/^(top|bottom|inside|outside|(block|inline)-(start|end))$/.test(l)?Uc(l,e.vertical,e.direction,this.layoutContext.page.side):l,u=c==="left"||c==="right"?e.direction==="rtl"==(c==="left")?"inline-end":"inline-start":c,d=this.pageFloatLayoutContext.getPageFloatClearEdge(u,this);switch(c){case"left":d=a*Math.max(d*a,this.leftFloatEdge*a);break;case"right":d=a*Math.max(d*a,this.rightFloatEdge*a);break;default:d=a*Math.max(d*a,Math.max(this.rightFloatEdge*a,this.leftFloatEdge*a))}if(i*a>=d*a)return e.viewNode.parentNode.removeChild(s),!1;{let h=Math.max(1,(d-i)*a);this.vertical?s.style.width=`${h}px`:s.style.height=`${h}px`,o=this.clientLayout.getElementClientRect(s);let f=this.getAfterEdge(o);if(!e.floatSide)if(this.vertical){let g=f-n.right-d;g>0==n.right>=0&&(g+=n.right),s.style.marginLeft=`${g}px`}else{let g=d-(f+n.top);g>0==n.top>=0&&(g+=n.top),s.style.marginBottom=`${g}px`}return e.clearSpacer=s,!0}}isBFC(e){return!!(nf(e)||tn.isInstanceOfRepetitiveElementsOwnerFormattingContext(e))}skipEdges(e,n,s){var y;let o=e.after?(y=e.parent)==null?void 0:y.formattingContext:e.formattingContext;if(o&&!this.isBFC(o))return v(e);let i=A("skipEdges"),a=!s&&n&&e&&e.after,l=s,c=null,u=[],d=[],h=!1;function f(){return!!s||!n&&Ie(l)&&!g()}function g(){var E;if(!c||e.floatSide)return!1;for(let C=c;C!=null&&C.parent;C=C.parent){let x=C.after?C.viewNode:(E=C.viewNode)==null?void 0:E.previousSibling;for(;x&&(ue(x,C.parent.whitespace)||Ns(x));)x=x.previousSibling;if(x)return!1}return!0}let m=()=>{e=u[0]||e,e.viewNode.parentNode.removeChild(e.viewNode),this.pageBreakType=l};return i.loopWithFrame(E=>{var C;for(;e;){e.formattingContext;let x=new Wn().find(e.formattingContext);do{if(!e.viewNode)break;if(e.inline&&e.viewNode.nodeType!=1){if(ue(e.viewNode,e.whitespace))break;if(!e.after){f()?m():this.checkOverflowAndSaveEdgeAndBreakPosition(c,null,!0,l)?(e=(this.stopAtOverflow&&c||e).modify(),e.overflow=!0):(e=e.modify(),e.breakBefore=l),E.breakLoop();return}}if(!e.after){if(e.floatSide&&(this.breakAtTheEdgeBeforeFloat=po(l)?l:null),x&&x.startNonInlineElementNode(e))break;if(e.clearSide&&this.applyClearance(e)&&n&&this.breakPositions.length===0&&this.saveEdgeBreakPosition(e.copy(),l,!1),!e.inline&&!e.repeatOnBreak&&(c?jc(c):this.breakPositions[this.breakPositions.length-1]instanceof Fs)&&this.saveEdgeBreakPosition(e.copy(),l,!1),!this.isBFC(e.formattingContext)||tn.isInstanceOfRepetitiveElementsOwnerFormattingContext(e.formattingContext)||this.isFloatNodeContext(e)||e.flexContainer||!e.nodeShadow&&!e.sourceNode.firstElementChild&&ue(e.sourceNode.firstChild,e.whitespace)){u.push(e.copy()),l=Ve(l,e.breakBefore),f()?m():(this.checkOverflowAndSaveEdgeAndBreakPosition(c,null,!0,l)||!this.layoutConstraint.allowLayout(e))&&(e=(this.stopAtOverflow&&c||e).modify(),e.overflow=!0),E.breakLoop();return}}if(e.viewNode.nodeType!=1)break;let S=e.viewNode.style;if(e.after){S.columnFill==="balance"&&S.getPropertyValue("--viv--saved-column-fill")==="auto"&&(S.columnFill="auto",S.removeProperty("--viv--saved-column-fill")),e.floatSide&&(l=l!=null?l:this.breakAtTheEdgeBeforeFloat,this.breakAtTheEdgeBeforeFloat=null);let w=e.sourceNode;if(w.localName==="svg"||w.localName==="math"||w.getAttribute("data-math-typeset")==="true"){h=!1,c=e.copy(),d.push(c),l=Ve(null,e.breakAfter),this.checkOverflowAndSaveEdgeAndBreakPosition(c,null,!this.stopAtOverflow,l);break}if(e.inline||x&&x.afterNonInlineElementNode(e,this.stopAtOverflow))break;if(h){if(f()){m(),E.breakLoop();return}u=[],n=!1,a=!1,l=null}h=!1,c=e.copy(),d.push(c),l=Ve(l,e.breakAfter),S&&!(this.zeroIndent(S.paddingBottom)&&this.zeroIndent(S.borderBottomWidth))&&(d=[c])}else{if(u.push(e.copy()),l=Ve(l,e.breakBefore),c&&Ie(l)&&Jh(c.viewNode,e.viewNode),(e.pageType!=((C=e.parent)==null?void 0:C.pageType)||!Ie(l))&&!this.layoutConstraint.allowLayout(e)&&(this.checkOverflowAndSaveEdgeAndBreakPosition(c,null,!this.stopAtOverflow,l),e=e.modify(),e.overflow=!0,this.stopAtOverflow)){E.breakLoop();return}let w=e.viewNode.localName;if(Yt[w]){f()?m():this.checkOverflowAndSaveEdgeAndBreakPosition(c,null,!0,l)&&(e=(this.stopAtOverflow&&c||e).modify(),e.overflow=!0),E.breakLoop();return}S&&!(this.zeroIndent(S.paddingTop)&&this.zeroIndent(S.borderTopWidth))&&(a=!1,d=[]),h=!0}}while(!1);let N=this.nextInTree(e,a);if(N.isPending()){N.then(S=>{e=S,E.continueLoop()});return}else e=N.get()}this.checkOverflowAndSaveEdgeAndBreakPosition(c,d,!this.stopAtOverflow,l)?c&&this.stopAtOverflow&&(e=c.modify(),e.overflow=!0):Ie(l)&&(this.pageBreakType=l),E.breakLoop()}).then(()=>{c&&(this.lastAfterPosition=c.toNodePosition()),i.finish(e)}),i.result()}skipTailEdges(e){let n=e.copy(),s=A("skipEdges"),o=null,i=!1;return s.loopWithFrame(a=>{for(;e;){do{if(!e.viewNode)break;if(e.inline&&e.viewNode.nodeType!=1){if(ue(e.viewNode,e.whitespace))break;if(!e.after){Ie(o)&&(this.pageBreakType=o),a.breakLoop();return}}if(!e.after&&(this.isFloatNodeContext(e)||e.flexContainer)){o=Ve(o,e.breakBefore),Ie(o)&&(this.pageBreakType=o),a.breakLoop();return}if(e.viewNode.nodeType!=1)break;let c=e.viewNode.style;if(e.after){if(i){if(Ie(o)){this.pageBreakType=o,a.breakLoop();return}o=null}i=!1,o=Ve(o,e.breakAfter)}else{o=Ve(o,e.breakBefore);let u=e.viewNode.localName;if(Yt[u]){Ie(o)&&(this.pageBreakType=o),a.breakLoop();return}if(c&&!(this.zeroIndent(c.paddingTop)&&this.zeroIndent(c.borderTopWidth))){a.breakLoop();return}}i=!0}while(!1);let l=this.layoutContext.nextInTree(e);if(l.isPending()){l.then(c=>{e=c,a.continueLoop()});return}else e=l.get()}n=null,a.breakLoop()}).then(()=>{s.finish(n)}),s.result()}layoutFloatOrFootnote(e){return Hn(e.floatReference)||e.floatSide==="footnote"?this.layoutPageFloat(e):this.layoutFloat(e)}layoutNext(e,n,s){let o=A("layoutNext");return this.skipEdges(e,n,s||null).then(i=>{if(e=i,!e||this.pageBreakType||this.stopByOverflow(e))o.finish(e);else{let a=e.formattingContext;new Wn().find(a).layout(e,this,n).thenFinish(o)}}),o.result()}clearOverflownViewNodes(e,n){if(e)for(let s=e.parent;e;e=s,s=s?s.parent:null){let o=(s||e).formattingContext;new Wn().find(o).clearOverflownViewNodes(this,s,e,n),n=!1}}initGeom(){let e=this.element.ownerDocument.createElement("div");e.style.position="absolute",e.style.top=`${this.paddingTop}px`,e.style.right=`${this.paddingRight}px`,e.style.bottom=`${this.paddingBottom}px`,e.style.left=`${this.paddingLeft}px`,this.element.appendChild(e);let n=this.clientLayout.getElementClientRect(e);this.element.removeChild(e);let s=this.originX+this.left+this.getInsetLeft(),o=this.originY+this.top+this.getInsetTop();this.box=new He(s,o,s+this.width,o+this.height),this.startEdge=n?this.vertical?this.rtl?n.bottom:n.top:this.rtl?n.right:n.left:0,this.endEdge=n?this.vertical?this.rtl?n.top:n.bottom:this.rtl?n.left:n.right:0,this.beforeEdge=n?this.vertical?n.right:n.top:0,this.afterEdge=n?this.vertical?n.left:n.bottom:0,this.leftFloatEdge=this.beforeEdge,this.rightFloatEdge=this.beforeEdge,this.bottommostFloatTop=this.beforeEdge,this.footnoteEdge=this.afterEdge,this.bands=eh(this.box,[this.getInnerShape()],this.getExclusions(),8,this.snapHeight,this.vertical),this.createFloats()}init(){this.chunkPositions=[],T(this.element,"width",`${this.width}px`),T(this.element,"height",`${this.height}px`),this.initGeom(),this.computedBlockSize=0,this.overflown=!1,this.pageBreakType=null,this.lastAfterPosition=null}saveEdgeBreakPosition(e,n,s){e.formattingContext;let o=e.copy(),i=new Wn().find(e.formattingContext),a=this.calculateClonedPaddingBorder(o),l=i.createEdgeBreakPosition(o,n,s,this.computedBlockSize+a);this.breakPositions.push(l)}saveBoxBreakPosition(e){let n=e[0].breakPenalty;if(n){let o=e[0];for(;o.parent&&o.inline;)o=o.parent;n=o.breakPenalty}let s=new Fs(e,n);this.breakPositions.push(s)}updateMaxReachedAfterEdge(e){if(!isNaN(e)){let n=this.getBoxDir()*(e-this.beforeEdge);this.computedBlockSize=Math.max(n,this.computedBlockSize)}}layout(e,n,s){if(this.chunkPositions.push(e),e.primary.after&&(this.lastAfterPosition=e.primary),this.stopAtOverflow&&this.overflown)return v(e);if(this.isFullWithPageFloats())return e.primary.after&&e.primary.steps.length===1?v(null):v(e);this.element.hasAttribute("data-vivliostyle-column")&&Qh(this);let o=A("layout");return this.openAllViews(e.primary).then(i=>{let a=null;if(i.viewNode)a=i.copy();else{let c=u=>{u.nodeContext.viewNode&&(a=u.nodeContext,this.layoutContext.removeEventListener("nextInTree",c))};this.layoutContext.addEventListener("nextInTree",c)}let l=new Qu(n,s);l.layout(i,this).then(c=>{this.doFinishBreak(c,l.context.overflownNodeContext,a,l.initialComputedBlockSize).then(u=>{let d=null;this.pseudoParent?d=v(null):d=this.doFinishBreakOfFragmentLayoutConstraints(u),d.then(()=>{if(this.pageFloatLayoutContext.isInvalidated()){o.finish(null);return}if(!u)o.finish(null);else{this.overflown=!0;let h=new ht(u.toNodePosition());o.finish(h)}})})})}),o.result()}isFullWithPageFloats(){return this.pageFloatLayoutContext.isColumnFullWithPageFloats(this)}getMaxBlockSizeOfPageFloats(){return this.pageFloatLayoutContext.getMaxBlockSizeOfPageFloats()}doFinishBreakOfFragmentLayoutConstraints(e){let n=A("doFinishBreakOfFragmentLayoutConstraints"),s=[].concat(this.fragmentLayoutConstraints);s.sort((i,a)=>i.getPriorityOfFinishBreak()-a.getPriorityOfFinishBreak());let o=0;return n.loop(()=>o<s.length?s[o++].finishBreak(e,this).thenReturn(!0):v(!1)).then(()=>{n.finish(!0)}),n.result()}doLayout(e,n,s){let o=A("doLayout"),i=null;return this.breakPositions=[],this.nodeContextOverflowingDueToRepetitiveElements=null,o.loopWithFrame(a=>{for(;e;){let l=!0;if(this.layoutNext(e,n,s||null).then(c=>{if(n=!1,s=null,this.nodeContextOverflowingDueToRepetitiveElements&&this.stopAtOverflow?(this.pageBreakType=null,e=this.nodeContextOverflowingDueToRepetitiveElements,e.overflow=!0):e=c,this.pageFloatLayoutContext.isInvalidated())a.breakLoop();else if(this.pageBreakType)a.breakLoop();else if(e&&this.stopByOverflow(e)){i=e;let u=this.findAcceptableBreakPosition();e=u.nodeContext,u.breakPosition&&u.breakPosition.breakPositionChosen(this),a.breakLoop()}else l?l=!1:a.continueLoop()}),l){l=!1;return}}this.computedBlockSize+=this.getOffsetByRepetitiveElements(),a.breakLoop()}).then(()=>{o.finish({nodeContext:e,overflownNodeContext:i})}),o.result()}redoLayout(){let e=this.chunkPositions,n=this.element.lastChild;for(;n!=this.last;){let l=n.previousSibling;this.element===n.parentNode&&this.layoutContext.isPseudoelement(n)||this.element.removeChild(n),n=l}this.killFloats(),this.init();let s=A("redoLayout"),o=0,i=null,a=!0;return s.loopWithFrame(l=>{if(o<e.length){let c=e[o++];this.layout(c,a).then(u=>{a=!1,u?(i=u,l.breakLoop()):l.continueLoop()});return}l.breakLoop()}).then(()=>{s.finish(i)}),s.result()}saveDistanceToBlockEndFloats(){let e=this.pageFloatLayoutContext.getBlockStartEdgeOfBlockEndFloats();e>0&&isFinite(e)&&(this.blockDistanceToBlockEndFloats=this.getBoxDir()*(e-this.beforeEdge-this.computedBlockSize))}collectElementsOffset(){let e=[];for(let n=this;n;n=n.pseudoParent)n.fragmentLayoutConstraints.forEach(s=>{if(tn.isInstanceOfRepetitiveElementsOwnerLayoutConstraint(s)){let o=s.getRepetitiveElements();e.push(o)}if(si.isInstanceOfAfterIfContinuesLayoutConstraint(s)){let o=s.getRepetitiveElements();e.push(o)}Dt.isInstanceOfTableRowLayoutConstraint(s)&&s.getElementsOffsetsForTableCell(this).forEach(o=>{e.push(o)})});return e}},Os=class{constructor(t,e,n){p(this,"startNodeContexts",[]);p(this,"column");this.column=Object.create(t),this.column.element=e,this.column.layoutContext=t.layoutContext.clone(),this.column.stopAtOverflow=!1,this.column.flowRootFormattingContext=n.formattingContext,this.column.pseudoParent=t;let s=this.column.calculateClonedPaddingBorder(n);this.column.footnoteEdge=this.column.footnoteEdge-s;let o=this;this.column.openAllViews=function(i){return Bs.prototype.openAllViews.call(this,i).thenAsync(a=>(o.startNodeContexts.push(a.copy()),v(a)))}}layout(t,e){return this.column.layout(t,e)}findAcceptableBreakPosition(t){let e=this.column.findAcceptableBreakPosition();if(t){let n=this.startNodeContexts[0].copy(),s=new nn(n,null,n.overflow,0);if(s.findAcceptableBreak(this.column,0),!e.nodeContext)return{breakPosition:s,nodeContext:n}}return e}finishBreak(t,e,n){return this.column.finishBreak(t,e,n)}doFinishBreakOfFragmentLayoutConstraints(t){this.column.doFinishBreakOfFragmentLayoutConstraints(t)}isStartNodeContext(t){let e=this.startNodeContexts[0];return e.viewNode===t.viewNode&&e.after===t.after&&e.offsetInNode===t.offsetInNode}isLastAfterNodeContext(t){return Mt(t.toNodePosition(),this.column.lastAfterPosition)}getColumnElement(){return this.column.element}getColumn(){return this.column}},Ao=class{breakTextNode(t,e,n,s,o,i){if(e.after)e.offsetInNode=t.length;else{let a=n-e.boxOffset,l=t.data;l.charCodeAt(a)==173?a=this.breakAfterSoftHyphen(t,l,a,e):a=this.breakAfterOtherCharacter(t,l,a,e),a>0&&(e=this.updateNodeContext(e,a,t))}return e}breakAfterSoftHyphen(t,e,n,s){let i=/[\u0620\u0626\u0628\u062A-\u062E\u0633-\u0647\u0649\u064A\u066E\u066F\u0678-\u0687\u069A-\u06BF\u06C1\u06C2\u06CC\u06CE\u06D0\u06D1\u06FA-\u06FC\u06FF\u0712-\u0714\u071A-\u071D\u071F-\u0727\u0729\u072B\u072D\u072E\u074E-\u0758\u075C-\u076A\u076D-\u0770\u0772\u0775-\u0777\u077A-\u077F\u07CA-\u07EA\u07FA\u0841-\u0845\u0848\u084A-\u0853\u0855\u0860\u0862-\u0865\u0868\u0883-\u0886\u0889-\u088D\u08A0-\u08A9\u08AF\u08B0\u08B3-\u08B8\u08BA-\u08C8\u1807\u180A\u1820-\u1878\u1887-\u18A8\u18AA\u200D\uA840-\uA871\u{10AC0}-\u{10AC4}\u{10AD3}-\u{10AD6}\u{10AD8}-\u{10ADC}\u{10ADE}-\u{10AE0}\u{10AEB}-\u{10AEE}\u{10B80}\u{10B82}\u{10B86}-\u{10B88}\u{10B8A}\u{10B8B}\u{10B8D}\u{10B90}\u{10BAD}\u{10BAE}\u{10D01}-\u{10D21}\u{10D23}\u{10EC3}\u{10EC4}\u{10F30}-\u{10F32}\u{10F34}-\u{10F44}\u{10F51}-\u{10F53}\u{10F70}-\u{10F73}\u{10F76}-\u{10F81}\u{10FB0}\u{10FB2}\u{10FB3}\u{10FB8}\u{10FBB}\u{10FBC}\u{10FBE}\u{10FBF}\u{10FC1}\u{10FC4}\u{10FCA}\u{1E900}-\u{1E943}]\p{Mn}*$/u.test(e.slice(0,n))?"\u200D":"";if(t.replaceData(n,e.length-n,s.breakWord?"":i+Vf(s)),i){let a=s.preprocessedTextContent[0][1];s.preprocessedTextContent[0][1]=a.slice(0,n+1)+i+a.slice(n+1)}return n+1}breakAfterOtherCharacter(t,e,n,s){let o=e.charAt(n);n++;let i=e.charAt(n);return t.replaceData(n,e.length-n,!s.breakWord&&Ll(o)&&Ll(i)?Vf(s):""),n}updateNodeContext(t,e,n){return t=t.modify(),t.offsetInNode+=e,t.breakBefore=null,t}};p(Ao,"instance");Ao.instance=new Ao;function Vf(r){return r.hyphenateCharacter||r.parent&&r.parent.hyphenateCharacter||"-"}var Qu=class extends $n{constructor(e,n){super();this.leadingEdge=e;p(this,"breakAfter");p(this,"initialPageBreakType",null);p(this,"initialComputedBlockSize",0);p(this,"initialOverflown",!1);p(this,"context",{overflownNodeContext:null});this.breakAfter=n||null}resolveLayoutMode(e){return new Ju(this.leadingEdge,this.breakAfter,this.context)}prepareLayout(e,n){n.fragmentLayoutConstraints=[],n.pseudoParent||of()}clearNodes(e){super.clearNodes(e);let n=e;for(;n;){let s=n.viewNode;s&&ia(s.parentNode,s),n=n.parent}}saveState(e,n){super.saveState(e,n),this.initialPageBreakType=n.pageBreakType,this.initialComputedBlockSize=n.computedBlockSize,this.initialOverflown=n.overflown}restoreState(e,n){super.restoreState(e,n),n.pageBreakType=this.initialPageBreakType,n.computedBlockSize=this.initialComputedBlockSize,n.overflown=this.initialOverflown}},Ju=class{constructor(t,e,n){this.leadingEdge=t;this.breakAfter=e;this.context=n}doLayout(t,e){let n=A("DefaultLayoutMode.doLayout");return LC(t,e).then(()=>{e.doLayout(t,this.leadingEdge,this.breakAfter).then(s=>{this.context.overflownNodeContext=s.overflownNodeContext,n.finish(s.nodeContext)})}),n.result()}accept(t,e){return e.pageFloatLayoutContext.isInvalidated()||e.pageBreakType||e.fragmentLayoutConstraints.length<=0?!0:e.fragmentLayoutConstraints.every(n=>n.allowLayout(t,this.context.overflownNodeContext,e))}postLayout(t,e,n,s){return s||(s=!n.fragmentLayoutConstraints.some(i=>i.nextCandidate(t))),n.fragmentLayoutConstraints.forEach(o=>{o.postLayout(s,t,e,n)}),s}},ed=class extends Bs{constructor(e,n,s,o,i,a,l){super(n,s,o,i,a);this.floatSide=e;this.parentContainer=l;p(this,"rootViewNodes",[]);p(this,"floatMargins",[]);p(this,"adjustContentRelativeSize",!0)}openAllViews(e){return super.openAllViews(e).thenAsync(n=>(n&&this.fixFloatSizeAndPosition(n),v(n)))}convertPercentageSizesToPx(e){let n=this.parentContainer.getPaddingRect(),s=n.x2-n.x1,o=n.y2-n.y1;function i(a,l){a.forEach(c=>{let u=gt(e,c);if(u&&u.charAt(u.length-1)==="%"){let d=parseFloat(u),h=l*d/100;T(e,c,`${h}px`)}})}i(["width","max-width","min-width"],s),i(["height","max-height","min-height"],o),i(["margin-top","margin-right","margin-bottom","margin-left","padding-top","padding-right","padding-bottom","padding-left"],this.vertical?o:s),["margin-top","margin-right","margin-bottom","margin-left"].forEach(a=>{gt(e,a)==="auto"&&T(e,a,"0")})}fixFloatSizeAndPosition(e){for(;e.parent;)e=e.parent;e.viewNode.nodeType;let n=e.viewNode;if(this.rootViewNodes.push(n),this.adjustContentRelativeSize&&this.convertPercentageSizesToPx(n),this.floatMargins.push(this.getComputedMargin(n)),this.adjustContentRelativeSize){let s=this.floatSide;if(this.parentContainer.vertical){if(s==="block-end"||s==="left"){let i=gt(n,"height");i!==""&&i!=="auto"&&T(n,"margin-top","auto")}}else if(s==="block-end"||s==="bottom"){let i=gt(n,"width");i!==""&&i!=="auto"&&T(n,"margin-left","auto")}}}getContentInlineSize(){return Math.max.apply(null,this.rootViewNodes.map((e,n)=>{let s=this.clientLayout.getElementClientRect(e),o=this.floatMargins[n];return this.vertical?o.top+s.height+o.bottom:o.left+s.width+o.right}))}};var Ht=class{constructor(t,e){this.parent=t;this.rootSourceNode=e;p(this,"formattingContextType","RepetitiveElementsOwner");p(this,"isRoot",!1);p(this,"repetitiveElements",null)}getName(){return"Repetitive elements owner formatting context (RepetitiveElementsOwnerFormattingContext)"}isFirstTime(t,e){return e}getParent(){return this.parent}getRepetitiveElements(){return this.repetitiveElements}getRootViewNode(t){let e=this.getRootNodeContext(t);return e?e.viewNode:null}getRootNodeContext(t){do if(!t.belongsTo(this)&&t.sourceNode===this.rootSourceNode)return t;while(t=t.parent);return null}initializeRepetitiveElements(t){if(this.repetitiveElements)return;la.some(n=>n.root===this.rootSourceNode?(this.repetitiveElements=n.elements,!0):!1)||(this.repetitiveElements=new nd(t,this.rootSourceNode),la.push({root:this.rootSourceNode,elements:this.repetitiveElements}))}saveState(){}restoreState(t){}},nd=class{constructor(t,e){this.vertical=t;this.ownerSourceNode=e;p(this,"headerSourceNode",null);p(this,"footerSourceNode",null);p(this,"headerViewNode",null);p(this,"footerViewNode",null);p(this,"headerNodePosition",null);p(this,"footerNodePosition",null);p(this,"headerHeight",0);p(this,"footerHeight",0);p(this,"isSkipHeader",!1);p(this,"isSkipFooter",!1);p(this,"enableSkippingFooter",!0);p(this,"enableSkippingHeader",!0);p(this,"doneInitialLayout",!1);p(this,"firstContentSourceNode",null);p(this,"lastContentSourceNode",null);p(this,"affectedNodeCache",[]);p(this,"afterLastContentNodeCache",[]);p(this,"allowInsert",!1);p(this,"allowInsertRepeatitiveElements")}setHeaderNodeContext(t){this.headerNodePosition||(this.headerNodePosition=Es(t,0),this.headerSourceNode=t.sourceNode,this.headerViewNode=t.viewNode)}setFooterNodeContext(t){this.footerNodePosition||(this.footerNodePosition=Es(t,0),this.footerSourceNode=t.sourceNode,this.footerViewNode=t.viewNode)}updateHeight(t){this.headerViewNode&&(this.headerHeight=ui(this.headerViewNode,t,this.vertical),this.headerViewNode=null),this.footerViewNode&&(this.footerHeight=ui(this.footerViewNode,t,this.vertical),this.footerViewNode=null)}prepareLayoutFragment(){this.isSkipHeader=this.isSkipFooter=!1,this.enableSkippingFooter=!0,this.enableSkippingHeader=!0}appendHeaderToFragment(t,e,n){return!this.headerNodePosition||this.isSkipHeader?v(!0):this.appendElementToFragment(this.headerNodePosition,t,e,n)}appendFooterToFragment(t,e,n){return!this.footerNodePosition||this.isSkipFooter?v(!0):this.appendElementToFragment(this.footerNodePosition,t,e,n)}appendElementToFragment(t,e,n,s){let o=e.viewNode.ownerDocument,i=e.viewNode,a=o.createElement("div");i.appendChild(a);let l=new Os(s,a,e),c=l.getColumn().pageBreakType;return l.getColumn().pageBreakType=null,this.allowInsertRepeatitiveElements=!0,l.layout(new ht(t),!0).thenAsync(()=>(this.allowInsertRepeatitiveElements=!1,i.removeChild(a),this.moveChildren(a,i,n),l.getColumn().pageBreakType=c,v(!0)))}moveChildren(t,e,n){if(e)for(;t.firstChild;){let s=t.firstChild;t.removeChild(s),s.setAttribute(_t,"1"),n?e.insertBefore(s,n):e.appendChild(s)}}calculateOffset(t){let e=0;return t&&!this.affectTo(t)||((!this.isSkipFooter||t&&this.isAfterLastContent(t))&&(e+=this.footerHeight),this.isSkipHeader||(e+=this.headerHeight)),e}calculateMinimumOffset(t){let e=0;return t&&!this.affectTo(t)||(!this.enableSkippingFooter&&t&&this.isAfterLastContent(t)&&(e+=this.footerHeight),this.enableSkippingHeader||(e+=this.headerHeight)),e}isAfterLastContent(t){return this.findResultFromCache(t,this.afterLastContentNodeCache,e=>this.isAfterNodeContextOf(this.lastContentSourceNode,t,!1))}affectTo(t){return this.findResultFromCache(t,this.affectedNodeCache,e=>this.isAfterNodeContextOf(this.ownerSourceNode,t,!0))}findResultFromCache(t,e,n){let s=e.filter(o=>o.nodeContext.sourceNode===t.sourceNode&&o.nodeContext.after===t.after);if(s.length>0)return s[0].result;{let o=n(t);return e.push({nodeContext:t,result:o}),o}}isAfterNodeContextOf(t,e,n){let s=[];for(let o=t;o;o=o.parentNode){if(e.sourceNode===o)return e.after;s.push(o)}for(let o=e.sourceNode;o;o=o.parentNode){let i=s.indexOf(o);if(i>=0)return n?i===0:!1;for(let a=o;a;a=a.previousElementSibling)if(s.includes(a))return!0}return e.after}isFirstContentNode(t){return t&&this.firstContentSourceNode===t.sourceNode}isEnableToUpdateState(){return!!(!this.isSkipFooter&&this.enableSkippingFooter&&this.footerNodePosition||!this.isSkipHeader&&this.enableSkippingHeader&&this.headerNodePosition)}updateState(){!this.isSkipFooter&&this.enableSkippingFooter&&this.footerNodePosition?this.isSkipFooter=!0:!this.isSkipHeader&&this.enableSkippingHeader&&this.headerNodePosition&&(this.isSkipHeader=!0)}preventSkippingHeader(){this.isSkipHeader=!1,this.enableSkippingHeader=!1}preventSkippingFooter(){this.isSkipFooter=!1,this.enableSkippingFooter=!1}isHeaderRegistered(){return!!this.headerNodePosition}isFooterRegistered(){return!!this.footerNodePosition}isHeaderSourceNode(t){return this.headerSourceNode===t}isFooterSourceNode(t){return this.footerSourceNode===t}},Si=class{constructor(t){this.formattingContext=t}accept(t,e){return!!t}postLayout(t,e,n,s){let o=this.formattingContext.getRepetitiveElements();return o&&(n.clientLayout,o.doneInitialLayout||(o.updateHeight(n),o.doneInitialLayout=!0)),s}},Ni=class{constructor(t){this.formattingContext=t}accept(t,e){return!0}postLayout(t,e,n,s){return s}},sd=class extends Si{constructor(e,n){super(e);this.processor=n}doLayout(e,n){return this.processor.doInitialLayout(e,n)}accept(e,n){return!1}},od=class extends Ni{constructor(e,n){super(e);this.processor=n}doLayout(e,n){return!e.belongsTo(this.formattingContext)&&!e.after&&n.fragmentLayoutConstraints.unshift(new Lo(e)),this.processor.doLayout(e,n)}},Lo=class r{constructor(t){p(this,"flagmentLayoutConstraintType","RepetitiveElementsOwner");p(this,"nodeContext");let e=Sn(t.formattingContext);this.nodeContext=e.getRootNodeContext(t)}allowLayout(t,e,n){let s=this.getRepetitiveElements();return!s||mn(this.nodeContext.viewNode)||!s.isEnableToUpdateState()?!0:!(e&&!t||t&&t.overflow)}nextCandidate(t){let e=this.getRepetitiveElements();return e&&e.isEnableToUpdateState()?(e.updateState(),!0):!1}postLayout(t,e,n,s){let o=this.getRepetitiveElements();o&&t&&s.stopAtOverflow&&(e==null||o.isAfterLastContent(e))&&o.preventSkippingFooter()}finishBreak(t,e){let n=Sn(this.nodeContext.formattingContext),s=this.getRepetitiveElements();if(!s)return v(!0);let o=this.nodeContext;return VC(n,o,e).thenAsync(()=>FC(n,o,e).thenAsync(()=>(s.prepareLayoutFragment(),v(!0))))}getRepetitiveElements(){return Sn(this.nodeContext.formattingContext).getRepetitiveElements()}equalsTo(t){return t instanceof r?Sn(this.nodeContext.formattingContext)===Sn(t.nodeContext.formattingContext):!1}getPriorityOfFinishBreak(){return 10}},id=class extends $n{constructor(e,n){super();this.formattingContext=e;this.processor=n}resolveLayoutMode(e){let n=this.formattingContext.getRepetitiveElements();return!e.belongsTo(this.formattingContext)&&!n.doneInitialLayout?new sd(this.formattingContext,this.processor):(!e.belongsTo(this.formattingContext)&&!e.after&&n&&n.preventSkippingHeader(),new od(this.formattingContext,this.processor))}},rd=class extends bn{constructor(e,n){super();this.formattingContext=e;this.column=n}startNonInlineElementNode(e){let n=this.formattingContext,s=e.nodeContext,o=n.getRepetitiveElements();if(s.parent&&n.rootSourceNode===s.parent.sourceNode){switch(s.repeatOnBreak){case"header":if(o.isHeaderRegistered())s.repeatOnBreak="none";else return o.setHeaderNodeContext(s),v(!0);break;case"footer":if(o.isFooterRegistered())s.repeatOnBreak="none";else return o.setFooterNodeContext(s),v(!0);break}o.firstContentSourceNode||(o.firstContentSourceNode=s.sourceNode)}return bn.prototype.startNonInlineElementNode.call(this,e)}afterNonInlineElementNode(e){let n=this.formattingContext,s=e.nodeContext;return s.sourceNode===n.rootSourceNode&&(n.getRepetitiveElements().lastContentSourceNode=e.lastAfterNodeContext&&e.lastAfterNodeContext.sourceNode,e.break=!0),s.repeatOnBreak==="header"||s.repeatOnBreak==="footer"?v(!0):bn.prototype.afterNonInlineElementNode.call(this,e)}};var ad=class extends sn{layout(t,e,n){if(e.isFloatNodeContext(t))return e.layoutFloatOrFootnote(t);let s=Sn(t.formattingContext);return s.getRootViewNode(t)?(n&&ld(t.parent,e),t.belongsTo(s)?sn.prototype.layout.call(this,t,e,n):new id(s,this).layout(t,e)):e.buildDeepElementView(t)}startNonInlineElementNode(t){let n=BC(t).getRepetitiveElements();return n&&!n.allowInsertRepeatitiveElements&&(n.isHeaderSourceNode(t.sourceNode)||n.isFooterSourceNode(t.sourceNode))&&t.viewNode.parentNode.removeChild(t.viewNode),!1}doInitialLayout(t,e){let n=Sn(t.formattingContext),s=A("BlockLayoutProcessor.doInitialLayout");return this.layoutEntireBlock(t,e).thenFinish(s),s.result()}layoutEntireBlock(t,e){let n=Sn(t.formattingContext),s=new rd(n,e);return new ws(s,e.layoutContext).iterate(t)}doLayout(t,e){let n=Sn(t.formattingContext),s=A("doLayout"),o=e.layoutContext.nextInTree(t,!1);return td(o,e).then(i=>{let a=i;s.loopWithFrame(l=>{for(;a;){let c=!0;if(e.layoutNext(a,!1).then(u=>{a=u,e.pageFloatLayoutContext.isInvalidated()||e.pageBreakType||a&&e.stopByOverflow(a)||a&&a.after&&a.sourceNode==n.rootSourceNode?l.breakLoop():c?c=!1:l.continueLoop()}),c){c=!1;return}}l.breakLoop()}).then(()=>{s.finish(a)})}),s.result()}finishBreak(t,e,n,s){return sn.prototype.finishBreak.call(this,t,e,n,s)}clearOverflownViewNodes(t,e,n,s){sn.prototype.clearOverflownViewNodes(t,e,n,s)}};function IC(r,t){for(let e=r;e;e=e.parent){let n=e.formattingContext;n&&n instanceof Ht&&!e.belongsTo(n)&&t(n,e)}}function ld(r,t){r&&IC(r.after?r.parent:r,(e,n)=>{Dt.isInstanceOfTableFormattingContext(e)||t.fragmentLayoutConstraints.push(new Lo(n))})}function VC(r,t,e){let n=r.getRepetitiveElements();if(n){let s=r.getRootNodeContext(t);if(s.viewNode){let o=s.viewNode.firstChild;return n.appendHeaderToFragment(s,o,e)}}return v(!0)}function FC(r,t,e){let n=r.getRepetitiveElements();if(n&&!n.isSkipFooter){let s=r.getRootNodeContext(t);if(s.viewNode)return n.appendFooterToFragment(s,null,e)}return v(!0)}function BC(r){let t=r.formattingContext;return!t||!(t instanceof Ht)?null:t}function Sn(r){return r instanceof Ht,r}var OC=new ad;Ue("RESOLVE_LAYOUT_PROCESSOR",r=>r instanceof Ht&&!Dt.isInstanceOfTableFormattingContext(r)?OC:null);var Pa=class{constructor(t,e){this.rowIndex=t;this.sourceNode=e;p(this,"cells",[])}addCell(t){this.cells.push(t)}getMinimumHeight(){return Math.min.apply(null,this.cells.map(t=>t.height))}},ud=class{constructor(t,e,n){this.rowIndex=t;this.columnIndex=e;p(this,"viewElement");p(this,"colSpan");p(this,"rowSpan");p(this,"height",0);p(this,"anchorSlot",null);this.viewElement=n,this.colSpan=n.colSpan||1,this.rowSpan=n.rowSpan||1}setHeight(t){this.height=t}setAnchorSlot(t){this.anchorSlot=t}},dd=class{constructor(t,e,n){this.rowIndex=t;this.columnIndex=e;this.cell=n}},pd=class{constructor(t,e,n){this.column=t;this.cellNodeContext=n;p(this,"pseudoColumn");p(this,"empty",!1);this.pseudoColumn=new Os(t,e,n)}findAcceptableBreakPosition(){let t=this.cellNodeContext.viewNode,{verticalAlign:e,alignContent:n}=t.style;e!=="top"&&e!=="baseline"&&T(t,"vertical-align","top"),n&&n!=="normal"&&T(t,"align-content","normal");let s=this.pseudoColumn.findAcceptableBreakPosition(!0);return T(t,"vertical-align",e),n&&n!=="normal"&&T(t,"align-content",n),s}},hd=class{constructor(t,e){this.viewNode=t;this.side=e}},fd=class extends nn{constructor(e,n,s,o){super(e,n,s,o);p(this,"formattingContext");p(this,"acceptableCellBreakPositions",null);p(this,"rowIndex",null);this.formattingContext=e.formattingContext}findAcceptableBreak(e,n){let s=super.findAcceptableBreak(e,n);return n<this.getMinBreakPenalty()?null:this.getAcceptableCellBreakPositions().every(i=>!!i.nodeContext)?s:null}getMinBreakPenalty(){let e=super.getMinBreakPenalty();this.getAcceptableCellBreakPositions().forEach(s=>{e+=s.breakPosition.getMinBreakPenalty()});let n=this.getCellFragments();return e+=Math.max(0,...n.map(s=>s.cellNodeContext.breakPenalty)),e}getAcceptableCellBreakPositions(){if(!this.acceptableCellBreakPositions){let e=this.formattingContext,n=this.getCellFragments();this.acceptableCellBreakPositions=n.map(s=>s.findAcceptableBreakPosition())}return this.acceptableCellBreakPositions}getRowIndex(){return this.rowIndex!=null?this.rowIndex:this.rowIndex=this.formattingContext.findRowIndexBySourceNode(this.position.sourceNode)}getCellFragments(){return this.formattingContext.getRowSpanningCellsOverflowingTheRow(this.getRowIndex()).map(this.formattingContext.getCellFragmentOfCell,this.formattingContext)}},gd=class extends Ts{constructor(e,n,s){super();this.rowIndex=e;this.beforeNodeContext=n;this.formattingContext=s;p(this,"acceptableCellBreakPositions",null)}findAcceptableBreak(e,n){if(this!==e.breakPositions[0]&&n<this.getMinBreakPenalty())return null;let s=this.getCellFragments(),o=this.getAcceptableCellBreakPositions(),i=o.every(a=>!!a.nodeContext)&&o.some((a,l)=>{let c=s[l].pseudoColumn,u=a.nodeContext;return!c.isStartNodeContext(u)&&!c.isLastAfterNodeContext(u)});return this.beforeNodeContext.overflow=o.some(a=>a.nodeContext&&a.nodeContext.overflow),i?this.beforeNodeContext:null}getMinBreakPenalty(){let n=this.formattingContext.getRowByIndex(this.rowIndex),s=this.beforeNodeContext.breakPenalty,o=this.getAcceptableCellBreakPositions(),i=this.getCellFragments();s+=Math.max(0,...i.map(l=>l.cellNodeContext.breakPenalty));let a=o.some((l,c)=>l.breakPosition instanceof Fs&&i[c].cellNodeContext.sourceNode.rowSpan>1);return o.forEach((l,c)=>{let u=l.breakPosition.getMinBreakPenalty();a&&l.breakPosition instanceof nn&&l.breakPosition.overflows&&u>=3&&(i[c].column.checkOverflowAndSaveEdge(l.nodeContext,null)||(u-=3)),s+=u}),s}getAcceptableCellBreakPositions(){if(!this.acceptableCellBreakPositions){let e=this.getCellFragments();this.acceptableCellBreakPositions=e.map(n=>n.findAcceptableBreakPosition())}return this.acceptableCellBreakPositions}getCellFragments(){return this.formattingContext.getCellsFallingOnRow(this.rowIndex).map(this.formattingContext.getCellFragmentOfCell,this.formattingContext)}},Kn=class extends Ht{constructor(e,n){super(e,n);this.tableSourceNode=n;p(this,"formattingContextType","Table");p(this,"vertical",!1);p(this,"columnCount",-1);p(this,"tableWidth",0);p(this,"captions",[]);p(this,"colGroups",null);p(this,"colWidths",null);p(this,"inlineBorderSpacing",0);p(this,"rows",[]);p(this,"slots",[]);p(this,"cellFragments",[]);p(this,"lastRowViewNode",null);p(this,"cellBreakPositions",[]);p(this,"repetitiveElements",null)}getName(){return"Table formatting context (Table.TableFormattingContext)"}isFirstTime(e,n){if(!n)return n;switch(e.display){case"table-row":return this.cellBreakPositions.length===0;case"table-cell":return!this.cellBreakPositions.some(s=>s.cellNodePosition.steps[0].node===e.sourceNode);default:return n}}getParent(){return this.parent}finishFragment(){this.cellFragments=[]}addRow(e,n){this.rows[e]=n}getRowSlots(e){let n=this.slots[e];return n||(n=this.slots[e]=[]),n}addCell(e,n){let s=this.rows[e];s||(this.addRow(e,new Pa(e,null)),s=this.rows[e]),s.addCell(n);let o=e+n.rowSpan,i=this.getRowSlots(e),a=0;for(;i[a];)a++;for(;e<o;e++){i=this.getRowSlots(e);for(let l=a;l<a+n.colSpan;l++){let c=i[l]=new dd(e,l,n);n.anchorSlot||n.setAnchorSlot(c)}}}getRowByIndex(e){let n=this.rows[e];return n}findRowIndexBySourceNode(e){return this.rows.findIndex(n=>e===n.sourceNode)}addCellFragment(e,n,s){let o=this.cellFragments[e];o||(o=this.cellFragments[e]=[]),o[n]=s}getCellsFallingOnRow(e){return this.getRowSlots(e).reduce((s,o)=>o.cell!==s[s.length-1]?s.concat(o.cell):s,[])}getRowSpanningCellsOverflowingTheRow(e){return this.getCellsFallingOnRow(e).filter(n=>n.rowIndex+n.rowSpan-1>e)}getCellFragmentOfCell(e){return this.cellFragments[e.rowIndex]&&this.cellFragments[e.rowIndex][e.columnIndex]}getColumnCount(){return this.columnCount<0&&(this.columnCount=Math.max.apply(null,this.rows.map(e=>e.cells.reduce((n,s)=>n+s.colSpan,0)))),this.columnCount}updateCellSizes(e){this.rows.forEach(n=>{n.cells.forEach(s=>{let o=bo(e,s.viewElement,this.vertical);s.viewElement=null,s.setHeight(this.vertical?o.width:o.height)})})}findCellFromColumn(e){if(!e)return null;let n=null,s=0,o=0;e:for(s=0;s<this.cellFragments.length;s++)if(this.cellFragments[s]){for(o=0;o<this.cellFragments[s].length;o++)if(this.cellFragments[s][o]&&e===this.cellFragments[s][o].pseudoColumn.getColumn()){n=this.rows[s].cells[o];break e}}if(!n)return null;for(;s<this.slots.length;s++)for(;o<this.slots[s].length;o++){let i=this.slots[s][o];if(i.cell===n)return{rowIndex:i.rowIndex,columnIndex:i.columnIndex}}return null}collectElementsOffsetOfUpperCells(e){let n=[];return this.slots.reduce((s,o,i)=>{if(i>=e.rowIndex)return s;let a=o[e.columnIndex]&&this.getCellFragmentOfCell(o[e.columnIndex].cell);return!a||n.includes(a)||(this.collectElementsOffsetFromColumn(a.pseudoColumn.getColumn(),s),n.push(a)),s},[])}collectElementsOffsetOfHighestColumn(){let e=[];return this.rows.forEach(n=>{n.cells.forEach((s,o)=>{e[o]||(e[o]={collected:[],elements:[]});let i=e[o],a=this.getCellFragmentOfCell(s);!a||i.collected.includes(a)||(this.collectElementsOffsetFromColumn(a.pseudoColumn.getColumn(),i.elements),i.collected.push(a))})}),[new md(e.map(n=>n.elements))]}collectElementsOffsetFromColumn(e,n){e.fragmentLayoutConstraints.forEach(s=>{if(tn.isInstanceOfRepetitiveElementsOwnerLayoutConstraint(s)){let o=s.getRepetitiveElements();n.push(o)}Dt.isInstanceOfTableRowLayoutConstraint(s)&&s.getElementsOffsetsForTableCell(null).forEach(o=>{n.push(o)})})}saveState(){return[].concat(this.cellBreakPositions)}restoreState(e){this.cellBreakPositions=e}},md=class{constructor(t){this.repeatitiveElementsInColumns=t}calculateOffset(t){return this.calculateMaxOffsetOfColumn(t,e=>e.current)}calculateMinimumOffset(t){return this.calculateMaxOffsetOfColumn(t,e=>e.minimum)}calculateMaxOffsetOfColumn(t,e){let n=0;return this.repeatitiveElementsInColumns.forEach(s=>{let o=Gn(t,s);n=Math.max(n,e(o))}),n}};function Rt(r){return r instanceof Kn,r}function DC(r){return r==="table-row-group"||r==="table-header-group"||r==="table-footer-group"}function MC(r){return r==="table"||r==="inline-table"}function Df(r){return DC(r)||MC(r)}function Mf(r,t,e){let n=r.nodeContext,s=n.display,o=n.parent?n.parent.display:null,i=!1;if(o==="inline-table"&&!(n.formattingContext instanceof Kn)){for(let l=n.parent;l;l=l.parent)if(l.formattingContext instanceof Kn){i=l.formattingContext===t;break}}return i||s==="table-row"&&!Df(o)||s==="table-cell"&&o!=="table-row"&&!Df(o)||n.formattingContext instanceof Kn&&n.formattingContext!==t?e.buildDeepElementView(n).thenAsync(l=>(r.nodeContext=l,v(!0))):null}var Cd=class extends bn{constructor(e,n){super();this.formattingContext=e;this.column=n;p(this,"rowIndex",-1);p(this,"columnIndex",0);p(this,"inRow",!1);p(this,"checkPoints",[]);p(this,"inHeaderOrFooter",!1)}startNonInlineElementNode(e){let n=this.formattingContext,s=Mf(e,n,this.column);if(s)return s;this.postLayoutBlockContents(e);let o=e.nodeContext,i=o.display,a=n.getRepetitiveElements();switch(i){case"table":n.inlineBorderSpacing=o.inlineBorderSpacing;break;case"table-caption":{let l=new hd(o.viewNode,o.captionSide);n.captions.push(l);break}case"table-header-group":return a.isHeaderRegistered()||(this.inHeaderOrFooter=!0,a.setHeaderNodeContext(o)),v(!0);case"table-footer-group":return a.isFooterRegistered()||(this.inHeaderOrFooter=!0,a.setFooterNodeContext(o)),v(!0);case"table-row":this.inHeaderOrFooter||(this.inRow=!0,this.rowIndex++,o.sourceNode,this.columnIndex=0,n.addRow(this.rowIndex,new Pa(this.rowIndex,o.sourceNode)),a.firstContentSourceNode||(a.firstContentSourceNode=o.sourceNode));break}return super.startNonInlineElementNode(e)}afterNonInlineElementNode(e){let n=this.formattingContext,s=e.nodeContext,o=s.display,i=this.column.clientLayout;if(this.postLayoutBlockContents(e),s.sourceNode===n.tableSourceNode){let a=i.getElementComputedStyle(n.getRootViewNode(s));n.tableWidth=parseFloat(a[n.vertical?"height":"width"]),n.getRepetitiveElements().lastContentSourceNode=e.lastAfterNodeContext&&e.lastAfterNodeContext.sourceNode,e.break=!0}else switch(o){case"table-header-group":case"table-footer-group":if(this.inHeaderOrFooter)return this.inHeaderOrFooter=!1,v(!0);break;case"table-row":this.inHeaderOrFooter||(n.lastRowViewNode=s.viewNode,this.inRow=!1);break;case"table-cell":if(!this.inHeaderOrFooter){this.inRow||(this.rowIndex++,this.columnIndex=0,this.inRow=!0);let a=s.viewNode;n.addCell(this.rowIndex,new ud(this.rowIndex,this.columnIndex,a)),this.columnIndex++}break}return super.afterNonInlineElementNode(e)}startNonElementNode(e){this.registerCheckPoint(e)}afterNonElementNode(e){this.registerCheckPoint(e)}startInlineElementNode(e){this.registerCheckPoint(e)}afterInlineElementNode(e){this.registerCheckPoint(e)}registerCheckPoint(e){let n=e.nodeContext;n&&n.viewNode&&!Cn(n)&&this.checkPoints.push(n.clone())}postLayoutBlockContents(e){this.checkPoints.length>0&&this.column.postLayoutBlock(e.nodeContext,this.checkPoints),this.checkPoints=[]}},Aa=class Aa extends bn{constructor(e,n){super(!0);this.formattingContext=e;this.column=n;p(this,"inRow",!1);p(this,"currentRowIndex",-1);p(this,"currentColumnIndex",0);p(this,"originalStopAtOverflow");p(this,"inHeader");p(this,"inFooter");this.originalStopAtOverflow=n.stopAtOverflow,n.stopAtOverflow=!1}resetColumn(){this.column.stopAtOverflow=this.originalStopAtOverflow}getColSpanningCellWidth(e){let n=this.formattingContext.colWidths;let s=0;for(let o=0;o<e.colSpan;o++)s+=n[e.anchorSlot.columnIndex+o];return s+=this.formattingContext.inlineBorderSpacing*(e.colSpan-1),s}layoutCell(e,n,s){let o=e.rowIndex,i=e.columnIndex,a=e.colSpan,l=n.viewNode,c=n.verticalAlign;a>1&&(T(l,"box-sizing","border-box"),T(l,this.formattingContext.vertical?"height":"width",`${this.getColSpanningCellWidth(e)}px`));let u=l.ownerDocument.createElement("div");l.appendChild(u);let d=new pd(this.column,u,n);return this.formattingContext.addCellFragment(o,i,d),s.primary.steps.length===1&&s.primary.after&&(d.empty=!0),d.pseudoColumn.layout(s,!0).thenReturn(!0)}hasBrokenCellAtSlot(e){let n=this.formattingContext.cellBreakPositions[0];return n?n.cell.anchorSlot.columnIndex===e:!1}extractRowSpanningCellBreakPositions(){let e=this.formattingContext.cellBreakPositions;if(e.length===0)return[];let n=[],s=0;do{let o=e[s],i=o.cell.rowIndex;if(i<this.currentRowIndex){let a=n[i];a||(a=n[i]=[]),a.push(o),e.splice(s,1)}else s++}while(s<e.length);return n}layoutRowSpanningCellsFromPreviousFragment(e){let n=this.formattingContext,s=this.extractRowSpanningCellBreakPositions(),o=s.reduce(h=>h+1,0);if(o===0)return v(!0);let i=this.column.layoutContext,a=e.nodeContext;a.viewNode.parentNode.removeChild(a.viewNode);let l=A("layoutRowSpanningCellsFromPreviousFragment"),c=v(!0),u=0,d=[];return s.forEach(h=>{c=c.thenAsync(()=>{let f=mo(h[0].cellNodePosition.steps[1],a.parent);return i.setCurrent(f,!1).thenAsync(()=>{let g=v(!0),m=0;function y(E){for(;m<E;){if(!d.includes(m)){let C=f.viewNode.ownerDocument.createElement("td");T(C,"padding","0"),f.viewNode.appendChild(C)}m++}}return h.forEach(E=>{g=g.thenAsync(()=>{let C=E.cell;y(C.anchorSlot.columnIndex);let x=E.cellNodePosition,N=mo(x.steps[0],f);return N.offsetInNode=x.offsetInNode,N.after=x.after,N.fragmentIndex=x.steps[0].fragmentIndex+1,i.setCurrent(N,!1).thenAsync(()=>{let S=E.breakChunkPosition;for(let w=0;w<C.colSpan;w++)d.push(m+w);return m+=C.colSpan,this.layoutCell(C,N,S).thenAsync(()=>(N.viewNode.rowSpan=C.rowIndex+C.rowSpan-this.currentRowIndex+o-u,v(!0)))})})}),g.thenAsync(()=>(y(n.getColumnCount()),u++,v(!0)))})})}),c.then(()=>{i.setCurrent(a,!0,e.atUnforcedBreak).then(()=>{l.finish(!0)})}),l.result()}startTableRow(e){if(this.inHeader||this.inFooter)return v(!0);let n=e.nodeContext,s=this.formattingContext;return this.currentRowIndex<0?(n.sourceNode,this.currentRowIndex=s.findRowIndexBySourceNode(n.sourceNode)):this.currentRowIndex++,this.currentColumnIndex=0,this.inRow=!0,this.layoutRowSpanningCellsFromPreviousFragment(e).thenAsync(()=>(this.registerCellFragmentIndex(),this.column.checkOverflowAndSaveEdgeAndBreakPosition(e.lastAfterNodeContext,null,!0,e.breakAtTheEdge)&&s.getRowSpanningCellsOverflowingTheRow(this.currentRowIndex-1).length===0&&(this.resetColumn(),n.overflow=!0,e.break=!0),v(!0)))}registerCellFragmentIndex(){this.formattingContext.getRowByIndex(this.currentRowIndex).cells.forEach(n=>{let s=this.formattingContext.cellBreakPositions[n.columnIndex];if(s&&s.cell.anchorSlot.columnIndex==n.anchorSlot.columnIndex){let o=s.cellNodePosition.steps[0],i=this.column.layoutContext.xmldoc.getElementOffset(o.node);Ff(i,o.fragmentIndex+1,1)}})}startTableCell(e){if(this.inHeader||this.inFooter)return v(!0);let n=e.nodeContext;this.inRow||(this.currentRowIndex<0?this.currentRowIndex=0:this.currentRowIndex++,this.currentColumnIndex=0,this.inRow=!0);let s=this.formattingContext.getRowByIndex(this.currentRowIndex).cells[this.currentColumnIndex];if(!s)return e.break=!0,v(!0);let o=n.copy().modify();o.after=!0,e.nodeContext=o;let i=A("startTableCell"),a;if(this.hasBrokenCellAtSlot(s.anchorSlot.columnIndex)){let l=this.formattingContext.cellBreakPositions.shift();n.fragmentIndex=l.cellNodePosition.steps[0].fragmentIndex+1,a=v(l.breakChunkPosition)}else a=this.column.nextInTree(n,e.atUnforcedBreak).thenAsync(l=>{l.viewNode&&n.viewNode.removeChild(l.viewNode);let c=Es(l,0);return v(new ht(c))});return a.then(l=>{this.layoutCell(s,n,l).then(()=>{this.afterNonInlineElementNode(e),this.currentColumnIndex++,i.finish(!0)})}),i.result()}startNonInlineBox(e){let n=Mf(e,Rt(this.formattingContext),this.column);if(n)return n;let s=e.nodeContext,o=this.formattingContext.getRepetitiveElements(),i=s.display;return i==="table-header-group"&&o&&o.isHeaderSourceNode(s.sourceNode)?(this.inHeader=!0,v(!0)):i==="table-footer-group"&&o&&o.isFooterSourceNode(s.sourceNode)?(this.inFooter=!0,v(!0)):i==="table-row"?this.startTableRow(e):i==="table-cell"?this.startTableCell(e):v(!0)}endNonInlineBox(e){let n=e.nodeContext;if(n.display==="table-row"&&(this.inRow=!1,!this.inHeader&&!this.inFooter)){let o=n.copy().modify();o.after=!1;let i=new gd(this.currentRowIndex,o,this.formattingContext);this.column.breakPositions.push(i)}return v(!0)}afterNonInlineElementNode(e){let n=e.nodeContext,s=this.formattingContext.getRepetitiveElements(),o=n.display;if(o==="table-header-group"?s&&!s.allowInsertRepeatitiveElements&&s.isHeaderSourceNode(n.sourceNode)?(this.inHeader=!1,n.viewNode.parentNode.removeChild(n.viewNode)):T(n.viewNode,"display","table-row-group"):o==="table-footer-group"&&(s&&!s.allowInsertRepeatitiveElements&&s.isFooterSourceNode(n.sourceNode)?(this.inFooter=!1,n.viewNode.parentNode.removeChild(n.viewNode)):T(n.viewNode,"display","table-row-group")),o&&Aa.ignoreList[o])n.viewNode.parentNode.removeChild(n.viewNode);else if(n.sourceNode===this.formattingContext.tableSourceNode)n.overflow=this.column.checkOverflowAndSaveEdge(n,null),this.resetColumn(),e.break=!0;else return super.afterNonInlineElementNode(e);return v(!0)}};p(Aa,"ignoreList",{"table-caption":!0,"table-column-group":!0,"table-column":!0});var bd=Aa,vi=[];function _C(r){let t=vi.findIndex(n=>n.root===r),e=vi[t];return e?e.tableLayoutOption:null}function UC(r){let t=vi.findIndex(e=>e.root===r);t>=0&&vi.splice(t,1)}var ka=class{layoutEntireTable(t,e){let n=Rt(t.formattingContext),s=new Cd(n,e);return new ws(s,e.layoutContext).iterate(t)}getColumnWidths(t,e,n,s){let o=t.ownerDocument,i=o.createElement("tr"),a=[];for(let c=0;c<e;c++){let u=o.createElement("td");i.appendChild(u),a.push(u)}t.parentNode.insertBefore(i,t.nextSibling);let l=a.map(c=>{let u=bo(s,c,n),d=n?u.height:u.width;return Math.ceil(d)});return t.parentNode.removeChild(i),l}getColGroupElements(t){let e=[],n=t.firstElementChild;for(;n;)n.localName==="colgroup"&&e.push(n),n=n.nextElementSibling;return e}normalizeAndGetColElements(t){let e=[];return t.forEach(n=>{let s=n.span;n.removeAttribute("span");let o=n.firstElementChild;for(;o;){if(o.localName==="col"){let i=o.span;for(o.removeAttribute("span"),s-=i;i-- >1;){let a=o.cloneNode(!0);n.insertBefore(a,o),e.push(a)}e.push(o)}o=o.nextElementSibling}for(;s-- >0;)o=n.ownerDocument.createElement("col"),n.appendChild(o),e.push(o)}),e}addMissingColElements(t,e,n,s){if(t.length<n){let o=s.ownerDocument.createElement("colgroup");e.push(o);for(let i=t.length;i<n;i++){let a=s.ownerDocument.createElement("col");o.appendChild(a),t.push(a)}}}normalizeColGroups(t,e,n){let s=t.vertical,o=t.lastRowViewNode;if(!o)return;t.lastRowViewNode=null;let a=o.ownerDocument.createDocumentFragment(),l=t.getColumnCount();if(!(l>0)){t.colGroups=a;return}let c=t.colWidths=this.getColumnWidths(o,l,s,n.clientLayout),u=this.getColGroupElements(e),d=this.normalizeAndGetColElements(u);this.addMissingColElements(d,u,l,e),d.forEach((h,f)=>{T(h,s?"height":"width",`${c[f]}px`)}),u.forEach(h=>{a.appendChild(h.cloneNode(!0))}),t.colGroups=a}doInitialLayout(t,e){let n=Rt(t.formattingContext);n.vertical=t.vertical,n.initializeRepetitiveElements(t.vertical),t.sourceNode;let s=_C(t.sourceNode);UC(t.sourceNode);let o=A("TableLayoutProcessor.doInitialLayout"),i=t.copy();return this.layoutEntireTable(t,e).then(a=>{let l=a.viewNode,c=bo(e.clientLayout,l,e.vertical),u=e.vertical?c.left:c.bottom;if(u+=(e.vertical?-1:1)*Gn(t,e.collectElementsOffset()).current,!e.isOverflown(u)&&(!s||!s.calculateBreakPositionsInside)){e.breakPositions.push(new Ed(i)),o.finish(a);return}this.normalizeColGroups(n,l,e),n.updateCellSizes(e.clientLayout),o.finish(null)}),o.result()}addCaptions(t,e,n){let s=t.captions;s.forEach((o,i)=>{o&&(e.insertBefore(o.viewNode,n),o.side==="top"&&(s[i]=null))})}addColGroups(t,e,n){t.colGroups&&this.getColGroupElements(e).length===0&&(e.insertBefore(t.colGroups.cloneNode(!0),n),T(e,"table-layout","fixed"),T(e,t.vertical?"height":"width",`${t.tableWidth}px`))}removeColGroups(t,e){if(t.colGroups&&e){let n=this.getColGroupElements(e);n&&n.forEach(s=>{e.removeChild(s)})}}doLayout(t,e){let n=Rt(t.formattingContext),s=n.getRootViewNode(t),o=s.firstChild;this.addCaptions(n,s,o),this.addColGroups(n,s,o);let i=new bd(n,e),a=new ws(i,e.layoutContext),l=A("TableFormattingContext.doLayout");return a.iterate(t).thenFinish(l),l.result()}layout(t,e,n){let s=Rt(t.formattingContext),o=s.getRootViewNode(t),i=A("TableFormattingContext.layout"),a;return o?(n&&ld(t.parent,e),a=new xd(s,this).layout(t,e)):a=e.buildDeepElementView(t),a.then(l=>{i.finish(l),e.element.hasAttribute("data-vivliostyle-column-height-adjusted")&&(T(e.element,"width",`${e.width}px`),T(e.element,"height",`${e.height}px`),e.element.removeAttribute("data-vivliostyle-column-height-adjusted"))}),i.result()}createEdgeBreakPosition(t,e,n,s){return new fd(t,e,n,s)}startNonInlineElementNode(t){return!1}afterNonInlineElementNode(t,e){return cd(t),!1}finishBreak(t,e,n,s){let o=Rt(e.formattingContext);if(e.display==="table-row"){e.sourceNode;let i=o.findRowIndexBySourceNode(e.sourceNode);o.cellBreakPositions=[];let a;if(e.after?a=o.getRowSpanningCellsOverflowingTheRow(i):a=o.getCellsFallingOnRow(i),a.length){let l=A("TableLayoutProcessor.finishBreak"),c=0;return l.loopWithFrame(u=>{if(c===a.length){u.breakLoop();return}let d=a[c++],h=o.getCellFragmentOfCell(d),f=h.findAcceptableBreakPosition().nodeContext;let g=h.cellNodeContext,m=g.toNodePosition(),y=new ht(f.toNodePosition());o.cellBreakPositions.push({cellNodePosition:m,breakChunkPosition:y,cell:d});let E=g.viewNode;h.column.layoutContext.processFragmentedBlockEdge(h.cellNodeContext),i<d.rowIndex+d.rowSpan-1&&(E.rowSpan=i-d.rowIndex+1),h.empty?u.continueLoop():h.pseudoColumn.finishBreak(f,!1,!0).then(()=>{HC(h,o,f),u.continueLoop()})}).then(()=>{t.clearOverflownViewNodes(e,!1),t.layoutContext.processFragmentedBlockEdge(e),cd(e),o.finishFragment(),l.finish(!0)}),l.result()}}return cd(e),o.finishFragment(),di.finishBreak(t,e,n,s)}clearOverflownViewNodes(t,e,n,s){sn.prototype.clearOverflownViewNodes(t,e,n,s)}};function HC(r,t,e){let n=t.getRepetitiveElements();if(!n||!(n.isHeaderRegistered()||n.isFooterRegistered()))return;let s=t.vertical,o=r.column,i=r.pseudoColumn.getColumnElement(),a=r.cellNodeContext.viewNode,l=bo(o.clientLayout,a,s),c=o.getComputedPaddingBorder(a);if(s){let u=l.right-o.footnoteEdge-n.calculateOffset(e)-c.right;T(i,"max-width",`${u}px`)}else{let u=o.footnoteEdge-n.calculateOffset(e)-l.top-c.top;T(i,"max-height",`${u}px`)}}function cd(r){let t=r.display==="table-row"?r.viewNode.parentElement:r.display==="table"?r.viewNode.querySelector("tbody"):null;if(!t)return;let e;try{e=t.querySelectorAll(":scope>tr:has(>:empty):not(:has(>:not([rowspan]:not([rowspan='1']),:empty)))")}catch(d){return}if(e.length===0)return;let n=Array.from(e).reduce((d,h)=>{let f=h.getBoundingClientRect(),g=r.vertical?f.width:f.height;return d+g},0),s=e[e.length-1],o=Array.from(t.children).indexOf(s),i=Array.from(s.children).reduce((d,h)=>{let f=h.rowSpan;return f>1&&o+f<t.childElementCount?Math.max(d,f):d},0),a=i?t.children[o+i-1]:t.lastElementChild;if(a!=t.lastElementChild&&a.querySelector(":scope>*>div>div")){for(let d=a;d&&d!==t.lastElementChild;d=d.nextElementSibling)if(d.querySelector(":scope>[rowspan]:not([rowspan='1'])")){a=d;break}}let l=a.getBoundingClientRect(),c=r.vertical?l.width:l.height,u=n+c;T(a,r.vertical?"width":"height",`${u}px`)}var xd=class extends $n{constructor(e,n){super();this.tableFormattingContext=e;this.processor=n}resolveLayoutMode(e){let n=this.tableFormattingContext.getRepetitiveElements();return!n||!n.doneInitialLayout?new yd(this.tableFormattingContext,this.processor):(e.sourceNode===this.tableFormattingContext.tableSourceNode&&!e.after&&n&&n.preventSkippingHeader(),new Nd(this.tableFormattingContext,this.processor))}clearNodes(e){super.clearNodes(e);let n=this.tableFormattingContext.getRootViewNode(e);this.processor.removeColGroups(this.tableFormattingContext,n)}restoreState(e,n){super.restoreState(e,n),this.tableFormattingContext.finishFragment()}},yd=class extends Si{constructor(e,n){super(e);this.processor=n}doLayout(e,n){return this.processor.doInitialLayout(e,n)}},Ed=class extends nn{constructor(t){super(t,null,t.overflow,0)}getMinBreakPenalty(){if(!this.isEdgeUpdated)throw new Error("EdgeBreakPosition.prototype.updateEdge not called");return(this.overflows?3:0)+(this.position.parent?this.position.parent.breakPenalty:0)}breakPositionChosen(t){t.fragmentLayoutConstraints.push(new Sd(this.position.sourceNode))}},Sd=class r{constructor(t){this.tableRootNode=t;p(this,"flagmentLayoutConstraintType","EntireTable")}allowLayout(t,e,n){return t.overflow,!1}nextCandidate(t){return!0}postLayout(t,e,n,s){e.sourceNode,vi.push({root:e.sourceNode,tableLayoutOption:{calculateBreakPositionsInside:!0}})}finishBreak(t,e){return v(!0)}equalsTo(t){return t instanceof r&&t.tableRootNode===this.tableRootNode}getPriorityOfFinishBreak(){return 0}},Nd=class extends Ni{constructor(e,n){super(e);this.processor=n}doLayout(e,n){let s=this.formattingContext.getRepetitiveElements();if(s&&!s.isAfterLastContent(e)){let o=new vd(e);n.fragmentLayoutConstraints.some(i=>o.equalsTo(i))||n.fragmentLayoutConstraints.unshift(o)}return this.processor.doLayout(e,n)}},vd=class r extends Lo{constructor(e){super(e);p(this,"flagmentLayoutConstraintType","TableRow");p(this,"cellFragmentLayoutConstraints",[])}allowLayout(e,n,s){let o=this.getRepetitiveElements();return!o||s.pseudoParent||mn(this.nodeContext.viewNode)||!o.isEnableToUpdateState()?!0:!(n&&!e||e&&e.overflow)}nextCandidate(e){let n=Rt(this.nodeContext.formattingContext);return this.collectCellFragmentLayoutConstraints(e,n).some(o=>o.constraints.some(i=>i.nextCandidate(e)))?!0:super.nextCandidate(e)}postLayout(e,n,s,o){let i=Rt(this.nodeContext.formattingContext);if(this.cellFragmentLayoutConstraints=this.collectCellFragmentLayoutConstraints(n,i),this.cellFragmentLayoutConstraints.forEach(a=>{a.constraints.forEach(l=>{l.postLayout(e,a.breakPosition,s,o)})}),!e){let a=i.getRootViewNode(this.nodeContext);new ka().removeColGroups(i,a),this.removeDummyRowNodes(s)}super.postLayout(e,n,s,o)}finishBreak(e,n){let s=Rt(this.nodeContext.formattingContext),o=A("finishBreak"),i=this.cellFragmentLayoutConstraints.reduce((l,c)=>l.concat(c.constraints.map(u=>({constraint:u,breakPosition:c.breakPosition}))),[]),a=0;return o.loop(()=>{if(a<i.length){let l=i[a++];return l.constraint.finishBreak(l.breakPosition,n).thenReturn(!0)}else return v(!1)}).then(()=>{o.finish(!0)}),o.result().thenAsync(()=>super.finishBreak(e,n))}removeDummyRowNodes(e){if(!(!e||e.display!=="table-row"||!e.viewNode))for(;e.viewNode.previousElementSibling;){let n=e.viewNode.previousElementSibling;n.parentNode&&n.parentNode.removeChild(n)}}collectCellFragmentLayoutConstraints(e,n){return this.getCellFragemnts(e,n).map(s=>({constraints:s.fragment.pseudoColumn.getColumn().fragmentLayoutConstraints,breakPosition:s.breakPosition}))}getCellFragemnts(e,n){let s=Number.MAX_VALUE;e&&e.display==="table-row"&&(e.sourceNode,s=n.findRowIndexBySourceNode(e.sourceNode)+1),s=Math.min(n.cellFragments.length,s);let o=[];for(let i=0;i<s;i++)n.cellFragments[i]&&n.cellFragments[i].forEach(a=>{a&&o.push({fragment:a,breakPosition:a.findAcceptableBreakPosition().nodeContext})});return o}getElementsOffsetsForTableCell(e){let n=Rt(this.nodeContext.formattingContext),s=n.findCellFromColumn(e);return s?n.collectElementsOffsetOfUpperCells(s):n.collectElementsOffsetOfHighestColumn()}equalsTo(e){return e instanceof r?Rt(this.nodeContext.formattingContext)===Rt(e.nodeContext.formattingContext):!1}},zC=new ka;function GC(r,t,e,n,s,o){if(!t)return null;if(e===b.table){let i=r.parent;return new Kn(i?i.formattingContext:null,r.sourceNode)}return null}function WC(r){return r instanceof Kn?zC:null}Ue("RESOLVE_FORMATTING_CONTEXT",GC);Ue("RESOLVE_LAYOUT_PROCESSOR",WC);function _f(r){return r.reduce((t,e)=>t+e,0)/r.length}function Uf(r){let t=_f(r);return _f(r.map(e=>{let n=e-t;return n*n}))}var Td=class{constructor(t,e){this.layoutResult=t;this.penalty=e}};function Ti(r){return r.vertical?r.width:r.height}function wi(r,t){r.vertical?r.width=t:r.height=t}var La=class{constructor(t,e,n){this.layoutContainer=t;this.columnGenerator=e;this.regionPageFloatLayoutContext=n;p(this,"originalContainerBlockSize");this.originalContainerBlockSize=Ti(t)}balanceColumns(t){let e=A("ColumnBalancer#balanceColumns");this.preBalance(t),this.savePageFloatLayoutContexts(t),this.layoutContainer.clear();let n=[this.createTrialResult(t)];return e.loopWithFrame(s=>{if(!this.hasNextCandidate(n)){s.breakLoop();return}this.updateCondition(n),this.columnGenerator().then(o=>{if(this.savePageFloatLayoutContexts(o),this.layoutContainer.clear(),!o){s.breakLoop();return}n.push(this.createTrialResult(o)),s.continueLoop()})}).then(()=>{let s=n.reduce((o,i)=>i.penalty<o.penalty?i:o,n[0]);this.restoreContents(s.layoutResult),this.postBalance(),e.finish(s.layoutResult)}),e.result()}createTrialResult(t){let e=this.calculatePenalty(t);return new Td(t,e)}preBalance(t){}postBalance(){wi(this.layoutContainer,this.originalContainerBlockSize)}savePageFloatLayoutContexts(t){let e=this.regionPageFloatLayoutContext.detachChildren();t&&(t.columnPageFloatLayoutContexts=e)}restoreContents(t){let e=this.layoutContainer.element;t.columns.forEach(n=>{e.appendChild(n.element)}),t.columnPageFloatLayoutContexts,this.regionPageFloatLayoutContext.attachChildren(t.columnPageFloatLayoutContexts)}},wd=1;function zf(r){let t=r[r.length-1];if(t.penalty===0)return!1;let e=r[r.length-2];if(e&&t.penalty>=e.penalty)return!1;let n=t.layoutResult.columns,s=Math.max.apply(null,n.map(i=>i.computedBlockSize)),o=Math.max.apply(null,n.map(i=>i.getMaxBlockSizeOfPageFloats()));return s>o+wd}function Gf(r,t){var o;let e=r[r.length-1].layoutResult.columns,s=Math.max.apply(null,e.map(i=>isNaN(i.blockDistanceToBlockEndFloats)?i.computedBlockSize:i.computedBlockSize-i.blockDistanceToBlockEndFloats+wd))-wd;if(s<Ti(t)?wi(t,s):wi(t,Ti(t)-1),t.vertical){let i=parseFloat((o=t.element.style)==null?void 0:o.width);t.originX=i-t.width}}var Pd=class extends La{constructor(e,n,s,o){super(s,e,n);this.columnCount=o;p(this,"originalPosition",null);p(this,"foundUpperBound",!1)}preBalance(e){let s=e.columns.reduce((o,i)=>o+i.computedBlockSize,0);wi(this.layoutContainer,s/this.columnCount),this.originalPosition=e.position}checkPosition(e){return this.originalPosition?this.originalPosition.isSamePosition(e):e===null}calculatePenalty(e){if(!this.checkPosition(e.position))return 1/0;let n=e.columns;return Hf(n)?1/0:Math.max.apply(null,n.map(s=>s.computedBlockSize))}hasNextCandidate(e){if(e.length===1)return!0;if(this.foundUpperBound)return zf(e);{let n=e[e.length-1];return this.checkPosition(n.layoutResult.position)&&!Hf(n.layoutResult.columns)?(this.foundUpperBound=!0,!0):Ti(this.layoutContainer)<this.originalContainerBlockSize}}updateCondition(e){if(this.foundUpperBound)Gf(e,this.layoutContainer);else{let n=Math.min(this.originalContainerBlockSize,Ti(this.layoutContainer)+this.originalContainerBlockSize*.1);wi(this.layoutContainer,n)}}};function Hf(r){if(r.length<=1)return!1;let t=r[r.length-1].computedBlockSize,e=r.slice(0,r.length-1),n=6;return e.every(s=>t>s.computedBlockSize+n)}var kd=class extends La{constructor(t,e,n){super(n,t,e)}calculatePenalty(t){if(t.columns.every(n=>n.computedBlockSize===0))return 1/0;let e=t.columns.filter(n=>!n.pageBreakType).map(n=>n.computedBlockSize);return Uf(e)}hasNextCandidate(t){return zf(t)}updateCondition(t){Gf(t,this.layoutContainer)}};function Wf(r,t,e,n,s,o,i){if(t===b.auto)return null;{let a=i.positions.length===0,l=o[o.length-1],c=!!(l&&l.pageBreakType);return a||c?new Pd(e,n,s,r):t===b.balance_all?new kd(e,n,s):(b.balance,null)}}var Pi=class{constructor(t,e,n){p(this,"endStuckFixed");p(this,"endFixed");p(this,"endSlipped");this.endStuckFixed=t,this.endFixed=e,this.endSlipped=n}},Ad=class{constructor(){p(this,"map",[])}getMaxFixed(){return this.map.length==0?0:this.map[this.map.length-1].endFixed}getMaxSlipped(){return this.map.length==0?0:this.map[this.map.length-1].endSlipped}addStuckRange(t){if(this.map.length==0)this.map.push(new Pi(t,t,t));else{let e=this.map[this.map.length-1],n=e.endSlipped+t-e.endFixed;e.endFixed==e.endStuckFixed?(e.endFixed=t,e.endStuckFixed=t,e.endSlipped=n):this.map.push(new Pi(t,t,n))}}addSlippedRange(t){this.map.length==0?this.map.push(new Pi(t,0,0)):this.map[this.map.length-1].endFixed=t}slippedByFixed(t){let e=mt(this.map.length,s=>t<=this.map[s].endFixed),n=this.map[e];return n.endSlipped-Math.max(0,n.endStuckFixed-t)}fixedBySlipped(t){let e=mt(this.map.length,s=>t<=this.map[s].endSlipped),n=this.map[e];return n.endStuckFixed-(n.endSlipped-t)}},Ld=class r{constructor(t,e,n,s,o,i,a,l){this.context=t;this.style=e;this.offset=n;this.isRoot=s;this.flowChunk=o;this.atBlockStart=i;this.atFlowStart=a;this.isParentBoxDisplayed=l;p(this,"flowName");p(this,"isBlockValue",null);p(this,"hasBoxValue",null);p(this,"styleValues",{});p(this,"beforeBox",null);p(this,"afterBox",null);p(this,"breakBefore",null);if(this.flowName=o.flowName,this.hasBox()){let c=e._pseudos;if(c&&c.before){let u=new r(t,c.before,n,!1,o,this.isBlock(),a,!0),d=u.styleValue("content");Nt(d)&&(this.beforeBox=u,this.breakBefore=u.breakBefore)}}this.breakBefore=Ve(this.getBreakValue("before"),this.breakBefore),this.atFlowStart&&Ie(this.breakBefore)&&(o.breakBefore=Ve(o.breakBefore,this.breakBefore))}buildAfterPseudoElementBox(t,e,n){if(this.hasBox()){let s=this.style._pseudos;if(s&&s.after){let o=new r(this.context,s.after,t,!1,this.flowChunk,e,n,!0),i=o.styleValue("content");Nt(i)&&(this.afterBox=o)}}}styleValue(t,e){if(!(t in this.styleValues)){let n=this.style[t];this.styleValues[t]=n?n.evaluate(this.context,t):e||null}return this.styleValues[t]}displayValue(){return this.styleValue("display",b.inline)}isBlock(){if(this.isBlockValue===null){let t=this.displayValue(),e=this.styleValue("position"),n=this.styleValue("float");this.isBlockValue=na(t,e,n,this.isRoot)}return this.isBlockValue}hasBox(){return this.hasBoxValue===null&&(this.hasBoxValue=this.isParentBoxDisplayed&&this.displayValue()!==b.none&&!ci(this.styleValue("position"))),this.hasBoxValue}getBreakValue(t){let e=null;if(this.isBlock()){let n=this.styleValue(`break-${t}`);n&&(e=n.toString())}return e}},Rd=class{constructor(t){this.context=t;p(this,"stack",[]);p(this,"atBlockStart",!0);p(this,"atFlowStart",!0);p(this,"atStartStack",[])}empty(){return this.stack.length===0}lastBox(){return this.stack[this.stack.length-1]}lastFlowName(){let t=this.lastBox();return t?t.flowChunk.flowName:null}isCurrentBoxDisplayed(){return this.stack.every(t=>t.displayValue()!==b.none)}push(t,e,n,s){let o=this.lastBox();s&&o&&s.flowName!==o.flowName&&this.atStartStack.push({atBlockStart:this.atBlockStart,atFlowStart:this.atFlowStart});let i=s||o.flowChunk,a=this.atFlowStart||!!s,l=this.isCurrentBoxDisplayed(),c=new Ld(this.context,t,e,n,i,a||this.atBlockStart,a,l);return this.stack.push(c),this.atBlockStart=c.hasBox()?!c.beforeBox&&c.isBlock():this.atBlockStart,this.atFlowStart=c.hasBox()?!c.beforeBox&&a:this.atFlowStart,c}encounteredTextNode(t){let e=this.lastBox();if((t.nodeType===Node.TEXT_NODE||t.nodeType===Node.CDATA_SECTION_NODE)&&(this.atBlockStart||this.atFlowStart)&&e.hasBox()){let n=e.styleValue("white-space",b.normal).toString(),s=Qr(n);s&&!ue(t,s)&&(this.atBlockStart=!1,this.atFlowStart=!1)}}pop(t){let e=this.stack.pop();if(e.buildAfterPseudoElementBox(t,this.atBlockStart,this.atFlowStart),this.atFlowStart&&e.afterBox){let s=e.afterBox.getBreakValue("before");e.flowChunk.breakBefore=Ve(e.flowChunk.breakBefore,s)}let n=this.lastBox();if(n)if(n.flowName===e.flowName)e.hasBox()&&(this.atBlockStart=this.atFlowStart=!1);else{let s=this.atStartStack.pop();this.atBlockStart=s.atBlockStart,this.atFlowStart=s.atFlowStart}return e}nearestBlockStartOffset(t){if(!t.atBlockStart)return t.offset;let e=this.stack.length-1,n=this.stack[e];for(n===t&&(e--,n=this.stack[e]);e>=0;){if(n.flowName!==t.flowName)return t.offset;if(!n.atBlockStart||n.isRoot)return n.offset;t=n,n=this.stack[--e]}throw new Error("No block start offset found!")}},ki=class{constructor(t,e,n,s,o,i,a,l){this.xmldoc=t;this.scope=n;this.context=s;this.primaryFlows=o;this.validatorSet=i;this.counterListener=a;p(this,"root");p(this,"cascadeHolder");p(this,"last");p(this,"rootStyle",{});p(this,"styleMap",{});p(this,"flows",{});p(this,"flowChunks",[]);p(this,"flowListener",null);p(this,"flowToReach",null);p(this,"idToReach",null);p(this,"cascade");p(this,"offsetMap");p(this,"primary",!0);p(this,"primaryStack",[]);p(this,"rootBackgroundAssigned",!1);p(this,"rootLayoutAssigned",!1);p(this,"lastOffset");p(this,"breakBeforeValues",{});p(this,"boxStack");p(this,"bodyReached",!0);this.root=t.root,this.cascadeHolder=e,this.last=this.root,this.cascade=e.createInstance(s,a,l,t.lang),this.offsetMap=new Ad;let c=t.getElementOffset(this.root);this.lastOffset=c,this.boxStack=new Rd(s),this.offsetMap.addStuckRange(c);let u=this.getAttrStyle(this.root);switch(this.cascade.pushElement(this,this.root,u,c),this.postprocessTopStyle(u,!1),this.root.namespaceURI){case"http://www.w3.org/1999/xhtml":this.bodyReached=!1;break}this.primaryStack.push(!0),this.styleMap={},this.styleMap[`e${c}`]=u,this.lastOffset++,this.replayFlowElementsFromOffset(-1)}hasProp(t,e,n){let s=t[n];return s&&s.evaluate(this.context)!==e[n]}transferPropsToRoot(t,e){for(let n in e){let s=t[n];if(s)this.rootStyle[n]=s,delete t[n];else{let o=e[n];o&&(this.rootStyle[n]=new H(o,vc))}}}postprocessTopStyle(t,e){var n;if(e)for(let s of["writing-mode","direction"])t[s]&&!(e&&this.rootStyle[s])&&(this.rootStyle[s]=t[s]);else for(let s in t)Yn(s)&&(this.rootStyle[s]=t[s]);if(!this.rootBackgroundAssigned){let s=this.hasProp(t,this.validatorSet.backgroundProps,"background-color")?t["background-color"].evaluate(this.context):null,o=this.hasProp(t,this.validatorSet.backgroundProps,"background-image")?t["background-image"].evaluate(this.context):null;(s&&!U(s)||o&&!U(o))&&(this.transferPropsToRoot(t,this.validatorSet.backgroundProps),this.rootBackgroundAssigned=!0)}if(!this.rootLayoutAssigned){for(let s=0;s<$f.length;s++)if(this.hasProp(t,this.validatorSet.layoutProps,$f[s])){this.transferPropsToRoot(t,this.validatorSet.layoutProps),this.rootLayoutAssigned=!0;break}}if(!e){let s=t["font-size"],o=!0;if(s&&!U(s.value)){let l=s.evaluate(this.context);if(l instanceof P){let c=l.num;switch(l.unit){case"em":case"rem":c*=this.context.initialFontSize;break;case"ex":c*=this.context.initialFontSize*Y.ex/Y.em;break;case"%":c*=this.context.initialFontSize/100;break;case"lh":case"rlh":c*=this.context.initialFontSize*Y.lh/Y.em;break;default:{let u=Y[l.unit];u&&(c*=u),o=!1}}this.context.rootFontSize=c,this.context.isRelativeRootFontSize=o}}let i=(n=this.context.rootFontSize)!=null?n:this.context.initialFontSize,a=t["line-height"];if(a&&!U(a.value)){let l=a.evaluate(this.context);if(l instanceof nt)this.context.rootLineHeight=l.num*i;else if(l instanceof P){let c=l.num;switch(l.unit){case"em":case"rem":c*=i;break;case"ex":c*=i*Y.ex/Y.em;break;case"%":c*=i/100;break;case"lh":case"rlh":c*=this.context.initialFontSize*Y.lh/Y.em;break;default:{let u=Y[l.unit];u&&(c*=u)}}this.context.rootLineHeight=c}}else this.context.rootLineHeight=this.context.fontSize()*Y.lh/Y.em}}getTopContainerStyle(){let t=0;for(;!this.bodyReached&&(t+=5e3,this.styleUntil(t,0)!=Number.POSITIVE_INFINITY););return this.rootStyle}getAttrStyle(t){if(t.style instanceof CSSStyleDeclaration){let e=t.getAttribute("style");if(e)return bf(this.scope,this.validatorSet,this.xmldoc.url,e)}return{}}getReachedOffset(){return this.lastOffset}replayFlowElementsFromOffset(t){if(t>=this.lastOffset)return;let e=this.context,n=this.xmldoc.getElementOffset(this.root);if(t<n){let i=this.getStyle(this.root,!1);let a=pe(i,"flow-into"),l=a?a.evaluate(e,"flow-into").toString():"body",c=this.encounteredFlowElement(l,i,this.root,n);this.boxStack.empty()&&this.boxStack.push(i,n,!0,c)}let s=this.xmldoc.getNodeByOffset(t),o=this.xmldoc.getNodeOffset(s,0,!1);if(!(o>=this.lastOffset))for(;;){if(s.nodeType!=1)o+=s.textContent.length;else{let a=s,l=this.getStyle(a,!1),c=l["flow-into"];if(c){let u=c.evaluate(e,"flow-into").toString();this.encounteredFlowElement(u,l,a,o)}o++}if(o>=this.lastOffset)break;let i=s.firstChild;if(i==null){for(;i=s.nextSibling,!i;)if(s=s.parentNode,s===this.root)return}s=i}}resetFlowChunkStream(t){this.flowListener=t;for(let e=0;e<this.flowChunks.length;e++)this.flowListener.encounteredFlowChunk(this.flowChunks[e],this.flows[this.flowChunks[e].flowName])}styleUntilFlowIsReached(t){this.flowToReach=t;let e=0;for(;!(this.flowToReach==null||(e+=5e3,this.styleUntil(e,0)==Number.POSITIVE_INFINITY)););}styleUntilIdIsReached(t){if(!t)return;this.idToReach=t;let e=0;for(;!(!this.idToReach||(e+=5e3,this.styleUntil(e,0)===Number.POSITIVE_INFINITY)););this.idToReach=null}encounteredFlowElement(t,e,n,s){let o=0,i=Number.POSITIVE_INFINITY,a=!1,l=!1,c=!1,u=e["flow-options"];if(u){let y=ah(u.evaluate(this.context,"flow-options"));a=!!y.exclusive,l=!!y.static,c=!!y.last}let d=e["flow-linger"];d&&(i=ql(d.evaluate(this.context,"flow-linger"),Number.POSITIVE_INFINITY));let h=e["flow-priority"];h&&(o=ql(h.evaluate(this.context,"flow-priority"),0));let f=this.breakBeforeValues[s]||null,g=this.flows[t];if(!g){let y=this.boxStack.lastFlowName();g=this.flows[t]=new Xr(t,y)}let m=new jr(t,n,s,o,i,a,l,c,f);return this.flowChunks.push(m),this.flowToReach==t&&(this.flowToReach=null),this.flowListener&&this.flowListener.encounteredFlowChunk(m,g),m}registerForcedBreakOffset(t,e,n){if(Ie(t)){let o=this.flows[n].forcedBreakOffsets;(o.length===0||o[o.length-1]<e)&&o.push(e)}let s=this.breakBeforeValues[e];this.breakBeforeValues[e]=Ve(s,t)}styleUntil(t,e){let n=-1,s;if(t<=this.lastOffset&&(s=this.offsetMap.slippedByFixed(t),n=s+e,n<this.offsetMap.getMaxSlipped()))return this.offsetMap.fixedBySlipped(n);if(this.last==null)return Number.POSITIVE_INFINITY;let o=this.context;for(;;){let i=this.last.firstChild;if(i==null)for(;;){if(this.last.nodeType==1){this.cascade.popElement(this.last),this.primary=this.primaryStack.pop();let a=this.boxStack.pop(this.lastOffset),l=null;if(a.afterBox){let c=a.afterBox.getBreakValue("before");this.registerForcedBreakOffset(c,a.afterBox.atBlockStart?this.boxStack.nearestBlockStartOffset(a):a.afterBox.offset,a.flowName),l=a.afterBox.getBreakValue("after")}l=Ve(l,a.getBreakValue("after")),this.registerForcedBreakOffset(l,this.lastOffset,a.flowName)}if(i=this.last.nextSibling,i)break;if(this.last=this.last.parentNode,this.last===this.root)return this.last=null,t<this.lastOffset&&(n<0&&(s=this.offsetMap.slippedByFixed(t),n=s+e),n<=this.offsetMap.getMaxSlipped())?this.offsetMap.fixedBySlipped(n):Number.POSITIVE_INFINITY}if(this.last=i,this.last.nodeType!=1)this.lastOffset+=this.last.textContent.length,this.boxStack.encounteredTextNode(this.last),this.primary?this.offsetMap.addStuckRange(this.lastOffset):this.offsetMap.addSlippedRange(this.lastOffset);else{let a=this.last,l=this.getAttrStyle(a);this.primaryStack.push(this.primary),this.cascade.pushElement(this,a,l,this.lastOffset);let c=a.getAttribute("id")||a.getAttributeNS("http://www.w3.org/XML/1998/namespace","id");c&&c===this.idToReach&&(this.idToReach=null),!this.bodyReached&&a.localName=="body"&&a.parentNode==this.root&&(this.postprocessTopStyle(l,!0),this.bodyReached=!0);let u,d=l["flow-into"];if(d){let f=d.evaluate(o,"flow-into").toString(),g=this.encounteredFlowElement(f,l,a,this.lastOffset);this.primary=!!this.primaryFlows[f],u=this.boxStack.push(l,this.lastOffset,a===this.root,g)}else u=this.boxStack.push(l,this.lastOffset,a===this.root),a===this.xmldoc.body&&(u.breakBefore=Ve(u.flowChunk.breakBefore,u.breakBefore));let h=this.boxStack.nearestBlockStartOffset(u);if(h===0){let f=l.page,g=f&&!U(f.value)&&f.value.toString();g&&g.toLowerCase()!=="auto"&&(this.cascade.firstPageType=g)}if(this.registerForcedBreakOffset(u.breakBefore,h,u.flowName),u.beforeBox){let f=u.beforeBox.getBreakValue("after");this.registerForcedBreakOffset(f,u.beforeBox.atBlockStart?h:u.offset,u.flowName)}if(this.primary&&u.displayValue()===b.none&&(this.primary=!1),this.styleMap[`e${this.lastOffset}`]=l,this.lastOffset++,this.primary?this.offsetMap.addStuckRange(this.lastOffset):this.offsetMap.addSlippedRange(this.lastOffset),this.bodyReached&&h===0)continue;if(t<this.lastOffset&&(n<0&&(s=this.offsetMap.slippedByFixed(t),n=s+e),n<=this.offsetMap.getMaxSlipped()))return this.offsetMap.fixedBySlipped(n)}}}getStyle(t,e){let n=this.xmldoc.getElementOffset(t),s=`e${n}`;return e&&(n=this.xmldoc.getNodeOffset(t,0,!0)),this.lastOffset<=n&&this.styleUntil(n,0),this.styleMap[s]}processContent(t,e,n){}},$f=["column-count","column-width","column-fill"];var Zn=class{constructor(t){this.validator=t;p(this,"success",null);p(this,"failure",null);p(this,"code",0)}isSpecial(){return this.code!=0}markAsStartGroup(){this.code=-1}isStartGroup(){return this.code==-1}markAsEndGroup(){this.code=-2}isEndGroup(){return this.code==-2}markAsStartAlternate(t){this.code=2*t+1}isStartAlternate(){return this.code>0&&this.code%2!=0}markAsEndAlternate(t){this.code=2*t+2}isEndAlternate(){return this.code>0&&this.code%2==0}getAlternate(){return Math.floor((this.code-1)/2)}},Nn=class{constructor(t,e){this.where=t;this.success=e;p(this,"what",-1)}};var Ms=class r{constructor(){p(this,"nodes",[]);p(this,"connections",[]);p(this,"match",[]);p(this,"nomatch",[]);p(this,"error",[]);p(this,"emptyHead",!0)}connect(t,e){for(let n=0;n<t.length;n++)this.connections[t[n]].what=e;t.splice(0,t.length)}clone(){let t=new r;for(let e=0;e<this.nodes.length;e++){let n=this.nodes[e],s=new Zn(n.validator);s.code=n.code,t.nodes.push(s)}for(let e=0;e<this.connections.length;e++){let n=this.connections[e],s=new Nn(n.where,n.success);s.what=n.what,t.connections.push(s)}return t.match.push(...this.match),t.nomatch.push(...this.nomatch),t.error.push(...this.error),t}addSpecialToArr(t,e,n){let s=this.nodes.length,o=new Zn(Xf);n>=0?e?o.markAsStartAlternate(n):o.markAsEndAlternate(n):e?o.markAsStartGroup():o.markAsEndGroup(),this.nodes.push(o),this.connect(t,s);let i=new Nn(s,!0),a=new Nn(s,!1);t.push(this.connections.length),this.connections.push(a),t.push(this.connections.length),this.connections.push(i)}endSpecialGroup(){let t=[this.match,this.nomatch,this.error];for(let e=0;e<t.length;e++)this.addSpecialToArr(t[e],!1,-1)}startSpecialGroup(){if(this.nodes.length)throw new Error("invalid call");this.addSpecialToArr(this.match,!0,-1)}endClause(t){this.addSpecialToArr(this.match,!1,t)}startClause(t){if(this.nodes.length)throw new Error("invalid call");let e=new Zn(Xf);e.markAsStartAlternate(t),this.nodes.push(e);let n=new Nn(0,!0),s=new Nn(0,!1);this.nomatch.push(this.connections.length),this.connections.push(s),this.match.push(this.connections.length),this.connections.push(n)}addPrimitive(t){let e=this.nodes.length;this.nodes.push(new Zn(t));let n=new Nn(e,!0),s=new Nn(e,!1);this.connect(this.match,e),this.emptyHead?(this.nomatch.push(this.connections.length),this.emptyHead=!1):this.error.push(this.connections.length),this.connections.push(s),this.match.push(this.connections.length),this.connections.push(n)}isSimple(){return this.nodes.length==1&&!this.nodes[0].isSpecial()}isPrimitive(){return this.isSimple()&&this.nodes[0].validator instanceof Ce}addGroup(t,e){if(t.nodes.length==0)return;let n=this.nodes.length;if(e==4&&n==1&&t.isPrimitive()&&this.isPrimitive()){this.nodes[0].validator=this.nodes[0].validator.combine(t.nodes[0].validator);return}for(let o=0;o<t.nodes.length;o++)this.nodes.push(t.nodes[o]);e==4?(this.emptyHead=!0,this.connect(this.nomatch,n)):this.connect(this.match,n);let s=this.connections.length;for(let o=0;o<t.connections.length;o++){let i=t.connections[o];i.where+=n,i.what>=0&&(i.what+=n),this.connections.push(i)}for(let o=0;o<t.match.length;o++)this.match.push(t.match[o]+s);if(e==3&&this.connect(this.match,n),e==2||e==3)for(let o=0;o<t.nomatch.length;o++)this.match.push(t.nomatch[o]+s);else if(this.emptyHead){for(let o=0;o<t.nomatch.length;o++)this.nomatch.push(t.nomatch[o]+s);this.emptyHead=t.emptyHead}else for(let o=0;o<t.nomatch.length;o++)this.error.push(t.nomatch[o]+s);for(let o=0;o<t.error.length;o++)this.error.push(t.error[o]+s);t.nodes=null,t.connections=null}finish(t,e){let n=this.nodes.length;this.nodes.push(t),this.nodes.push(e),this.connect(this.match,n),this.connect(this.nomatch,n+1),this.connect(this.error,n+1);for(let s of this.connections)s.success?this.nodes[s.where].success=this.nodes[s.what]:this.nodes[s.where].failure=this.nodes[s.what];for(let s=0;s<n;s++)if(this.nodes[s].failure==null||this.nodes[s].success==null)throw new Error("Invalid validator state");return this.nodes[0]}},YC=1,Yf=2,qf=4,Ds=8,Ra=16,Id=32,Ia=64,Kf=128,Ai=256,Li=512,Vd=1024,Zf=2048,Qf=4096,Jf=8192,Va=class extends ct{constructor(){super()}validateForShorthand(t,e){let n=t[e].visit(this);return n?[n]:null}},Ce=class r extends Va{constructor(e,n,s){super();this.allowed=e;this.idents=n;this.units=s}visitEmpty(e){return this.allowed&YC?e:null}visitSlash(e){return this.allowed&Zf?e:null}visitStr(e){return this.allowed&Yf?e:null}visitIdent(e){let n=this.idents[e.name.toLowerCase()];return n||(this.allowed&qf||this.allowed&Ia&&CSS.supports("color",e.name)?e:null)}visitNumeric(e){return e.num==0&&!(this.allowed&Li)?e.unit=="%"&&this.allowed&Vd?e:null:e.num<0&&!(this.allowed&Ai)?null:this.units[e.unit]?e:null}visitNum(e){return e.num==0?this.allowed&Li?e:null:e.num<=0&&!(this.allowed&Ai)?null:this.allowed&Ra?e:null}visitInt(e){if(e.num==0)return this.allowed&Li?e:null;if(e.num<=0&&!(this.allowed&Ai))return null;if(this.allowed&(Id|Ra))return e;let n=this.idents[`${e.num}`];return n||null}visitHexColor(e){return this.allowed&Ia&&/^([0-9A-F]{3,4}|([0-9A-F]{2}){3,4})$/i.test(e.hex)?e:null}visitURL(e){return this.allowed&Kf?e:null}visitURange(e){return this.allowed&Qf?e:null}visitSpaceList(e){return null}visitCommaList(e){return null}visitFunc(e){return this.allowed&Ia&&CSS.supports("color",e.toString())||this.allowed&Jf&&CSS.supports("background-image",e.toString())||e.name==="calc"&&this.allowed&(Ds|Ra|Id|Ai|Li|Vd)?e:null}visitExpr(e){return this.allowed&2046?e:null}combine(e){let n={},s={};for(let o in this.idents)n[o]=this.idents[o];for(let o in e.idents)n[o]=e.idents[o];for(let o in this.units)s[o]=this.units[o];for(let o in e.units)s[o]=e.units[o];return new r(this.allowed|e.allowed,n,s)}},j={},Xf=new Ce(0,j,j),Ri=class extends Va{constructor(e){super();p(this,"successTerminal");p(this,"failureTerminal");p(this,"first");this.successTerminal=new Zn(null),this.failureTerminal=new Zn(null),this.first=e.finish(this.successTerminal,this.failureTerminal)}validateList(e,n,s){let o=n?[]:e,i=this.first,a=s,l=null,c=null;for(;i!==this.successTerminal&&i!==this.failureTerminal;){if(a>=e.length){i=i.failure;continue}let u=e[a],d=u;if(i.isSpecial()){let h=!0;i.isStartGroup()?(l?l.push(c):l=[c],c=[]):i.isEndGroup()?l.length>0?c=l.pop():c=null:i.isEndAlternate()?c[i.getAlternate()]="taken":h=c[i.getAlternate()]==null,i=h?i.success:i.failure}else{if(a==0&&!n&&i.validator instanceof _s&&this instanceof _s){if(d=new q(e).visit(i.validator),d){a=e.length,i=i.success;continue}}else if(a==0&&!n&&i.validator instanceof Ii&&this instanceof _s){if(d=new ge(e).visit(i.validator),d){a=e.length,i=i.success;continue}}else d=u.visit(i.validator);if(!d){i=i.failure;continue}if(d!==u&&e===o){o=[];for(let h=0;h<a;h++)o[h]=e[h]}e!==o&&(o[a-s]=d),a++,i=i.success}}return i===this.successTerminal&&(n?o.length>0:a==e.length)?o:null}validateSingle(e){let n=null,s=this.first;for(;s!==this.successTerminal&&s!==this.failureTerminal;){if(!e){s=s.failure;continue}if(s.isSpecial()){s=s.success;continue}if(n=e.visit(s.validator),!n){s=s.failure;continue}e=null,s=s.success}return s===this.successTerminal?n:null}visitEmpty(e){return this.validateSingle(e)}visitSlash(e){return this.validateSingle(e)}visitStr(e){return this.validateSingle(e)}visitIdent(e){return this.validateSingle(e)}visitNumeric(e){return this.validateSingle(e)}visitNum(e){return this.validateSingle(e)}visitInt(e){return this.validateSingle(e)}visitHexColor(e){return this.validateSingle(e)}visitURL(e){return this.validateSingle(e)}visitURange(e){return this.validateSingle(e)}visitSpaceList(e){return null}visitCommaList(e){return null}visitFunc(e){return this.validateSingle(e)}visitExpr(e){return null}},_s=class extends Ri{constructor(t){super(t)}visitSpaceList(t){let e=this.validateList(t.values,!1,0);return e===t.values?t:e?new q(e):null}visitCommaList(t){let e=this.first,n=!1;for(;e;){if(e.validator instanceof Ii){n=!0;break}e=e.failure}if(n){let s=this.validateList(t.values,!1,0);return s===t.values?t:s?new ge(s):null}return null}validateForShorthand(t,e){return this.validateList(t,!0,e)}},Ii=class extends Ri{constructor(t){super(t)}visitSpaceList(t){return this.validateSingle(t)}visitCommaList(t){let e=this.validateList(t.values,!1,0);return e===t.values?t:e?new ge(e):null}validateForShorthand(t,e){let n=this.first,s;for(;n!==this.failureTerminal;){if(s=n.validator.validateForShorthand(t,e),s)return s;n=n.failure}return null}},Fd=class extends Ri{constructor(e,n){super(n);this.name=e}validateSingle(e){return null}visitFunc(e){if(e.name.toLowerCase()!=this.name)return null;let n=this.validateList(e.values,!1,0);return n===e.values?e:n?new kt(e.name,n):null}},Fa=class{tryParse(t,e,n){return e}success(t,e){}},Ba=class extends Fa{constructor(e,n){super();this.name=n;p(this,"validator");this.validator=e.validators[this.name]}tryParse(e,n,s){if(s.values[this.name])return n;let o=this.validator.validateForShorthand(e,n);if(o){let i=o.length,a=i>1?new q(o):o[0];return this.success(a,s),n+i}return n}success(e,n){n.values[this.name]=e}},Bd=class extends Ba{constructor(e,n){super(e,n[0]);this.names=n}success(e,n){for(let s=0;s<this.names.length;s++)n.values[this.names[s]]=e}},Od=class extends Fa{constructor(e,n){super();this.nodes=e;this.slash=n}tryParse(e,n,s){let o=n;if(this.slash)if(e[n]==eo){if(++n==e.length)return o}else return o;let i=this.nodes[0].tryParse(e,n,s);if(i==n)return o;n=i;for(let a=1;a<this.nodes.length&&n<e.length&&(i=this.nodes[a].tryParse(e,n,s),i!=n);a++)n=i;return n}},Vi=class extends ct{constructor(){super(...arguments);p(this,"syntax",null);p(this,"propList",null);p(this,"error",!1);p(this,"values",{});p(this,"validatorSet",null)}setOwner(e){this.validatorSet=e}syntaxNodeForProperty(e){return new Ba(this.validatorSet,e)}clone(){let e=new this.constructor;return e.syntax=this.syntax,e.propList=this.propList,e.validatorSet=this.validatorSet,e}init(e,n){this.syntax=e,this.propList=n}finish(e,n){var s,o;if(!this.error){for(let i of this.propList)n.simpleProperty(i,(o=(s=this.values[i])!=null?s:this.validatorSet.defaultValues[i])!=null?o:b.initial,e);return!0}return!1}propagateDefaultingValue(e,n,s){for(let o of this.propList)s.simpleProperty(o,e,n)}validateList(e){return this.error=!0,0}validateSingle(e){return this.validateList([e]),null}visitEmpty(e){return this.validateSingle(e)}visitStr(e){return this.validateSingle(e)}visitIdent(e){return this.validateSingle(e)}visitNumeric(e){return this.validateSingle(e)}visitNum(e){return this.validateSingle(e)}visitInt(e){return this.validateSingle(e)}visitHexColor(e){return this.validateSingle(e)}visitURL(e){return this.validateSingle(e)}visitSpaceList(e){return this.validateList(e.values),null}visitCommaList(e){return this.error=!0,null}visitFunc(e){return this.validateSingle(e)}visitExpr(e){return this.validateSingle(e)}},Qn=class extends Vi{constructor(){super()}validateList(t){let e=0,n=0;for(;e<t.length;){let s=this.syntax[n].tryParse(t,e,this);if(s>e){e=s,n=0;continue}if(++n==this.syntax.length){this.error=!0;break}}return e}},Oa=class extends Vi{constructor(){super()}validateList(t){if(t.length>this.syntax.length||t.length==0)return this.error=!0,0;for(let e=0;e<this.syntax.length;e++){let n=e;for(;n>=t.length;)n=n==1?0:n-2;if(this.syntax[e].tryParse(t,n,this)!=n+1)return this.error=!0,0}return t.length}createSyntaxNode(){return new Bd(this.validatorSet,this.propList)}},Dd=class extends Vi{constructor(){super()}validateList(t){let e=t.length;for(let n=0;n<t.length;n++)if(t[n]===eo){e=n;break}if(e>this.syntax.length||t.length==0)return this.error=!0,0;for(let n=0;n<this.syntax.length;n++){let s=n;for(;s>=e;)s=s==1?0:s-2;let o;if(e+1<t.length)for(o=e+n+1;o>=t.length;)o=o-(o==e+2?1:2);else o=s;let i=[t[s],t[o]];if(this.syntax[n].tryParse(i,0,this)!=2)return this.error=!0,0}return t.length}},Md=class extends Qn{constructor(){super()}mergeIn(t,e){var n,s;for(let o of this.propList){let i=(s=(n=e[o])!=null?n:this.validatorSet.defaultValues[o])!=null?s:b.initial,a=t[o];a||(a=[],t[o]=a),a.push(i)}}visitCommaList(t){let e={};for(let n=0;n<t.values.length;n++)if(this.values={},t.values[n]instanceof ge?this.error=!0:(t.values[n].visit(this),this.mergeIn(e,this.values),this.values["background-color"]&&n!=t.values.length-1&&(this.error=!0)),this.error)return null;this.values={};for(let n in e)n=="background-color"?this.values[n]=e[n].pop():this.values[n]=new ge(e[n]);return null}},_d=class extends Qn{constructor(){super()}init(t,e){super.init(t,e),this.propList.push("font-family","line-height","font-size","font-stretch","font-variant-ligatures","font-variant-caps","font-variant-numeric","font-variant-east-asian")}validateList(t){let e=super.validateList(t),n=this.values["font-variant_css2"];n&&(delete this.values["font-variant_css2"],this.values["font-variant-caps"]=n);let s=this.values["font-stretch_css3"];if(s&&(delete this.values["font-stretch_css3"],this.values["font-stretch"]=s),e+2>t.length)return this.error=!0,e;this.error=!1;let o=this.validatorSet.validators;if(!t[e].visit(o["font-size"]))return this.error=!0,e;if(this.values["font-size"]=t[e++],t[e]===eo){if(e++,e+2>t.length)return this.error=!0,e;if(!t[e].visit(o["line-height"]))return this.error=!0,e;this.values["line-height"]=t[e++]}let i=e==t.length-1?t[e]:new q(t.slice(e,t.length));return i.visit(o["font-family"])?(this.values["font-family"]=i,t.length):(this.error=!0,e)}visitCommaList(t){if(t.values[0].visit(this),this.error)return null;let e=[this.values["font-family"]];for(let s=1;s<t.values.length;s++)e.push(t.values[s]);let n=new ge(e);return n.visit(this.validatorSet.validators["font-family"])?this.values["font-family"]=n:this.error=!0,null}visitIdent(t){let e=this.validatorSet.systemFonts[t.name];if(e)for(let n in e)this.values[n]=e[n];else this.error=!0;return null}},Ud=class extends Qn{validateList(t){if(t.length===1&&t[0]instanceof be)switch(t[0].name.toLowerCase()){case"normal":t=[this.validatorSet.defaultValues["text-autospace"],this.validatorSet.defaultValues["text-spacing-trim"]];break;case"auto":t=[b.auto,b.auto];break;case"none":t=[L("no-autospace"),L("space-all")];break}return super.validateList(t)}},qC=["unicode-bidi","direction","margin-block-start","margin-block-end","margin-inline-start","margin-inline-end","padding-block-start","padding-block-end","padding-inline-start","padding-inline-end","border-block-start-color","border-block-end-color","border-inline-start-color","border-inline-end-color","border-block-start-style","border-block-end-style","border-inline-start-style","border-inline-end-style","border-block-start-width","border-block-end-width","border-inline-start-width","border-inline-end-width","block-start","block-end","inline-start","inline-end","block-size","inline-size","max-block-size","max-inline-size","min-block-size","min-inline-size","behavior","bleed","conflicting-partitions","crop-offset","crop-marks-line-color","enabled","flow-consume","flow-from","flow-into","flow-linger","flow-options","flow-priority","font-display","font-size-adjust","font-stretch_css3","font-variant_css2","glyph-orientation-vertical","marks","min-page-height","min-page-width","repeat-on-break","required","required-partitions","ruby-align","shape-inside","snap-height","snap-width","template","text-decoration-skip","text-justify","text-zoom","unicode-range","utilization","wrap-flow"],Hd=class extends Qn{constructor(){super()}init(t,e){super.init(t,e);for(let n in this.validatorSet.validators)qC.includes(n)||this.propList.push(n)}validateList(t){return this.error=!0,0}},jf={SIMPLE:Qn,INSETS:Oa,INSETS_SLASH:Dd,COMMA:Md,FONT:_d,TEXT_SPACING:Ud,ALL:Hd},zd=class{constructor(){p(this,"validators",{});p(this,"prefixes",{});p(this,"defaultValues",{});p(this,"namedValidators",{});p(this,"systemFonts",{});p(this,"shorthands",{});p(this,"layoutProps",{});p(this,"backgroundProps",{})}addReplacement(t,e){let n;if(e.type==3)n=new P(e.num,e.text);else if(e.type==7)n=new Js(e.text);else if(e.type==1)n=L(e.text);else throw new Error("unexpected replacement");if(t.isPrimitive()){let o=t.nodes[0].validator.idents;for(let i in o)o[i]=n;return t}throw new Error("unexpected replacement")}newGroup(t,e){let n=new Ms;if(t=="||"){for(let o=0;o<e.length;o++){let i=new Ms;i.startClause(o),i.addGroup(e[o],1),i.endClause(o),n.addGroup(i,o==0?1:4)}let s=new Ms;return s.startSpecialGroup(),s.addGroup(n,3),s.endSpecialGroup(),s}else{let s;switch(t){case" ":s=1;break;case"|":case"||":s=4;break;default:throw new Error("unexpected op")}for(let o=0;o<e.length;o++)n.addGroup(e[o],o==0?1:s);return n}}addCounts(t,e,n){let s=new Ms;for(let o=0;o<e;o++)s.addGroup(t.clone(),1);if(n==Number.POSITIVE_INFINITY)s.addGroup(t,3);else for(let o=e;o<n;o++)s.addGroup(t.clone(),2);return s}primitive(t){let e=new Ms;return e.addPrimitive(t),e}newFunc(t,e){let n;switch(t){case"COMMA":n=new Ii(e);break;case"SPACE":n=new _s(e);break;default:n=new Fd(t.toLowerCase(),e);break}return this.primitive(n)}initBuiltInValidators(){this.namedValidators.COLOR=this.primitive(new Ce(Ia,j,j)),this.namedValidators.IMAGE_FUNCTION=this.primitive(new Ce(Jf,j,j)),this.namedValidators.POS_INT=this.primitive(new Ce(Id,j,j)),this.namedValidators.POS_NUM=this.primitive(new Ce(Ra,j,j)),this.namedValidators.POS_PERCENTAGE=this.primitive(new Ce(Ds,j,{"%":O})),this.namedValidators.NEGATIVE=this.primitive(new Ce(Ai,j,j)),this.namedValidators.ZERO=this.primitive(new Ce(Li,j,j)),this.namedValidators.ZERO_PERCENTAGE=this.primitive(new Ce(Vd,j,j)),this.namedValidators.POS_LENGTH=this.primitive(new Ce(Ds,j,{em:O,ex:O,ch:O,rem:O,lh:O,rlh:O,vw:O,vh:O,vi:O,vb:O,vmin:O,vmax:O,pvw:O,pvh:O,pvi:O,pvb:O,pvmin:O,pvmax:O,cm:O,mm:O,in:O,px:O,pt:O,pc:O,q:O})),this.namedValidators.POS_ANGLE=this.primitive(new Ce(Ds,j,{deg:O,grad:O,rad:O,turn:O})),this.namedValidators.POS_TIME=this.primitive(new Ce(Ds,j,{s:O,ms:O})),this.namedValidators.FREQUENCY=this.primitive(new Ce(Ds,j,{Hz:O,kHz:O})),this.namedValidators.RESOLUTION=this.primitive(new Ce(Ds,j,{dpi:O,dpcm:O,dppx:O})),this.namedValidators.URI=this.primitive(new Ce(Kf,j,j)),this.namedValidators.URANGE=this.primitive(new Ce(Qf,j,j)),this.namedValidators.IDENT=this.primitive(new Ce(qf,j,j)),this.namedValidators.STRING=this.primitive(new Ce(Yf,j,j)),this.namedValidators.SLASH=this.primitive(new Ce(Zf,j,j));let t={"font-family":L("sans-serif")};this.systemFonts.caption=t,this.systemFonts.icon=t,this.systemFonts.menu=t,this.systemFonts["message-box"]=t,this.systemFonts["small-caption"]=t,this.systemFonts["status-bar"]=t}isBuiltIn(t){return!!t.match(/^[A-Z_0-9]+$/)}readNameAndPrefixes(t,e){let n=t.token();if(n.type==0)return null;let s={"":!0};if(n.type==14){do{if(t.consume(),n=t.token(),n.type!=1)throw new Error("Prefix name expected");s[n.text]=!0,t.consume(),n=t.token()}while(n.type==16);if(n.type!=15)throw new Error("']' expected");t.consume(),n=t.token()}if(n.type!=1)throw new Error("Property name expected");if(e==2?n.text=="SHORTHANDS":n.text=="DEFAULTS")return t.consume(),null;let o=n.text;if(t.consume(),e!=2){if(t.token().type!=39)throw new Error("'=' expected");this.isBuiltIn(o)||(this.prefixes[o]=s)}else if(t.token().type!=18)throw new Error("':' expected");return o}parseValidators(t){for(;;){let e=this.readNameAndPrefixes(t,1);if(!e)return;let n=[],s=[],o="",i,a=!0,l=()=>{if(n.length==0)throw new Error("No values");return n.length==1?n[0]:this.newGroup(o,n)},c=d=>{if(a)throw new Error(`'${d}': unexpected`);if(o&&o!=d)throw new Error(`mixed operators: '${d}' and '${o}'`);o=d,a=!0},u=null;for(;!u;){t.consume();let d=t.token();switch(d.type){case 1:if(a||c(" "),this.isBuiltIn(d.text)){let h=this.namedValidators[d.text];if(!h)throw new Error(`'${d.text}' unexpected`);n.push(h.clone())}else{let h={};h[d.text.toLowerCase()]=L(d.text),n.push(this.primitive(new Ce(0,h,j)))}a=!1;break;case 5:{let h={};h[`${d.num}`]=new ut(d.num),n.push(this.primitive(new Ce(0,h,j))),a=!1;break}case 34:c("|");break;case 25:c("||");break;case 14:a||c(" "),s.push({vals:n,op:o,b:"["}),o="",n=[],a=!0;break;case 6:a||c(" "),s.push({vals:n,op:o,b:"(",fn:d.text}),o="",n=[],a=!0;break;case 15:{i=l();let h=s.pop();if(h.b!="[")throw new Error("']' unexpected");n=h.vals,n.push(i),o=h.op,a=!1;break}case 11:{i=l();let h=s.pop();if(h.b!="(")throw new Error("')' unexpected");n=h.vals,n.push(this.newFunc(h.fn,i)),o=h.op,a=!1;break}case 18:if(a)throw new Error("':' unexpected");t.consume(),n.push(this.addReplacement(n.pop(),t.token()));break;case 22:if(a)throw new Error("'?' unexpected");n.push(this.addCounts(n.pop(),0,1));break;case 36:if(a)throw new Error("'*' unexpected");n.push(this.addCounts(n.pop(),0,Number.POSITIVE_INFINITY));break;case 23:if(a)throw new Error("'+' unexpected");n.push(this.addCounts(n.pop(),1,Number.POSITIVE_INFINITY));break;case 12:{if(t.consume(),d=t.token(),d.type!=5)throw new Error("<int> expected");let h=d.num,f=h;if(t.consume(),d=t.token(),d.type==16){if(t.consume(),d=t.token(),d.type!=5)throw new Error("<int> expected");f=d.num,t.consume(),d=t.token()}if(d.type!=13)throw new Error("'}' expected");n.push(this.addCounts(n.pop(),h,f));break}case 17:if(u=l(),s.length>0)throw new Error(`unclosed '${s.pop().b}'`);break;default:throw new Error("unexpected token")}}t.consume(),this.isBuiltIn(e)?this.namedValidators[e]=u:u.isSimple()?this.validators[e]=u.nodes[0].validator:this.validators[e]=new _s(u)}}parseDefaults(t){for(;;){let e=this.readNameAndPrefixes(t,2);if(!e)return;let n=[];for(;;){t.consume();let s=t.token();if(s.type==17){t.consume();break}switch(s.type){case 1:n.push(L(s.text));break;case 4:n.push(new nt(s.num));break;case 5:n.push(new ut(s.num));break;case 3:n.push(new P(s.num,s.text));break;default:throw new Error("unexpected token")}}this.defaultValues[e]=n.length>1?new q(n):n[0]}}parseShorthands(t){for(;;){let e=this.readNameAndPrefixes(t,3);if(!e)return;let n=t.nthToken(1),s;n.type==1&&jf[n.text]?(s=new jf[n.text],t.consume()):s=new Qn,s.setOwner(this);let o=!1,i=[],a=!1,l=[],c=[];for(;!o;)switch(t.consume(),n=t.token(),n.type){case 1:if(this.validators[n.text])i.push(s.syntaxNodeForProperty(n.text)),n.text.includes("_")||c.push(n.text);else if(this.shorthands[n.text]instanceof Oa){let u=this.shorthands[n.text];i.push(u.createSyntaxNode()),c.push(...u.propList)}else throw new Error(`'${n.text}' is neither a simple property nor an inset shorthand`);break;case 19:if(i.length>0||a)throw new Error("unexpected slash");a=!0;break;case 14:l.push({slash:a,syntax:i}),i=[],a=!1;break;case 15:{let u=new Od(i,a),d=l.pop();i=d.syntax,a=d.slash,i.push(u);break}case 17:o=!0,t.consume();break;default:throw new Error("unexpected token")}s.init(i,c),this.shorthands[e]=s}}parse(t){let e=new De(t,null);this.parseValidators(e),this.parseDefaults(e),this.parseShorthands(e),this.backgroundProps=this.makePropSet(["background"]),this.layoutProps=this.makePropSet(["margin","border","padding","columns","column-gap","column-rule","column-fill"])}makePropSet(t){var n;let e={};for(let s of t){let o=this.shorthands[s],i=o?o.propList:[s];for(let a of i)e[a]=(n=this.defaultValues[a])!=null?n:b.initial}return e}validatePropertyAndHandleShorthand(t,e,n,s){if(xt(t)||s.ruleType==="font-face"||KC(e)){s.simpleProperty(t,e,n);return}let o="",i=t;t=t.toLowerCase();let a=t.match(/^-([a-z]+)-([-a-z0-9]+)$/);a&&(o=a[1],t=a[2]);let l=this.prefixes[t];if(!l||!l[o]){CSS.supports(i,e.toString())?s.simpleProperty(i,e,n):o&&!kl.includes(`-${o}-`)||s.unknownProperty(i,e);return}let c=this.validators[t];if(c){let u=U(e)||e.isExpr()?e:e.visit(c);u?s.simpleProperty(t,u,n):!o&&CSS.supports(t,e.toString())?s.simpleProperty(t,e,n):s.invalidPropertyValue(i,e)}else{let u=this.shorthands[t].clone();U(e)?u.propagateDefaultingValue(e,n,s):(e.visit(u),u.finish(n,s)||s.invalidPropertyValue(i,e))}}};function Wd(){let r=new zd;return r.initBuiltInValidators(),r.parse(Cc),r}var Gd=class extends ct{constructor(){super(...arguments);p(this,"varFound",!1)}visitFunc(e){return e.name==="var"?this.varFound=!0:this.varFound||this.visitValues(e.values),null}};function KC(r){let t=new Gd;return r.visit(t),t.varFound}var ny=`OTTO${new Date().valueOf()}`;function $d(r){return Object.keys(r).filter(t=>!["src","font-family","font-display"].includes(t)).sort()}function QC(r){let t=new $e;for(let e of $d(r))t.append(`${e}:${r[e].toString()};`);return t.toString()}function tg(r,t){let e={};for(let n in r)e[n]=pe(r,n).evaluate(t,n);return e}var Fi=class{constructor(t){this.properties=t;p(this,"fontTraitKey");p(this,"src");p(this,"blobURLs",[]);p(this,"blobs",[]);p(this,"family");this.fontTraitKey=QC(this.properties),this.src=this.properties.src?this.properties.src.toString():null;let e=this.properties["font-family"];this.family=e?e.stringValue():null}traitsEqual(t){return this.fontTraitKey==t.fontTraitKey}makeAtRule(t,e){let n=new $e;n.append(`@font-face {
|
|
1506
1513
|
font-family: `),n.append(this.family),n.append(`;
|
|
1507
|
-
`);for(let s of
|
|
1508
|
-
`);if(e){n.append('src: url("');let s=
|
|
1514
|
+
`);for(let s of $d(this.properties))n.append(s),n.append(": "),this.properties[s].appendTo(n,!0),n.append(`;
|
|
1515
|
+
`);if(e){n.append('src: url("');let s=gh(e);n.append(s),this.blobURLs.push(s),this.blobs.push(e),n.append('")')}else n.append("src: "),n.append(t);return n.append(`;
|
|
1509
1516
|
}
|
|
1510
|
-
`),n.toString()}},La=class{constructor(t){this.deobfuscator=t;d(this,"familyMap",{})}registerFamily(t,e){let n=t.family,s=this.familyMap[n],o=e.family;if(s){if(s!=o)throw new Error(`E_FONT_FAMILY_INCONSISTENT ${t.family}`)}else this.familyMap[n]=o}filterFontFamily(t){if(t instanceof ge){let e=t.values,n=[];for(let s of e){let o=this.familyMap[s.stringValue()];o&&n.push(L(o)),n.push(s)}return new ge(n)}else{let e=this.familyMap[t.stringValue()];return e?new ge([L(e),t]):t}}},Ra=class{constructor(t,e,n){this.head=t;this.body=e;d(this,"srcURLMap",{});d(this,"familyPrefix");d(this,"familyCounter",0);this.familyPrefix=n||"Fnt_"}getViewFontFamily(t,e){let n=t.family,s=e.familyMap[n];return s||(s=this.familyPrefix+ ++this.familyCounter,e.familyMap[n]=s,s)}initFont(t,e,n){let s=A("initFont"),o=t.src,i={};for(let u of Vd(t.properties))i[u]=t.properties[u];let a=this.getViewFontFamily(t,n);i["font-family"]=L(a);let l=new Li(i),c=this.head.ownerDocument.createElement("style");return c.textContent=l.makeAtRule(o,e),this.head.appendChild(c),V.debug("Load font:",o),s.finish(l),s.result()}loadFont(t,e){let n=t.src,s=t.family+";"+n,o=this.srcURLMap[s];return o?o.piggyback(i=>{let a=i;a.traitsEqual(t)?(e.registerFamily(t,a),V.debug("Found already-loaded font:",n)):V.warn("E_FONT_FACE_INCOMPATIBLE",t.src)}):(o=new Zt(()=>{let i=A("loadFont"),a=n.replace(/^url\("([^"]+)"\).*$/,"$1"),l=e.deobfuscator?e.deobfuscator(a):null;return l?hs(a,"blob").then(c=>{if(!c.responseBlob){i.finish(null);return}l(c.responseBlob).then(u=>{this.initFont(t,u,e).thenFinish(i)})}):this.initFont(t,null,e).thenFinish(i),i.result()},`loadFont ${n}`),this.srcURLMap[s]=o,o.start()),o}findOrLoadFonts(t,e){let n=[];for(let s of t){if(!s.src||!s.family){V.warn("E_FONT_FACE_INVALID");continue}n.push(this.loadFont(s,e))}return Rn(n).thenAsync(()=>this.waitFontLoading())}waitFontLoading(){let t=this.head.ownerDocument.fonts,e=0;if(t.forEach(s=>{s.status==="unloaded"&&(e++,s.load().catch(o=>{}))}),e===0)return v(!0);let n=A("waitFontLoading");return n.loop(()=>n.sleep(20).thenAsync(()=>t.status==="loading"?v(!0):v(!1))).thenFinish(n),n.result()}};var DC=1,wo=class{constructor(t,e,n,s,o){this.name=e;this.pseudoName=n;this.classes=s;this.parent=o;d(this,"specified",{});d(this,"children",[]);d(this,"pageMaster",null);d(this,"index",0);d(this,"key");d(this,"_scope");this._scope=t,this.key=`p${DC++}`,o&&(this.index=o.children.length,o.children.push(this))}get scope(){return this._scope}createInstance(t){throw new Error("E_UNEXPECTED_CALL")}clone(t){throw new Error("E_UNEXPECTED_CALL")}copySpecified(t){let e=this.specified,n=t.specified;for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}cloneChildren(t){for(let e=0;e<this.children.length;e++)this.children[e].clone({parent:t})}},Ia=class extends wo{constructor(t){super(t,null,null,[],null),this.specified.width=new M(An,0),this.specified.height=new M(Ln,0)}},Va=class extends is{constructor(e,n){super(e,o);this.pageMaster=n;let s=this;function o(i,a){let l=i.match(/^([^.]+)\.([^.]+)$/);if(l){let c=s.pageMaster.keyMap[l[1]];if(c){let p=this.lookupInstance(c);if(p)return a?p.resolveFunc(l[2]):p.resolveName(l[2])}}return null}}},Po=class r extends wo{constructor(e,n,s,o,i,a,l){super(e,n,s,o,i);this.condition=a;this.specificity=l;d(this,"keyMap",{});e instanceof Va||(this._scope=new Va(e,this)),this.pageMaster=this,this.specified.width=new M(An,0),this.specified.height=new M(Ln,0),this.specified["wrap-flow"]=new M(b.auto,0),this.specified.position=new M(b.relative,0),this.specified.overflow=new M(b.visible,0)}createInstance(e){return new Os(e,this)}clone(e){let n=new r(this.scope,this.name,e.pseudoName||this.pseudoName,this.classes,this.parent,this.condition,this.specificity);return this.copySpecified(n),this.cloneChildren(n),n}resetScope(){this.scope.pageMaster=this}},Fa=class r extends wo{constructor(t,e,n,s,o){super(t,e,n,s,o),this.pageMaster=o.pageMaster,e&&(this.pageMaster.keyMap[e]=this.key),this.specified["wrap-flow"]=new M(b.auto,0)}createInstance(t){return new Fd(t,this)}clone(t){let e=new r(t.parent.scope,this.name,this.pseudoName,this.classes,t.parent);return this.copySpecified(e),this.cloneChildren(e),e}},Zn=class r extends wo{constructor(t,e,n,s,o){super(t,e,n,s,o),this.pageMaster=o.pageMaster,e&&(this.pageMaster.keyMap[e]=this.key)}createInstance(t){return new on(t,this)}clone(t){let e=new r(t.parent.scope,this.name,this.pseudoName,this.classes,t.parent);return this.copySpecified(e),this.cloneChildren(e),e}};function MC(r,t,e){return!t||_(t)?new oe(r,e):t.toExpr(r,r.zero)}function ee(r,t,e){return!t||t===b.auto||_(t)?null:t.toExpr(r,e)}function _C(r,t,e){return!t||t===b.normal||_(t)?null:t.toExpr(r,e)}function st(r,t,e){return!t||t===b.auto||_(t)?r.zero:t.toExpr(r,e)}function Od(r,t,e){return!t||_(t)?r.zero:t===b.auto?null:t.toExpr(r,e)}function Ht(r,t,e,n){return!t||e===b.none||_(t)?r.zero:t.toExpr(r,n)}function Xf(r,t,e){return!t||_(t)?e:t===b._true?r._true:t===b._false?r._false:t.toExpr(r,r.zero)}var ko=class{constructor(t,e){this.parentInstance=t;this.pageBox=e;d(this,"cascaded",{});d(this,"style",{});d(this,"autoWidth",null);d(this,"autoHeight",null);d(this,"children",[]);d(this,"isAutoWidth",!1);d(this,"isAutoHeight",!1);d(this,"isTopDependentOnAutoHeight",!1);d(this,"isRightDependentOnAutoWidth",!1);d(this,"calculatedWidth",0);d(this,"calculatedHeight",0);d(this,"pageMasterInstance",null);d(this,"namedValues",{});d(this,"namedFuncs",{});d(this,"vertical",!1);d(this,"rtl",!1);d(this,"suppressEmptyBoxGeneration",!1);d(this,"borderBoxSizing",!1);t&&t.children.push(this)}reset(){this.calculatedWidth=0,this.calculatedHeight=0}addNamedValues(t,e){let n=this.resolveName(t),s=this.resolveName(e);if(!n||!s)throw new Error("E_INTERNAL");return H(this.pageBox.scope,n,s)}resolveName(t){let e=this.namedValues[t];if(e)return e;let n=this.style[t];switch(n&&(e=n.toExpr(this.pageBox.scope,this.pageBox.scope.zero)),t){case"margin-left-edge":e=this.resolveName("left");break;case"margin-top-edge":e=this.resolveName("top");break;case"margin-right-edge":e=this.addNamedValues("border-right-edge","margin-right");break;case"margin-bottom-edge":e=this.addNamedValues("border-bottom-edge","margin-bottom");break;case"border-left-edge":e=this.addNamedValues("margin-left-edge","margin-left");break;case"border-top-edge":e=this.addNamedValues("margin-top-edge","margin-top");break;case"border-right-edge":e=this.addNamedValues("padding-right-edge","border-right-width");break;case"border-bottom-edge":e=this.addNamedValues("padding-bottom-edge","border-bottom-width");break;case"padding-left-edge":e=this.addNamedValues("border-left-edge","border-left-width");break;case"padding-top-edge":e=this.addNamedValues("border-top-edge","border-top-width");break;case"padding-right-edge":e=this.addNamedValues("right-edge","padding-right");break;case"padding-bottom-edge":e=this.addNamedValues("bottom-edge","padding-bottom");break;case"left-edge":e=this.addNamedValues("padding-left-edge","padding-left");break;case"top-edge":e=this.addNamedValues("padding-top-edge","padding-top");break;case"right-edge":e=this.addNamedValues("left-edge","width");break;case"bottom-edge":e=this.addNamedValues("top-edge","height");break}if(!e){let s;if(t=="extent")s=this.vertical?"width":"height";else if(t=="measure")s=this.vertical?"height":"width";else{let o=this.vertical?ku:Au;s=t;for(let i in o)s=s.replace(i,o[i])}s!=t&&(e=this.resolveName(s))}return e&&(this.namedValues[t]=e),e}resolveFunc(t){let e=this.namedFuncs[t];if(e)return e;switch(t){case"columns":{let n=this.pageBox.scope,s=new js(n,0),o=this.resolveName("column-count"),i=this.resolveName("column-width"),a=this.resolveName("column-gap");e=Y(n,Ys(n,new ln(n,"min",[s,o]),H(n,i,a)),a);break}}return e&&(this.namedFuncs[t]=e),e}initEnabled(){let t=this.pageBox.scope,e=this.style,n=Xf(t,e.enabled,t._true),s=ee(t,e.page,t.zero);if(s){let a=new J(t,"page-number");n=et(t,n,new Pn(t,s,a))}let o=ee(t,e["min-page-width"],t.zero);o&&(n=et(t,n,new rs(t,new J(t,"page-width"),o)));let i=ee(t,e["min-page-height"],t.zero);i&&(n=et(t,n,new rs(t,new J(t,"page-height"),i))),n=this.boxSpecificEnabled(n),e.enabled=new F(n)}boxSpecificEnabled(t){return t}initHorizontal(){let t=this.pageBox.scope,e=this.style,n=this.parentInstance?this.parentInstance.style.width.toExpr(t,null):null,s=ee(t,e.left,n),o=ee(t,e["margin-left"],n),i=Ht(t,e["border-left-width"],e["border-left-style"],n),a=st(t,e["padding-left"],n),l=ee(t,e.width,n),c=ee(t,e["max-width"],n),u=st(t,e["padding-right"],n),p=Ht(t,e["border-right-width"],e["border-right-style"],n),h=ee(t,e["margin-right"],n),f=ee(t,e.right,n),g=H(t,i,a),m=H(t,i,u);if(s&&f&&l){let C=Y(t,n,H(t,l,H(t,H(t,s,g),m)));o?h?f=Y(t,C,h):h=Y(t,C,H(t,f,o)):(C=Y(t,C,f),h?o=Y(t,C,h):(o=Ys(t,C,new oe(t,.5)),h=o))}else{o||(o=t.zero),h||(h=t.zero),!s&&!f&&!l&&(s=t.zero),!s&&!l?(l=this.autoWidth,this.isAutoWidth=!0):!s&&!f?s=t.zero:!l&&!f&&(l=this.autoWidth,this.isAutoWidth=!0);let C=Y(t,n,H(t,H(t,o,g),H(t,h,m)));this.isAutoWidth&&(c||(c=Y(t,C,s||f)),!this.vertical&&(ee(t,e["column-width"],null)||ee(t,e["column-count"],null))&&(l=c,this.isAutoWidth=!1)),s?l?f||(f=Y(t,C,H(t,s,l))):l=Y(t,C,H(t,s,f)):s=Y(t,C,H(t,f,l))}let E=e["snap-width"]||(this.parentInstance?this.parentInstance.style["snap-width"]:null),y=st(t,E,n);e.left=new F(s),e["margin-left"]=new F(o),e["border-left-width"]=new F(i),e["padding-left"]=new F(a),e.width=new F(l),e["max-width"]=new F(c||l),e["padding-right"]=new F(u),e["border-right-width"]=new F(p),e["margin-right"]=new F(h),e.right=new F(f),e["snap-width"]=new F(y)}initVertical(){let t=this.pageBox.scope,e=this.style,n=this.parentInstance?this.parentInstance.style.width.toExpr(t,null):null,s=this.parentInstance?this.parentInstance.style.height.toExpr(t,null):null,o=ee(t,e.top,s),i=ee(t,e["margin-top"],n),a=Ht(t,e["border-top-width"],e["border-top-style"],n),l=st(t,e["padding-top"],n),c=ee(t,e.height,s),u=ee(t,e["max-height"],s),p=st(t,e["padding-bottom"],n),h=Ht(t,e["border-bottom-width"],e["border-bottom-style"],n),f=ee(t,e["margin-bottom"],n),g=ee(t,e.bottom,s),m=H(t,a,l),E=H(t,h,p);if(o&&g&&c){let x=Y(t,s,H(t,c,H(t,H(t,o,m),E)));i?f?g=Y(t,x,i):f=Y(t,x,H(t,g,i)):(x=Y(t,x,g),f?i=Y(t,x,f):(i=Ys(t,x,new oe(t,.5)),f=i))}else{i||(i=t.zero),f||(f=t.zero),!o&&!g&&!c&&(o=t.zero),!o&&!c?(c=this.autoHeight,this.isAutoHeight=!0):!o&&!g?o=t.zero:!c&&!g&&(c=this.autoHeight,this.isAutoHeight=!0);let x=Y(t,s,H(t,H(t,i,m),H(t,f,E)));this.isAutoHeight&&(u||(u=Y(t,x,o||g)),this.vertical&&(ee(t,e["column-width"],null)||ee(t,e["column-count"],null))&&(c=u,this.isAutoHeight=!1)),o?c?g||(g=Y(t,x,H(t,o,c))):c=Y(t,x,H(t,g,o)):o=Y(t,x,H(t,g,c))}let y=e["snap-height"]||(this.parentInstance?this.parentInstance.style["snap-height"]:null),C=st(t,y,n);e.top=new F(o),e["margin-top"]=new F(i),e["border-top-width"]=new F(a),e["padding-top"]=new F(l),e.height=new F(c),e["max-height"]=new F(u||c),e["padding-bottom"]=new F(p),e["border-bottom-width"]=new F(h),e["margin-bottom"]=new F(f),e.bottom=new F(g),e["snap-height"]=new F(C)}initColumns(){let t=this.pageBox.scope,e=this.style,n=ee(t,e[this.vertical?"height":"width"],null),s=ee(t,e["column-width"],n),o=ee(t,e["column-count"],null),i=_C(t,e["column-gap"],null);i||(i=new Vt(t,1,"em")),s&&!o&&(o=new ln(t,"floor",[$o(t,H(t,n,i),H(t,s,i))]),o=new ln(t,"max",[t.one,o])),o||(o=t.one),s=Y(t,$o(t,H(t,n,i),o),i),e["column-width"]=new F(s),e["column-count"]=new F(o),e["column-gap"]=new F(i)}depends(t,e,n){return this.style[t].toExpr(this.pageBox.scope,null).depend(e,n)}init(t){var l;t.registerInstance(this.pageBox.key,this);let n=this.pageBox.scope,s=this.style,o=this.parentInstance?this.parentInstance.getActiveRegions(t):null,i=fa(this.cascaded,t,o,!1,null);this.vertical=pa(i,t,this.parentInstance?this.parentInstance.vertical:!1),this.rtl=ha(i,t,this.parentInstance?this.parentInstance.rtl:!1),this.borderBoxSizing=((l=i["box-sizing"])==null?void 0:l.value)===b.border_box;let a=!!(t instanceof Qn&&t.currentLayoutPosition&&new J(n,"left-page").evaluate(t));ga(i,s,this.vertical,this.rtl,a,(c,u)=>u.value),this.autoWidth=new ie(n,()=>this.calculatedWidth,"autoWidth"),this.autoHeight=new ie(n,()=>this.calculatedHeight,"autoHeight"),this.initHorizontal(),this.initVertical(),this.initColumns(),this.initEnabled()}getProp(t,e){var s,o;let n=this.style[e];return!n&&Xn(e)&&(e==="font-size"&&t.isRelativeRootFontSize&&t.rootFontSize?n=new P(t.rootFontSize,"px"):n=(o=((s=t.styler)==null?void 0:s.rootStyle)[e])==null?void 0:o.value),n&&(n=gi(t,n,e)),n}getPropAsNumber(t,e){var s,o;let n=this.style[e];if(n){let i=/\b(height|top|bottom)\b/.test(e)?(s=t.pageAreaHeight)!=null?s:t.pageHeight():(o=t.pageAreaWidth)!=null?o:t.pageWidth();n=gi(t,n,e,i)}return Le(n,t)}getSpecial(t,e){let n=Lu(this.cascaded,e);if(n){let s=[];for(let o=0;o<n.length;o++){let i=n[o].evaluate(t,"");i&&i!==O&&s.push(i)}if(s.length)return s}return null}getActiveRegions(t){let e=this.getSpecial(t,"region-id");if(e){let n=[];for(let s=0;s<e.length;s++)n[s]=e[s].toString();return n}return null}propagateProperty(t,e,n,s){this.propagatePropertyToElement(t,e.element,n,s)}propagatePropertyToElement(t,e,n,s){let o=this.getProp(t,n);o&&(o.isNumeric()&&mr(o.unit)&&(o=xr(o,t)),n==="font-family"&&(o=s.filterFontFamily(o)),(n.startsWith("background")||n==="z-index")&&e.parentElement.hasAttribute("data-vivliostyle-bleed-box")&&(e=e.parentElement),T(e,n,o.toString()))}propagateDelayedProperty(t,e,n,s){let o=this.getProp(t,n);o&&s.push(new Dn(e.element,n,o))}assignLeftPosition(t,e){let n=this.getPropAsNumber(t,"left"),s=this.getPropAsNumber(t,"margin-left"),o=this.getPropAsNumber(t,"padding-left"),i=this.getPropAsNumber(t,"border-left-width"),a=this.getPropAsNumber(t,"width");e.setHorizontalPosition(n,a),T(e.element,"margin-left",`${s}px`),T(e.element,"padding-left",`${o}px`),T(e.element,"border-left-width",`${i}px`),e.marginLeft=s,e.borderLeft=i,e.paddingLeft=o}assignRightPosition(t,e){let n=this.getPropAsNumber(t,"right"),s=this.getPropAsNumber(t,"snap-height"),o=this.getPropAsNumber(t,"margin-right"),i=this.getPropAsNumber(t,"padding-right"),a=this.getPropAsNumber(t,"border-right-width");if(T(e.element,"margin-right",`${o}px`),T(e.element,"padding-right",`${i}px`),T(e.element,"border-right-width",`${a}px`),e.marginRight=o,e.borderRight=a,this.vertical&&s>0){let l=n+e.getInsetRight(),c=l-Math.floor(l/s)*s;c>0&&(e.snapOffsetX=s-c,i+=e.snapOffsetX)}e.paddingRight=i,e.snapWidth=s}assignTopPosition(t,e){let n=this.getPropAsNumber(t,"snap-height"),s=this.getPropAsNumber(t,"top"),o=this.getPropAsNumber(t,"margin-top"),i=this.getPropAsNumber(t,"padding-top"),a=this.getPropAsNumber(t,"border-top-width");if(e.top=s,e.marginTop=o,e.borderTop=a,e.snapHeight=n,!this.vertical&&n>0){let l=s+e.getInsetTop(),c=l-Math.floor(l/n)*n;c>0&&(e.snapOffsetY=n-c,i+=e.snapOffsetY)}e.paddingTop=i,T(e.element,"top",`${s}px`),T(e.element,"margin-top",`${o}px`),T(e.element,"padding-top",`${i}px`),T(e.element,"border-top-width",`${a}px`)}assignBottomPosition(t,e){let n=this.getPropAsNumber(t,"margin-bottom"),s=this.getPropAsNumber(t,"padding-bottom"),o=this.getPropAsNumber(t,"border-bottom-width"),i=this.getPropAsNumber(t,"height")-e.snapOffsetY;T(e.element,"height",`${i}px`),T(e.element,"margin-bottom",`${n}px`),T(e.element,"padding-bottom",`${s}px`),T(e.element,"border-bottom-width",`${o}px`),e.height=i-e.snapOffsetY,e.marginBottom=n,e.borderBottom=o,e.paddingBottom=s}assignBeforePosition(t,e){this.vertical?this.assignRightPosition(t,e):this.assignTopPosition(t,e)}assignAfterPosition(t,e){this.vertical?this.assignLeftPosition(t,e):this.assignBottomPosition(t,e)}assignStartEndPosition(t,e){this.vertical?(this.assignTopPosition(t,e),this.assignBottomPosition(t,e)):(this.assignRightPosition(t,e),this.assignLeftPosition(t,e))}sizeWithMaxHeight(t,e){T(e.element,"border-top-width","0px");let n=this.getPropAsNumber(t,"max-height");this.isTopDependentOnAutoHeight?e.setVerticalPosition(0,n):(this.assignTopPosition(t,e),n-=e.snapOffsetY,e.height=n,T(e.element,"height",`${n}px`))}sizeWithMaxWidth(t,e){T(e.element,"border-left-width","0px");let n=this.getPropAsNumber(t,"max-width");if(this.isRightDependentOnAutoWidth)e.setHorizontalPosition(0,n);else{this.assignRightPosition(t,e),n-=e.snapOffsetX,e.width=n;let s=this.getPropAsNumber(t,"right");T(e.element,"right",`${s}px`),T(e.element,"width",`${n}px`)}}prepareContainer(t,e,n,s,o){(!this.parentInstance||this.vertical!=this.parentInstance.vertical)&&T(e.element,"writing-mode",this.vertical?"vertical-rl":"horizontal-tb"),(!this.parentInstance||this.rtl!=this.parentInstance.rtl)&&T(e.element,"direction",this.rtl?"rtl":"ltr"),(this.vertical?this.isAutoWidth:this.isAutoHeight)?this.vertical?this.sizeWithMaxWidth(t,e):this.sizeWithMaxHeight(t,e):(this.assignBeforePosition(t,e),this.assignAfterPosition(t,e)),(this.vertical?this.isAutoHeight:this.isAutoWidth)?this.vertical?this.sizeWithMaxHeight(t,e):this.sizeWithMaxWidth(t,e):this.assignStartEndPosition(t,e);for(let i=0;i<Hf.length;i++)this.propagateProperty(t,e,Hf[i],s)}transferContentProps(t,e,n,s){for(let o=0;o<Gf.length;o++)this.propagateProperty(t,e,Gf[o],s);if(this.style["text-overflow"]){let o=e.element.firstElementChild;T(o,"text-overflow","inherit"),T(o,"overflow","inherit")}}transferSingleUriContentProps(t,e,n){let s=()=>{var a,l;let i=(l=(a=this.cascaded.width)!=null?a:this.cascaded[this.vertical?"block-size":"inline-size"])==null?void 0:l.value;return!!i&&i!==b.auto&&!_(i)},o=()=>{var a,l;let i=(l=(a=this.cascaded.height)!=null?a:this.cascaded[this.vertical?"inline-size":"block-size"])==null?void 0:l.value;return!!i&&i!==b.auto&&!_(i)};for(let i=0;i<Wf.length;i++){let a=Wf[i];if(a==="width"||a==="height"){if(a==="width"&&!s()||a==="height"&&!o())continue;T(e,a,"100%");continue}this.propagatePropertyToElement(t,e,a,n)}}finishContainer(t,e,n,s,o,i,a){this.vertical?this.calculatedWidth=e.computedBlockSize+e.snapOffsetX:this.calculatedHeight=e.computedBlockSize+e.snapOffsetY;let l=(this.vertical||!s)&&this.isAutoHeight,c=(!this.vertical||!s)&&this.isAutoWidth,u=null;if((c||l)&&(c&&T(e.element,"width","auto"),l&&T(e.element,"height","auto"),u=i.getElementClientRect(s?s.element:e.element),c&&(this.calculatedWidth=Math.ceil(u.right-u.left-e.paddingLeft-e.borderLeft-e.paddingRight-e.borderRight),this.vertical&&(this.calculatedWidth+=e.snapOffsetX)),l&&(this.calculatedHeight=u.bottom-u.top-e.paddingTop-e.borderTop-e.paddingBottom-e.borderBottom,this.vertical||(this.calculatedHeight+=e.snapOffsetY))),(this.vertical?this.isAutoHeight:this.isAutoWidth)&&this.assignStartEndPosition(t,e),(this.vertical?this.isAutoWidth:this.isAutoHeight)&&((this.vertical?this.isRightDependentOnAutoWidth:this.isTopDependentOnAutoHeight)&&this.assignBeforePosition(t,e),this.assignAfterPosition(t,e)),o>1){let p=this.getPropAsNumber(t,"column-rule-width"),h=this.getProp(t,"column-rule-style"),f=this.getProp(t,"column-rule-color");if(p>0&&h&&h!=b.none&&f!=b.transparent){let g=this.getPropAsNumber(t,"column-gap"),m=this.vertical?e.height:e.width,E=this.vertical?"border-top":"border-left";for(let y=1;y<o;y++){let C=this.vertical?(m+g)*y/o-g/2+e.paddingTop-p/2:(m+g)*y/o-g/2+e.paddingLeft-p/2,x=this.vertical?e.width+e.paddingLeft+e.paddingRight:e.height+e.paddingTop+e.paddingBottom,N=e.element.ownerDocument.createElement("div");T(N,"position","absolute"),T(N,this.vertical?"left":"top","0px"),T(N,this.vertical?"top":"left",`${C}px`),T(N,this.vertical?"height":"width","0px"),T(N,this.vertical?"width":"height",`${x}px`),T(N,E,`${p}px ${h.toString()}${f?` ${f.toString()}`:""}`),e.element.insertBefore(N,e.element.firstChild)}}}for(let p=0;p<zf.length;p++)this.propagateProperty(t,e,zf[p],a);for(let p=0;p<$f.length;p++)this.propagateDelayedProperty(t,e,$f[p],n.delayedItems)}applyCascadeAndInit(t,e){let n=this.cascaded,s=this.pageBox.specified;for(let i in s)this instanceof Sn&&this.pageBox.pseudoName=="vivliostyle-page-rule-master"&&(i==="writing-mode"||i==="direction")||Ts(i)&&Cn(n,i,pe(s,i));if(this.pageBox.pseudoName==Ii)for(let i in e)(i.match(/^background-/)||i=="writing-mode")&&(n[i]=e[i]);if(this.pageBox.pseudoName=="layout-host")for(let i in e)!i.match(/^background-/)&&i!="writing-mode"&&(n[i]=e[i]);t.pushRule(this.pageBox.classes,null,n);let o=n.content;o&&(n.content=o.filterValue(new xo(t,null,t.counterResolver))),this.init(t.context);for(let i of this.pageBox.children)i.createInstance(this).applyCascadeAndInit(t,e);t.popRule()}resolveAutoSizing(t){this.isAutoWidth&&(this.isRightDependentOnAutoWidth=this.depends("right",this.autoWidth,t)||this.depends("margin-right",this.autoWidth,t)||this.depends("border-right-width",this.autoWidth,t)||this.depends("padding-right",this.autoWidth,t)),this.isAutoHeight&&(this.isTopDependentOnAutoHeight=this.depends("top",this.autoHeight,t)||this.depends("margin-top",this.autoHeight,t)||this.depends("border-top-width",this.autoHeight,t)||this.depends("padding-top",this.autoHeight,t));for(let e of this.children)e.resolveAutoSizing(t)}},Hf=["border-left-style","border-right-style","border-top-style","border-bottom-style","border-left-color","border-right-color","border-top-color","border-bottom-color","box-sizing","outline-style","outline-color","outline-width","overflow","visibility"],zf=["border-top-left-radius","border-top-right-radius","border-bottom-right-radius","border-bottom-left-radius","border-start-start-radius","border-start-end-radius","border-end-start-radius","border-end-end-radius","border-image-source","border-image-slice","border-image-width","border-image-outset","border-image-repeat","background-attachment","background-color","background-image","background-repeat","background-position","background-clip","background-origin","background-size","box-shadow","opacity","z-index","background-blend-mode","isolation","mix-blend-mode","filter"],Gf=["color","font-family","font-size","font-style","font-weight","line-height","letter-spacing","text-align","text-align-last","text-decoration","text-indent","text-transform","white-space","text-wrap","text-wrap-mode","text-wrap-style","word-spacing","font-feature-settings","font-kerning","font-size-adjust","font-variant-ligatures","font-variant-caps","font-variant-numeric","font-variant-east-asian","font-stretch","text-combine-upright","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-fill-color","text-orientation","text-shadow","text-stroke-color","text-stroke-width","text-underline-offset","text-underline-position","text-overflow"],Wf=["width","height","image-resolution","object-fit","object-position"],$f=["transform","transform-origin"],Ii="background-host",Ba=class extends ko{constructor(t){super(null,t)}applyCascadeAndInit(t,e){super.applyCascadeAndInit(t,e),this.children.sort((s,o)=>o.pageBox.specificity-s.pageBox.specificity||s.pageBox.index-o.pageBox.index)}},Os=class extends ko{constructor(t,e){super(t,e),this.pageMasterInstance=this}boxSpecificEnabled(t){let e=this.pageBox.pageMaster;return e.condition&&(t=et(e.scope,t,e.condition)),t}adjustPageLayout(t,e,n){}},Fd=class extends ko{constructor(t,e){super(t,e),this.pageMasterInstance=t.pageMasterInstance}},on=class extends ko{constructor(t,e){super(t,e),this.pageMasterInstance=t.pageMasterInstance}processPartitionList(t,e,n){let s=null;if(e instanceof be&&(s=[e]),e instanceof ge&&(s=e.values),s){let o=this.pageBox.scope;for(let i=0;i<s.length;i++)if(s[i]instanceof be){let a=Wo(s[i].name,"enabled"),l=new J(o,a);n&&(l=new gt(o,l)),t=et(o,t,l)}}return t}boxSpecificEnabled(t){let e=this.pageBox.scope,n=this.style,s=Xf(e,n.required,e._false)!==e._false;if(s||this.isAutoHeight){let o=MC(e,n["flow-from"],"body"),i=new ln(e,"has-content",[o]);t=et(e,t,i)}if(t=this.processPartitionList(t,n["required-partitions"],!1),t=this.processPartitionList(t,n["conflicting-partitions"],!0),s){let o=this.pageMasterInstance.style.enabled,i=o?o.toExpr(e,null):e._true;i=et(e,i,t),this.pageMasterInstance.style.enabled=new F(i)}return t}prepareContainer(t,e,n,s,o){var i;this.pageBox.pageMaster instanceof Vi||(T(e.element,"overflow","hidden"),e.element.setAttribute("data-vivliostyle-page-partition",(i=this.pageBox.name)!=null?i:"")),super.prepareContainer(t,e,n,s,o)}},Ri=class extends Qt{constructor(e,n,s,o){super(e,n,!1);this.target=s;this.validatorSet=o}property(e,n,s){this.validatorSet.validatePropertyAndHandleShorthand(e,n,s,this)}unknownProperty(e,n){this.report(`E_INVALID_PROPERTY ${e}: ${n.toString()}`)}invalidPropertyValue(e,n){this.report(`E_INVALID_PROPERTY_VALUE ${e}: ${n.toString()}`)}simpleProperty(e,n,s){this.target.specified[e]=new M(n,s?Rr:Ir)}},Oa=class extends Ri{constructor(t,e,n,s){super(t,e,n,s)}},Bd=class r extends Ri{constructor(t,e,n,s){super(t,e,n,s),n.specified.width=new M(Fl,0),n.specified.height=new M(Fl,0)}startPartitionRule(t,e,n){let s=new Zn(this.scope,t,e,n,this.target),o=new Oa(this.scope,this.owner,s,this.validatorSet);this.owner.pushHandler(o)}startPartitionGroupRule(t,e,n){let s=new Fa(this.scope,t,e,n,this.target),o=new r(this.scope,this.owner,s,this.validatorSet);this.owner.pushHandler(o)}},Da=class extends Ri{constructor(t,e,n,s){super(t,e,n,s)}startPartitionRule(t,e,n){let s=new Zn(this.scope,t,e,n,this.target),o=new Oa(this.scope,this.owner,s,this.validatorSet);this.owner.pushHandler(o)}startPartitionGroupRule(t,e,n){let s=new Fa(this.scope,t,e,n,this.target),o=new Bd(this.scope,this.owner,s,this.validatorSet);this.owner.pushHandler(o)}};function tp(r){var n,s;let t=(n=r["writing-mode"])==null?void 0:n.value,e=(s=r.direction)==null?void 0:s.value;return t===b.vertical_lr||t!==b.vertical_rl&&e!==b.rtl?"ltr":"rtl"}var UC={a10:{width:new P(26,"mm"),height:new P(37,"mm")},a9:{width:new P(37,"mm"),height:new P(52,"mm")},a8:{width:new P(52,"mm"),height:new P(74,"mm")},a7:{width:new P(74,"mm"),height:new P(105,"mm")},a6:{width:new P(105,"mm"),height:new P(148,"mm")},a5:{width:new P(148,"mm"),height:new P(210,"mm")},a4:{width:new P(210,"mm"),height:new P(297,"mm")},a3:{width:new P(297,"mm"),height:new P(420,"mm")},a2:{width:new P(420,"mm"),height:new P(594,"mm")},a1:{width:new P(594,"mm"),height:new P(841,"mm")},a0:{width:new P(841,"mm"),height:new P(1189,"mm")},b10:{width:new P(31,"mm"),height:new P(44,"mm")},b9:{width:new P(44,"mm"),height:new P(62,"mm")},b8:{width:new P(62,"mm"),height:new P(88,"mm")},b7:{width:new P(88,"mm"),height:new P(125,"mm")},b6:{width:new P(125,"mm"),height:new P(176,"mm")},b5:{width:new P(176,"mm"),height:new P(250,"mm")},b4:{width:new P(250,"mm"),height:new P(353,"mm")},b3:{width:new P(353,"mm"),height:new P(500,"mm")},b2:{width:new P(500,"mm"),height:new P(707,"mm")},b1:{width:new P(707,"mm"),height:new P(1e3,"mm")},b0:{width:new P(1e3,"mm"),height:new P(1414,"mm")},c10:{width:new P(28,"mm"),height:new P(40,"mm")},c9:{width:new P(40,"mm"),height:new P(57,"mm")},c8:{width:new P(57,"mm"),height:new P(81,"mm")},c7:{width:new P(81,"mm"),height:new P(114,"mm")},c6:{width:new P(114,"mm"),height:new P(162,"mm")},c5:{width:new P(162,"mm"),height:new P(229,"mm")},c4:{width:new P(229,"mm"),height:new P(324,"mm")},c3:{width:new P(324,"mm"),height:new P(458,"mm")},c2:{width:new P(458,"mm"),height:new P(648,"mm")},c1:{width:new P(648,"mm"),height:new P(917,"mm")},c0:{width:new P(917,"mm"),height:new P(1297,"mm")},"jis-b10":{width:new P(32,"mm"),height:new P(45,"mm")},"jis-b9":{width:new P(45,"mm"),height:new P(64,"mm")},"jis-b8":{width:new P(64,"mm"),height:new P(91,"mm")},"jis-b7":{width:new P(91,"mm"),height:new P(128,"mm")},"jis-b6":{width:new P(128,"mm"),height:new P(182,"mm")},"jis-b5":{width:new P(182,"mm"),height:new P(257,"mm")},"jis-b4":{width:new P(257,"mm"),height:new P(364,"mm")},"jis-b3":{width:new P(364,"mm"),height:new P(515,"mm")},"jis-b2":{width:new P(515,"mm"),height:new P(728,"mm")},"jis-b1":{width:new P(728,"mm"),height:new P(1030,"mm")},"jis-b0":{width:new P(1030,"mm"),height:new P(1456,"mm")},letter:{width:new P(8.5,"in"),height:new P(11,"in")},legal:{width:new P(8.5,"in"),height:new P(14,"in")},ledger:{width:new P(11,"in"),height:new P(17,"in")}},HC=new P(.24,"pt"),$x=new P(3,"mm"),zC=new P(10,"mm"),GC=new P(13,"mm");function Mi(r){let t={width:An,height:Ln,bleed:te,bleedOffset:te,cropOffset:te},e=r.size;if(!(!e||e.value===b.auto)){let c=e.value,u,p;if(c.isSpaceList()?(u=c.values[0],p=c.values[1]):(u=c,p=null),u.isNumeric())t.width=u,t.height=p||u;else{let h=u.name&&UC[u.name.toLowerCase()];h&&(p&&p===b.landscape?(t.width=h.height,t.height=h.width):(t.width=h.width,t.height=h.height))}}let n=r.marks,s=r.bleed,o=n&&!_(n.value)?n.value:b.none,i=s&&!_(s.value)?s.value:b.auto;if(i===b.auto){if(o!==b.none){let c=!1;o.isSpaceList()?c=o.values.some(u=>u===b.crop):c=o===b.crop,c&&(t.bleed=new P(6,"pt"))}}else i.isNumeric()&&(t.bleed=i);let a=r["crop-offset"],l=a&&!_(a.value)?a.value:b.auto;return l===b.auto?o!==b.none&&(t.bleedOffset=GC):l.isNumeric()&&(t.cropOffset=l),t}function np(r,t){let e={},n=Math.max(0,r.bleed.num)*t.queryUnitSize(r.bleed.unit,!1),s=!r.cropOffset.num&&r.bleedOffset.num?r.bleedOffset.num*t.queryUnitSize(r.bleedOffset.unit,!1):Math.max(0,r.cropOffset.num*t.queryUnitSize(r.cropOffset.unit,!1)-n),o=n+s,i=r.width;i===An?t.pref.defaultPaperSize?e.pageWidth=t.pref.defaultPaperSize.width*t.queryUnitSize("px",!1):e.pageWidth=(t.pref.spreadView?Math.floor(t.viewportWidth/2)-t.pref.pageBorder:t.viewportWidth)-o*2:e.pageWidth=i.num*t.queryUnitSize(i.unit,!1);let a=r.height;return a===Ln?t.pref.defaultPaperSize?e.pageHeight=t.pref.defaultPaperSize.height*t.queryUnitSize("px",!1):e.pageHeight=t.viewportHeight-o*2:e.pageHeight=a.num*t.queryUnitSize(a.unit,!1),e.bleed=n,e.bleedOffset=s,e.cropOffset=o,e}function Yf(r,t,e){let n=r.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",t),n.setAttribute("height",e),n.style.position="absolute",n}function Fi(r,t,e,n){n=n||"polyline";let s=r.createElementNS("http://www.w3.org/2000/svg",n);return s.setAttribute("stroke",e===b.auto?"#010101":e.toString()),s.setAttribute("stroke-width",t),s.setAttribute("fill","none"),s}var Dd=(s=>(s.TOP_LEFT="top left",s.TOP_RIGHT="top right",s.BOTTOM_LEFT="bottom left",s.BOTTOM_RIGHT="bottom right",s))(Dd||{});function WC(r,t,e,n,s,o,i){let a=s;a<=o+2*$.mm&&(a=o+s/2);let l=Math.max(s,a),c=o+l+e/2,u=Yf(r,c,c),p=[[0,o+s],[s,o+s],[s,o+s-a]],h=p.map(m=>[m[1],m[0]]);(t==="top right"||t==="bottom right")&&(p=p.map(m=>[o+l-m[0],m[1]]),h=h.map(m=>[o+l-m[0],m[1]])),(t==="bottom left"||t==="bottom right")&&(p=p.map(m=>[m[0],o+l-m[1]]),h=h.map(m=>[m[0],o+l-m[1]]));let f=Fi(r,e,n);f.setAttribute("points",p.map(m=>m.join(",")).join(" ")),u.appendChild(f);let g=Fi(r,e,n);return g.setAttribute("points",h.map(m=>m.join(",")).join(" ")),u.appendChild(g),t.split(" ").forEach(m=>{u.style[m]=`${i}px`}),u}var Bi=(s=>(s.TOP="top",s.BOTTOM="bottom",s.LEFT="left",s.RIGHT="right",s))(Bi||{});function $C(r,t,e,n,s,o){let i=s*2,a,l;t==="top"||t==="bottom"?(a=i,l=s):(a=s,l=i);let c=Yf(r,a,l),u=Fi(r,e,n);u.setAttribute("points",`0,${l/2} ${a},${l/2}`),c.appendChild(u);let p=Fi(r,e,n);p.setAttribute("points",`${a/2},0 ${a/2},${l}`),c.appendChild(p);let h=Fi(r,e,n,"circle");h.setAttribute("cx",a/2),h.setAttribute("cy",l/2),h.setAttribute("r",s/4),c.appendChild(h);let f;switch(t){case"top":f="bottom";break;case"bottom":f="top";break;case"left":f="right";break;case"right":f="left";break}return Object.keys(Bi).forEach(g=>{let m=Bi[g];m===t?c.style[m]=`${o}px`:m!==f&&(c.style[m]="0",c.style[`margin-${m}`]="auto")}),c}function Kf(r,t,e,n){let s=!1,o=!1,i=r.marks;if(i){let m=i.value;m instanceof K?m.values.forEach(E=>{E===b.crop?s=!0:E===b.cross&&(o=!0)}):m===b.crop?s=!0:m===b.cross&&(o=!0)}let a=t.bleed;if(!s&&!o)return;let l=e.container,c=l.ownerDocument;let u=Le(HC,n),p=Math.max(0,t.bleedOffset-Le(zC,n)),h=t.bleedOffset-p,f=r["crop-marks-line-color"],g=f&&!_(f.value)?f.value:b.auto;s&&Object.keys(Dd).forEach(m=>{let E=Dd[m],y=WC(c,E,u,g,h,a,p);l.appendChild(y)}),o&&Object.keys(Bi).forEach(m=>{let E=Bi[m],y=$C(c,E,u,g,h,p);l.appendChild(y)})}var Md=(()=>{let r=["left","right","top","bottom","before","after","start","end","block-start","block-end","inline-start","inline-end","inside","outside"],t={width:!0,height:!0,"block-size":!0,"inline-size":!0,margin:!0,padding:!0,border:!0,outline:!0,"outline-width":!0,"outline-style":!0,"outline-color":!0,"border-radius":!0,"border-top-left-radius":!0,"border-top-right-radius":!0,"border-bottom-right-radius":!0,"border-bottom-left-radius":!0,"border-start-start-radius":!0,"border-start-end-radius":!0,"border-end-start-radius":!0,"border-end-end-radius":!0,"box-shadow":!0,"box-sizing":!0};return r.forEach(e=>{t[`margin-${e}`]=!0,t[`padding-${e}`]=!0,t[`border-${e}-width`]=!0,t[`border-${e}-style`]=!0,t[`border-${e}-color`]=!0}),t})();var sp={"top-left-corner":{order:1,isInTopRow:!0,isInBottomRow:!1,isInLeftColumn:!0,isInRightColumn:!1,positionAlongVariableDimension:null},"top-left":{order:2,isInTopRow:!0,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:"start"},"top-center":{order:3,isInTopRow:!0,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:"center"},"top-right":{order:4,isInTopRow:!0,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:"end"},"top-right-corner":{order:5,isInTopRow:!0,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!0,positionAlongVariableDimension:null},"right-top":{order:6,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!0,positionAlongVariableDimension:"start"},"right-middle":{order:7,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!0,positionAlongVariableDimension:"center"},"right-bottom":{order:8,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!0,positionAlongVariableDimension:"end"},"bottom-right-corner":{order:9,isInTopRow:!1,isInBottomRow:!0,isInLeftColumn:!1,isInRightColumn:!0,positionAlongVariableDimension:null},"bottom-right":{order:10,isInTopRow:!1,isInBottomRow:!0,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:"end"},"bottom-center":{order:11,isInTopRow:!1,isInBottomRow:!0,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:"center"},"bottom-left":{order:12,isInTopRow:!1,isInBottomRow:!0,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:"start"},"bottom-left-corner":{order:13,isInTopRow:!1,isInBottomRow:!0,isInLeftColumn:!0,isInRightColumn:!1,positionAlongVariableDimension:null},"left-bottom":{order:14,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!0,isInRightColumn:!1,positionAlongVariableDimension:"end"},"left-middle":{order:15,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!0,isInRightColumn:!1,positionAlongVariableDimension:"center"},"left-top":{order:16,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!0,isInRightColumn:!1,positionAlongVariableDimension:"start"}},XC=(()=>{let r=sp;return Object.keys(r).sort((t,e)=>r[t].order-r[e].order)})(),Ha="vivliostyle-page-rule-master",Oi="_marginBoxes",Vi=class extends Po{constructor(e,n,s){super(e,null,Ha,[],n,null,0);d(this,"pageMarginBoxes",{});let o=Mi(s),i=new _d(this.scope,this,s,o);this.createPageMarginBoxes(s),this.applySpecified(s,o)}createPageMarginBoxes(e){let n=e[Oi];n&&XC.forEach(s=>{n[s]&&(this.pageMarginBoxes[s]=new Hd(this.scope,this,s,e))})}applySpecified(e,n){this.specified.position=new M(b.relative,0),this.specified.width=new M(n.width,0),this.specified.height=new M(n.height,0);for(let s in e)!Md[s]&&s!=="background-clip"&&(this.specified[s]=e[s])}createInstance(e){return new Sn(e,this)}},_d=class extends Zn{constructor(e,n,s,o){super(e,null,null,[],n);this.pageSize=o;let i=new Ud(this.scope,this);this.applySpecified(s)}applySpecified(e){this.specified["wrap-flow"]=new M(b.auto,0),this.specified["z-index"]=new M(new ct(0),0),this.specified.position=new M(b.absolute,0),this.specified.overflow=new M(b.visible,0);for(let n in Md)Md.hasOwnProperty(n)&&(this.specified[n]=e[n])}createInstance(e){return new Gd(e,this)}},Ud=class extends Zn{constructor(t,e){super(t,null,null,[],e),this.specified["flow-from"]=new M(L("body"),0)}createInstance(t){return new Di(t,this)}},Hd=class extends Zn{constructor(e,n,s,o){super(e,null,null,[],n);this.marginBoxName=s;this.applySpecified(o)}applySpecified(e){let n=e[Oi][this.marginBoxName];for(let s in e){let o=e[s],i=n[s];(Pu[s]||i&&i.value===b.inherit)&&(this.specified[s]=o)}for(let s in n)if(Object.prototype.hasOwnProperty.call(n,s)){let o=n[s];o&&o.value!==O&&o.value!==b.inherit&&o.value!==b.unset&&o.value!==b.revert&&(this.specified[s]=o)}}createInstance(e){return new Wd(e,this)}},Sn=class extends Os{constructor(e,n){super(e,n);d(this,"pageAreaDimension",null);d(this,"pageMarginBoxInstances",{})}applyCascadeAndInit(e,n){let s=this.cascaded;for(let o in n)if(Object.prototype.hasOwnProperty.call(n,o))switch(o){case"writing-mode":case"direction":s[o]=n[o]}super.applyCascadeAndInit(e,n)}initHorizontal(){let e=this.style;e.left=te,e["margin-left"]=te,e["border-left-width"]=te,e["padding-left"]=te,e["padding-right"]=te,e["border-right-width"]=te,e["margin-right"]=te,e.right=te}initVertical(){let e=this.style;e.top=te,e["margin-top"]=te,e["border-top-width"]=te,e["padding-top"]=te,e["padding-bottom"]=te,e["border-bottom-width"]=te,e["margin-bottom"]=te,e.bottom=te}setPageAreaDimension(e){this.pageAreaDimension=e;let n=this.style;n.width=new F(e.borderBoxWidth),n.height=new F(e.borderBoxHeight),n["padding-left"]=new F(e.marginLeft),n["padding-right"]=new F(e.marginRight),n["padding-top"]=new F(e.marginTop),n["padding-bottom"]=new F(e.marginBottom)}adjustPageLayout(e,n,s){let o=n.marginBoxes,i={start:this.pageAreaDimension.marginLeft,end:this.pageAreaDimension.marginRight,extent:this.pageAreaDimension.borderBoxWidth},a={start:this.pageAreaDimension.marginTop,end:this.pageAreaDimension.marginBottom,extent:this.pageAreaDimension.borderBoxHeight};this.sizeMarginBoxesAlongVariableDimension(o.top,!0,i,e,s),this.sizeMarginBoxesAlongVariableDimension(o.bottom,!0,i,e,s),this.sizeMarginBoxesAlongVariableDimension(o.left,!1,a,e,s),this.sizeMarginBoxesAlongVariableDimension(o.right,!1,a,e,s)}sizeMarginBoxesAlongVariableDimension(e,n,s,o,i){let a="start",l="center",c="end",u=this.pageBox.scope,p={},h={},f={};for(let S in e){let w=sp[S];if(w){let k=e[S],I=this.pageMarginBoxInstances[S],U=new Ao(k,I.style,n,u,i);p[w.positionAlongVariableDimension]=k,h[w.positionAlongVariableDimension]=I,f[w.positionAlongVariableDimension]=U}}let g={start:s.start.evaluate(o),end:s.end.evaluate(o),extent:s.extent.evaluate(o)},m=this.getSizesOfMarginBoxesAlongVariableDimension(f,g.extent),E=!1,y={};Object.keys(p).forEach(S=>{let w=S,k=ee(u,h[w].style[n?"max-width":"max-height"],s.extent);if(k){let I=k.evaluate(o);if(m[w]>I){let U=f[w]=new Ma(p[w],h[w].style,n,u,i,I);y[w]=U.getOuterSize(),E=!0}}}),E&&(m=this.getSizesOfMarginBoxesAlongVariableDimension(f,g.extent),E=!1,[a,l,c].forEach(S=>{var w;m[S]=(w=y[S])!=null?w:m[S]}));let C={};Object.keys(p).forEach(S=>{let w=S,k=ee(u,h[w].style[n?"min-width":"min-height"],s.extent);if(k){let I=k.evaluate(o);if(m[w]<I){let U=f[w]=new Ma(p[w],h[w].style,n,u,i,I);C[w]=U.getOuterSize(),E=!0}}}),E&&(m=this.getSizesOfMarginBoxesAlongVariableDimension(f,g.extent),[a,l,c].forEach(S=>{m[S]=C[S]||m[S]}));let x=g.start+g.extent,N=g.start+(g.start+g.extent);[a,l,c].forEach(S=>{let w=m[S];if(w!=null){let k=p[S],I=0;switch(S){case a:I=n?k.left:k.top;break;case l:I=(N-w)/2;break;case c:I=x-w;break}n?k.setHorizontalPosition(I,w-k.getInsetLeft()-k.getInsetRight()):k.setVerticalPosition(I,w-k.getInsetTop()-k.getInsetBottom())}})}getSizesOfMarginBoxesAlongVariableDimension(e,n){var l;let s=e.start,o=e.center,i=e.end,a={};if(o){let c=[s,i],u=new zd(c),p=this.distributeAutoMarginBoxSizes(o,u,n);p.xSize!=null&&(a.center=p.xSize);let h=(l=p.xSize)!=null?l:o.getOuterSize(),f=Math.max((n-h)/2,0);s&&(a.start=s.hasAutoSize()?f:s.getOuterSize()),i&&(a.end=i.hasAutoSize()?f:i.getOuterSize())}else{let c=this.distributeAutoMarginBoxSizes(s,i,n);c.xSize!=null&&(a.start=c.xSize),c.ySize!=null&&(a.end=c.ySize)}return a}distributeAutoMarginBoxSizes(e,n,s){let o={xSize:null,ySize:null};if(e instanceof Ao&&e.minMaxFitContent&&(o.xSize=e.getOuterSize()),n instanceof Ao&&n.minMaxFitContent&&(o.ySize=n.getOuterSize()),e&&n)if(e.hasAutoSize()&&n.hasAutoSize()){let i=e.getOuterMaxContentSize(),a=n.getOuterMaxContentSize();if(i>0&&a>0){let l=i+a;if(l<s)o.xSize=s*i/l;else{let c=e.getOuterMinContentSize(),u=n.getOuterMinContentSize(),p=c+u;p<s?o.xSize=c+(s-p)*(i-c)/(l-p):p>0&&(o.xSize=s*c/p)}o.xSize>0&&(o.ySize=s-o.xSize)}else i>0?o.xSize=s:a>0&&(o.ySize=s)}else e.hasAutoSize()?o.xSize=Math.max(s-n.getOuterSize(),0):n.hasAutoSize()&&(o.ySize=Math.max(s-e.getOuterSize(),0));else e?e.hasAutoSize()&&(o.xSize=s):n&&n.hasAutoSize()&&(o.ySize=s);return o}prepareContainer(e,n,s,o,i){n.element.setAttribute("data-vivliostyle-page-box",!0),super.prepareContainer(e,n,s,o,i)}},Ao=class{constructor(t,e,n,s,o){this.container=t;this.isHorizontal=n;this.clientLayout=o;d(this,"hasAutoSize_");d(this,"size",null);d(this,"minMaxFitContent",null);let i=e[n?"width":"height"];if(this.hasAutoSize_=!i||i===b.auto||_(i),this.minMaxFitContent=i instanceof be&&(i.name==="min-content"||i.name==="max-content"||i.name==="fit-content")?i.name:null,this.minMaxFitContent){let a=this.getSize();if(this.isHorizontal){let l=a[this.minMaxFitContent==="min-content"?"min-content width":this.minMaxFitContent==="max-content"?"max-content width":"fit-content width"];this.container.setHorizontalPosition(this.container.left,l)}else{let l=a[this.minMaxFitContent==="min-content"?"min-content height":this.minMaxFitContent==="max-content"?"max-content height":"fit-content height"];this.container.setVerticalPosition(this.container.top,l)}}}hasAutoSize(){return this.hasAutoSize_}getSize(){if(!this.size){let t=this.isHorizontal?["max-content width","min-content width","fit-content width"]:["max-content height","min-content height","fit-content height"];this.size=ro(this.clientLayout,this.container.element,t)}return this.size}getOuterMaxContentSize(){let t=this.getSize();return this.isHorizontal?this.container.getInsetLeft()+t["max-content width"]+this.container.getInsetRight():this.container.getInsetTop()+t["max-content height"]+this.container.getInsetBottom()}getOuterMinContentSize(){let t=this.getSize();return this.isHorizontal?this.container.getInsetLeft()+t["min-content width"]+this.container.getInsetRight():this.container.getInsetTop()+t["min-content height"]+this.container.getInsetBottom()}getOuterSize(){return this.isHorizontal?this.container.getInsetLeft()+this.container.width+this.container.getInsetRight():this.container.getInsetTop()+this.container.height+this.container.getInsetBottom()}},zd=class{constructor(t){this.params=t}hasAutoSize(){return this.params.some(t=>{var e;return(e=t==null?void 0:t.hasAutoSize())!=null?e:!1})}getOuterMaxContentSize(){let t=this.params.map(e=>{var n;return(n=e==null?void 0:e.getOuterMaxContentSize())!=null?n:0});return Math.max.apply(null,t)*t.length}getOuterMinContentSize(){let t=this.params.map(e=>{var n;return(n=e==null?void 0:e.getOuterMinContentSize())!=null?n:0});return Math.max.apply(null,t)*t.length}getOuterSize(){let t=this.params.map(e=>{var n;return(n=e==null?void 0:e.getOuterSize())!=null?n:0});return Math.max.apply(null,t)*t.length}},Ma=class extends Ao{constructor(e,n,s,o,i,a){super(e,n,s,o,i);d(this,"fixedSize");this.fixedSize=a}hasAutoSize(){return!1}getOuterMaxContentSize(){return this.getOuterSize()}getOuterMinContentSize(){return this.getOuterSize()}getOuterSize(){return this.isHorizontal?this.container.getInsetLeft()+this.fixedSize+this.container.getInsetRight():this.container.getInsetTop()+this.fixedSize+this.container.getInsetBottom()}},Gd=class extends on{constructor(e,n){super(e,n);d(this,"borderBoxWidth",null);d(this,"borderBoxHeight",null);d(this,"contentBoxWidth",null);d(this,"contentBoxHeight",null);d(this,"marginTop",null);d(this,"marginRight",null);d(this,"marginBottom",null);d(this,"marginLeft",null)}applyCascadeAndInit(e,n){for(let o in n)o.match(/^background-/)&&(this.cascaded[o]=n[o]);super.applyCascadeAndInit(e,n),this.parentInstance.setPageAreaDimension({borderBoxWidth:this.borderBoxWidth,borderBoxHeight:this.borderBoxHeight,marginTop:this.marginTop,marginRight:this.marginRight,marginBottom:this.marginBottom,marginLeft:this.marginLeft})}initHorizontal(){let e=this.resolvePageBoxDimensions({start:"left",end:"right",extent:"width"});this.borderBoxWidth=e.borderBoxExtent,this.contentBoxWidth=e.contentBoxExtent,this.marginLeft=e.marginStart,this.marginRight=e.marginEnd}initVertical(){let e=this.resolvePageBoxDimensions({start:"top",end:"bottom",extent:"height"});this.borderBoxHeight=e.borderBoxExtent,this.contentBoxHeight=e.contentBoxExtent,this.marginTop=e.marginStart,this.marginBottom=e.marginEnd}resolvePageBoxDimensions(e){let n=this.style,s=this.pageBox.pageSize,o=this.pageBox.scope,i=e.start,a=e.end,l=e.extent,c=s[l].toExpr(o,null),u=ee(o,n[l],c),p=ee(o,n[`margin-${i}`],c),h=ee(o,n[`margin-${a}`],c),f=st(o,n[`padding-${i}`],c),g=st(o,n[`padding-${a}`],c),m=Ht(o,n[`border-${i}-width`],n[`border-${i}-style`],c),E=Ht(o,n[`border-${a}-width`],n[`border-${a}-style`],c),y=H(o,H(o,m,f),H(o,E,g)),C,x,N;return u?(this.borderBoxSizing?(x=u,N=Y(o,x,y)):(N=u,x=H(o,N,y)),C=Y(o,c,x),!p&&!h?(p=Ys(o,C,new oe(o,.5)),h=p):p?h=Y(o,C,p):p=Y(o,C,h)):(p||(p=o.zero),h||(h=o.zero),C=H(o,p,h),x=Y(o,c,C),N=Y(o,x,y),u=this.borderBoxSizing?x:N),n[i]=new F(p),n[a]=new F(h),n[`margin-${i}`]=te,n[`margin-${a}`]=te,n[`border-${i}-width`]=new F(m),n[`border-${a}-width`]=new F(E),n[`padding-${i}`]=new F(f),n[`padding-${a}`]=new F(g),n[l]=new F(u),n[`max-${l}`]=new F(u),{borderBoxExtent:x,contentBoxExtent:N,marginStart:p,marginEnd:h}}prepareContainer(e,n,s,o,i){n.element.setAttribute("data-vivliostyle-page-area-container",!0),super.prepareContainer(e,n,s,o,i),T(n.element,"position","relative"),T(n.element,"inset",""),T(n.element,"display","flow-root")}},Di=class extends on{constructor(t,e){super(t,e)}applyCascadeAndInit(t,e){for(let n in e)n.match(/^column.*$/)&&(this.cascaded[n]=e[n]);super.applyCascadeAndInit(t,{})}initHorizontal(){let t=this.style,e=this.parentInstance.style,n=this.pageBox.scope;t.left=e["padding-left"],t.width=new F(this.parentInstance.contentBoxWidth),t["margin-left"]=new F(new Yt(n,e.left.toExpr(n,null))),t["margin-right"]=new F(new Yt(n,e.right.toExpr(n,null))),t["border-left-width"]=e.left,t["border-right-width"]=e.right,t["border-left-style"]=b.solid,t["border-right-style"]=b.solid,t["border-left-color"]=b.transparent,t["border-right-color"]=b.transparent}initVertical(){let t=this.style,e=this.parentInstance.style,n=this.pageBox.scope;t.top=e["padding-top"],t.height=new F(this.parentInstance.contentBoxHeight),t["margin-top"]=new F(new Yt(n,e.top.toExpr(n,null))),t["margin-bottom"]=new F(new Yt(n,e.bottom.toExpr(n,null))),t["border-top-width"]=e.top,t["border-bottom-width"]=e.bottom,t["border-top-style"]=b.solid,t["border-bottom-style"]=b.solid,t["border-top-color"]=b.transparent,t["border-bottom-color"]=b.transparent}prepareContainer(t,e,n,s,o){e.element.setAttribute("data-vivliostyle-page-area",!0),n.pageAreaElement=e.element,super.prepareContainer(t,e,n,s,o),t.pageAreaWidth=parseFloat(n.pageAreaElement.style.width),t.pageAreaHeight=parseFloat(n.pageAreaElement.style.height),T(e.element,"position","relative"),T(e.element,"inset",""),T(e.element,"display","flow-root")}},Wd=class extends on{constructor(e,n){super(e,n);d(this,"boxInfo");d(this,"suppressEmptyBoxGeneration",!0);let s=n.marginBoxName;this.boxInfo=sp[s];let o=e;o.pageMarginBoxInstances[s]=this}prepareContainer(e,n,s,o,i){n.element.setAttribute("data-vivliostyle-page-margin-box",this.pageBox.marginBoxName),this.applyVerticalAlign(e,n.element),super.prepareContainer(e,n,s,o,i)}applyVerticalAlign(e,n){T(n,"display","flex"),T(n,"flex-flow",this.vertical?this.rtl?"row-reverse":"row":"column");let s=this.getProp(e,"vertical-align"),o=null;s===L("middle")?o="center":s===L("top")?o="flex-start":s===L("bottom")&&(o="flex-end"),o&&T(n,"justify-content",o);let i=this.getProp(e,"content");if(this.vertical||i instanceof Ue||i instanceof F&&i.expr instanceof ie&&i.expr.str.startsWith("running-element-")){let a="center";(this.boxInfo.isInTopRow||this.boxInfo.isInBottomRow)&&(this.boxInfo.isInLeftColumn||this.boxInfo.positionAlongVariableDimension==="end"?a=this.vertical||this.rtl?"start":"end":(this.boxInfo.isInRightColumn||this.boxInfo.positionAlongVariableDimension==="start")&&(a=this.vertical||this.rtl?"end":"start")),T(n,"align-items",a)}}positionAlongVariableDimension(e,n){let s=this.style,o=this.pageBox.scope,i=e.start,a=e.end,l=e.extent,c=i==="left",u=c?n.borderBoxWidth:n.borderBoxHeight,p=ee(o,s[l],u),h=c?n.marginLeft:n.marginTop;if(this.boxInfo.positionAlongVariableDimension==="start")s[i]=new F(h);else if(p){let f=st(o,s[`margin-${i}`],u),g=st(o,s[`margin-${a}`],u),m=st(o,s[`padding-${i}`],u),E=st(o,s[`padding-${a}`],u),y=Ht(o,s[`border-${i}-width`],s[`border-${i}-style`],u),C=Ht(o,s[`border-${a}-width`],s[`border-${a}-style`],u),x=H(o,p,H(o,this.borderBoxSizing?o.zero:H(o,H(o,m,E),H(o,y,C)),H(o,f,g)));switch(this.boxInfo.positionAlongVariableDimension){case"center":s[i]=new F(H(o,h,$o(o,Y(o,u,x),new oe(o,2))));break;case"end":s[i]=new F(Y(o,H(o,h,u),x));break}}}positionAndSizeAlongFixedDimension(e,n){let s=this.style,o=this.pageBox.scope,i=this.borderBoxSizing,a=e.inside,l=e.outside,c=e.extent,u=n[`margin${l.charAt(0).toUpperCase()}${l.substring(1)}`],p=Od(o,s[`margin-${a}`],u),h=Od(o,s[`margin-${l}`],u),f=st(o,s[`padding-${a}`],u),g=st(o,s[`padding-${l}`],u),m=Ht(o,s[`border-${a}-width`],s[`border-${a}-style`],u),E=Ht(o,s[`border-${l}-width`],s[`border-${l}-style`],u),y=ee(o,s[c],u),C=null;function x(N){if(C)return C;C={extent:y?y.evaluate(N):null,marginInside:p?p.evaluate(N):null,marginOutside:h?h.evaluate(N):null};let S=u.evaluate(N),w=0;return i||[m,f,g,E].forEach(k=>{k&&(w+=k.evaluate(N))}),(C.marginInside===null||C.marginOutside===null)&&w+C.extent+C.marginInside+C.marginOutside>S&&(C.marginInside===null&&(C.marginInside=0),C.marginOutside===null&&(C.marginOutside=0)),C.extent!==null&&C.marginInside!==null&&C.marginOutside!==null&&(C.marginOutside=null),C.extent===null?(C.extent=S-w-C.marginInside-C.marginOutside,C.marginInside===null&&(C.marginInside=0),C.marginOutside===null&&(C.marginOutside=0)):typeof C.extent=="number"&&(C.marginInside===null&&typeof C.marginOutside=="number"?C.marginInside=S-w-C.extent-C.marginOutside:typeof C.marginInside=="number"&&C.marginOutside===null?C.marginOutside=S-w-C.extent-C.marginInside:C.marginInside=C.marginOutside=(S-w-C.extent)/2),C}s[c]=new F(new ie(o,function(){let N=x(this).extent;return N===null?"auto":N},c)),s[`margin-${a}`]=new F(new ie(o,function(){let N=x(this).marginInside;return N===null?"auto":N},`margin-${a}`)),s[`margin-${l}`]=new F(new ie(o,function(){let N=x(this).marginOutside;return N===null?"auto":N},`margin-${l}`)),a==="left"?s.left=new F(H(o,n.marginLeft,n.borderBoxWidth)):a==="top"&&(s.top=new F(H(o,n.marginTop,n.borderBoxHeight)))}initHorizontal(){let n=this.parentInstance.pageAreaDimension;this.boxInfo.isInLeftColumn?this.positionAndSizeAlongFixedDimension({inside:"right",outside:"left",extent:"width"},n):this.boxInfo.isInRightColumn?this.positionAndSizeAlongFixedDimension({inside:"left",outside:"right",extent:"width"},n):this.positionAlongVariableDimension({start:"left",end:"right",extent:"width"},n)}initVertical(){let n=this.parentInstance.pageAreaDimension;this.boxInfo.isInTopRow?this.positionAndSizeAlongFixedDimension({inside:"bottom",outside:"top",extent:"height"},n):this.boxInfo.isInBottomRow?this.positionAndSizeAlongFixedDimension({inside:"top",outside:"bottom",extent:"height"},n):this.positionAlongVariableDimension({start:"top",end:"bottom",extent:"height"},n)}finishContainer(e,n,s,o,i,a,l){super.finishContainer(e,n,s,o,i,a,l);let c=s.marginBoxes,u=this.pageBox.marginBoxName,p=this.boxInfo;!p.isInLeftColumn&&!p.isInRightColumn?p.isInTopRow?c.top[u]=n:p.isInBottomRow&&(c.bottom[u]=n):!p.isInTopRow&&!p.isInBottomRow&&(p.isInLeftColumn?c.left[u]=n:p.isInRightColumn&&(c.right[u]=n));let h=this.parentInstance.pageAreaDimension,f=this.getProp(e,"width"),g=f instanceof be&&(f.name==="min-content"||f.name==="max-content"||f.name==="fit-content")?f.name:null,m=this.getPropAsNumber(e,"min-width"),E=this.getPropAsNumber(e,"max-width");if(g||m||E){g&&T(n.element,"width",g),m&&T(n.element,"min-width",`${m}px`),E&&T(n.element,"max-width",`${E}px`);let S=this.getProp(e,"margin-left"),w=this.getProp(e,"margin-right");if(p.isInLeftColumn){let k=h.borderBoxWidth.evaluate(e)+h.marginRight.evaluate(e);T(n.element,"right",`${k}px`),(S===b.auto||w!==b.auto)&&T(n.element,"margin-left","auto"),w===b.auto&&T(n.element,"margin-right","auto")}else p.isInRightColumn&&(T(n.element,"right","0"),(w===b.auto||S!==b.auto)&&T(n.element,"margin-right","auto"),S===b.auto&&T(n.element,"margin-left","auto"))}let y=this.getProp(e,"height"),C=y instanceof be&&(y.name==="min-content"||y.name==="max-content"||y.name==="fit-content")?y.name:null,x=this.getPropAsNumber(e,"min-height"),N=this.getPropAsNumber(e,"max-height");if(C||x||N){C&&T(n.element,"height",C),x&&T(n.element,"min-height",`${x}px`),N&&T(n.element,"max-height",`${N}px`);let S=this.getProp(e,"margin-top"),w=this.getProp(e,"margin-bottom");if(p.isInTopRow){let k=h.borderBoxHeight.evaluate(e)+h.marginBottom.evaluate(e);T(n.element,"bottom",`${k}px`),(S===b.auto||w!==b.auto)&&T(n.element,"margin-top","auto"),w===b.auto&&T(n.element,"margin-bottom","auto")}else p.isInBottomRow&&(T(n.element,"bottom","0"),(w===b.auto||S!==b.auto)&&T(n.element,"margin-bottom","auto"),S===b.auto&&T(n.element,"margin-top","auto"))}}},_a=class{constructor(t,e,n,s,o){this.cascadeInstance=t;this.pageScope=e;this.rootPageBoxInstance=n;this.context=s;this.docElementStyle=o;d(this,"pageMasterCache",{});this.definePageProgression()}definePageProgression(){let t=this.pageScope,e=this.context,n=e.isVersoFirstPage,s=new J(t,"page-number"),o=new Pn(t,new Xs(t,s,new oe(t,2)),n?t.one:t.zero);t.defineName("recto-page",new gt(t,o)),t.defineName("verso-page",o),(e.pageProgression||tp(this.docElementStyle))==="ltr"?(t.defineName("left-page",o),t.defineName("right-page",new gt(t,o))):(t.defineName("left-page",new gt(t,o)),t.defineName("right-page",o))}getCascadedPageStyle(t){let e={};return this.cascadeInstance.pushRule([],t,e),this.cascadeInstance.popRule(),e}getPageRulePageMaster(t,e){let n=t.pageBox;if(Object.keys(e).length===0)return n.resetScope(),t;let s=this.makeCacheKey(e,n),o=this.pageMasterCache[s];return o||(n.pseudoName===Ii?o=this.generatePageRuleMaster(e):o=this.generateCascadedPageMaster(e,n),this.pageMasterCache[s]=o),o.pageBox.resetScope(),o}makeCacheKey(t,e){var o;let n=this.makeCascadeValueObjectKey(t),s=((o=this.context.currentLayoutPosition)==null?void 0:o.page)%2;return`${e.key}^${n}^${s}`}makeCascadeValueObjectKey(t){let e=[];for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let s=t[n],o;s instanceof M?o=`${s.value}`:o=this.makeCascadeValueObjectKey(s),e.push(n+o+(s.priority||""))}return e.sort().join("^")}generatePageRuleMaster(t){let n=new Vi(this.pageScope,this.rootPageBoxInstance.pageBox,t).createInstance(this.rootPageBoxInstance);return n.applyCascadeAndInit(this.cascadeInstance,this.docElementStyle),n.resolveAutoSizing(this.context),n}generateCascadedPageMaster(t,e){let n=e.clone({pseudoName:Ha}),s=n.specified,o=t.size;if(o&&!_(o.value)){let a=Mi(t),l=o.priority;sn(s,"width",new M(a.width,l),this.context),sn(s,"height",new M(a.height,l),this.context)}["counter-reset","counter-increment"].forEach(a=>{s[a]&&(t[a]=s[a])});let i=n.createInstance(this.rootPageBoxInstance);return i.applyCascadeAndInit(this.cascadeInstance,this.docElementStyle),i.resolveAutoSizing(this.context),i}},$d=class extends q{constructor(e){super();this.pageType=e}apply(e){e.currentPageType===this.pageType&&this.chained.apply(e)}getPriority(){return 3}makePrimary(e){return this.chained&&e.insertInTable(e.pagetypes,this.pageType,this.chained),!0}},Xd=class extends q{constructor(e){super();this.scope=e}apply(e){new J(this.scope,"page-number").evaluate(e.context)===1&&this.chained.apply(e)}getPriority(){return 2}},jd=class extends q{constructor(e){super();this.scope=e}apply(e){new J(this.scope,"blank-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 2}},Yd=class extends q{constructor(e){super();this.scope=e}apply(e){new J(this.scope,"left-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},Kd=class extends q{constructor(e){super();this.scope=e}apply(e){new J(this.scope,"right-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},qd=class extends q{constructor(e){super();this.scope=e}apply(e){new J(this.scope,"recto-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},Zd=class extends q{constructor(e){super();this.scope=e}apply(e){new J(this.scope,"verso-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},Qd=class extends $n{constructor(e,n,s){super(n,s);this.scope=e;this.a=n;this.b=s}apply(e){let n=e.context,s=n.layoutPositionAtPageStart.page;n.blankPageAtStart&&s--,s&&this.matchANPlusB(s)&&this.chained.apply(e)}getPriority(){return 2}},Jd=class extends ws{constructor(t,e){super(t,e,null,null,null)}apply(t){jC(t.context,t.currentStyle,this.style,this.specificity,t)}};function jC(r,t,e,n,s){fi(r,t,e,n,null,null,null);let o=e[Oi];if(o){let i=Eo(t,Oi);for(let a in o)if(o.hasOwnProperty(a)){let l=i[a];l||(l={},i[a]=l),fi(r,l,o[a],n,null,null,null)}}}var Ua=class extends xn{constructor(e,n,s,o,i){super(e,n,s==null?void 0:s.condition,s,null,o,!1);this.pageProps=i;d(this,"currentPageSelectors",[]);d(this,"currentNamedPageSelector","");d(this,"currentPseudoPageClassSelectors",[])}startPageRule(){this.startSelectorRule()}tagSelector(e,n){this.currentNamedPageSelector=n,n&&(this.chain.push(new $d(n)),this.specificity+=65536)}pseudoclassSelector(e,n){if(e=e.toLowerCase(),n)switch(e){case"nth":{let[s,o]=n;this.currentPseudoPageClassSelectors.push(`:${e}(${s}n${o<0?o:"+"+o})`),this.chain.push(new Qd(this.scope,s,o)),this.specificity+=256}break;default:this.reportAndSkip(`E_INVALID_PAGE_SELECTOR :${e}(${n.join("")})`);break}else switch(this.currentPseudoPageClassSelectors.push(`:${e}`),e){case"first":this.chain.push(new Xd(this.scope)),this.specificity+=256;break;case"blank":this.chain.push(new jd(this.scope)),this.specificity+=256;break;case"left":this.chain.push(new Yd(this.scope)),this.specificity+=1;break;case"right":this.chain.push(new Kd(this.scope)),this.specificity+=1;break;case"recto":this.chain.push(new qd(this.scope)),this.specificity+=1;break;case"verso":this.chain.push(new Zd(this.scope)),this.specificity+=1;break;default:this.reportAndSkip(`E_INVALID_PAGE_SELECTOR :${e}`);break}}finishSelector(){let e;!this.currentNamedPageSelector&&!this.currentPseudoPageClassSelectors.length?e=null:e=[this.currentNamedPageSelector].concat(this.currentPseudoPageClassSelectors.sort()),this.currentPageSelectors.push({selectors:e,specificity:this.specificity}),this.currentNamedPageSelector="",this.currentPseudoPageClassSelectors=[]}nextSelector(){this.finishSelector(),super.nextSelector()}startRuleBody(){this.finishSelector(),super.startRuleBody()}simpleProperty(e,n,s){if((e==="bleed"||e==="marks")&&!this.currentPageSelectors.some(a=>a.selectors===null))return;super.simpleProperty(e,n,s);let o=pe(this.elementStyle,e),i=this.pageProps;if(e==="bleed"||e==="marks")i[""]||(i[""]={}),Object.keys(i).forEach(a=>{Cn(i[a],e,o)});else if(e==="size"){let a=i[""];this.currentPageSelectors.forEach(l=>{let c=new M(o.value,o.priority+l.specificity),u=l.selectors?l.selectors.join(""):"",p=i[u];p?sn(p,e,c):(p=i[u]={},Cn(p,e,c),a&&["bleed","marks"].forEach(h=>{a[h]&&Cn(p,h,a[h])}))})}}insertNonPrimary(e){this.cascade.insertInTable(this.cascade.pagetypes,"*",e)}makeApplyRuleAction(e){return new Jd(this.elementStyle,e)}startPageMarginBoxRule(e){let n=Eo(this.elementStyle,Oi),s=n[e];s||(s={},n[e]=s);let o=new ep(this.scope,this.owner,this.validatorSet,s);this.owner.pushHandler(o)}},ep=class extends Qt{constructor(e,n,s,o){super(e,n,!1);this.validatorSet=s;this.boxStyle=o}property(e,n,s){this.validatorSet.validatePropertyAndHandleShorthand(e,n,s,this)}invalidPropertyValue(e,n){this.report(`E_INVALID_PROPERTY_VALUE ${e}: ${n.toString()}`)}unknownProperty(e,n){this.report(`E_INVALID_PROPERTY ${e}: ${n.toString()}`)}simpleProperty(e,n,s){let o=s?this.getImportantSpecificity():this.getBaseSpecificity(),i=new M(n,o);Cn(this.boxStyle,e,i)}};var zt=!0;function Zf(r){zt=r}var Ds=[];function qf(r,t){return r===t||(r.src||t.src?r.src===t.src:r.textContent===t.textContent)}function Qf(r){let t=Array.from(r.querySelectorAll("body > :not(script):not(link):not(style) ~ script"));return Array.from(r.querySelectorAll("head > script, body > script")).filter(e=>!t.includes(e))}function za(r,t,e){var u,p;if(!zt)return v(!1);if(!(e!=null&&e.inHead)&&!(e!=null&&e.atEnd)&&Qf(r.ownerDocument).includes(r))return v(!1);let n=r.textContent,s=r.src,o=r.type==="module",i=(o||s)&&r.async,a=o&&!i||s&&r.defer,l=!(e!=null&&e.atEnd)&&((e==null?void 0:e.forceDefer)||a||i);if(op(t)||(t.onload=null),l)return Ds.some(h=>qf(h,r))||Ds.push(r),v(!0);if(s.includes("/mathjax")){let h=t.document.head.querySelector("script[src*='MathJax.js']:not([data-vivliostyle-scripting])");if(h){if(s.includes("/mathjax@3"))t.document.head.removeChild(h),(p=(u=t.MathJax)==null?void 0:u.version)!=null&&p.startsWith("2.")&&delete t.MathJax;else if(s.includes("/MathJax.js"))return v(!0)}}for(let h of t.document.head.getElementsByTagName("script"))h.hasAttribute("data-vivliostyle-scripting")&&qf(h,r)&&t.document.head.removeChild(h);let c=t.document.createElement("script");c.textContent=n,s&&(c.src=s),c.async=i,c.defer=a,c.setAttribute("data-vivliostyle-scripting","true");for(let h of r.attributes)["src","async","defer"].includes(h.name)||c.setAttribute(h.name,h.value);if(V.debug("script:",s),s){let h=In(c);return t.document.head.appendChild(c),Rn([h])}else return t.document.head.appendChild(c),v(!0)}function KC(r,t){var o;let e={},n=i=>{var c;let a=(c=i["font-family"])==null?void 0:c.value;if(a)if(a.values)for(let u of a.values)e[u.stringValue()]=!0;else e[a.stringValue()]=!0;let l=i._marginBoxes;if(l)for(let u of Object.values(l))n(u)},s=i=>{if(i instanceof ws)n(i.style);else if(i instanceof bn||Array.isArray(i))for(let a of Object.values(i))s(a)};for(let i of Object.values(t.cascade.code))for(let a of Object.values(i!=null?i:{}))s(a);for(let i of r.querySelectorAll("[style]"))(o=i.style)!=null&&o.fontFamily&&(e[i.style.fontFamily]=!0);return Object.keys(e).join(",")}function qC(r,t,e){var s;let n=(s=t.document.querySelector("[data-vivliostyle-textcontent]"))!=null?s:t.document.createElement("div");return n.style.position="fixed",n.style.fontSize="0",n.setAttribute("data-vivliostyle-textcontent","true"),n.setAttribute("aria-hidden","true"),n.style.fontFamily=KC(r,e),n.textContent=r.documentElement.textContent,t.document.body.appendChild(n),n}function Jf(r,t,e){if(!zt)return v(!1);let n=Qf(r);if(n.length===0)return v(!1);let s=n.some(u=>!(u.async||u.defer||u.type==="module")),o=s?qC(r,t,e):null,i=t.document.fonts,a=t.$,l=!1,c=A("loadScripts");return c.loop(()=>{if(n.length===0)return s?c.sleep(20).thenAsync(()=>{var p,h;return i.status==="loading"||t.document.documentElement.classList.contains("wf-loading")||(p=t.FontJSON)!=null&&p.Font&&((h=t.ret)!=null&&h.readyState)&&t.ret.readyState<4?v(!0):v(!1)}):v(!1);let u=n.shift();return za(u,t,{inHead:!0,forceDefer:l}).thenAsync(()=>(!l&&t.$!==a&&(Ds.push(u),l=!0),n.length===0&&s&&(V.debug("dispatchEvent: DOMContentLoaded (document)"),t.document.dispatchEvent(new Event("DOMContentLoaded"))),v(!0)))}).then(()=>{o&&o.remove(),c.finish(!0)}),c.result()}function eg(r){if(!zt)return v(!1);let t=A("loadScripts");return t.loop(()=>Ds.length===0?v(!1):za(Ds.shift(),r,{atEnd:!0}).thenReturn(Ds.length>0)).then(()=>{V.debug("dispatchEvent: DOMContentLoaded (window)"),r.dispatchEvent(new Event("DOMContentLoaded")),V.debug("dispatchEvent: load (window)"),r.dispatchEvent(new Event("load")),t.finish(!0)}),t.result()}function op(r){return zt?Ds.length>0||!!r.document.head.querySelector("script[data-vivliostyle-scripting]"):!1}var tg=(r,t,e)=>r.replace(/[uU][rR][lL]\(\s*"((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^"\r\n])+)"/gm,(n,s)=>`url("${e.transformURL(s,t)}"`).replace(/[uU][rR][lL]\(\s*'((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^'\r\n])+)'/gm,(n,s)=>`url('${e.transformURL(s,t)}'`).replace(/[uU][rR][lL]\(\s*((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^"'\r\n\)\s])+)/gm,(n,s)=>`url(${e.transformURL(s,t)}`);var QC={};function JC(r){r.addEventListener("load",()=>{r.contentWindow.navigator.epubReadingSystem={name:"adapt",version:"0.1",layoutStyle:"paginated",hasFeature:function(t,e){switch(t){case"mouse-events":return!0}return!1}}},!1)}var _i=class _i extends vn{constructor(e,n,s,o,i,a,l,c,u,p,h,f,g){super();this.flowName=e;this.context=n;this.viewport=s;this.styler=o;this.regionIds=i;this.xmldoc=a;this.docFaces=l;this.footnoteStyle=c;this.stylerProducer=u;this.page=p;this.customRenderer=h;this.fallbackMap=f;this.documentURLTransformer=g;d(this,"document");d(this,"exprContentListener");d(this,"nodeContext",null);d(this,"viewRoot",null);d(this,"isFootnote",!1);d(this,"sourceNode",null);d(this,"offsetInNode",0);d(this,"viewNode",null);this.document=s.document,this.exprContentListener=o.counterListener.getExprContentListener()}clone(){return new _i(this.flowName,this.context,this.viewport,this.styler,this.regionIds,this.xmldoc,this.docFaces,this.footnoteStyle,this.stylerProducer,this.page,this.customRenderer,this.fallbackMap,this.documentURLTransformer)}createPseudoelementShadow(e,n,s,o,i,a,l,c){let u=this.getPseudoMap(s,this.regionIds,this.isFootnote,this.nodeContext,a);if(!u)return c;let p=[],h=No.createElementNS("http://www.pyroxy.com/ns/shadow","root"),f=h;for(let m of gf){let E;if(m){if(!u[m]||m=="footnote-marker"&&!(n&&this.isFootnote))continue;if(m.match(/^first-/)){let y=o.display;if(!y||y===b.inline)continue;let C=e.firstElementChild;if(C&&ue(C.previousSibling)){let x=i.getStyle(C,!1);if(x){let N=pe(x,"display");if(N!=null&&N.value&&N.value!==b.inline)continue}}}if(m==="before"||m==="after"){let y=u[m].content;if(!y||!Et(y.value))continue}p.push(m),E=No.createElementNS("http://www.w3.org/1999/xhtml","span"),Ci(E,m)}else E=No.createElementNS("http://www.pyroxy.com/ns/shadow","content");f.appendChild(E),m.match(/^first-/)&&(f=E)}if(!p.length)return c;let g=new mi(e,s,i,a,this.exprContentListener);return new bs(e,h,null,l,c,yt.ROOTLESS,g)}getPseudoMap(e,n,s,o,i){let a=St(e,"_pseudos");if(!a)return null;let l={};for(let c in a){let u=l[c]={};So(u,a[c],i),la(u,i,a[c]),Fu(a[c],n,s,(p,h)=>{So(u,h,i),Vu(h,f=>{So(u,f,i)})})}return l}createRefShadow(e,n,s,o,i){let a=A("createRefShadow");return this.xmldoc.store.load(e).then(l=>{let c=l;if(c){let u=c.getElement(e);if(u){let p=this.stylerProducer.getStylerForDoc(c);i=new bs(s,u,c,o,i,n,p)}}a.finish(i)}),a.result()}createShadows(e,n,s,o,i,a,l){let c=A("createShadows"),u=null,p=o.template,h;if(p instanceof Ue||p===b.footnote){let f=p instanceof Ue?p.url:Q("user-agent.xml#footnote",$t);h=this.createRefShadow(f,yt.ROOTLESS,e,l,u)}else h=v(u);return h.then(f=>{let g=null;if(e.namespaceURI=="http://www.pyroxy.com/ns/shadow"&&e.localName=="include"){let E=e.getAttribute("href"),y=null;E?y=l?l.xmldoc:this.xmldoc:l&&(l.owner.namespaceURI=="http://www.w3.org/1999/xhtml"?E=l.owner.getAttribute("href"):E=l.owner.getAttributeNS("http://www.w3.org/1999/xlink","href"),y=l.parentShadow?l.parentShadow.xmldoc:this.xmldoc),E&&(E=Q(E,y.url),g=this.createRefShadow(E,yt.ROOTED,e,l,f))}g==null&&(g=v(f));let m=null;g.then(E=>{if(o.display===b.table_cell){let y=Q("user-agent.xml#table-cell",$t);m=this.createRefShadow(y,yt.ROOTLESS,e,l,E)}else m=v(E);m.then(y=>{y=this.createPseudoelementShadow(e,n,s,o,i,a,l,y),c.finish(y)})})}),c.result()}setViewRoot(e,n){this.viewRoot=e,this.isFootnote=n}computeStyle(e,n,s,o){var y;let i=this.context,a=fa(s,i,this.regionIds,this.isFootnote,this.nodeContext),l=!((y=this.nodeContext)!=null&&y.parent);l&&(!a["writing-mode"]&&this.styler.rootStyle["writing-mode"]&&(a["writing-mode"]=this.styler.rootStyle["writing-mode"]),!a.direction&&this.styler.rootStyle.direction&&(a.direction=this.styler.rootStyle.direction));let c=e;e=pa(a,i,e);let u=!l&&e!==c;n=ha(a,i,n);let p=(C,x)=>{let N;u&&(e?/^(min-|max-)?(height|inline-size)$/.test(C)&&(N=i.pageAreaHeight):/^(min-|max-)?(width|inline-size)$/.test(C)&&(N=i.pageAreaWidth));let S=x.evaluate(i,C,N,e);return C=="font-family"&&(S=this.docFaces.filterFontFamily(S)),S},h=!!new J(i.style.pageScope,"left-page").evaluate(i);if(ga(a,o,e,n,h,p),u){let C=o[e?"height":"width"];(!C||C===b.auto)&&(o[e?"height":"width"]=b.max_content)}if(ii(o.position))return o.position=b.fixed,o.visibility=b.hidden,e;let f=o.position,g=o.float,m=o.display||(this.sourceNode.namespaceURI==="http://www.w3.org/1999/xhtml"?b.inline:void 0),E=Fc(m,f,g,this.sourceNode===this.xmldoc.root);return["display","position","float"].forEach(C=>{E[C]&&(o[C]=E[C])}),e}inheritFromSourceParent(e){let n=this.nodeContext.sourceNode,s=[],o=null,i=this.nodeContext.shadowContext,a=-1;for(;n&&n.nodeType==1;){let h=i&&i.root==n;if(!h||i.type==yt.ROOTLESS){let g=(i?i.styler:this.styler).getStyle(n,!1);s.push(g),o=o||Oo(n)}h?(n=i.owner,i=i.parentShadow):(n=n.parentNode,a++)}let l=a===0,c=this.context.queryUnitSize("em",l),u={"font-size":new M(new P(c,"px"),0)},p=new sa(u,this.context);for(let h=s.length-1;h>=0;--h){let f=s[h],g=[];for(let y in f)Xn(y)&&g.push(y);g.sort(Bl);let m,E;for(let y of g){p.setPropName(y);let C=pe(f,y),x=C;_(C.value)||(y==="font-size"&&h===s.length-1&&this.context.isRelativeRootFontSize&&this.context.rootFontSize?x=new M(new P(this.context.rootFontSize,"px"),C.priority):y==="line-height"&&h===s.length-1&&this.context.rootLineHeight&&C.value instanceof P&&(C.value.unit==="lh"||C.value.unit==="rlh")?x=new M(new P(this.context.rootLineHeight,"px"),C.priority):h===0&&C.value instanceof P&&C.value.unit==="lh"?x=new M(new P(C.value.num*this.getLineHeightUnitSize(y,m,E),"px"),C.priority):Ct(y)||(x=C.filterValue(p)),y==="font-size"?m=x.value:y==="line-height"&&(E=x.value),u[y]=x)}}for(let h in e)Xn(h)||(u[h]=e[h]);return{lang:o,elementStyle:u}}resolveURL(e){return e=Q(e,this.xmldoc.url),this.fallbackMap[e]||e}inheritLangAttribute(){this.nodeContext.lang=Oo(this.nodeContext.sourceNode)||this.nodeContext.parent&&this.nodeContext.parent.lang||this.nodeContext.lang}transferPolyfilledInheritedProps(e){let n=Yh().filter(s=>e[s]);if(n.length){let s=this.nodeContext.inheritedProps;if(this.nodeContext.parent){s=this.nodeContext.inheritedProps={};for(let o in this.nodeContext.parent.inheritedProps)s[o]=this.nodeContext.parent.inheritedProps[o]}n.forEach(o=>{let i=e[o];if(i){if(_(i))i===b.initial&&(s[o]=void 0);else if(i instanceof ct)s[o]=i.num;else if(i instanceof be)s[o]=i.name;else if(i instanceof P){let a=i;switch(a.unit){case"dpi":case"dpcm":case"dppx":s[o]=a.num*$[a.unit];break;default:s[o]=i}}else s[o]=i;["widows","orphans"].includes(o)||delete e[o]}})}}resolveFormattingContext(e,n,s,o,i,a){let l=We("RESOLVE_FORMATTING_CONTEXT");for(let c=0;c<l.length;c++){let u=l[c](e,n,s,o,i,a);if(u){e.formattingContext=u;return}}}createElementView(e,n){var y,C,x,N;let s=!0,o=A("createElementView"),i=this.sourceNode,a=this.nodeContext.shadowContext?this.nodeContext.shadowContext.styler:this.styler,l=a.getStyle(i,!1);if(!this.nodeContext.shadowContext){let S=this.xmldoc.getElementOffset(i);Wn.registerFragmentIndex(S,this.nodeContext.fragmentIndex,0)}let c={};if(!this.nodeContext.parent){let S=this.inheritFromSourceParent(l);l=S.elementStyle,this.nodeContext.lang=S.lang}let u=l.position,p=l.float,h=l["float-reference"],f=p&&!_(p.value)&&p.value!==b.none&&h&&!_(h.value)?Fh(h.value.toString()):null;if(this.nodeContext.parent&&(ii(u==null?void 0:u.value)||f&&_n(f))){let S=this.inheritFromSourceParent(l);l=S.elementStyle,this.nodeContext.lang=S.lang}this.nodeContext.vertical=this.computeStyle(this.nodeContext.vertical,this.nodeContext.direction==="rtl",l,c),f&&_n(f)&&c.display===b.block&&(c.display=b.flow_root),a.processContent(i,c,(C=this.nodeContext.viewNode)!=null?C:(y=this.nodeContext.parent)==null?void 0:y.viewNode),this.transferPolyfilledInheritedProps(c),this.inheritLangAttribute(),c.direction&&(this.nodeContext.direction=c.direction.toString());let g=c["flow-into"];if(g&&g.toString()!=this.flowName)return o.finish(!1),o.result();if(zt&&i.localName==="script"&&i.namespaceURI==="http://www.w3.org/1999/xhtml")return za(i,this.viewport.window).thenFinish(o),o.result();let m=c.display;if(_(m)&&(m===b.initial||m===b.unset?m=b.inline:m===b.inherit?m=((x=this.nodeContext.parent)==null?void 0:x.display)&&L((N=this.nodeContext.parent)==null?void 0:N.display):m=null),m===b.none)return o.finish(!1),o.result();let E=this.nodeContext.parent==null;return this.nodeContext.flexContainer=m===b.flex,this.createShadows(i,E,l,c,a,this.context,this.nodeContext.shadowContext).then(S=>{var Cp,bp;this.nodeContext.nodeShadow=S;let w=c.position,k=c.float,I=c.clear,U=this.nodeContext.vertical?b.vertical_rl:b.horizontal_tb,Se=this.nodeContext.parent?this.nodeContext.parent.vertical?b.vertical_rl:b.horizontal_tb:U,Z=Oh(i);this.nodeContext.establishesBFC=Dh(m,w,k,c.overflow,U,Se,Z),this.nodeContext.containingBlockForAbsolute=Mh(w),this.nodeContext.isInsideBFC()&&k!==b.footnote&&!(f&&_n(f))&&(k=null,I=null);let ae=k instanceof K||k===b.left||k===b.right||k===b.top||k===b.bottom||k===b.inline_start||k===b.inline_end||k===b.block_start||k===b.block_end||k===b.snap_block||k===b.snap_inline||k===b.inside||k===b.outside||k===b.footnote;k&&(delete c.float,k===b.footnote&&(this.isFootnote?(ae=!1,c.display=b.block):c.display=b.inline)),I&&(I===b.inherit&&this.nodeContext.parent&&this.nodeContext.parent.clearSide&&(I=L(this.nodeContext.parent.clearSide)),(I===b.left||I===b.right||I===b.top||I===b.bottom||I===b.inline_start||I===b.inline_end||I===b.block_start||I===b.block_end||I===b.inside||I===b.outside||I===b.both||I===b.all||I===b.same)&&(delete c.clear,c.display&&c.display!=b.inline&&(this.nodeContext.clearSide=I.toString())));let we=m===b.list_item&&c["ua-list-item-count"],Ge=c["break-inside"];(ae||Ge&&!_(Ge)&&Ge!==b.auto)&&this.nodeContext.breakPenalty++,m&&m!==b.inline&&hn(m)&&this.nodeContext.breakPenalty++,this.nodeContext.inline=!ae&&!m||hn(m)||qr(m),this.nodeContext.display=m?m.toString():"inline",this.nodeContext.floatSide=ae?k.toString():null,this.nodeContext.floatReference=f||de.INLINE;let R=c["float-min-wrap-block"];this.nodeContext.floatMinWrapBlock=R&&!_(R)?R:null;let G=this.isInsideNonRootMultiColumn(),B=c["column-span"];if(this.nodeContext.columnSpan=!G&&B&&!_(B)?B:null,!this.nodeContext.inline){let D=c["break-after"];D&&!_(D)&&!(G&&D===b.column)&&(this.nodeContext.breakAfter=D.toString(),Br[this.nodeContext.breakAfter]&&delete c["break-after"]);let ot=c["break-before"];ot&&!_(ot)&&!(G&&ot===b.column)&&(this.nodeContext.fragmentIndex===1&&(this.nodeContext.breakBefore=ot.toString()),Br[this.nodeContext.breakBefore]&&delete c["break-before"]);let Nt=c.page,it=Nt&&!_(Nt)&&Nt.toString();!it&&!this.nodeContext.parent&&(this.nodeContext.shadowContext||m===b.table_header_group||m===b.table_footer_group)&&(it=this.styler.cascade.currentPageType),!it||it.toLowerCase()==="auto"?it=this.nodeContext.pageType:this.nodeContext.pageType=it,this.styler.cascade.currentPageType!==it&&!(!it&&c.position===b.fixed)&&(this.nodeContext.fragmentIndex===1&&!Fn(this.nodeContext.breakBefore)&&(this.nodeContext.breakBefore="page"),it!==this.styler.cascade.previousPageType&&(this.styler.cascade.previousPageType=this.styler.cascade.currentPageType),this.styler.cascade.currentPageType=it)}this.nodeContext.verticalAlign=c["vertical-align"]&&c["vertical-align"].toString()||"baseline",this.nodeContext.captionSide=c["caption-side"]&&c["caption-side"].toString()||"top";let z=c["border-collapse"];if(!z||z===L("separate")){let D=c["border-spacing"],ot,Nt;D&&(D instanceof K?(ot=D.values[0],Nt=D.values[1]):ot=Nt=D,ot.isNumeric()&&(this.nodeContext.inlineBorderSpacing=Le(ot,this.context)),Nt.isNumeric()&&(this.nodeContext.blockBorderSpacing=Le(Nt,this.context)))}let X=c["footnote-policy"];this.nodeContext.footnotePolicy=X&&!_(X)?X:null;let he=c["x-first-pseudo"];if(he){let D=this.nodeContext.parent?this.nodeContext.parent.firstPseudo:null;this.nodeContext.firstPseudo=new Hr(D,he.num)}this.nodeContext.inline||this.processAfterIfcontinues(i,l,a,this.context);let es=c["white-space"];if(es){let D=$r(es.toString());D!==null&&(this.nodeContext.whitespace=D)}let Lo=c["hyphenate-character"];Lo&&Lo instanceof ce&&(this.nodeContext.hyphenateCharacter=Lo.str);let hg=c["word-break"],fg=c["line-break"],mp=c["overflow-wrap"];(hg===b.break_all||fg===b.anywhere||mp===b.break_word||mp===b.anywhere)&&(this.nodeContext.breakWord=!0),this.resolveFormattingContext(this.nodeContext,e,m,w,k,E),this.nodeContext.parent&&this.nodeContext.parent.formattingContext&&(e=this.nodeContext.parent.formattingContext.isFirstTime(this.nodeContext,e)),this.nodeContext.inline||(this.nodeContext.repeatOnBreak=this.processRepeatOnBreak(c),this.findAndProcessRepeatingElements(i,a));let ts=!1,ol=null,Ro=[],Lt=i.namespaceURI,j=i.localName;if(Lt=="http://www.w3.org/1999/xhtml"?(j=="html"||j=="body"||j=="script"||j=="link"||j=="meta"?j="div":j=="vide_"?j="video":j=="audi_"?j="audio":j=="object"&&(ts=!!this.customRenderer),i.getAttribute(ma)&&(bp=(Cp=l.content)==null?void 0:Cp.value)!=null&&bp.url&&(j="img")):Lt=="http://www.idpf.org/2007/ops"?(j="span",Lt="http://www.w3.org/1999/xhtml"):Lt=="http://www.pyroxy.com/ns/shadow"?(Lt="http://www.w3.org/1999/xhtml",j=this.nodeContext.inline?"span":"div"):ts=!!this.customRenderer,we)e?j="li":(j="div",m=b.block,c.display=m);else if(j=="body"||j=="li")j="div";else if(j=="q")j="span";else if(j=="a"){let D=c["hyperlink-processing"];D&&D.toString()!="normal"&&(j="span")}c.behavior&&c.behavior.toString()!="none"&&this.customRenderer&&(ts=!0),i.dataset&&i.getAttribute("data-math-typeset")==="true"&&(ts=!0);let il;if(ts){let D=this.nodeContext.parent?this.nodeContext.parent.viewNode:null;il=this.customRenderer(i,D,c)}else il=v(null);il.then(D=>{if(D)ts&&(s=D.getAttribute("data-adapt-process-children")=="true");else if(c.display===b.none){o.finish(!1);return}else D=this.createElement(Lt,j);j=="a"&&D.addEventListener("click",this.page.hrefHandler,!1),ol&&(this.applyPseudoelementStyle(this.nodeContext,"inner",ol),D.appendChild(ol)),D.localName=="iframe"&&D.namespaceURI=="http://www.w3.org/1999/xhtml"&&JC(D);let ot=this.nodeContext.inheritedProps["image-resolution"],Nt=[],it=c.width,rl=c.height,gg=i.getAttribute("width"),mg=i.getAttribute("height"),al=it===b.auto||!it&&!gg,ll=rl===b.auto||!rl&&!mg,xp=i.attributes,Cg=xp.length,$i=null,yp=null;for(let Je=0;Je<Cg;Je++){let Gt=xp[Je],rt=Gt.namespaceURI,se=Gt.localName,fe=Gt.nodeValue;if(rt){if(rt=="http://www.w3.org/2000/xmlns/")continue;rt=="http://www.w3.org/1999/xlink"&&se=="href"&&(fe=this.documentURLTransformer.transformURL(this.resolveURL(fe),this.xmldoc.url))}else{if(!zt&&se.match(/^on/)||se=="style")continue;if((se=="id"||se=="name")&&e){let je=this.documentURLTransformer.transformFragment(fe,this.xmldoc.url);D.setAttribute(se,fe),D.setAttribute("data-vivliostyle-id",je);let vt=D.ownerDocument.createElement("a");vt.setAttribute(se,je),vt.setAttribute(Mt,"1"),D.appendChild(vt),this.page.registerElementWithId(D,je);continue}if(se=="src"||se=="href"||se=="poster")fe=this.resolveURL(fe),se==="href"&&(fe=this.documentURLTransformer.transformURL(fe,this.xmldoc.url));else if(se=="srcset")fe=fe.split(",").map(je=>this.resolveURL(je.trim())).join(",");else if(se==="data"&&ts&&j==="object"&&D.hasAttribute("data"))continue;if(se==="poster"&&j==="video"&&Lt==="http://www.w3.org/1999/xhtml"&&al&&ll){let je=new Image,vt=In(je,fe);Ro.push(vt),Nt.push({image:je,element:D,fetcher:vt})}}if(Lt=="http://www.w3.org/2000/svg"&&/^[A-Z\-]+$/.test(se)&&(se=se.toLowerCase()),this.isSVGUrlAttribute(se)&&(fe=tg(fe,this.xmldoc.url,this.documentURLTransformer)),rt){let je=QC[rt];je&&(se=`${je}:${se}`)}if(se=="src"&&!rt&&(j=="img"||j=="input")&&Lt=="http://www.w3.org/1999/xhtml")$i=fe;else if(se=="alt"&&!rt&&j=="img"&&Lt=="http://www.w3.org/1999/xhtml")yp=fe;else if(se=="href"&&j=="image"&&Lt=="http://www.w3.org/2000/svg"&&rt=="http://www.w3.org/1999/xlink")this.page.fetchers.push(In(D,fe));else if(rt)D.setAttributeNS(rt,se,fe);else try{D.setAttribute(se,fe)}catch(je){V.warn(je)}}if($i){let Je=j==="input"?new Image:D,Gt=In(Je,$i,yp);Je!==D&&(D.src=$i);let rt=()=>{var fe,je;if(c.position===b.fixed)return!0;for(let vt=(fe=this.nodeContext.parent)==null?void 0:fe.viewNode;vt&&vt!==this.viewRoot;vt=vt.parentElement)if(((je=vt.style)==null?void 0:je.position)==="fixed")return!0;return!1};!al&&!ll&&!(()=>{let fe=this.nodeContext.vertical?it:rl;return fe instanceof P&&fe.unit==="%"})()&&!rt()?this.page.fetchers.push(Gt):(al&&ll&&ot&&ot!==1&&Nt.push({image:Je,element:D,fetcher:Gt}),Ro.push(Gt))}delete c.content;let cl=c["list-style-image"];if(cl&&cl instanceof Ue){let Je=cl.url;Ro.push(In(new Image,Je))}if(this.preprocessElementStyle(c),this.applyComputedStyles(D,c),this.nodeContext.inline)e||(dt(D,"inline-start"),ms(D)&&dt(D,"clone"));else if(e){if(!Yr(c.position)){let Je=c["margin-break"],Gt=this.getBreakTypeAt(this.nodeContext),rt=Gt!==null,se=Gt==="auto";(Je===b.discard&&rt||Je!==b.keep&&se&&!this.nodeContext.floatSide)&&Fr(D,"block-start")}}else{let Je=this.nodeContext.vertical?"width":"height";It(D,Je)&&T(D,Je,this.nodeContext.display==="table-row"?"0.01px":""),dt(D,"block-start"),ms(D)&&dt(D,"clone"),Fr(D,"block-start")}we&&D.setAttribute("value",c["ua-list-item-count"].stringValue()),this.viewNode=D,Ro.length?Rn(Ro).then(()=>{ot>0&&this.modifyElemDimensionWithImageResolution(Nt,ot,c,this.nodeContext.vertical),o.finish(s)}):o.timeSlice().then(()=>{o.finish(s)})})}),o.result()}isInsideNonRootMultiColumn(){var e;for(let n=(e=this.nodeContext.parent)==null?void 0:e.viewNode;n;n=n.parentNode){let s=n.nodeType===1?n.style:null;if(!s)break;if(!isNaN(parseFloat(s.columnCount))||!isNaN(parseFloat(s.columnWidth)))return!0;if(s.position==="absolute")break}return!1}getBreakTypeAt(e){var s,o,i,a,l;if(this.isInsideTable(e))return null;for(let c=e;c&&!c.after;c=c.parent){if(De(c.breakBefore))return c.breakBefore;if(c.fragmentIndex===1&&!c.parent)return c.sourceNode===c.sourceNode.ownerDocument.documentElement?"page":null;if((s=c.parent)!=null&&s.floatSide)return null;let u=(o=c.parent)==null?void 0:o.viewNode;if(u){let p=this.viewport.window.getComputedStyle(u),h=parseFloat(p.paddingBlockStart),f=parseFloat(p.borderBlockStartWidth);if(h||f)return null;let g=u==null?void 0:u.firstChild;for(;g&&(ue(g,c.parent.whitespace)||!c.floatSide&&ys(g));)g=g.nextSibling;if(g&&g!==c.viewNode)return null}}let n=(l=(a=(i=this.context)==null?void 0:i.currentLayoutPosition)==null?void 0:a.flowPositions[this.flowName])==null?void 0:l.startBreakType;return De(n)?n:"auto"}isInsideTable(e){for(let n=e;n&&!n.after;n=n.parent)if(n.display&&n.display.startsWith("table"))return!0;return!1}processAfterIfcontinues(e,n,s,o){let i=this.getPseudoMap(n,this.regionIds,this.isFootnote,this.nodeContext,o);if(i&&i["after-if-continues"]&&i["after-if-continues"].content){let a=new mi(e,n,s,o,this.exprContentListener);this.nodeContext.afterIfContinues=new Ca(e,a)}}isSVGUrlAttribute(e){return _i.SVG_URL_ATTRIBUTES.includes(e.toLowerCase())}modifyElemDimensionWithImageResolution(e,n,s,o){e.forEach(i=>{if(i.fetcher.get().get()==="load"){let a=i.image,l=a.width/n,c=a.height/n,u=i.element;if(l>0&&c>0){if(s["box-sizing"]===b.border_box&&(s["border-left-style"]!==b.none&&(l+=Le(s["border-left-width"],this.context)),s["border-right-style"]!==b.none&&(l+=Le(s["border-right-width"],this.context)),s["border-top-style"]!==b.none&&(c+=Le(s["border-top-width"],this.context)),s["border-bottom-style"]!==b.none&&(c+=Le(s["border-bottom-width"],this.context))),n>1){let p=s["max-width"]||b.none,h=s["max-height"]||b.none;if(p===b.none&&h===b.none)T(u,"max-width",`${l}px`);else if(p!==b.none&&h===b.none)T(u,"width",`${l}px`);else if(p===b.none&&h!==b.none)T(u,"height",`${c}px`);else{p.isNumeric(),h.isNumeric();let f=p,g=h;f.unit!=="%"?T(u,"max-width",`${Math.min(l,Le(f,this.context))}px`):g.unit!=="%"?T(u,"max-height",`${Math.min(c,Le(g,this.context))}px`):o?T(u,"height",`${c}px`):T(u,"width",`${l}px`)}}else if(n<1){let p=s["min-width"]||te,h=s["min-height"]||te;p.isNumeric(),p.isNumeric();let f=p,g=h;f.num===0&&g.num===0?T(u,"min-width",`${l}px`):f.num!==0&&g.num===0?T(u,"width",`${l}px`):f.num===0&&g.num!==0?T(u,"height",`${c}px`):f.unit!=="%"?T(u,"min-width",`${Math.max(l,Le(f,this.context))}px`):g.unit!=="%"?T(u,"min-height",`${Math.max(c,Le(g,this.context))}px`):o?T(u,"height",`${c}px`):T(u,"width",`${l}px`)}}}})}preprocessElementStyle(e){We("PREPROCESS_ELEMENT_STYLE").forEach(s=>{s(this.nodeContext,e)})}findAndProcessRepeatingElements(e,n){for(let s=e.firstChild;s;s=s.nextSibling){if(s.nodeType!==1)continue;let o={},i=n.getStyle(s,!1);if(this.computeStyle(this.nodeContext.vertical,this.nodeContext.direction==="rtl",i,o),!this.processRepeatOnBreak(o))continue;if(this.nodeContext.formattingContext instanceof Ut&&!this.nodeContext.belongsTo(this.nodeContext.formattingContext))return;let l=this.nodeContext.parent,c=l&&l.formattingContext;this.nodeContext.formattingContext=new Ut(c,this.nodeContext.sourceNode),this.nodeContext.formattingContext.initializeRepetitiveElements(this.nodeContext.vertical);return}}processRepeatOnBreak(e){let n=e["repeat-on-break"];return n!==b.none&&((n===b.auto||_(n))&&(e.display===b.table_header_group?n=b.header:e.display===b.table_footer_group?n=b.footer:n=b.none),n&&n!==b.none)?n.toString():null}createTextNodeView(){let e=A("createTextNodeView");return this.preprocessTextContent().then(()=>{let n=this.offsetInNode||0,s=wc(this.nodeContext.preprocessedTextContent).substr(n);this.viewNode=document.createTextNode(s),e.finish(!0)}),e.result()}preprocessTextContent(){if(this.nodeContext.preprocessedTextContent!=null)return v(!0);let e,n=e=this.sourceNode.textContent,s=A("preprocessTextContent"),o=We("PREPROCESS_TEXT_CONTENT"),i=0;return s.loop(()=>i>=o.length?v(!1):o[i++](this.nodeContext,n).thenAsync(a=>(n=a,v(!0)))).then(()=>{this.nodeContext.preprocessedTextContent=Nh(e,n),s.finish(!0)}),s.result()}createNodeView(e,n){let s=A("createNodeView"),o,i=!0;return this.sourceNode.nodeType==1?o=this.createElementView(e,n):this.sourceNode.nodeType==8?(this.viewNode=null,o=v(!0)):o=this.createTextNodeView(),o.then(a=>{var l,c;if(i=a,this.nodeContext.viewNode=this.viewNode,this.viewNode){let u=(f,g)=>(f==null?void 0:f.nodeType)===1&&As(f)===g,p=this.nodeContext.parent,h=p?u(this.viewNode,"after")&&u(p.viewNode,"first-letter")&&((l=p.viewNode)!=null&&l.hasChildNodes())?p.parent.viewNode:p.viewNode:this.viewRoot;if(h&&(this.nodeContext.inline&&!(this.viewNode.nodeType===3&&ue(this.viewNode))&&!h.hasChildNodes()&&yc(h).includes("block-start")&&dt(h,"text-start"),h.appendChild(this.viewNode),this.viewNode.nodeType===1&&this.viewNode.hasAttribute("data-vivliostyle-id"))){let f=this.viewNode,g=f.querySelector(":scope > a:empty[id^='viv-id-']");if(g&&(f.closest("[style*='position: absolute']")||/(table|flex|grid|ruby)/.test(f.style.display))){let m=g.getAttribute("id");g.ownerDocument.querySelectorAll(`a[id="${m}"]`).forEach(y=>{var C;(C=y.parentElement)==null||C.removeChild(y)});let E=h.closest("[data-vivliostyle-bleed-box]");(c=E==null?void 0:E.parentElement)==null||c.insertBefore(g,E)}}}s.finish(i)}),s.result()}setCurrent(e,n,s){return this.nodeContext=e,e?(this.sourceNode=e.sourceNode,this.offsetInNode=e.offsetInNode):(this.sourceNode=null,this.offsetInNode=-1),this.viewNode=null,this.nodeContext?this.createNodeView(n,!!s):v(!0)}processShadowContent(e){if(e.shadowContext==null||e.sourceNode.localName!="content"||e.sourceNode.namespaceURI!="http://www.pyroxy.com/ns/shadow")return e;let n=e.boxOffset,s=e.shadowContext,o=e.parent,i,a,l=s.subShadow||s.parentShadow;s.subShadow?(i=s.root,a=s.type,a==yt.ROOTLESS&&(i=i.firstChild)):(i=s.owner.firstChild,a=yt.ROOTLESS);let c=e.sourceNode.nextSibling;if(c?(e.sourceNode=c,e.resetView()):e.shadowSibling?e=e.shadowSibling:i?e=null:(e=e.parent.modify(),e.after=!0),i){let u=new Mn(i,o,n);return u.shadowContext=l,u.shadowType=a,u.shadowSibling=e,u}return e.boxOffset=n,e}nextPositionInTree(e){let n=e.boxOffset+1;if(e.after){if(!e.parent)return null;if(e.shadowType!=yt.ROOTED){let s=e.sourceNode.nextSibling;if(s)return e=e.modify(),e.boxOffset=n,e.sourceNode=s,e.resetView(),this.processShadowContent(e)}return e.shadowSibling?(e=e.shadowSibling.modify(),e.boxOffset=n,e):(e=e.parent.modify(),e.boxOffset=n,e.after=!0,e)}else{if(e.nodeShadow){let o=e.nodeShadow.root;if(e.nodeShadow.type==yt.ROOTLESS&&(o=o.firstChild),o){let i=new Mn(o,e,n);return i.shadowContext=e.nodeShadow,i.shadowType=e.nodeShadow.type,this.processShadowContent(i)}}let s=e.sourceNode.firstChild;if(s)return this.processShadowContent(new Mn(s,e,n));if(e.sourceNode.nodeType!=1){let o=wc(e.preprocessedTextContent);n+=o.length-1-e.offsetInNode}return e=e.modify(),e.boxOffset=n,e.after=!0,e}}isTransclusion(e,n,s){let o=pe(n,"hyperlink-processing");if(!o)return!1;let i=o.evaluate(this.context,"hyperlink-processing");return i?i.toString()==s:!1}nextInTree(e,n){let s=this.nextPositionInTree(e);if(!s||s.after)return v(s);let o=A("nextInTree");return this.setCurrent(s,!0,n).then(i=>{(!s.viewNode||!i)&&(s=s.modify(),s.after=!0,s.viewNode||(s.inline=!0)),this.dispatchEvent({type:"nextInTree",nodeContext:s}),o.finish(s)}),o.result()}addImageFetchers(e){if(e instanceof ge){let n=e.values;for(let s=0;s<n.length;s++)this.addImageFetchers(n[s])}else if(e instanceof Ue){let n=e.url;this.page.fetchers.push(In(new Image,n))}}applyComputedStyles(e,n){var u,p,h;let s=n["background-image"];s&&this.addImageFetchers(s);let o=n.position===b.relative,i=((u=this.nodeContext)==null?void 0:u.parent)===null&&((p=this.sourceNode)==null?void 0:p.parentElement)===null&&!!((h=this.viewRoot)!=null&&h.parentElement),a=Object.keys(n);a.sort(Bl);let l,c;for(let f of a){if(eb[f])continue;let g=n[f];if(!(!g||g===O&&!Ct(f))){if(g=g.visit(new Nr(this.xmldoc.url,this.documentURLTransformer)),g instanceof P&&mr(g.unit)&&(g.unit==="lh"?g=new P(g.num*this.getLineHeightUnitSize(f,l,c),"px"):g=xr(g,this.context)),f==="font-size"?l=g:f==="line-height"&&(c=g),Ph[f]||o&&kh[f]){this.page.delayedItems.push(new Dn(e,f,g));continue}i&&this.page.pageAreaElement&&Xn(f)?T(this.page.pageAreaElement.parentElement.parentElement,f,g.toString()):T(e,f,g.toString())}}}getLineHeightUnitSize(e,n,s){var u,p,h,f;let o=$.lh/$.em,i=((p=(u=this.nodeContext.parent)==null?void 0:u.viewNode)==null?void 0:p.nodeType)===1?this.viewport.window.getComputedStyle(this.nodeContext.parent.viewNode):null,a=i?parseFloat(i.fontSize):this.context.fontSize(),l=i?i.lineHeight==="normal"?a*o:parseFloat(i.lineHeight):this.context.rootLineHeight;if(e==="line-height"||e==="font-size")return l;let c=null;if(s){if(s instanceof tt||s instanceof P&&(s.unit==="em"||s.unit==="%"))c=s instanceof P&&s.unit==="%"?s.num/100:s.num;else if(s instanceof P)return s.num*this.context.queryUnitSize(s.unit,!1)}else for(let g=(h=this.nodeContext.parent)==null?void 0:h.viewNode;;g=g.parentNode){if(!g||g.nodeType!==1){c=o;break}let m=(f=g==null?void 0:g.style)==null?void 0:f.lineHeight;if(m){/^[0-9.]+$/.test(m)&&(c=parseFloat(m)),m==="normal"&&(c=o);break}}return c!==null?n instanceof P?c*Ru(n,a,this.context).num:c*a:l}applyPseudoelementStyle(e,n,s){if(e.after)return;let o=this.sourceNode,a=(e.shadowContext?e.shadowContext.styler:this.styler).getStyle(o,!1),l=St(a,"_pseudos");if(!l||(a=l[n],!a))return;let c={};e.vertical=this.computeStyle(e.vertical,e.direction==="rtl",a,c);let u=c.content;Et(u)&&(u.visit(new dn(s,this.context,u,this.exprContentListener)),delete c.content),this.applyComputedStyles(s,c)}peelOff(e,n){let s=A("peelOff"),o=e.firstPseudo,i=e.offsetInNode,a=e.after;if(n>0){let h=e.viewNode.textContent;e.viewNode.textContent=h.substr(0,n),i+=n}else if(!a&&e.viewNode&&i==0){let h=e.viewNode.parentNode;h&&h.removeChild(e.viewNode)}let l=e.boxOffset+n,c=[];for(;e.firstPseudo===o;)c.push(e),e=e.parent;let u=c.pop(),p=u.shadowSibling;return s.loop(()=>{for(;c.length>0;){u=c.pop(),e=new Mn(u.sourceNode,e,l),c.length==0&&(e.offsetInNode=i,e.after=a),e.shadowType=u.shadowType,e.shadowContext=u.shadowContext,e.nodeShadow=u.nodeShadow,e.shadowSibling=u.shadowSibling?u.shadowSibling:p,p=null;let h=this.setCurrent(e,!1);if(h.isPending())return h}return v(!1)}).then(()=>{s.finish(e)}),s.result()}createElement(e,n){return e=="http://www.w3.org/1999/xhtml"?this.document.createElement(n):this.document.createElementNS(e,n)}applyFootnoteStyle(e,n,s){let o={},i=St(this.footnoteStyle,"_pseudos");if(e=this.computeStyle(e,n,this.footnoteStyle,o),i&&i.before){let a={},l=this.createElement("http://www.w3.org/1999/xhtml","span");Ci(l,"before"),s.appendChild(l),this.computeStyle(e,n,i.before,a),delete a.content,this.applyComputedStyles(l,a)}return delete o.content,this.applyComputedStyles(s,o),e}processFragmentedBlockEdge(e){var i,a,l;let n=!e.inline&&e.after?e.parent:e,s=!1;if(e.inline&&e.after&&!e.shadowContext&&((i=e.sourceNode.nextSibling)==null?void 0:i.nodeType)===1){let c=e.sourceNode.nextSibling,u=(a=pe(this.styler.getStyle(c,!1),"display"))==null?void 0:a.value.toString();s=u&&!hn(u)||c.getAttribute("data-math-typeset")==="true"&&/^\s*(\$\$|\\\[)/.test(c.textContent)}let o=0;for(let c=n;c;c=c.parent){if(((l=c.viewNode)==null?void 0:l.nodeType)!==1)continue;let u=c.viewNode;if(u.style)if(c.inline){if(dt(u,"inline-end"),ms(u)){let p=c.vertical?u.offsetWidth:u.offsetHeight;dt(u,"clone"),(c.vertical?u.offsetWidth:u.offsetHeight)>p&&this.fixClonedBoxDecorationOverflow(u)}}else{let p=this.nodeContext.vertical?"width":"height";if(It(u,p)&&T(u,p,""),dt(u,"block-end"),!o++&&c!==n){let{textAlign:h}=this.viewport.window.getComputedStyle(u);if(h==="justify"&&!s){let f=this.createChildAnonymousBlockIfNeeded(u);f?f!==u?Ec(f,["block-start","text-start","block-end","text-end","justify"]):(dt(u,"text-end"),dt(u,"justify")):dt(u,"text-end")}else dt(u,"text-end")}ms(u)&&dt(u,"clone"),Fr(u,"block-end")}}}fixClonedBoxDecorationOverflow(e){let n=this.viewport.window.getComputedStyle(e),s=parseFloat(n.paddingInlineEnd),o=parseFloat(n.borderInlineEndWidth),i=-(s+o);isNaN(i)||(e.style.marginInlineEnd=`${i}px`)}createChildAnonymousBlockIfNeeded(e){let n=i=>{let{display:a,position:l,float:c}=this.viewport.window.getComputedStyle(i);if(i.localName==="ruby"||jt[i.localName])return!1;if(i.localName==="br")return!0;if((a==="inline"||a==="contents")&&i.hasChildNodes()){let u=i.lastElementChild;if(u&&(!u.nextSibling||u.nextSibling===i.lastChild&&ue(u.nextSibling))){let p=n(u);if(p||p===null)return p}for(let p=u==null?void 0:u.previousElementSibling;p;p=p.previousElementSibling){let h=n(p);if(h||h===null)return null}return!1}if(a==="none"||l==="absolute"||l==="fixed"||c&&c!=="none"||i.hasAttribute(Mt)){let u=i.previousElementSibling;return u&&(u.nextSibling===i||u.nextSibling===i.previousSibling&&ue(u.nextSibling))?n(u):!1}return!(!a||hn(a))},s=null;for(let i=e.lastElementChild;i;i=i.previousElementSibling){let a=n(i);if(a){s=i;break}if(a===null)return null}if(!s)return e;if(s===e.lastElementChild&&(!s.nextSibling||s.nextSibling===e.lastChild&&ue(s.nextSibling)))return null;let o=e.ownerDocument.createElement("span");o.className="viv-anonymous-block";for(let i=s.nextSibling,a=null;i;i=a)a=i.nextSibling,o.appendChild(i);return e.appendChild(o),o}convertLengthToPx(e,n,s){let o=e.num,i=e.unit;if(Op(i)){let a=n;for(;a&&a.nodeType!==1;)a=a.parentNode;let l=parseFloat(s.getElementComputedStyle(a)["font-size"]);return this.context,ua(e,l,this.context).num}else{let a=this.context.queryUnitSize(i,!1);return a?o*a:e}}isSameNodePositionStep(e,n){if(e.shadowContext){if(!n.shadowContext)return!1;let s=e.node.nodeType===1?e.node:e.node.parentElement,o=n.node.nodeType===1?n.node:n.node.parentElement;return e.shadowContext.owner===n.shadowContext.owner&&As(s)===As(o)}else return e.node===n.node}isSameNodePosition(e,n){return e.offsetInNode===n.offsetInNode&&e.after==n.after&&e.steps.length===n.steps.length&&e.steps.every((s,o)=>{let i=n.steps[o];return this.isSameNodePositionStep(s,i)})}isPseudoelement(e){return!!As(e)}};d(_i,"SVG_URL_ATTRIBUTES",["color-profile","clip-path","cursor","filter","marker","marker-start","marker-end","marker-mid","fill","stroke","mask"]);var Wa=_i,eb={"float-min-wrap-block":!0,"float-reference":!0,"flow-into":!0,"flow-linger":!0,"flow-options":!0,"flow-priority":!0,"footnote-policy":!0,"margin-break":!0,page:!0},Ga=null,$a=class{constructor(t){d(this,"layoutBox");d(this,"window");d(this,"scaleRatio");this.layoutBox=t.layoutBox,this.window=t.window,this.scaleRatio=t.scaleRatio}scaleRect(t){return Ga?{left:t.left*this.scaleRatio,top:t.top*this.scaleRatio,right:t.right*this.scaleRatio,bottom:t.bottom*this.scaleRatio,width:t.width*this.scaleRatio,height:t.height*this.scaleRatio}:t}subtractOffsets(t,e){let n=e.left,s=e.top;return{left:t.left-n,top:t.top-s,right:t.right-n,bottom:t.bottom-s,width:t.width,height:t.height}}getRangeClientRects(t){let e=t.getClientRects(),n=this.layoutBox.getBoundingClientRect();return Array.from(e).map(s=>this.scaleRect(this.subtractOffsets(s,n)))}getElementClientRect(t){let n=t.getBoundingClientRect();if(n.left===0&&n.top===0&&n.right===0&&n.bottom===0)return n;let s=this.layoutBox.getBoundingClientRect();return this.scaleRect(this.subtractOffsets(n,s))}getElementComputedStyle(t){return this.window.getComputedStyle(t,null)}adjustLengthValue(t){let e=64*(this.scaleRatio||1);return Math.floor(t*e)/e}},Nn=class{constructor(t,e,n,s,o,i){this.window=t;this.fontSize=e;this.pixelRatio=n;d(this,"document");d(this,"root");d(this,"outerZoomBox");d(this,"contentContainer");d(this,"layoutBox");d(this,"width");d(this,"height");d(this,"scaleRatio",1);this.document=t.document,this.root=s||this.document.body;let a=this.root.firstElementChild;a||(a=this.document.createElement("div"),a.setAttribute("data-vivliostyle-outer-zoom-box","true"),this.root.appendChild(a));let l=a.firstElementChild;l||(l=this.document.createElement("div"),l.setAttribute("data-vivliostyle-spread-container","true"),a.appendChild(l)),n>0&&CSS.supports("zoom","8")&&(T(this.root,"--viv-outputPixelRatio",`${n}`),T(this.root,"--viv-devicePixelRatio",`${t.devicePixelRatio}`),this.scaleRatio=n/t.devicePixelRatio,Ga===null&&(Ga=!("currentCSSZoom"in l)),Ga&&T(this.root,"--viv-scaleRectRatio",`${this.scaleRatio}`));let c=a.nextElementSibling;c||(c=this.document.createElement("div"),c.setAttribute("data-vivliostyle-layout-box","true"),this.root.appendChild(c)),this.outerZoomBox=a,this.contentContainer=l,this.layoutBox=c,this.width=o||parseFloat(t.getComputedStyle(this.root).width)||this.root.offsetWidth||t.innerWidth,this.height=i||parseFloat(t.getComputedStyle(this.root).height)||this.root.offsetHeight||t.innerHeight;let u={width:794,height:1056},p=!t.outerWidth&&!t.outerHeight||/Headless/.test(navigator.userAgent)||navigator.webdriver&&t.innerWidth===800&&t.innerHeight===600;(!this.width||!o&&p)&&(this.width=u.width),(!this.height||!i&&p)&&(this.height=u.height)}resetZoom(){T(this.outerZoomBox,"width",""),T(this.outerZoomBox,"height",""),T(this.contentContainer,"width",""),T(this.contentContainer,"height",""),T(this.contentContainer,"transform","")}zoom(t,e,n){T(this.root,"--viv-outputScale",`${n}`),T(this.outerZoomBox,"width",`${t*n}px`),T(this.outerZoomBox,"height",`${e*n}px`),T(this.contentContainer,"width",`${t}px`),T(this.contentContainer,"height",`${e}px`)}clear(){let t=this.root;for(;t.lastChild;)t.removeChild(t.lastChild)}};var Ui=class{constructor(t,e,n){this.store=t;this.url=e;this.document=n;d(this,"lang",null);d(this,"totalOffset",-1);d(this,"root");d(this,"body");d(this,"head");d(this,"last");d(this,"lastOffset",1);d(this,"idMap");this.root=n.documentElement;let s=null,o=null;if(this.root.namespaceURI=="http://www.w3.org/1999/xhtml"){for(let i=this.root.firstChild;i;i=i.nextSibling){if(i.nodeType!=1)continue;let a=i;if(a.namespaceURI=="http://www.w3.org/1999/xhtml")switch(a.localName){case"head":o=a;break;case"body":s=a;break}}this.lang=this.root.getAttribute("lang")}this.body=s,this.head=o,this.last=this.root,this.last.setAttribute(Rt,"0")}doc(){return new Ya([this.document])}getElementOffset(t){let e=t.getAttribute(Rt);if(e)return parseInt(e,10);let n=this.lastOffset,s=this.last;for(;s!=t;){let o=s.firstChild;if(!o){for(;o=s.nextSibling,!o;)if(s=s.parentNode,s==null)throw new Error("Internal error")}s=o,o.nodeType==1?(o.setAttribute(Rt,n.toString()),++n):n+=o.textContent.length}return this.lastOffset=n,this.last=t,n-1}getNodeOffset(t,e,n){let s=0,o=t,i=null;if(o.nodeType==1){if(!n)return this.getElementOffset(o)}else{if(s=e,i=o.previousSibling,!i)return o=o.parentNode,s+=1,this.getElementOffset(o)+s;o=i}for(;;){for(;o.lastChild;)o=o.lastChild;if(o.nodeType==1)break;if(s+=o.textContent.length,i=o.previousSibling,!i){o=o.parentNode;break}o=i}return s+=1,this.getElementOffset(o)+s}getTotalOffset(){return this.totalOffset<0&&(this.totalOffset=this.getNodeOffset(this.root,0,!0)),this.totalOffset}getNodeByOffset(t){let e,n=this.root;for(;;){if(e=this.getElementOffset(n),e>=t)return n;let l=n.children;if(!l)break;let c=ft(l.length,u=>{let p=l[u];return this.getElementOffset(p)>t});if(c==0)break;n=l[c-1]}let s=e+1,o=n,i=o.firstChild||o.nextSibling,a=null;for(;;){if(i){if(i.nodeType==1||(o=i,a=o,s+=i.textContent.length,s>t&&!/^\s*$/.test(i.textContent)))break}else if(o=o.parentNode,!o)break;i=o.nextSibling}return i&&a&&/^\s*$/.test(a.textContent)&&(a=i),a||n}buildIdMap(t){let e=t.getAttribute("id");e&&!this.idMap[e]&&(this.idMap[e]=t);let n=t.getAttributeNS("http://www.w3.org/XML/1998/namespace","id");n&&!this.idMap[n]&&(this.idMap[n]=t);for(let s=t.firstElementChild;s;s=s.nextElementSibling)this.buildIdMap(s)}getElement(t){let e=t.match(/([^#]*)#(.+)$/);if(!e||e[1]&&e[1]!=this.url)return null;let n=e[2],s=this.document.getElementById(n);return!s&&this.document.getElementsByName&&(s=this.document.getElementsByName(n)[0]),s||(this.idMap||(this.idMap={},this.buildIdMap(this.document.documentElement)),s=this.idMap[n]),s}},rp=(o=>(o.TEXT_HTML="text/html",o.TEXT_XML="text/xml",o.APPLICATION_XML="application/xml",o.APPLICATION_XHTML_XML="application/xhtml+xml",o.IMAGE_SVG_XML="image/svg+xml",o))(rp||{});function ja(r,t,e){let n=e||new DOMParser,s;try{s=n.parseFromString(r,t)}catch(o){}if(s){let o=s.documentElement,i="parsererror";if(o.localName===i)return null;for(let a=o.firstElementChild;a;a=a.nextElementSibling)if(a.localName===i)return null}else return null;return s}function tb(r){let t=r.contentType;if(t){let n=Object.keys(rp);for(let s=0;s<n.length;s++)if(rp[n[s]]===t)return t;if(t.match(/\+xml$/))return"application/xml"}let e=r.url.match(/\.([^./]+)$/);if(e)switch(e[1]){case"html":case"htm":return"text/html";case"xhtml":case"xht":return"application/xhtml+xml";case"svg":case"svgz":return"image/svg+xml";case"opf":case"xml":return"application/xml"}return null}function lp(r,t){let e=r.responseXML;if(!e){let s=new DOMParser,o=r.responseText;if(o){let i=tb(r);if(e=ja(o,i||"application/xml",s),e&&!i){let a=e.documentElement;a.localName.toLowerCase()==="html"&&!a.namespaceURI?e=ja(o,"text/html",s):a.localName.toLowerCase()==="svg"&&e.contentType!=="image/svg+xml"&&(e=ja(o,"image/svg+xml",s))}e||(e=ja(o,"text/html",s))}}let n=e?new Ui(t,r.url,e):null;return v(n)}function ng(){return new ps(lp,"document")}var ap=class r{constructor(t){this.fn=t}check(t){return this.fn(t)}withAttribute(t,e){return new r(n=>this.check(n)&&n.nodeType==1&&n.getAttribute(t)==e)}withChild(t,e){return new r(n=>{if(!this.check(n))return!1;let s=new Ya([n]);return s=s.child(t),e&&(s=s.predicate(e)),s.size()>0})}},cp=new ap(r=>!0),Ya=class r{constructor(t){this.nodes=t}asArray(){return this.nodes}size(){return this.nodes.length}predicate(t){let e=[];for(let n of this.nodes)t.check(n)&&e.push(n);return new r(e)}forEachNode(t){let e=[],n=s=>{e.push(s)};for(let s=0;s<this.nodes.length;s++)t(this.nodes[s],n);return new r(e)}forEach(t){let e=[];for(let n=0;n<this.nodes.length;n++)e.push(t(this.nodes[n]));return e}forEachNonNull(t){let e=[];for(let n=0;n<this.nodes.length;n++){let s=t(this.nodes[n]);s!=null&&e.push(s)}return e}child(t){return this.forEachNode((e,n)=>{for(let s=e.firstChild;s;s=s.nextSibling)s.nodeType==1&&s.localName==t&&n(s)})}childElements(){return this.forEachNode((t,e)=>{for(let n=t.firstChild;n;n=n.nextSibling)n.nodeType==1&&e(n)})}attribute(t){return this.forEachNonNull(e=>e.nodeType==1?e.getAttribute(t):null)}textContent(){return this.forEach(t=>t.textContent)}};var nb=new Zt(()=>{let r=A("uaStylesheetBase"),t=Id(),e=Q("user-agent-base.css",$t),n=new xn(null,null,null,null,null,t,!0);return n.startStylesheet("UA"),ef(n.cascade),Vr(dc,n,e,null,null).thenFinish(r),r.result()},"uaStylesheetBaseFetcher");function sb(){return nb.get()}var up=class{constructor(t,e,n,s,o,i,a,l,c,u){this.store=t;this.rootScope=e;this.pageScope=n;this.cascade=s;this.rootBox=o;this.fontFaces=i;this.footnoteProps=a;this.flowProps=l;this.viewportProps=c;this.pageProps=u;d(this,"fontDeobfuscator");d(this,"validatorSet");this.fontDeobfuscator=t.fontDeobfuscator,this.validatorSet=t.validatorSet,this.pageScope.defineBuiltIn("has-content",function(p){p=p;let h=this,f=h.currentLayoutPosition,g=f.firstFlowChunkOfFlow(p);return h.matchPageSide(f.startSideOfFlow(p))&&f.hasContent(p,h.lookupOffset)&&!!g&&!h.flowChunkIsAfterParentFlowForcedBreak(g)}),this.pageScope.defineName("page-number",new ie(this.pageScope,function(){let p=this;return p.pageNumberOffset+p.currentLayoutPosition.page},"page-number")),this.pageScope.defineName("blank-page",new ie(this.pageScope,function(){let h=this.currentLayoutPosition;return h==null?void 0:h.isBlankPage},"blank-page"))}sizeViewport(t,e,n,s){if(this.viewportProps.length){let o=new zs(this.rootScope,t,e,n),i=Qh(o,this.viewportProps),a=i.width,l=i.height,c=i["text-zoom"],u=1;if(a&&l||c){let p=$.em;if((c?c.evaluate(o,"text-zoom"):null)===b.scale&&(u=p/n,n=p,t*=u,e*=u),a&&l){let f=Le(a.evaluate(o,"width"),o),g=Le(l.evaluate(o,"height"),o);if(f>0&&g>0)return{width:s&&s.spreadView?(f+s.pageBorder)*2:f,height:g,fontSize:n}}}}return{width:t,height:e,fontSize:n}}},Qn=class extends zs{constructor(e,n,s,o,i,a,l,c,u,p,h,f,g){super(e.rootScope,o.width,o.height,o.fontSize);this.style=e;this.xmldoc=n;this.viewport=o;this.clientLayout=i;this.fontMapper=a;this.customRenderer=l;this.fallbackMap=c;this.pageNumberOffset=u;this.documentURLTransformer=p;this.counterStore=h;d(this,"lang");d(this,"primaryFlows",{body:!0});d(this,"rootPageBoxInstance",null);d(this,"styler",null);d(this,"stylerMap",null);d(this,"currentLayoutPosition",null);d(this,"layoutPositionAtPageStart",null);d(this,"lookupOffset",0);d(this,"faces");d(this,"pageBoxInstances",{});d(this,"pageManager",null);d(this,"rootPageFloatLayoutContext");d(this,"pageBreaks",{});d(this,"pageProgression",null);d(this,"isVersoFirstPage",!1);d(this,"blankPageAtStart",!1);d(this,"pageSheetSize",{});d(this,"pageSheetHeight",0);d(this,"pageSheetWidth",0);this.lang=n.lang||s,this.faces=new La(this.style.fontDeobfuscator),this.rootPageFloatLayoutContext=new pn(null,null,null,null,null,null,null),this.pageProgression=f||null,this.isVersoFirstPage=!!g;for(let m in e.flowProps){let E=e.flowProps[m],y=pe(E,"flow-consume");y&&(y.evaluate(this,"flow-consume")==b.all?this.primaryFlows[m]=!0:delete this.primaryFlows[m])}}init(){let e=A("StyleInstance.init"),n=this.counterStore.createCounterListener(this.xmldoc.url),s=this.counterStore.createCounterResolver(this.xmldoc.url,this.style.rootScope,this.style.pageScope);this.styler=new vi(this.xmldoc,this.style.cascade,this.style.rootScope,this,this.primaryFlows,this.style.validatorSet,n,s),s.setStyler(this.styler),this.styler.resetFlowChunkStream(this),this.stylerMap={},this.stylerMap[this.xmldoc.url]=this.styler;let o=this.styler.getTopContainerStyle();this.pageProgression||(this.pageProgression=tp(o)),this.matchStartPageSide(this.styler.breakBeforeValues[0])||(this.pageNumberOffset===0?this.isVersoFirstPage=!0:this.blankPageAtStart=!0);let i=this.style.rootBox;this.rootPageBoxInstance=new Ba(i);let a=this.style.cascade.createInstance(this,n,s,this.lang);this.styler.cascade.currentPageType=this.styler.cascade.firstPageType,this.rootPageBoxInstance.applyCascadeAndInit(a,o),this.rootPageBoxInstance.resolveAutoSizing(this),this.pageManager=new _a(a,this.style.pageScope,this.rootPageBoxInstance,this,o);let l=[];for(let u of this.style.fontFaces){if(u.condition&&!u.condition.evaluate(this))continue;let p=_f(u.properties,this),h=new Li(p);l.push(h)}this.fontMapper.findOrLoadFonts(l,this.faces).then(()=>{Jf(this.xmldoc.document,this.viewport.window,this.styler).thenFinish(e)});let c=this.style.pageProps;return c[""]||(c[""]={}),Object.keys(c).forEach(u=>{let p=c[u];this.styler.cascade.applyVarFilter([p],this.styler,null),this.styler.cascade.applyCalcFilter(p,this.styler.context);let h=np(Mi(p),this);this.pageSheetSize[u]={width:h.pageWidth+h.cropOffset*2,height:h.pageHeight+h.cropOffset*2}}),e.result()}matchStartPageSide(e){let n=this.pageNumberOffset%2==(this.isVersoFirstPage?1:0),s=this.pageProgression=="ltr";switch(e){case"left":return n!==s;case"right":return n===s;case"recto":return n;case"verso":return!n;default:return!0}}getStylerForDoc(e){let n=this.stylerMap[e.url];if(!n){let s=this.style.store.getStyleForDoc(e),o=new zs(s.rootScope,this.pageWidth(),this.pageHeight(),this.initialFontSize),i=this.counterStore.createCounterListener(e.url),a=this.counterStore.createCounterResolver(e.url,s.rootScope,s.pageScope);n=new vi(e,s.cascade,s.rootScope,o,this.primaryFlows,s.validatorSet,i,a),this.stylerMap[e.url]=n}return n}registerInstance(e,n){this.pageBoxInstances[e]=n}lookupInstance(e){return this.pageBoxInstances[e]}encounteredFlowChunk(e,n){let s=this.currentLayoutPosition;if(s){s.flows[e.flowName]?n=s.flows[e.flowName]:s.flows[e.flowName]=n;let o=s.flowPositions[e.flowName];o||(o=new Gr,s.flowPositions[e.flowName]=o);let i=Ih(e.element),a=new pt(i),l=new zr(a,e);o.positions.push(l)}}evalSupportsTest(e,n,s){if(s)return e==="selector"?this.evalSupportsSelector(n):!1;if(!e)return!1;let o=!0;class i{unknownProperty(p,h){o=!1}invalidPropertyValue(p,h){o=!1}simpleProperty(p,h,f){}}let a=new i,l=Jt(this.style.rootScope,new Oe(n,null),"");return l?(this.xmldoc.store.validatorSet.validatePropertyAndHandleShorthand(e,l,!1,a),o):!1}evalSupportsSelector(e){let n=new Ka(null),s=new Oe(e+"{}",n);return new Vn(me,s,n,"").runParser(Number.POSITIVE_INFINITY,!1,!1,!1,!1)?!n.cascadeParserHandler.invalid:!1}getConsumedOffset(e){let n=Number.POSITIVE_INFINITY;for(let s=0;s<e.positions.length;s++){let o=e.positions[s].chunkPosition.primary,i=o.steps[0].node,a=o.offsetInNode,l=o.after,c=0;for(;i.ownerDocument!=this.xmldoc.document;)c++,i=o.steps[c].node,l=!1,a=0;let u=this.xmldoc.getNodeOffset(i,a,l);u<n&&(n=u)}return n}getPosition(e,n){if(!e)return 0;let s=Number.POSITIVE_INFINITY;for(let o in this.primaryFlows){let i=e.flowPositions[o];if(!n&&(!i||i.positions.length==0)&&this.currentLayoutPosition&&(this.styler.styleUntilFlowIsReached(o),i=this.currentLayoutPosition.flowPositions[o],e!=this.currentLayoutPosition&&i&&(i=i.clone(),e.flowPositions[o]=i)),i){let a=this.getConsumedOffset(i);a<s&&(s=a)}}return s}dumpLocation(e){V.debug("Location - page",this.currentLayoutPosition.page),V.debug(" current:",e),V.debug(" lookup:",this.lookupOffset);for(let n in this.currentLayoutPosition.flowPositions){let s=this.currentLayoutPosition.flowPositions[n];for(let o of s.positions)V.debug(" Chunk",`${n}:`,o.flowChunk.startOffset)}}matchPageSide(e){switch(e){case"left":case"right":case"recto":case"verso":return new J(this.style.pageScope,`${e}-page`).evaluate(this);default:return!0}}updateStartSide(e){for(let n in e.flowPositions){let s=e.flowPositions[n];if(s&&s.positions.length>0){let o=s.positions[0].flowChunk;if(this.getConsumedOffset(s)===o.startOffset){let i=s.positions[0].flowChunk.breakBefore,a=s.startBreakType;s.startBreakType=Sc(Fe(a,i))}}}}selectPageMaster(e){let n=this.currentLayoutPosition,s=this.getPosition(n);if(s==Number.POSITIVE_INFINITY)return null;let o=this.rootPageBoxInstance.children,i;for(let a=0;a<o.length;a++){if(i=o[a],i.pageBox.pseudoName===Ha)continue;let l=1;i.pageBox.pseudoName===Ii&&!(this.actualPageWidth&&this.actualPageHeight)&&(l=1/0);let c=i.getProp(this,"utilization");c&&c.isNum()&&(l=c.num);let u=this.queryUnitSize("em",!1),p=this.pageWidth()*this.pageHeight(),h=Math.ceil(l*p/(u*u)),f=this.styler.cascade.currentPageType;this.lookupOffset=this.styler.styleUntil(s,h),this.styler.cascade.currentPageType=f,this.updateStartSide(n),this.layoutPositionAtPageStart=n.clone(),this.initLingering(),this.clearScope(this.style.pageScope);let g=i.getProp(this,"enabled");if(!g||g===b._true){if(n.page===1&&this.blankPageAtStart){i.style={};let m=e.size;e={},m&&(e.size=m)}return this.pageManager.getPageRulePageMaster(i,e)}}throw new Error("No enabled page masters")}flowChunkIsAfterParentFlowForcedBreak(e){let n=this.layoutPositionAtPageStart.flows,s=n[e.flowName].parentFlowName;if(s){let o=e.startOffset,i=n[s].forcedBreakOffsets;if(!i.length||o<i[0])return!1;let a=ft(i.length,p=>i[p]>o)-1,l=i[a],c=this.layoutPositionAtPageStart.flowPositions[s],u=this.getConsumedOffset(c);return l<u?!1:u<l?!0:!this.matchPageSide(c.startBreakType)}return!1}setFormattingContextToColumn(e,n){let s=this.currentLayoutPosition.flows[n];s.formattingContext||(s.formattingContext=new fo(null)),e.flowRootFormattingContext=s.formattingContext}layoutDeferredPageFloats(e){let n=e.pageFloatLayoutContext,s=n.getDeferredPageFloatContinuations(),o=c=>{if(c.floatReference!==de.PAGE)return!1;let u=this.layoutPositionAtPageStart.flowPositions.body,p=u&&this.getConsumedOffset(u),h=this.xmldoc.getNodeOffset(c.nodePosition.steps[0].node,0,!1);return h!=null&&p!=null&&h>p},i=A("layoutDeferredPageFloats"),a=!1,l=0;return i.loopWithFrame(c=>{if(l===s.length){c.breakLoop();return}let u=s[l++],p=u.float;if(o(p)){c.breakLoop();return}let h=new _t().findByFloat(p),f=h.findPageFloatFragment(p,n);if(f&&f.hasFloat(p)){c.continueLoop();return}else if(n.isForbidden(p)||n.hasPrecedingFloatsDeferredToNext(p)){n.deferPageFloat(u),c.breakLoop();return}e.layoutPageFloatInner(u,h,null,f).then(g=>{if(!g){c.breakLoop();return}let m=n.parent.isInvalidated();if(m){c.breakLoop();return}else n.isInvalidated()&&!m&&(a=!0,n.validate());c.continueLoop()})}).then(()=>{a&&n.invalidate(),i.finish(!0)}),i.result()}getLastAfterPositionIfDeferredFloatsExists(e,n){if(e.pageFloatLayoutContext.getPageFloatContinuationsDeferredToNext().length>0)if(e.lastAfterPosition){let i;return n?(i=n.clone(),i.primary=e.lastAfterPosition):i=new pt(e.lastAfterPosition),i}else return null;else return null}layoutColumn(e,n){let s=this.currentLayoutPosition.flowPositions[n];if(!s||!this.matchPageSide(s.startBreakType))return v(!0);this.setFormattingContextToColumn(e,n),e.init(),this.primaryFlows[n]&&e.bands.length>0&&(e.forceNonfitting=!1);let o=A("layoutColumn");return this.layoutDeferredPageFloats(e).then(()=>{if(e.pageFloatLayoutContext.isInvalidated()){o.finish(!0);return}let i=[],a=[],l=!0;o.loopWithFrame(c=>{if(e.pageFloatLayoutContext.hasContinuingFloatFragmentsInFlow(n)){c.breakLoop();return}for(;s.positions.length-a.length>0;){let u=0;for(;a.includes(u);)u++;let p=s.positions[u];if(p.flowChunk.startOffset>this.lookupOffset||this.flowChunkIsAfterParentFlowForcedBreak(p.flowChunk))break;for(let g=u+1;g<s.positions.length;g++){if(a.includes(g))continue;let m=s.positions[g];if(m.flowChunk.startOffset>this.lookupOffset||this.flowChunkIsAfterParentFlowForcedBreak(m.flowChunk))break;m.flowChunk.isBetter(p.flowChunk)&&(p=m,u=g)}let h=p.flowChunk,f=!0;if(e.layout(p.chunkPosition,l,s.breakAfter).then(g=>{if(e.pageFloatLayoutContext.isInvalidated()){c.breakLoop();return}if(l=!1,p.flowChunk.repeated&&(g===null||h.exclusive)&&i.push(u),h.exclusive){a.push(u),c.breakLoop();return}else{let m=!!g||!!e.pageBreakType,E=this.getLastAfterPositionIfDeferredFloatsExists(e,g);if(e.pageBreakType&&E?(p.chunkPosition=E,s.breakAfter=e.pageBreakType,e.pageBreakType=null):(a.push(u),(g||E)&&(p.chunkPosition=g||E,i.push(u)),s.startBreakType=Sc(e.pageBreakType)),m){c.breakLoop();return}}e.forceNonfitting=!1,f?f=!1:c.continueLoop()}),f){f=!1;return}}c.breakLoop()}).then(()=>{if(!e.pageFloatLayoutContext.isInvalidated()){s.positions=s.positions.filter((u,p)=>i.includes(p)||!a.includes(p)),s.breakAfter==="column"&&(s.breakAfter=null),e.saveDistanceToBlockEndFloats();let c=e.pageFloatLayoutContext.getMaxReachedAfterEdge();e.updateMaxReachedAfterEdge(c)}o.finish(!0)})}),o.result()}createLayoutConstraint(e){let n=this.currentLayoutPosition.page-1,s=this.counterStore.createLayoutConstraint(n);return new ba([s].concat(e.getLayoutConstraints()))}createAndLayoutColumn(e,n,s,o,i,a,l,c,u,p,h,f,g,m){let E=e.vertical?e.isAutoWidth&&e.isRightDependentOnAutoWidth:e.isAutoHeight&&e.isTopDependentOnAutoHeight,y=i.element,C=new pn(c,de.COLUMN,null,l,null,null,null),x=this.currentLayoutPosition.clone(),N=A("createAndLayoutColumn"),S;return N.loopWithFrame(w=>{let k=this.createLayoutConstraint(C);if(u>1){let I=this.viewport.document.createElement("div");if(T(I,"position","absolute"),y.appendChild(I),S=new Rs(I,g,this.clientLayout,k,C),S.forceNonfitting=m,S.vertical=i.vertical,S.rtl=i.rtl,S.snapHeight=i.snapHeight,S.snapWidth=i.snapWidth,i.vertical){let U=(i.rtl?u-a-1:a)*(h+p)+i.paddingTop,Se=parseFloat(y.style.width);S.setHorizontalPosition(i.paddingLeft+Se-i.width,i.width),S.setVerticalPosition(U,h)}else{let U=(i.rtl?u-a-1:a)*(h+p)+i.paddingLeft;S.setVerticalPosition(i.paddingTop,i.height),S.setHorizontalPosition(U,h)}S.originX=n,S.originY=s}else S=new Rs(y,g,this.clientLayout,k,C),S.copyFrom(i);S.exclusions=E?[]:o.concat(),S.innerShape=f,C.setContainer(S),(S.vertical?S.height:S.width)>=0?this.layoutColumn(S,l).then(()=>{C.isInvalidated()||C.finish(),S.pageFloatLayoutContext.isInvalidated()&&!c.isInvalidated()?(S.pageFloatLayoutContext.validate(),this.currentLayoutPosition=x.clone(),S.element!==y&&y.removeChild(S.element),w.continueLoop()):w.breakLoop()}):(C.finish(),w.breakLoop())}).then(()=>{N.finish(S)}),N.result()}setPagePageFloatLayoutContextContainer(e,n,s){(n instanceof Di||n instanceof Os&&!(n instanceof Sn))&&e.setContainer(s)}getRegionPageFloatLayoutContext(e,n,s,o){n instanceof on;let i=n.getProp(this,"writing-mode")||null,a=n.getProp(this,"direction")||null;return new pn(e,de.REGION,s,o,null,i,a)}layoutFlowColumnsWithBalancing(e,n,s,o,i,a,l,c,u){let p=this.currentLayoutPosition.clone(),h=this.getRegionPageFloatLayoutContext(a,n,l,c),f=!0,g=()=>(this.currentLayoutPosition=p.clone(),this.layoutFlowColumns(e,n,s,o,i,a,h,l,c,u,f).thenAsync(m=>m?v({columns:m,position:this.currentLayoutPosition}):v(null)));return g().thenAsync(m=>{if(!m)return v(null);if(u<=1)return v(m.columns);let E=n.getProp(this,"column-fill")||b.balance,y=this.currentLayoutPosition.flowPositions[c];let C=kf(u,E,g,h,l,m.columns,y);return C?(f=!1,a.lock(),h.lock(),C.balanceColumns(m).thenAsync(x=>(a.unlock(),a.validate(),h.unlock(),this.currentLayoutPosition=x.position,v(x.columns)))):v(m.columns)})}layoutFlowColumns(e,n,s,o,i,a,l,c,u,p,h){let f=A("layoutFlowColumns"),g=this.currentLayoutPosition.clone(),m=n.getPropAsNumber(this,"column-gap"),E=p>1?n.getPropAsNumber(this,"column-width"):c.vertical?c.height:c.width,y=n.getActiveRegions(this),C=n.getProp(this,"shape-inside"),x=vr(C,0,0,c.width,c.height,this),N=new Wa(u,this,this.viewport,this.styler,y,this.xmldoc,this.faces,this.style.footnoteProps,this,e,this.customRenderer,this.fallbackMap,this.documentURLTransformer),S=0,w=null,k=[];return f.loopWithFrame(I=>{this.createAndLayoutColumn(n,s,o,i,c,S++,u,l,p,m,E,x,N,h).then(U=>{if(a.isInvalidated()){k=null,I.breakLoop();return}if((!!U.pageBreakType&&U.pageBreakType!=="column"||S===p)&&!l.isInvalidated()&&l.finish(),l.isInvalidated()){S=0,this.currentLayoutPosition=g.clone(),l.validate(),l.isLocked()?(k=null,I.breakLoop()):I.continueLoop();return}w=U,k[S-1]=w,w.pageBreakType&&w.pageBreakType!="column"&&(S=p,w.pageBreakType!="region"&&(this.pageBreaks[u]=!0)),S<p?I.continueLoop():I.breakLoop()})}).then(()=>{f.finish(k)}),f.result()}layoutContainer(e,n,s,o,i,a,l){n.reset();let c=n.getProp(this,"enabled");if(c&&c!==b._true)return v(!0);let u=A("layoutContainer"),h=n.getProp(this,"wrap-flow")===b.auto,f=n.getProp(this,"flow-from"),g=this.viewport.document.createElement("div"),m=n.getProp(this,"position");T(g,"position",m?m.name:"absolute");let E=n instanceof Sn;n instanceof on?s.appendChild(g):s.insertBefore(g,s.firstChild);let C=new uo(g);C.vertical=n.vertical,C.rtl=n.rtl,C.borderBoxSizing=n.borderBoxSizing,C.exclusions=a,n.prepareContainer(this,C,e,this.faces,this.clientLayout),n instanceof Sn&&(C.width<=0||C.height<=0)&&V.warn("Negative or zero page area size"),C.originX=o,C.originY=i,o+=C.left+C.marginLeft+C.borderLeft,i+=C.top+C.marginTop+C.borderTop,this.setPagePageFloatLayoutContextContainer(l,n,C);let x,N=!1;if(!f||!f.isIdent()){let S=n.getProp(this,"content");if(S instanceof F&&S.expr instanceof ie&&S.expr.str.startsWith("running-element-"))S.visit(new dn(g,this,S,this.counterStore.getExprContentListener()));else if(S&&Et(S)){let w="span";S.url&&(w="img");let k=this.viewport.document.createElement(w);S.visit(new dn(k,this,S,this.counterStore.getExprContentListener())),g.appendChild(k),w=="img"&&n.transferSingleUriContentProps(this,k,this.faces),n.transferContentProps(this,C,e,this.faces),w=="span"&&hf(k,n.getProp(this,"text-autospace"),n.getProp(this,"text-spacing-trim"),n.getProp(this,"hanging-punctuation"),this.lang,n.vertical)}else n.suppressEmptyBoxGeneration&&(s.removeChild(g),N=!0);N||n.finishContainer(this,C,e,null,1,this.clientLayout,this.faces),x=v(!0)}else if(this.pageBreaks[f.toString()])l.isInvalidated()||n.finishContainer(this,C,e,null,1,this.clientLayout,this.faces),x=v(!0);else{let S=A("layoutContainer.inner"),w=f.toString(),k=n.getPropAsNumber(this,"column-count");this.layoutFlowColumnsWithBalancing(e,n,o,i,a,l,C,w,k).then(I=>{if(!l.isInvalidated()){let U=I[0];U.element===g&&(C=U),C.computedBlockSize=Math.max.apply(null,I.map(Z=>Z.computedBlockSize)),n.finishContainer(this,C,e,U,k,this.clientLayout,this.faces);let Se=this.currentLayoutPosition.flowPositions[w];Se&&Se.breakAfter==="region"&&(Se.breakAfter=null)}S.finish(!0)}),x=S.result()}return x.then(()=>{if(l.isInvalidated()){u.finish(!0);return}if(!n.isAutoHeight||Math.floor(C.computedBlockSize)>0){if(!N&&!h){let w=n.getProp(this,"shape-outside"),k=C.getOuterShape(w,this);a.push(k)}}else if(n.children.length==0){s.removeChild(g),u.finish(!0);return}let S=E?0:n.children.length-1;u.loop(()=>{for(;S>=0&&S<n.children.length;){let w=n.children[E?S++:S--],k=this.layoutContainer(e,w,g,o,i,a,l);if(k.isPending())return k.thenAsync(()=>v(!l.isInvalidated()));if(l.isInvalidated())break}return v(!1)}).then(()=>{u.finish(!0)})}),u.result()}processLinger(){let e=this.currentLayoutPosition.page;for(let n in this.currentLayoutPosition.flowPositions){let s=this.currentLayoutPosition.flowPositions[n];for(let o=s.positions.length-1;o>=0;o--){let i=s.positions[o];i.flowChunk.startPage>=0&&i.flowChunk.startPage+i.flowChunk.linger-1<=e&&s.positions.splice(o,1)}}}initLingering(){let e=this.currentLayoutPosition.page;for(let n in this.currentLayoutPosition.flowPositions){let s=this.currentLayoutPosition.flowPositions[n];for(let o=s.positions.length-1;o>=0;o--){let i=s.positions[o];i.flowChunk.startPage<0&&i.flowChunk.startOffset<this.lookupOffset&&(i.flowChunk.startPage=e)}}}noMorePrimaryFlows(e){for(let n in this.primaryFlows){let s=e.flowPositions[n];if(s&&s.positions.length>0)return!1}return!0}layoutNextPage(e,n){var g;let s=e.container===e.bleedBox;this.pageBreaks={},n?(this.currentLayoutPosition=n.clone(),this.styler.replayFlowElementsFromOffset(n.highestSeenOffset)):(this.currentLayoutPosition=new Wr,this.styler.replayFlowElementsFromOffset(-1)),this.lang&&e.bleedBox.setAttribute("lang",this.lang),n=this.currentLayoutPosition;let o=1e4;if(n.page>o)throw new Error(`Too many pages generated (over ${o} pages)`);let i=n.startSideOfFlow("body");n.isBlankPage=Fn(i)&&this.matchPageSide(i),e.isBlankPage=n.isBlankPage,n.page++,e.pageType==null&&(e.pageType=(g=e.isBlankPage?this.styler.cascade.previousPageType:this.styler.cascade.currentPageType)!=null?g:"",this.styler.cascade.previousPageType=this.styler.cascade.currentPageType),this.clearScope(this.style.pageScope),this.layoutPositionAtPageStart=n.clone();let a=s?{}:this.pageManager.getCascadedPageStyle(e.pageType);if(this.styler.cascade.applyVarFilter([a],this.styler,null),this.styler.cascade.applyCalcFilter(a,this.styler.context),!s){let m=new J(this.style.pageScope,"left-page");e.side=m.evaluate(this)?"left":"right",e.container.setAttribute("data-vivliostyle-page-side",e.side)}let l=this.selectPageMaster(a);if(!l)return v(null);let c=0;if(!s){e.setAutoPageWidth(l.pageBox.specified.width.value===An),e.setAutoPageHeight(l.pageBox.specified.height.value===Ln),this.counterStore.setCurrentPage(e),this.counterStore.updatePageCounters(a,this);let m=np(Mi(a),this);this.setPageSizeAndBleed(m,e),Kf(a,m,e,this),c=m.bleedOffset+m.bleed}let u=!s&&l.getProp(this,"writing-mode")||b.horizontal_tb;this.pageVertical=u!=b.horizontal_tb;let p=l.getProp(this,"direction")||b.ltr,h=new pn(this.rootPageFloatLayoutContext,de.PAGE,null,null,null,u,p),f=A("layoutNextPage");return f.loopWithFrame(m=>{this.layoutContainer(e,l,e.bleedBox,c,c,[],h).then(()=>{h.isInvalidated()||h.finish(),h.isInvalidated()?(this.currentLayoutPosition=this.layoutPositionAtPageStart.clone(),h.validate(),m.continueLoop()):m.breakLoop()})}).then(()=>{l.adjustPageLayout(this,e,this.clientLayout),s||(this.processLinger(),n=this.currentLayoutPosition,Object.keys(n.flowPositions).forEach(E=>{let y=n.flowPositions[E],C=y.breakAfter;C&&(C==="page"||!this.matchPageSide(C))&&(y.breakAfter=null)})),this.currentLayoutPosition=this.layoutPositionAtPageStart=null,n.highestSeenOffset=this.styler.getReachedOffset();let m=this.style.store.getTriggersForDoc(this.xmldoc);e.finish(m,this.clientLayout),this.noMorePrimaryFlows(n)&&(n=null),f.finish(n)}),f.result()}setPageSizeAndBleed(e,n){this.actualPageWidth=e.pageWidth,this.actualPageHeight=e.pageHeight,this.pageSheetWidth=e.pageWidth+e.cropOffset*2,this.pageSheetHeight=e.pageHeight+e.cropOffset*2,n.container.style.width=`${this.pageSheetWidth}px`,n.container.style.height=`${this.pageSheetHeight}px`,n.bleedBox.style.left=`${e.bleedOffset}px`,n.bleedBox.style.width=`${e.pageWidth}px`,n.bleedBox.style.top=`${e.bleedOffset}px`,n.bleedBox.style.height=`${e.pageHeight}px`,n.bleedBox.style.padding=`${e.bleed}px`}},dp=class r extends xn{constructor(e,n,s,o){super(e.rootScope,e,n,s,o,e.validatorSet,!s);this.masterHandler=e;d(this,"insideRegion",!1)}startPageTemplateRule(){}startPageMasterRule(e,n,s){let o=new Po(this.masterHandler.pageScope,e,n,s,this.masterHandler.rootBox,this.condition,this.owner.getBaseSpecificity());this.masterHandler.pushHandler(new Da(o.scope,this.masterHandler,o,this.validatorSet))}startWhenRule(e){let n=e.expr;this.condition!=null&&(n=et(this.scope,this.condition,n)),this.masterHandler.pushHandler(new r(this.masterHandler,n,this,this.regionId))}startDefineRule(){this.masterHandler.pushHandler(new aa(this.scope,this.owner))}startFontFaceRule(){let e={};this.masterHandler.fontFaces.push({properties:e,condition:this.condition}),this.masterHandler.pushHandler(new ks(this.scope,this.owner,null,e,this.masterHandler.validatorSet,"font-face"))}startFlowRule(e){let n=this.masterHandler.flowProps[e];n||(n={},this.masterHandler.flowProps[e]=n),this.masterHandler.pushHandler(new ks(this.scope,this.owner,null,n,this.masterHandler.validatorSet))}startViewportRule(){let e={};this.masterHandler.viewportProps.push(e),this.masterHandler.pushHandler(new ks(this.scope,this.owner,this.condition,e,this.masterHandler.validatorSet))}startFootnoteRule(e){let n=this.masterHandler.footnoteProps;if(e){let s=Eo(n,"_pseudos");n=s[e],n||(n={},s[e]=n)}this.masterHandler.pushHandler(new ks(this.scope,this.owner,null,n,this.masterHandler.validatorSet))}startRegionRule(){this.insideRegion=!0,this.startSelectorRule()}startPageRule(){let e=new Ua(this.masterHandler.pageScope,this.masterHandler,this,this.validatorSet,this.masterHandler.pageProps);this.masterHandler.pushHandler(e),e.startPageRule()}startRuleBody(){if(xn.prototype.startRuleBody.call(this),this.insideRegion){this.insideRegion=!1;let e=`R${this.masterHandler.regionCount++}`;this.special("region-id",L(e)),this.endRule();let n=new r(this.masterHandler,this.condition,this,e);this.masterHandler.pushHandler(n),n.startRuleBody()}}},Ka=class extends kr{constructor(e){super();this.validatorSet=e;d(this,"rootScope");d(this,"pageScope");d(this,"rootBox");d(this,"cascadeParserHandler");d(this,"regionCount",0);d(this,"fontFaces",[]);d(this,"footnoteProps",{});d(this,"flowProps",{});d(this,"viewportProps",[]);d(this,"pageProps",{});this.rootScope=new is(null),this.pageScope=new is(this.rootScope),this.rootBox=new Ia(this.rootScope),this.cascadeParserHandler=new dp(this,null,null,null),this.slave=this.cascadeParserHandler}};function ob(r,t){return t.parseOPSResource(r)}var qa=class extends ps{constructor(e){super(ob,"document");this.fontDeobfuscator=e;d(this,"styleByKey",{});d(this,"styleFetcherByKey",{});d(this,"styleByDocURL",{});d(this,"triggersByDocURL",{});d(this,"validatorSet",null);d(this,"styleSheets",[]);d(this,"triggerSingleDocumentPreprocessing",!1)}init(e,n){this.setStyleSheets(e,n);let s=A("OPSDocStore.init");return this.validatorSet=Id(),sb().then(()=>{this.triggerSingleDocumentPreprocessing=!0,s.finish(!0)}),s.result()}getStyleForDoc(e){return this.styleByDocURL[e.url]}getTriggersForDoc(e){return this.triggersByDocURL[e.url]}setStyleSheets(e,n){this.clearStyleSheets(),e&&e.forEach(this.addAuthorStyleSheet,this),n&&n.forEach(this.addUserStyleSheet,this)}clearStyleSheets(){this.styleSheets.splice(0)}addAuthorStyleSheet(e){let n=e.url;n&&(n=Q(Tn(n),rn)),this.styleSheets.push({url:n,text:e.text,flavor:"Author",classes:null,media:null})}addUserStyleSheet(e){let n=e.url;n&&(n=Q(Tn(n),rn)),this.styleSheets.push({url:n,text:e.text,flavor:"User",classes:null,media:null})}parseOPSResource(e){let n=A("OPSDocStore.load"),s=e.url,o=s.endsWith("?viv-toc-box");return lp(e,this).then(i=>{var f;if(!i){n.finish(null);return}if(this.triggerSingleDocumentPreprocessing){let g=We("PREPROCESS_SINGLE_DOCUMENT");for(let m=0;m<g.length;m++)try{g[m](i.document)}catch(E){V.warn("Error during single document preprocessing:",E)}}let a=[],l=i.document.getElementsByTagNameNS("http://www.idpf.org/2007/ops","trigger");for(let g=0;g<l.length;g++){let m=l[g],E=m.getAttributeNS("http://www.w3.org/2001/xml-events","observer"),y=m.getAttributeNS("http://www.w3.org/2001/xml-events","event"),C=m.getAttribute("action"),x=m.getAttribute("ref");E&&y&&C&&x&&a.push({observer:E,event:y,action:C,ref:x})}this.triggersByDocURL[s]=a;let c=[];if(c.push({url:Q("user-agent-page.css",$t),text:uc,flavor:"UA",classes:null,media:null}),o)c.push({url:Q("user-agent-toc.css",$t),text:pc,flavor:"UA",classes:null,media:null});else{let g=i.document.querySelectorAll("style, link, meta");for(let m of g){let E=m.namespaceURI,y=m.localName;if(E=="http://www.w3.org/1999/xhtml")if(y=="style"){let C=m.getAttribute("class"),x=m.getAttribute("media"),N=m.getAttribute("title");c.push({url:s,text:m.textContent,flavor:"Author",classes:N?C:null,media:x})}else if(y=="link"){let C=m.getAttribute("href"),x=(f=m.getAttribute("rel"))==null?void 0:f.split(/\s+/),N=m.getAttribute("class"),S=m.getAttribute("media");if(C&&(x!=null&&x.includes("stylesheet"))&&(!x.includes("alternate")||N)){let w=Q(C,s),k=m.getAttribute("title");c.push({url:w,text:null,classes:k?N:null,media:S,flavor:"Author"})}}else y=="meta"&&m.getAttribute("name")=="viewport"&&c.push({url:s,text:this.processViewportMeta(m),flavor:"Author",classes:null,media:null})}for(let m=0;m<this.styleSheets.length;m++)c.push(this.styleSheets[m])}let u="";for(let g=0;g<c.length;g++)u+=c[g].url,u+="^",c[g].text&&(u+=c[g].text),u+="^";let p=this.styleByKey[u];if(p){this.styleByDocURL[s]=p,n.finish(i);return}let h=this.styleFetcherByKey[u];h||(h=new Zt(()=>{let g=A("fetchStylesheet"),m=0,E=new Ka(this.validatorSet);return g.loop(()=>{if(m<c.length){let y=c[m++];return E.startStylesheet(y.flavor),y.text!==null?Vr(y.text,E,y.url,y.classes,y.media).thenReturn(!0):mc(y.url,E,y.classes,y.media)}return v(!1)}).then(()=>{let y=E.cascadeParserHandler.finish();p=new up(this,E.rootScope,E.pageScope,y,E.rootBox,E.fontFaces,E.footnoteProps,E.flowProps,E.viewportProps,E.pageProps),this.styleByKey[u]=p,delete this.styleFetcherByKey[u],g.finish(p)}),g.result()},`FetchStylesheet ${s}`),this.styleFetcherByKey[u]=h,h.start()),h.get().then(g=>{this.styleByDocURL[s]=g,n.finish(i)})}),n.result()}processViewportMeta(e){return""}};var Hi="\u25B8",ig="\u25BE",ib="\u25B9";function Qa(r){let t=Array.from(r.querySelectorAll("nav[*|type],nav[epub\\:type]"));if(t.length>0||(t=Array.from(r.querySelectorAll("[role=doc-toc]")),t.length>0))return t;let e="nav,.toc,#toc,#table-of-contents,#contents,[role=directory]";for(let n of r.querySelectorAll(e)){if(t.find(o=>o.contains(n)))continue;let s=n;/^h[1-6]$/.test(s.localName)&&(s.previousElementSibling?s=s.nextElementSibling:s=s.parentElement),s&&s.querySelector("li a[href]")&&t.push(s)}return t}function rg(r){let t=Qa(r),e=[];for(let n of t)for(let s of n.querySelectorAll("li a[href]"))e.push(s);return e}var Za=class{constructor(t,e,n,s,o,i,a,l,c,u){this.store=t;this.url=e;this.lang=n;this.clientLayout=s;this.fontMapper=o;this.rendererFactory=a;this.fallbackMap=l;this.documentURLTransformer=c;this.counterStore=u;d(this,"pref");d(this,"page",null);d(this,"instance",null);this.pref=gr(i),this.pref.spreadView=!1}setAutoHeight(t,e){if(e--!=0){for(let n=t.firstChild;n;n=n.nextSibling)if(n.nodeType==1){let s=n;It(s,"height","auto")!="auto"&&(T(s,"height","auto"),this.setAutoHeight(s,e)),It(s,"position","static")=="absolute"&&(T(s,"position","relative"),this.setAutoHeight(s,e))}}}makeCustomRenderer(t){let e=this.rendererFactory.makeCustomRenderer(t);return(n,s,o)=>{let i=o.behavior;if(i)switch(i.toString()){case"toc-node-anchor":o.color=b.inherit,o["text-decoration"]=b.none;break;case"toc-node":o.display=b.block,o.margin=te,o.padding=te,o["padding-inline-start"]=new P(1.25,"em");break;case"toc-node-first-child":o.display=b.inline_block,o.margin=new P(.2,"em"),o["vertical-align"]=b.top,o.color=b.inherit,o["text-decoration"]=b.none;break;case"toc-container":o.padding=te;break}if(!i||i.toString()!="toc-node"&&i.toString()!="toc-container")return e(n,s,o);let a=n.firstChild;a&&a.nodeType!==1&&ue(a)&&n.replaceChild(n.ownerDocument.createComment(a.textContent),a);let l=s.getAttribute("data-adapt-class");if(l=="toc-node"){let u=s.firstChild;u.textContent!=Hi&&(u.textContent=Hi,T(u,"cursor","pointer"),u.addEventListener("click",rb,!1),u.setAttribute("role","button"),u.setAttribute("aria-expanded","false"),s.setAttribute("aria-expanded","false"),s.style.height!=="0px"&&(u.tabIndex=0))}let c=s.ownerDocument.createElement("div");if(c.setAttribute("data-adapt-process-children","true"),i.toString()=="toc-node"){let u=s.ownerDocument.createElement("div");if(u.textContent=ib,T(u,"margin","0.2em 0 0 -1em"),T(u,"margin-inline-start","-1em"),T(u,"margin-inline-end","0"),T(u,"display","inline-block"),T(u,"width","1em"),T(u,"text-align","center"),T(u,"vertical-align","top"),T(u,"cursor","default"),T(u,"font-family","Menlo,sans-serif"),c.appendChild(u),T(c,"overflow","hidden"),c.setAttribute("data-adapt-class","toc-node"),c.setAttribute("role","treeitem"),l=="toc-node"||l=="toc-container"){T(c,"height","0px");let p=n.firstElementChild;p&&p.localName==="a"&&(p.tabIndex=-1)}else s.setAttribute("role","tree")}else l=="toc-node"&&(c.setAttribute("data-adapt-class","toc-container"),c.setAttribute("role","group"),c.setAttribute("aria-hidden","true"));return v(c)}}showTOC(t,e,n,s,o){if(this.page)return v(this.page);let i=A("showTOC"),a=new co(t,t);this.page=a;let l=Tt(this.url)+"?viv-toc-box";return this.store.load(l).then(c=>{for(let g of Qa(c.document))g.setAttribute("data-vivliostyle-role","doc-toc");let u=this.store.getStyleForDoc(c),p=u.sizeViewport(n,1e5,o);e=new Nn(e.window,p.fontSize,0,e.root,p.width,p.height);let h=this.makeCustomRenderer(c),f=new Qn(u,c,this.lang,e,this.clientLayout,this.fontMapper,h,this.fallbackMap,0,this.documentURLTransformer,this.counterStore);this.instance=f,f.pref=this.pref,f.init().then(()=>{f.layoutNextPage(a,null).then(()=>{this.setAutoHeight(t,2),i.finish(a)})})}),i.result()}hideTOC(){this.page&&(this.page.container.style.visibility="hidden",this.page.container.setAttribute("aria-hidden","true"))}isTOCVisible(){return!!this.page&&this.page.container.style.visibility==="visible"}getTOC(){if(!this.page)return[];function t(s){if(!s)return[];let o=s.querySelectorAll(":scope > [role=treeitem] > a[href]");return Array.from(o).map(e)}function e(s){let o=new URL(s.href),[,i]=o.hash.match(/^#?(.*)$/),a=s.innerText,l=s.parentElement.querySelector("[role=group]"),c=t(l);return{id:i,title:a,children:c}}let n=this.page.container.querySelector("[role=tree]");return t(n)}};function rb(r){let t=r.target,e=t.textContent==Hi;t.textContent=e?ig:Hi;let n=t.parentNode;t.setAttribute("aria-expanded",e?"true":"false"),n.setAttribute("aria-expanded",e?"true":"false");let s=n.firstChild;for(;s;){if(s.nodeType===1){let o=s,i=o.getAttribute("data-adapt-class");if(i==="toc-container"){if(o.setAttribute("aria-hidden",e?"false":"true"),o.firstChild){s=o.firstChild;continue}}else if(i==="toc-node"&&(o.style.height=e?"auto":"0px",o.children.length>=2&&(o.children[1].tabIndex=e?0:-1),o.children.length>=3&&(o.children[0].tabIndex=e?0:-1,!e))){let a=o.children[0];if(a.textContent==ig){a.textContent=Hi,a.setAttribute("aria-expanded","false"),o.setAttribute("aria-expanded","false"),s=o.children[2];continue}}}for(;!s.nextSibling&&s.parentNode!==n;)s=s.parentNode;s=s.nextSibling}r.stopPropagation()}var Gi=class extends qa{constructor(){super(null);d(this,"plainXMLStore");d(this,"jsonStore");d(this,"opfByURL",{});d(this,"primaryOPFByEPubURL",{});d(this,"deobfuscators",{});d(this,"documents",{});this.fontDeobfuscator=this.makeDeobfuscatorFactory(),this.plainXMLStore=ng(),this.jsonStore=sh()}makeDeobfuscatorFactory(){return e=>this.deobfuscators[e]}loadAsPlainXML(e,n,s){return this.plainXMLStore.load(e,n,s)}startLoadingAsPlainXML(e){this.plainXMLStore.fetch(e)}loadAsJSON(e,n,s){return this.jsonStore.load(e,n,s)}loadPubDoc(e){let n=A("loadPubDoc");return hs(e,null,"HEAD").then(s=>{if(s.status>=400)this.loadEPUBDoc(e).then(o=>{if(o){n.finish(o);return}V.error(`Failed to fetch a source document from ${e} (${s.status}${s.statusText?" "+s.statusText:""})`),n.finish(null)});else if(!s.status&&!s.responseXML&&!s.responseText&&!s.responseBlob&&!s.contentType&&/\/[^/.]+(?:[#?]|$)/.test(e)&&(e=e.replace(/([#?]|$)/,"/$1")),s.contentType=="application/oebps-package+xml"||/\.opf(?:[#?]|$)/.test(e)){let[,o,i]=e.match(/^((?:.*\/)?)([^/]*)$/);this.loadOPF(o,i).thenFinish(n)}else s.contentType=="application/ld+json"||s.contentType=="application/webpub+json"||s.contentType=="application/audiobook+json"||s.contentType=="application/json"||/\.json(?:ld)?(?:[#?]|$)/.test(e)?this.loadAsJSON(e,!0).then(o=>{if(!o){this.reportLoadError(e),n.finish(null);return}let i=new Ms(this,e);i.initWithWebPubManifest(o,void 0,e).then(()=>{n.finish(i)})}):this.loadWebPub(e).then(o=>{if(o){n.finish(o);return}this.loadEPUBDoc(e).then(i=>{if(i){n.finish(i);return}V.error(`Failed to load ${e}.`),n.finish(null)})})}),n.result()}loadEPUBDoc(e){let n=A("loadEPUBDoc");e.endsWith("/")||(e=e+"/"),this.startLoadingAsPlainXML(e+"META-INF/encryption.xml");let s=e+"META-INF/container.xml";return this.loadAsPlainXML(s).then(o=>{if(o){let i=o.doc().child("container").child("rootfiles").child("rootfile").attribute("full-path");for(let a of i)if(a){this.loadOPF(e,a).thenFinish(n);return}}n.finish(null)}),n.result()}loadOPF(e,n){let s=e+n,o=this.opfByURL[s];if(o)return v(o);let i=A("loadOPF");return this.loadAsPlainXML(s,!0,`Failed to fetch EPUB OPF ${s}`).then(a=>{a?(o=new Ms(this,e),this.opfByURL[s]=o,this.primaryOPFByEPubURL[e]=o,this.plainXMLStore.resources[e+"META-INF/container.xml"]?this.loadAsPlainXML(e+"META-INF/encryption.xml").then(l=>{o.initWithXMLDoc(a,l).then(()=>{i.finish(o)})}):o.initWithXMLDoc(a,null).then(()=>{i.finish(o)})):this.reportLoadError(s)}),i.result()}loadWebPub(e){let n=A("loadWebPub");return this.load(e).then(s=>{if(!s)this.reportLoadError(e);else if(s.document.querySelector("a[href='META-INF/'],a[href$='/META-INF/']"))n.finish(null);else{let o=s.document,i=new Ms(this,e),a=o.querySelector("link[rel='publication'],link[rel='manifest'][type='application/webpub+json']");if(a){let l=a.getAttribute("href");if(/^#/.test(l)){let c=Hs(o.getElementById(l.substr(1)).textContent);i.initWithWebPubManifest(c,o).then(()=>{n.finish(i)})}else{let c=Q(a.getAttribute("href"),e);this.loadAsJSON(c,!0,`Failed to fetch Publication Manifest ${c}`).then(u=>{i.initWithWebPubManifest(u,o,c).then(()=>{n.finish(i)})})}}else i.initWithWebPubManifest({},o).then(()=>{i.toc&&i.toc.src===s.url&&Qa(o).length===0&&(i.toc=null),n.finish(i)})}}),n.result()}addDocument(e,n){let s=A("EPUBDocStore.load"),o=Tt(e);return(this.documents[o]=this.parseOPSResource({status:200,statusText:"",url:o,contentType:n.contentType,responseText:null,responseXML:n,responseBlob:null})).thenFinish(s),s.result()}reportLoadError(e){let n=o=>o.replace(/([^:/?#]|^)[/?#].*/,"$1"),s=()=>{let o=n(e);return!(o===n(rn)||Object.keys(this.resources).find(a=>this.resources[a]&&n(a)===o)||!/^https?:?\/\/[^/]/.test(e)||/\.(xhtml|xht|xml|opf)$/i.test(e))};e.startsWith("data:")?V.error(`Failed to load ${e}. Invalid data.`):e.startsWith("http:")&&rn.startsWith("https:")?V.error(`Failed to load ${e}. Mixed Content ("http:" content on "https:" context) is not allowed.`):s()?V.error(`Failed to load ${e}. This may be caused by the server not allowing cross-origin resource sharing (CORS).`):V.error(`Failed to load ${e}. The target resource is invalid.`)}load(e){let n=Tt(e),s=this.documents[n];if(s)return s.isPending()?s:v(s.get());{let o=A("EPUBDocStore.load");return s=super.load(n,!0,`Failed to fetch a source document from ${n}`),s.then(i=>{i?o.finish(i):this.reportLoadError(n)}),o.result()}}processViewportMeta(e){let n=e.getAttribute("content");if(!n)return"";let s={},o;for(;(o=n.match(/^,?\s*([-A-Za-z_.][-A-Za-z_0-9.]*)\s*=\s*([-+A-Za-z_0-9.]*)\s*/))!=null;)n=n.substr(o[0].length),s[o[1]]=o[2];let i=s.width-0,a=s.height-0;if(i&&a){let l=!!Object.values(this.primaryOPFByEPubURL).find(c=>c.prePaginated);return`@-epubx-viewport{width:${i}px;height:${a}px;}`+(l?`@page{size:${i}px ${a}px;margin:0;}`:"@page{margin:0;}")}return""}},el=class{constructor(){d(this,"id",null);d(this,"src","");d(this,"mediaType",null);d(this,"title",null);d(this,"itemRefElement",null);d(this,"spineIndex",-1);d(this,"compressedSize",0);d(this,"compressed",null);d(this,"epage",0);d(this,"epageCount",0);d(this,"startPage",null);d(this,"skipPagesBefore",null);d(this,"itemProperties");this.itemProperties=Tp}initWithElement(t,e){this.id=t.getAttribute("id"),this.src=Q(t.getAttribute("href"),e),this.mediaType=t.getAttribute("media-type");let n=t.getAttribute("properties");n&&(this.itemProperties=kp(n.split(/\s+/)))}initWithParam(t){this.spineIndex=t.index,this.id=`item${t.index+1}`,this.src=t.url,this.startPage=t.startPage,this.skipPagesBefore=t.skipPagesBefore}};function lb(r){return r.id}function cb(r){return t=>{let e=A("deobfuscator");return ub("SHA-1",r).then(n=>{let s=t.slice(0,1040),o=t.slice(1040,t.size);th(s).then(i=>{let a=new DataView(i);for(let l=0;l<a.byteLength;l++){let c=a.getUint8(l);c^=n[l%20],a.setUint8(l,c)}e.finish(fc([a,o]))})}),e.result()}}function ub(r,t){let e=A("makeDigest"),n=e.suspend();return window.crypto.subtle.digest(r,new TextEncoder().encode(t)).then(s=>{n.schedule(new Uint8Array(s))}),e.result()}var Jn={dcterms:"http://purl.org/dc/terms/",marc:"http://id.loc.gov/vocabulary/",media:"http://www.idpf.org/epub/vocab/overlays/#",rendition:"http://www.idpf.org/vocab/rendition/#",onix:"http://www.editeur.org/ONIX/book/codelists/current.html#",xsd:"http://www.w3.org/2001/XMLSchema#",opf:"http://www.idpf.org/2007/opf"},zi="http://idpf.org/epub/vocab/package/meta/#",Te={language:`${Jn.dcterms}language`,title:`${Jn.dcterms}title`,creator:`${Jn.dcterms}creator`,layout:`${Jn.rendition}layout`,titleType:`${zi}title-type`,displaySeq:`${zi}display-seq`,alternateScript:`${zi}alternate-script`,role:`${zi}role`};function db(r,t){let e={};return(n,s)=>{var p,h,f,g,m,E;let o,i,a=n.r||e,l=s.r||e;if(r==Te.title&&(o=((p=a[Te.titleType])==null?void 0:p[0].v)=="main",i=((h=l[Te.titleType])==null?void 0:h[0].v)=="main",o!=i))return o?-1:1;let c=parseInt((f=a[Te.displaySeq])==null?void 0:f[0].v,10);isNaN(c)&&(c=Number.MAX_VALUE);let u=parseInt((g=l[Te.displaySeq])==null?void 0:g[0].v,10);return isNaN(u)&&(u=Number.MAX_VALUE),c!=u?c-u:r!=Te.language&&t&&(o=((m=a[Te.language]||a[Te.alternateScript])==null?void 0:m[0].v)==t,i=((E=l[Te.language]||l[Te.alternateScript])==null?void 0:E[0].v)==t,o!=i)?o?-1:1:n.o-s.o}}function pb(r,t){let e;if(!t)e=Jn;else{e={};for(let h in Jn)e[h]=Jn[h];let p;for(;(p=t.match(/^\s*([A-Z_a-z\u007F-\uFFFF][-.A-Z_a-z0-9\u007F-\uFFFF]*):\s*(\S+)/))!=null;)t=t.substr(p[0].length),e[p[1]]=p[2]}let n=p=>{if(p){let h=p.match(/^\s*(([^:]*):)?(\S+)\s*$/);if(h){let f=h[2]?e[h[2]]:zi;if(f)return f+h[3]}}return null},s=1,o=r.childElements().forEachNonNull(p=>{if(p.localName=="meta"){let h=n(p.getAttribute("property"));if(h)return{name:h,value:p.textContent,id:p.getAttribute("id"),order:s++,refines:p.getAttribute("refines"),lang:null,scheme:n(p.getAttribute("scheme")),role:null}}else if(p.namespaceURI=="http://purl.org/dc/elements/1.1/")return{name:Jn.dcterms+p.localName,order:s++,lang:p.getAttribute("xml:lang"),value:p.textContent,id:p.getAttribute("id"),refines:null,scheme:null,role:p.getAttribute("role")||p.getAttribute("opf:role")};return null}),i=Qi(o,p=>p.refines),a=p=>Ap(p,(h,f)=>h.map(g=>{let m={v:g.value,o:g.order};g.scheme&&(m.s=g.scheme);let E=i[`#${g.id}`]||[];if(E.length||g.lang||g.role){g.lang&&E.push({name:Te.language,value:g.lang,lang:null,id:null,refines:g.id,scheme:null,order:g.order,role:null}),g.role&&E.push({name:Te.role,value:g.role,lang:null,id:null,refines:g.id,scheme:null,order:g.order,role:null});let y=Qi(E,C=>C.name);m.r=a(y)}return m})),l=a(Qi(o,p=>p.refines?null:p.name)),c=null;l[Te.language]&&(c=l[Te.language][0].v);let u=p=>{for(let h in p){let f=p[h];f.sort(db(h,c));for(let g=0;g<f.length;g++){let m=f[g].r;m&&u(m)}}};return u(l),l}function hb(){let r=window.MathJax;return r?r.Hub:null}var ag={"application/xhtml+xml":!0,"image/jpeg":!0,"image/png":!0,"image/svg+xml":!0,"image/gif":!0,"audio/mp3":!0},pp="viv-id-",Ms=class{constructor(t,e){this.store=t;this.pubURL=e;d(this,"opfXML",null);d(this,"encXML",null);d(this,"items",null);d(this,"spine",null);d(this,"itemMap",null);d(this,"itemMapByPath",null);d(this,"uid",null);d(this,"bindings",{});d(this,"lang",null);d(this,"epageCount",0);d(this,"prePaginated",!1);d(this,"epageIsRenderedPage",!0);d(this,"epageCountCallback",null);d(this,"metadata",{});d(this,"toc",null);d(this,"cover",null);d(this,"fallbackMap",{});d(this,"pageProgression",null);d(this,"documentURLTransformer");this.documentURLTransformer=this.createDocumentURLTransformer()}createDocumentURLTransformer(){let t=this;class e{transformFragment(s,o){let i=o+(s?`#${s}`:"");return pp+Nl(i,":")}transformURL(s,o){let i=s.match(/^([^#]*)#?(.*)$/);if(i){let a=i[1]||o.replace(/\?viv-toc-box$/,""),l=decodeURIComponent(i[2]);if(a&&t.spine.some(c=>c.src===a))return`#${this.transformFragment(l,a)}`}return s}restoreURL(s){s.charAt(0)==="#"&&(s=s.substring(1)),s.indexOf(pp)===0&&(s=s.substring(pp.length));let i=Pp(s,":").match(/^([^#]*)#?(.*)$/);return i?[i[1],i[2]]:[]}}return new e}getMetadata(){return this.metadata}getPathFromURL(t){if(t.startsWith("data:"))return t===this.pubURL?"":t;if(this.pubURL){let e=Q("",this.pubURL);return t===e||t+"/"===e?"":(e.charAt(e.length-1)!="/"&&(e+="/"),t.substr(0,e.length)==e?decodeURIComponent(t.substr(e.length)):null)}else return t}initWithXMLDoc(t,e){this.opfXML=t,this.encXML=e;let n=t.doc().child("package"),s=n.attribute("unique-identifier")[0];if(s){let c=t.getElement(`${t.url}#${s}`);c&&(this.uid=c.textContent.replace(/[ \n\r\t]/g,""))}let o={};this.items=n.child("manifest").child("item").asArray().map(c=>{let u=new el,p=c;u.initWithElement(p,t.url);let h=p.getAttribute("fallback");return h&&!ag[u.mediaType]&&(o[u.src]=h),!this.toc&&u.itemProperties.nav&&(this.toc=u),!this.cover&&u.itemProperties["cover-image"]&&(this.cover=u),u}),this.itemMap=vl(this.items,lb),this.itemMapByPath=vl(this.items,c=>this.getPathFromURL(c.src));for(let c in o){let u=c;for(;;){let p=this.itemMap[o[u]];if(!p)break;if(ag[p.mediaType]){this.fallbackMap[c]=p.src;break}u=p.src}}this.spine=n.child("spine").child("itemref").asArray().map((c,u)=>{let p=c,h=p.getAttribute("idref"),f=this.itemMap[h];return f&&(f.itemRefElement=p,f.spineIndex=u),f});let i=n.child("spine").attribute("page-progression-direction")[0];i&&(this.pageProgression=dl(i));let a=e?e.doc().child("encryption").child("EncryptedData").predicate(cp.withChild("EncryptionMethod",cp.withAttribute("Algorithm","http://www.idpf.org/2008/embedding"))).child("CipherData").child("CipherReference").attribute("URI"):[],l=n.child("bindings").child("mediaType").asArray();for(let c=0;c<l.length;c++){let u=l[c].getAttribute("handler"),p=l[c].getAttribute("media-type");p&&u&&this.itemMap[u]&&(this.bindings[p]=this.itemMap[u].src)}if(this.metadata=pb(n.child("metadata"),n.attribute("prefix")[0]),this.metadata[Te.language]&&(this.lang=this.metadata[Te.language][0].v),this.metadata[Te.layout]&&(this.prePaginated=this.metadata[Te.layout][0].v==="pre-paginated"),a.length>0&&this.uid){let c=cb(this.uid);for(let u=0;u<a.length;u++)this.store.deobfuscators[this.pubURL+a[u]]=c}return this.prePaginated&&this.assignAutoPages(),v(!0)}assignAutoPages(){let t=0;for(let e of this.spine){let n=this.prePaginated?1:Math.ceil(e.compressedSize/1024);e.epage=t,e.epageCount=n,t+=n}this.epageCount=t,this.epageCountCallback&&this.epageCountCallback(this.epageCount)}setEPageCountMode(t){this.epageIsRenderedPage=t||this.prePaginated}countEPages(t){if(this.epageCountCallback=t,this.epageIsRenderedPage)return this.prePaginated&&this.epageCount==0&&this.assignAutoPages(),v(!0);let e=0,n=0,s=A("countEPages");return s.loopWithFrame(o=>{if(n===this.spine.length){o.breakLoop();return}let i=this.spine[n++];i.epage=e,this.store.load(i.src).then(a=>{let l=1800,c=a.lang||this.lang;c&&c.match(/^(ja|ko|zh)/)&&(l/=3),i.epageCount=Math.ceil(a.getTotalOffset()/l),e+=i.epageCount,this.epageCount=e,this.epageCountCallback&&this.epageCountCallback(this.epageCount),o.continueLoop()})}).thenFinish(s),s.result()}initWithChapters(t,e){this.itemMap={},this.itemMapByPath={},this.items=[],this.spine=this.items;let n=this.opfXML=new Ui(null,"",new DOMParser().parseFromString("<spine></spine>","text/xml"));return t.forEach(s=>{let o=new el;o.initWithParam(s),o.id;let i=n.document.createElement("itemref");i.setAttribute("idref",o.id),n.root.appendChild(i),o.itemRefElement=i,this.itemMap[o.id]=o;let a=this.getPathFromURL(s.url);a==null&&(a=s.url),this.itemMapByPath[a]=o,this.items.push(o)}),e?this.store.addDocument(t[0].url,e):v(null)}initWithWebPubManifest(t,e,n){var h,f,g,m;t.readingProgression&&(this.pageProgression=t.readingProgression),this.metadata===void 0&&(this.metadata={});let s=t.name||((h=t.metadata)==null?void 0:h.title)||(e==null?void 0:e.title);s&&(this.metadata[Te.title]=(Array.isArray(s)?s:[s]).map(E=>{var y;return{v:(y=E.value)!=null?y:E}}));let o=t.author||t.creator||((f=t.metadata)==null?void 0:f.author)||Array.from((g=e==null?void 0:e.querySelectorAll("meta[name='author'], meta[name='DC.Creator']"))!=null?g:[]).map(E=>E.content);o&&o.length!==0&&(this.metadata[Te.creator]=(Array.isArray(o)?o:[o]).map(E=>{var y;return{v:(y=E.name)!=null?y:E}}));let i=t.inLanguage||((m=t.metadata)==null?void 0:m.language)||(e==null?void 0:e.documentElement.lang)||(e==null?void 0:e.documentElement.getAttribute("xml:lang"));i&&(this.metadata[Te.language]=(Array.isArray(i)?i:[i]).map(E=>({v:E})));let a=this.getPathFromURL(this.pubURL);if(!t.readingOrder&&e&&a!==null){t.readingOrder=[encodeURI(a)];for(let E of rg(e)){let y=E.getAttribute("href");if(/^(https?:)?\/\//.test(y)||/\.(jpe?g|png|gif|pdf|svg|mml)([#?]|$)/.test(y))continue;let C=Tt(Q(y,this.pubURL)),x=this.getPathFromURL(C),N=x!==null?encodeURI(x):C;t.readingOrder.indexOf(N)==-1&&t.readingOrder.push(N)}}let l=[],c=0,u=-1;[t.readingOrder,t.resources].forEach(E=>{E instanceof Array&&E.forEach(y=>{let C=E===t.readingOrder,x=typeof y=="string"?y:y.url||y.href,N=typeof y=="string"?"":y.encodingFormat||y.href&&y.type||"";if(C||N==="text/html"||N==="application/xhtml+xml"||!N&&y.rel!=="stylesheet"&&/(^|\/)([^/]+\.(x?html|htm|xht)|[^/.]*)([#?]|$)/.test(x)){let S=n?n.replace(/\/[^/]+$/,"/"):this.pubURL,w={url:Q(Tn(x),S),index:c++,startPage:null,skipPagesBefore:null};y.rel==="contents"&&u===-1&&(u=w.index),l.push(w)}})});let p=A("initWithWebPubManifest");return this.initWithChapters(l).then(()=>{var y,C;u!==-1&&(this.toc=this.items[u]),this.toc||(this.toc=n?(y=this.items)==null?void 0:y[0]:this.itemMapByPath[a]);let E=(C=t.readingOrder)==null?void 0:C.length;E&&E<this.items.length&&this.items.splice(E),p.finish(!0)}),p.result()}getCFI(t,e){let n=this.spine[t],s=A("getCFI");return this.store.load(n.src).then(o=>{let i=o.getNodeByOffset(e),a=null;if(i){let l=o.getNodeOffset(i,0,!1),c=e-l,u=new Do;u.prependPathFromNode(i,c,!1,null),n.itemRefElement&&u.prependPathFromNode(n.itemRefElement,0,!1,null),a=u.toString()}s.finish(a)}),s.result()}resolveFragment(t){return un("resolveFragment",e=>{if(!t){e.finish(null);return}let n=new Do;n.fromString(t);let s;if(this.opfXML){let o=n.navigate(this.opfXML.document);if(o.node.nodeType!=1||o.after||!o.ref){e.finish(null);return}let i=o.node,a=i.getAttribute("idref");if(i.localName!="itemref"||!a||!this.itemMap[a]){e.finish(null);return}s=this.itemMap[a],n=o.ref}else s=this.spine[0];this.store.load(s.src).then(o=>{let i=n.navigate(o.document),a=o.getNodeOffset(i.node,i.offset,i.after);e.finish({spineIndex:s.spineIndex,offsetInItem:a,pageIndex:-1})})},(e,n)=>{V.warn(n,"Cannot resolve fragment:",t),e.finish(null)})}resolveEPage(t){return un("resolveEPage",e=>{if(t<=0){e.finish({spineIndex:0,offsetInItem:0,pageIndex:-1});return}if(this.epageIsRenderedPage){let o=this.spine.findIndex(l=>l.epage==0&&l.epageCount==0||l.epage<=t&&l.epage+l.epageCount>t);o==-1&&(o=this.spine.length-1);let i=this.spine[o];(!i||i.epageCount==0)&&(i=this.spine[--o]);let a=Math.floor(t-i.epage);e.finish({spineIndex:o,offsetInItem:-1,pageIndex:a});return}let n=ft(this.spine.length,o=>{let i=this.spine[o];return i.epage+i.epageCount>t});n==this.spine.length&&n--;let s=this.spine[n];this.store.load(s.src).then(o=>{t-=s.epage,t>s.epageCount&&(t=s.epageCount);let i=0;if(t>0){let a=o.getTotalOffset();i=Math.round(a*t/s.epageCount),i==a&&i--}e.finish({spineIndex:n,offsetInItem:i,pageIndex:-1})})},(e,n)=>{V.warn(n,"Cannot resolve epage:",t),e.finish(null)})}getEPageFromPosition(t){let e=this.spine[t.spineIndex];if(this.epageIsRenderedPage){let s=e.epage+t.pageIndex;return v(s)}if(t.offsetInItem<=0)return v(e.epage);let n=A("getEPage");return this.store.load(e.src).then(s=>{let o=s.getTotalOffset(),i=Math.min(o,t.offsetInItem);n.finish(e.epage+i*e.epageCount/o)}),n.result()}},Ja=(r,t)=>({page:r,position:{spineIndex:r.spineIndex,pageIndex:t,offsetInItem:r.offset}}),tl=class{constructor(t,e,n,s,o){this.opf=t;this.viewport=e;this.fontMapper=n;this.pageSheetSizeReporter=o;d(this,"spineItems",[]);d(this,"spineItemLoadingContinuations",[]);d(this,"pref");d(this,"clientLayout");d(this,"counterStore");d(this,"tocAutohide",!1);d(this,"tocVisible",!1);d(this,"tocView");this.pref=gr(s),this.clientLayout=new $a(e),this.counterStore=new Tr(t.documentURLTransformer)}getPage(t){let e=this.spineItems[t.spineIndex];return e?e.pages[t.pageIndex]:null}getCurrentPageProgression(t){if(this.opf.pageProgression)return this.opf.pageProgression;{let e=this.spineItems[t?t.spineIndex:0];return e?e.instance.pageProgression:null}}finishPageContainer(t,e,n){e.container.style.display="none",e.container.style.visibility="visible",e.container.style.position="",e.container.style.top="",e.container.style.left="",e.container.setAttribute("data-vivliostyle-page-side",e.side);let s=t.pages[n];if(e.isFirstPage=t.item.spineIndex==0&&n==0,t.pages[n]=e,this.opf.epageIsRenderedPage){if(n==0&&t.item.spineIndex>0){let o=this.opf.spine[t.item.spineIndex-1];t.item.epage=o.epage+o.epageCount}t.item.epageCount=t.pages.length,this.opf.epageCount=this.opf.spine.reduce((o,i)=>o+i.epageCount,0),this.opf.epageCountCallback&&this.opf.epageCountCallback(this.opf.epageCount)}if(s)t.instance.viewport.contentContainer.replaceChild(e.container,s.container),s.dispatchEvent({type:"replaced",target:null,currentTarget:null,preventDefault:null,newPage:e});else{let o=null;if(n>0)o=t.pages[n-1].container.nextElementSibling;else for(let i=t.item.spineIndex+1;i<this.spineItems.length;i++){let a=this.spineItems[i];if(a&&a.pages[0]){o=a.pages[0].container;break}}t.instance.viewport.contentContainer.insertBefore(e.container,o)}this.pageSheetSizeReporter({width:t.instance.pageSheetWidth,height:t.instance.pageSheetHeight},t.instance.pageSheetSize,t.item.spineIndex,t.instance.pageNumberOffset+n)}renderSinglePage(t,e){let n=A("renderSinglePage"),s=t.pages[e?e.page:0],o=this.makePage(t,e);return s&&(o.pageType=s.pageType),t.instance.layoutNextPage(o,e).then(i=>{e=i;let a=e?e.page-1:t.layoutPositions.length-1;this.finishPageContainer(t,o,a),this.counterStore.finishPage(o.spineIndex,a);let l=null;if(e){let c=t.layoutPositions[e.page];t.layoutPositions[e.page]=e,c&&t.pages[e.page]&&(e.isSamePosition(c)||(l=this.renderSinglePage(t,e)))}l||(l=v(!0)),l.then(()=>{let c=this.counterStore.getUnresolvedRefsToPage(o),u=0;n.loopWithFrame(p=>{if(u++,u>c.length){p.breakLoop();return}let h=c[u-1];if(h.refs=h.refs.filter(f=>!f.isResolved()),h.refs.length===0){p.continueLoop();return}this.getPageViewItem(h.spineIndex).then(f=>{if(!f){p.continueLoop();return}let{currentPageType:g,previousPageType:m}=f.instance.styler.cascade,E=f.instance.scopes;f.instance.scopes={},this.counterStore.pushPageCounters(h.pageCounters),this.counterStore.pushReferencesToSolve(h.refs);let y=f.layoutPositions[h.pageIndex];this.renderSinglePage(f,y).then(C=>{f.instance.styler.cascade.currentPageType=g,f.instance.styler.cascade.previousPageType=m,f.instance.scopes=E,this.counterStore.popPageCounters(),this.counterStore.popReferencesToSolve();let x=C.pageAndPosition.position;x.spineIndex===o.spineIndex&&x.pageIndex===a&&(o=C.pageAndPosition.page),p.continueLoop()})})}).then(()=>{o.container.parentElement||(o=t.pages[a]),o.isLastPage=!e&&t.item.spineIndex===this.opf.spine.length-1,o.isLastPage&&(this.viewport,this.counterStore.finishLastPage(this.viewport)),o.container.setAttribute("data-vivliostyle-page-index",a),o.container.setAttribute("data-vivliostyle-spine-index",o.spineIndex),n.finish({pageAndPosition:Ja(o,a),nextLayoutPosition:e})})})}),n.result()}normalizeSeekPosition(t,e){let n=t.pageIndex,s=-1;if(n<0){s=t.offsetInItem;let o=ft(e.layoutPositions.length,i=>e.instance.getPosition(e.layoutPositions[i],!0)>s);o===e.layoutPositions.length?e.complete?n=e.layoutPositions.length-1:n=Number.POSITIVE_INFINITY:n=o-1}else n===Number.POSITIVE_INFINITY&&t.offsetInItem!==-1&&(s=t.offsetInItem);return{spineIndex:t.spineIndex,pageIndex:n,offsetInItem:s}}findPage(t,e){let n=A("findPage");return this.getPageViewItem(t.spineIndex).then(s=>{if(!s){n.finish(null);return}let o=null,i;n.loopWithFrame(a=>{let l=this.normalizeSeekPosition(t,s);i=l.pageIndex,o=s.pages[i],o?a.breakLoop():s.complete?(i=s.layoutPositions.length-1,o=s.pages[i],a.breakLoop()):e?this.renderPage(l).then(c=>{c&&(o=c.page,i=c.position.pageIndex),a.breakLoop()}):n.sleep(100).then(()=>{a.continueLoop()})}).then(()=>{n.finish(Ja(o,i))})}),n.result()}renderPage(t){let e=A("renderPage");return this.getPageViewItem(t.spineIndex).then(n=>{if(!n){e.finish(null);return}let s=this.normalizeSeekPosition(t,n),o=s.pageIndex,i=s.offsetInItem,a=n.pages[o];if(a){e.finish(Ja(a,o));return}e.loopWithFrame(l=>{if(o<n.layoutPositions.length){l.breakLoop();return}if(n.complete){o=n.layoutPositions.length-1,l.breakLoop();return}let c=n.layoutPositions[n.layoutPositions.length-1];this.renderSinglePage(n,c).then(u=>{let p=u.pageAndPosition.page;if(c=u.nextLayoutPosition,c){if(i>=0&&n.instance.getPosition(c)>i){a=p,o=n.layoutPositions.length-2,l.breakLoop();return}l.continueLoop()}else a=p,o=u.pageAndPosition.position.pageIndex,n.complete=!0,l.breakLoop()})}).then(()=>{a=a||n.pages[o];let l=n.layoutPositions[o];if(a){e.finish(Ja(a,o));return}this.renderSinglePage(n,l).then(c=>{c.nextLayoutPosition||(n.complete=!0),e.finish(c.pageAndPosition)})})}),e.result()}renderAllPages(){let t=A("renderAllPages");return this.renderPagesUpto({spineIndex:this.opf.spine.length-1,pageIndex:Number.POSITIVE_INFINITY,offsetInItem:-1},!1).then(e=>{t.loopWithFrame(n=>{this.spineItems.some(s=>s==null?void 0:s.pages.some(o=>o==null?void 0:o.fetchers.some(i=>!i.arrived)))?t.sleep(100).then(()=>{n.continueLoop()}):n.breakLoop()}).then(()=>{t.finish(e)})}),t.result()}renderPagesUpto(t,e){let n=A("renderPagesUpto");t||(t={spineIndex:0,pageIndex:0,offsetInItem:0});let s=t.spineIndex,o=t.pageIndex,i=0;e&&(i=s);let a;return n.loopWithFrame(l=>{let c={spineIndex:i,pageIndex:i===s?o:Number.POSITIVE_INFINITY,offsetInItem:i===s?t.offsetInItem:-1};this.renderPage(c).then(u=>{a=u,++i>s?l.breakLoop():l.continueLoop()})}).then(()=>{n.finish(a)}),n.result()}firstPage(t,e){return this.findPage({spineIndex:0,pageIndex:0,offsetInItem:-1},e)}lastPage(t,e){return this.findPage({spineIndex:this.opf.spine.length-1,pageIndex:Number.POSITIVE_INFINITY,offsetInItem:-1},e)}nextPage(t,e){let n=t.spineIndex,s=t.pageIndex,o=A("nextPage");return this.getPageViewItem(n).then(i=>{if(!i){o.finish(null);return}if(i.complete&&s==i.layoutPositions.length-1){if(n>=this.opf.spine.length-1){o.finish(null);return}n++,s=0;let a=this.spineItems[n],l=a&&a.pages[0],c=i.pages[i.pages.length-1];l&&c&&l.side==c.side&&(a.pages.forEach(u=>{u.container&&u.container.remove()}),this.spineItems[n]=null,this.spineItemLoadingContinuations[n]=null)}else s++;this.findPage({spineIndex:n,pageIndex:s,offsetInItem:-1},e).thenFinish(o)}),o.result()}previousPage(t,e){let n=t.spineIndex,s=t.pageIndex;if(s==0){if(n==0)return v(null);n--,s=Number.POSITIVE_INFINITY}else s--;return this.findPage({spineIndex:n,pageIndex:s,offsetInItem:-1},e)}isRectoPage(t,e){let n=t.side==="left",s=this.getCurrentPageProgression(e)==="ltr";return!n&&s||n&&!s}getSpread(t,e){let n=this.getPage(t);if(!n)return v({left:null,right:null});let s=A("getSpread"),o=n.side==="left",i;return this.isRectoPage(n,t)?i=this.previousPage(t,e):i=this.nextPage(t,e),i.then(a=>{let l=this.getPage(t),c=a&&a.page;c&&c.side===l.side&&(c=null),o?s.finish({left:l,right:c}):s.finish({left:c,right:l})}),s.result()}nextSpread(t,e){let n=this.getPage(t);if(!n)return v(null);let s=this.isRectoPage(n,t),o=this.nextPage(t,e);return s?o:o.thenAsync(i=>{if(i){if(i.page.side===n.side)return o;let a=this.nextPage(i.position,e);return a.thenAsync(l=>l?a:o)}else return v(null)})}previousSpread(t,e){let n=this.getPage(t);if(!n)return v(null);let s=this.isRectoPage(n,t),o=this.previousPage(t,e),i=n.container.previousElementSibling;return s?o.thenAsync(a=>a?a.page.side===n.side||a.page.container!==i?o:this.previousPage(a.position,e):v(null)):o}navigateToEPage(t,e,n){let s=A("navigateToEPage");return this.opf.resolveEPage(t).then(o=>{o?this.findPage(o,n).thenFinish(s):s.finish(null)}),s.result()}navigateToFragment(t,e,n){let s=A("navigateToCFI");return this.opf.resolveFragment(t).then(o=>{o?this.findPage(o,n).thenFinish(s):s.finish(null)}),s.result()}navigateTo(t,e,n){V.debug("Navigate to",t);let s=this.opf.getPathFromURL(Tt(t));if(!s){if(this.opf.opfXML&&t.match(/^#epubcfi\(/))s=this.opf.getPathFromURL(this.opf.opfXML.url);else if(t.charAt(0)==="#"){let a=this.opf.documentURLTransformer.restoreURL(t);this.opf.opfXML?(s=this.opf.getPathFromURL(a[0]),s==null&&(s=a[0])):s=a[0],t=a[0]+(a[1]?`#${a[1]}`:"")}if(s==null)return v(null)}let o=this.opf.itemMapByPath[s];if(!o){if(this.opf.opfXML&&s==this.opf.getPathFromURL(this.opf.opfXML.url)){let a=t.indexOf("#");if(a>=0)return this.navigateToFragment(t.substr(a+1),e,n)}return v(null)}let i=A("navigateTo");return this.getPageViewItem(o.spineIndex).then(a=>{if(!a){i.finish(null);return}let l=a.xmldoc.getElement(t);this.findPage({spineIndex:o.spineIndex,pageIndex:-1,offsetInItem:l?a.xmldoc.getElementOffset(l):0},n).thenFinish(i)}),i.result()}makePage(t,e){let n=t.instance.viewport,s=n.document.createElement("div");s.setAttribute("data-vivliostyle-page-container","true"),s.setAttribute("role","region"),ns||(s.style.visibility="hidden"),n.layoutBox.appendChild(s);let o=n.document.createElement("div");o.setAttribute("data-vivliostyle-bleed-box","true"),s.appendChild(o);let i=new co(s,o);if(i.spineIndex=t.item.spineIndex,i.position=e,i.offset=t.instance.getPosition(e),i.offset===0&&!(t.instance.blankPageAtStart&&t.pages.length===0)){let a=this.opf.documentURLTransformer.transformFragment("",t.item.src);o.setAttribute("id",a),i.registerElementWithId(o,a)}if(n!==this.viewport){let a=kl(this.viewport.width,this.viewport.height,n.width,n.height),l=Jt(null,new Oe(a,null),"");i.delayedItems.push(new Dn(s,"transform",l))}return i}makeObjectView(t,e,n,s){let o=e.getAttribute("data"),i=null;if(o){o=Q(o,t.url);let a=e.getAttribute("media-type");if(!a){let l=this.opf.getPathFromURL(o);if(l){let c=this.opf.itemMapByPath[l];c&&(a=c.mediaType)}}if(a){let l=this.opf.bindings[a];if(l){i=this.viewport.document.createElement("iframe"),i.style.border="none";let c=El(o),u=El(a),p=new Xe;p.append(l),p.append("?src="),p.append(c),p.append("&type="),p.append(u);for(let g=e.firstChild;g;g=g.nextSibling)if(g.nodeType==1){let m=g;if(m.localName=="param"&&m.namespaceURI=="http://www.w3.org/1999/xhtml"){let E=m.getAttribute("name"),y=m.getAttribute("value");E&&y&&(p.append("&"),p.append(encodeURIComponent(E)),p.append("="),p.append(encodeURIComponent(y)))}}i.setAttribute("src",p.toString());let h=e.getAttribute("width");h&&i.setAttribute("width",h);let f=e.getAttribute("height");f&&i.setAttribute("height",f)}}}return i||(i=this.viewport.document.createElement("object"),o&&i.setAttribute("data",o),i.setAttribute("data-adapt-process-children","true")),v(i)}makeMathJaxView(t,e,n,s){let o=hb();if(o){let i=n.ownerDocument,a=i.createElement("span");n.appendChild(a);let l=i.importNode(e,!0);this.resolveURLsInMathML(l,t),a.appendChild(l);let c=o.queue;c.Push(["Typeset",o,a]);let u=A("makeMathJaxView"),p=u.suspend();return c.Push(()=>{p.schedule(a)}),u.result()}return v(null)}resolveURLsInMathML(t,e){if(t!=null){if(t.nodeType===1&&t.tagName==="mglyph"){let n=Array.from(t.attributes);for(let s of n){if(s.name!=="src")continue;let o=Q(s.nodeValue,e.url);s.namespaceURI?t.setAttributeNS(s.namespaceURI,s.name,o):t.setAttribute(s.name,o)}}t.firstChild&&this.resolveURLsInMathML(t.firstChild,e),t.nextSibling&&this.resolveURLsInMathML(t.nextSibling,e)}}makeCustomRenderer(t){return(e,n,s)=>e.localName=="object"&&e.namespaceURI=="http://www.w3.org/1999/xhtml"?this.makeObjectView(t,e,n,s):e.namespaceURI=="http://www.w3.org/1998/Math/MathML"?this.makeMathJaxView(t,e,n,s):e.dataset&&e.dataset.mathTypeset=="true"?this.makeMathJaxView(t,e,n,s):v(null)}getPageViewItem(t){if(t===-1||t>=this.opf.spine.length)return v(null);let e=this.spineItems[t];if(e)return v(e);let n=A("getPageViewItem"),s=this.spineItemLoadingContinuations[t];if(s){let a=n.suspend();return s.push(a),n.result()}else s=this.spineItemLoadingContinuations[t]=[];let o=this.opf.spine[t],i=this.opf.store;return i.load(o.src).then(a=>{var x;let l=o.itemRefElement.getAttribute("properties");l&&a.root.setAttribute("data-vivliostyle-epub-spine-properties",l),o.title=a.document.title;let c=i.getStyleForDoc(a),u=this.makeCustomRenderer(a),p=this.viewport,h=c.sizeViewport(p.width,p.height,p.fontSize,this.pref);(h.width!=p.width||h.height!=p.height||h.fontSize!=p.fontSize)&&(p=new Nn(p.window,h.fontSize,p.pixelRatio,p.root,h.width,h.height));let f=(x=this.spineItems[0])==null?void 0:x.instance.isVersoFirstPage,g=this.spineItems[t-1],m,E;if(o.startPage!==null)m=o.startPage-1,E=m;else{if(t>0&&(!g||!g.complete))m=o.epage||t,!this.opf.prePaginated&&m%2==(f?1:0)&&m++,E=m;else{m=g?g.instance.pageNumberOffset+g.pages.length:0;let N=this.counterStore.currentPageCounters.page;E=!N||!N.length?m:N[N.length-1]}o.skipPagesBefore!==null&&(m+=o.skipPagesBefore,E+=o.skipPagesBefore)}this.counterStore.forceSetPageCounter(E);let y=new Qn(c,a,this.opf.lang,p,this.clientLayout,this.fontMapper,u,this.opf.fallbackMap,m,this.opf.documentURLTransformer,this.counterStore,this.opf.pageProgression,f);y.pref=this.pref;let C=this.opf.metadata&&this.opf.metadata[Te.title];y.pubTitle=C&&C[0]&&C[0].v||"",y.docTitle=o.title||"",y.init().then(()=>{!this.opf.pageProgression&&y.pageProgression&&(this.opf.pageProgression=y.pageProgression),e={item:o,xmldoc:a,instance:y,layoutPositions:[null],pages:[],complete:!1},this.spineItems[t]=e,n.finish(e),s.forEach(N=>{N.schedule(e)})})}),n.result()}removeRenderedPages(){let t=this.spineItems;for(let e of t)e&&e.pages.splice(0);this.viewport.clear()}hasAutoSizedPages(){let t=this.spineItems;for(let e of t)if(e){let n=e.pages;for(let s of n)if(s.isAutoPageWidth&&s.isAutoPageHeight)return!0}return!1}hasPages(){return this.spineItems.some(t=>t&&t.pages.length>0)}showTOC(t){let e=this.opf,n=e.toc;if(this.tocAutohide=t,!n)return v(null);if(this.tocVisible=!0,this.tocView&&this.tocView.page)return this.tocView.page.container.style.visibility="visible",this.tocView.page.container.setAttribute("aria-hidden","false"),v(this.tocView.page);let s=A("showTOC");this.tocView||(this.tocView=new Za(e.store,n.src,e.lang,this.clientLayout,this.fontMapper,this.pref,this,e.fallbackMap,e.documentURLTransformer,this.counterStore));let o=this.viewport,i=Math.min(344,Math.round(.67*o.width)-16),a=o.height-6,l=o.document.createElement("div");return o.root.appendChild(l),ns||(l.style.visibility="hidden"),l.style.width=`${i+16}px`,l.style.maxHeight=`${a}px`,l.setAttribute("data-vivliostyle-toc-box","true"),l.setAttribute("role","navigation"),this.tocView.showTOC(l,o,i,a,this.viewport.fontSize).then(c=>{l.style.visibility="visible",l.setAttribute("aria-hidden","false"),s.finish(c)}),s.result()}hideTOC(){this.tocVisible=!1,this.tocView&&this.tocView.hideTOC()}isTOCVisible(){return this.tocVisible&&!!this.tocView&&this.tocView.isTOCVisible()}};var lg="data-vivliostyle-viewer-status",gb="data-vivliostyle-spread-view",hp=(n=>(n.SINGLE_PAGE="singlePage",n.SPREAD="spread",n.AUTO_SPREAD="autoSpread",n))(hp||{}),nl=class{constructor(t,e,n,s){this.window=t;this.viewportElement=e;this.instanceId=n;this.callbackFn=s;d(this,"fontMapper");d(this,"kick");d(this,"sendCommand");d(this,"resizeListener");d(this,"hyperlinkListener");d(this,"pageRuleStyleElement");d(this,"pageSheetSizeAlreadySet",!1);d(this,"renderTask",null);d(this,"actions");d(this,"readyState");d(this,"packageURL");d(this,"opf");d(this,"touchActive");d(this,"touchX");d(this,"touchY");d(this,"needResize");d(this,"resized");d(this,"needRefresh");d(this,"viewportSize");d(this,"currentPage");d(this,"currentSpread");d(this,"pagePosition");d(this,"fontSize");d(this,"zoom");d(this,"fitToScreen");d(this,"pageViewMode");d(this,"waitForLoading");d(this,"renderAllPages");d(this,"pref");d(this,"pageSizes");d(this,"pixelRatio");d(this,"pixelRatioLimit");d(this,"viewport");d(this,"opfView");let o=e.ownerDocument,i=(a,l)=>{let c=o.getElementById(a);return c||(c=o.createElement("style"),c.id=a,l&&(c.textContent=l),o.head.appendChild(c)),c};i("vivliostyle-viewport-screen-css",rc),i("vivliostyle-viewport-css",ac),i("vivliostyle-polyfill-css",hc),e.setAttribute("data-vivliostyle-viewer-viewport",!0),ns&&e.setAttribute("data-vivliostyle-debug",!0),e.setAttribute(lg,"loading"),this.fontMapper=new Ra(o.head,e),this.init(),this.kick=()=>{},this.sendCommand=()=>{},this.resizeListener=()=>{this.needResize=!0,this.resized=!0,this.kick()},this.pageReplacedListener=this.pageReplacedListener.bind(this),this.hyperlinkListener=a=>{},this.pageRuleStyleElement=i("vivliostyle-page-rules"),this.actions={loadPublication:this.loadPublication,loadXML:this.loadXML,configure:this.configure,moveTo:this.moveTo,toc:this.showTOC},this.addLogListeners()}init(){this.readyState="loading",this.packageURL=[],this.opf=null,this.touchActive=!1,this.touchX=0,this.touchY=0,this.needResize=!1,this.resized=!1,this.needRefresh=!1,this.viewportSize=null,this.currentPage=null,this.currentSpread=null,this.pagePosition=null,this.fontSize=16,this.zoom=1,this.fitToScreen=!1,this.pageViewMode="singlePage",this.waitForLoading=!1,this.renderAllPages=!0,this.pref=Pl(),this.pageSizes=[],this.pixelRatioLimit=/Chrome/.test(navigator.userAgent)?16:0,this.pixelRatio=Math.min(8,this.pixelRatioLimit)}addLogListeners(){let t=fl;V.addListener(t.DEBUG,e=>{this.callback({t:"debug",content:e})}),V.addListener(t.INFO,e=>{this.callback({t:"info",content:e})}),V.addListener(t.WARN,e=>{this.callback({t:"warn",content:e})}),V.addListener(t.ERROR,e=>{this.callback({t:"error",content:e})})}callback(t){t.i=this.instanceId,this.callbackFn(t)}setReadyState(t){this.readyState!==t&&(this.readyState=t,this.viewportElement.setAttribute(lg,t),this.callback({t:"readystatechange"}))}loadPublication(t){Ye.registerStartTiming("beforeRender"),this.setReadyState("loading");let e=t.url,n=t.fragment,s=t.authorStyleSheet,o=t.userStyleSheet;this.viewport=null;let i=A("loadPublication");return this.configure(t).then(()=>{let a=new Gi;a.init(s,o).then(()=>{let l=Q(Tn(e),this.window.location.href);this.packageURL=[l],a.loadPubDoc(l).then(c=>{c?(this.opf=c,this.render(n).then(()=>{i.finish(!0)})):i.finish(!1)})})}),i.result()}loadXML(t){Ye.registerStartTiming("beforeRender"),this.setReadyState("loading");let e=t.url,n=t.document,s=t.fragment,o=t.authorStyleSheet,i=t.userStyleSheet;this.viewport=null;let a=A("loadXML");return this.configure(t).then(()=>{let l=new Gi;l.init(o,i).then(()=>{let c=e.map((u,p)=>({url:Q(Tn(u.url),this.window.location.href),index:p,startPage:u.startPage,skipPagesBefore:u.skipPagesBefore}));this.packageURL=c.map(u=>u.url),this.opf=new Ms(l,""),this.opf.initWithChapters(c,n).then(()=>{this.render(s).then(()=>{a.finish(!0)})})})}),a.result()}render(t){this.cancelRenderingTask();let e;return t?e=this.opf.resolveFragment(t).thenAsync(n=>(this.pagePosition=n,v(!0))):e=v(!0),e.thenAsync(()=>(Ye.registerEndTiming("beforeRender"),this.resize()))}resolveLength(t){let e=parseFloat(t),n=/[a-z]+$/,s;if(typeof t=="string"&&(s=t.match(n))){let o=s[0];if(o==="em"||o==="rem")return e*this.fontSize;if(o==="ex")return e*$.ex*this.fontSize/$.em;let i=$[o];if(i)return e*i}return e}configure(t){if(typeof t.autoresize=="boolean"&&(t.autoresize?(this.viewportSize=null,this.window.addEventListener("resize",this.resizeListener,!1),this.needResize=!0):this.window.removeEventListener("resize",this.resizeListener,!1)),typeof t.fontSize=="number"){let e=t.fontSize;e>=5&&e<=72&&this.fontSize!=e&&(this.fontSize=e,this.needResize=!0)}if(typeof t.viewport=="object"&&t.viewport){let e=t.viewport,n={marginLeft:this.resolveLength(e["margin-left"])||0,marginRight:this.resolveLength(e["margin-right"])||0,marginTop:this.resolveLength(e["margin-top"])||0,marginBottom:this.resolveLength(e["margin-bottom"])||0,width:this.resolveLength(e.width)||0,height:this.resolveLength(e.height)||0};(n.width>=200||n.height>=200)&&(this.window.removeEventListener("resize",this.resizeListener,!1),this.viewportSize=n,this.needResize=!0)}if(typeof t.hyphenate=="boolean"&&(this.pref.hyphenate=t.hyphenate,this.needResize=!0),typeof t.horizontal=="boolean"&&(this.pref.horizontal=t.horizontal,this.needResize=!0),typeof t.nightMode=="boolean"&&(this.pref.nightMode=t.nightMode,this.needResize=!0),typeof t.lineHeight=="number"&&(this.pref.lineHeight=t.lineHeight,this.needResize=!0),typeof t.columnWidth=="number"&&(this.pref.columnWidth=t.columnWidth,this.needResize=!0),typeof t.fontFamily=="string"&&(this.pref.fontFamily=t.fontFamily,this.needResize=!0),typeof t.load=="boolean"&&(this.waitForLoading=t.load),typeof t.renderAllPages=="boolean"&&(this.renderAllPages=t.renderAllPages),typeof t.userAgentRootURL=="string"&&(Cl(t.userAgentRootURL.replace(/resources\/?$/,"")),bl(t.userAgentRootURL)),typeof t.rootURL=="string"&&(Cl(t.rootURL),bl(`${rn}resources/`)),typeof t.pageViewMode=="string"&&t.pageViewMode!==this.pageViewMode&&(this.pageViewMode=t.pageViewMode,this.needResize=!0),typeof t.pageBorder=="number"&&t.pageBorder!==this.pref.pageBorder&&(this.viewport=null,this.pref.pageBorder=t.pageBorder,this.needResize=!0),typeof t.zoom=="number"&&t.zoom!==this.zoom&&(this.zoom=t.zoom,this.needRefresh=!0),typeof t.fitToScreen=="boolean"&&t.fitToScreen!==this.fitToScreen&&(this.fitToScreen=t.fitToScreen,this.needRefresh=!0),typeof t.defaultPaperSize=="object"&&typeof t.defaultPaperSize.width=="number"&&typeof t.defaultPaperSize.height=="number"&&(this.viewport=null,this.pref.defaultPaperSize=t.defaultPaperSize,this.needResize=!0),typeof t.allowScripts=="boolean"&&t.allowScripts!==zt&&(Zf(t.allowScripts),this.needResize=!0),typeof t.pixelRatio=="number"){let e=Math.min(t.pixelRatio,this.pixelRatioLimit);e!==this.pixelRatio&&(this.pixelRatio=e,this.needResize=!0)}return this.configurePlugins(t),v(!0)}configurePlugins(t){We("CONFIGURATION").forEach(n=>{let s=n(t);this.needResize=s.needResize||this.needResize,this.needRefresh=s.needRefresh||this.needRefresh})}pageReplacedListener(t){let e=this.currentPage,n=this.currentSpread,s=t.target;n?(n.left===s||n.right===s)&&this.showCurrent(t.newPage):e===t.target&&this.showCurrent(t.newPage)}forCurrentPages(t){let e=[];this.currentPage&&e.push(this.currentPage),this.currentSpread&&(e.push(this.currentSpread.left),e.push(this.currentSpread.right)),e.forEach(n=>{n&&t(n)})}removePageListeners(){this.forCurrentPages(t=>{t.removeEventListener("hyperlink",this.hyperlinkListener,!1),t.removeEventListener("replaced",this.pageReplacedListener,!1)})}hidePages(){this.removePageListeners(),this.forCurrentPages(t=>{T(t.container,"display","none")}),this.currentPage=null,this.currentSpread=null}showSinglePage(t){t.addEventListener("hyperlink",this.hyperlinkListener,!1),t.addEventListener("replaced",this.pageReplacedListener,!1),T(t.container,"visibility","visible"),T(t.container,"display","block")}showPage(t){this.hidePages(),this.currentPage=t,t.container.style.marginLeft="",t.container.style.marginRight="",this.showSinglePage(t)}showSpread(t){if(this.hidePages(),this.currentSpread=t,t.left&&t.right){let e=parseFloat(t.left.container.style.width),n=parseFloat(t.right.container.style.width);e&&n&&e!==n&&(e<n?t.left.container.style.marginLeft=`${n-e}px`:t.right.container.style.marginRight=`${e-n}px`)}t.left&&(this.showSinglePage(t.left),t.right?t.left.container.removeAttribute("data-vivliostyle-unpaired-page"):t.left.container.setAttribute("data-vivliostyle-unpaired-page",!0)),t.right&&(this.showSinglePage(t.right),t.left?t.right.container.removeAttribute("data-vivliostyle-unpaired-page"):t.right.container.setAttribute("data-vivliostyle-unpaired-page",!0))}reportPosition(){let t=A("reportPosition");return this.pagePosition,this.opf.getCFI(this.pagePosition.spineIndex,this.pagePosition.offsetInItem).then(e=>{let n=this.currentPage;(this.waitForLoading&&n.fetchers.length>0?Rn(n.fetchers):v(!0)).then(()=>{this.sendLocationNotification(n,e).thenFinish(t)})}),t.result()}createViewport(){let t=this.viewportElement;if(this.viewportSize){let e=this.viewportSize;return t.style.marginLeft=`${e.marginLeft}px`,t.style.marginRight=`${e.marginRight}px`,t.style.marginTop=`${e.marginTop}px`,t.style.marginBottom=`${e.marginBottom}px`,new Nn(this.window,this.fontSize,this.pixelRatio,t,e.width,e.height)}else return new Nn(this.window,this.fontSize,this.pixelRatio,t)}resolveSpreadView(t,e){switch(this.pageViewMode){case"singlePage":return!1;case"spread":return!0;case"autoSpread":default:return(t.width-this.pref.pageBorder)/t.height>=(e?e.width*2/e.height:1.45)&&(!!e||t.width>800)}}updateSpreadView(t){this.pref.spreadView=t,this.viewportElement.setAttribute(gb,t.toString())}sizeIsGood(){var i;let t=this.createViewport(),e=((i=this.opfView)==null?void 0:i.hasPages())&&!this.opfView.hasAutoSizedPages(),n=this.resolveSpreadView(t,this.resized&&e?this.pageSizes[0]:null);this.resized=!1;let s=this.pref.spreadView!==n;return this.updateSpreadView(n),this.pixelRatio&&this.opfView&&this.pixelRatio/this.window.devicePixelRatio!==this.opfView.clientLayout.scaleRatio||this.viewportSize||!this.viewport||this.viewport.fontSize!=this.fontSize?!1:!s&&t.width==this.viewport.width&&t.height==this.viewport.height||!s&&t.width==this.viewport.width&&t.height!=this.viewport.height&&/Android|iPhone|iPad|iPod/.test(navigator.userAgent)?!0:e?(this.viewport.width=t.width,this.viewport.height=t.height,this.needRefresh=!0,!0):!1}setPageSize(t,e,n,s){this.pageSizes[s]=t,this.setPageSizePageRules(e,n,s),s===0&&this.pageViewMode==="autoSpread"&&!this.opfView.hasAutoSizedPages()&&this.updateSpreadView(this.resolveSpreadView(this.viewport,t))}setPageSizePageRules(t,e,n){var o,i;if(this.pageRuleStyleElement&&(!this.pageSheetSizeAlreadySet||this.pageSizes[n].width!==((o=this.pageSizes[n-1])==null?void 0:o.width)||this.pageSizes[n].height!==((i=this.pageSizes[n-1])==null?void 0:i.height))){let c=function(m){let E=m*.75;return Math.ceil(E)};var s=c;let a=Math.max(...this.pageSizes.map(m=>m.width)),l=Math.max(...this.pageSizes.map(m=>m.height)),u=c(a),p=c(l),h=u*((this.pixelRatio||1)-1)+2,f=p*((this.pixelRatio||1)-1)+2,g=`@page {size: ${u}pt ${p}pt; margin: 0 ${-h}pt ${-f}pt 0;}`;this.pageRuleStyleElement.textContent=g,this.pageSheetSizeAlreadySet=!0}}removePageSizePageRules(){this.pageRuleStyleElement&&(this.pageRuleStyleElement.textContent="",this.pageSheetSizeAlreadySet=!1)}reset(){let t=!1,e=!1;this.opfView&&(t=this.opfView.tocVisible,e=this.opfView.tocAutohide,this.opfView.removeRenderedPages()),this.pageSizes=[],this.removePageSizePageRules(),this.viewport=this.createViewport(),this.viewport.resetZoom(),this.opfView=new tl(this.opf,this.viewport,this.fontMapper,this.pref,this.setPageSize.bind(this)),t&&this.sendCommand({a:"toc",v:"show",autohide:e})}showCurrent(t,e){this.needRefresh=!1,this.removePageListeners();let n=this.resolveSpreadView(this.viewport,t.dimensions);return n!==this.pref.spreadView&&this.updateSpreadView(n),n?this.opfView.getSpread(this.pagePosition,e).thenAsync(s=>!s.left&&!s.right?v(null):s.left&&s.right&&(!this.resolveSpreadView(this.viewport,s.left.dimensions)||!this.resolveSpreadView(this.viewport,s.right.dimensions))?(this.updateSpreadView(!1),this.showPage(t),this.setPageZoom(t),this.currentPage=t,v(null)):(this.showSpread(s),this.setSpreadZoom(s),this.currentPage=t.side==="left"?s.left:s.right,v(null))):(this.showPage(t),this.setPageZoom(t),this.currentPage=t,v(null))}setPageZoom(t){let e=this.getAdjustedZoomFactor(t.dimensions);this.viewport.zoom(t.dimensions.width,t.dimensions.height,e)}setSpreadZoom(t){let e=this.getSpreadDimensions(t);this.viewport.zoom(e.width,e.height,this.getAdjustedZoomFactor(e))}getAdjustedZoomFactor(t){return this.fitToScreen?this.calculateZoomFactorToFitInsideViewPort(t):this.zoom}getSpreadDimensions(t){let e=0,n=0;return t.left&&(e+=t.left.dimensions.width,n=t.left.dimensions.height),t.right&&(e+=t.right.dimensions.width,n=Math.max(n,t.right.dimensions.height)),t.left&&t.right&&(e+=this.pref.pageBorder*2,e+=Math.abs(t.left.dimensions.width-t.right.dimensions.width)),{width:e,height:n}}queryZoomFactor(t){if(!this.currentPage)throw new Error("no page exists.");switch(t){case"fit inside viewport":{let e;return this.pref.spreadView?(this.currentSpread,e=this.getSpreadDimensions(this.currentSpread)):e=this.currentPage.dimensions,this.calculateZoomFactorToFitInsideViewPort(e)}default:throw new Error(`unknown zoom type: ${t}`)}}calculateZoomFactorToFitInsideViewPort(t){if(!this.viewport)return this.zoom;let e=this.viewport.width/t.width,n=this.viewport.height/t.height;return Math.min(e,n)}cancelRenderingTask(){this.renderTask&&this.renderTask.interrupt(new sl),this.renderTask=null}resize(){if(this.needResize=!1,this.needRefresh=!1,this.sizeIsGood())return v(!0);this.setReadyState("loading"),this.cancelRenderingTask();let t=Ko().getScheduler().run(()=>un("resize",e=>{if(!this.opf){e.finish(!1);return}this.renderTask=t,Ye.registerStartTiming("render (resize)"),this.reset(),this.pagePosition&&(this.pagePosition.pageIndex==0&&this.pagePosition.offsetInItem==0||(this.pagePosition.pageIndex=-1)),this.opf.setEPageCountMode(this.renderAllPages),this.opfView.renderPagesUpto(this.pagePosition,!this.renderAllPages).then(n=>{if(!n){e.finish(!1);return}this.pagePosition=n.position,this.showCurrent(n.page,!0).then(()=>{this.setReadyState("interactive"),this.opf.countEPages(s=>{let o={t:"nav",epageCount:s,first:this.currentPage.isFirstPage,last:this.currentPage.isLastPage,metadata:this.opf.metadata,docTitle:this.opf.spine[this.pagePosition.spineIndex].title};(this.currentPage.isFirstPage||this.pagePosition.pageIndex==0&&this.opf.spine[this.pagePosition.spineIndex].epage)&&(o.epage=this.opf.spine[this.pagePosition.spineIndex].epage),this.callback(o)}).then(()=>{this.reportPosition().then(s=>{(this.renderAllPages?this.opfView.renderAllPages():v(null)).then(()=>{this.renderTask===t&&(this.renderTask=null),Ye.registerEndTiming("render (resize)"),zt&&op(this.window)?eg(this.window).then(()=>{this.renderAllPages&&this.setReadyState("complete"),this.callback({t:"loaded"}),e.finish(s)}):(this.renderAllPages&&this.setReadyState("complete"),this.callback({t:"loaded"}),e.finish(s))})})})})})},(e,n)=>{if(n instanceof sl)Ye.registerEndTiming("render (resize)"),V.debug(n.message);else throw n}));return v(!0)}sendLocationNotification(t,e){let n=A("sendLocationNotification"),s={t:"nav",first:t.isFirstPage,last:t.isLastPage,metadata:this.opf.metadata,docTitle:this.opf.spine[t.spineIndex].title};return this.opf.getEPageFromPosition(this.pagePosition).then(o=>{s.epage=o,s.epageCount=this.opf.epageCount,e&&(s.cfi=e),this.callback(s),n.finish(!0)}),n.result()}getCurrentPageProgression(){return this.opfView?this.opfView.getCurrentPageProgression(this.pagePosition):null}moveTo(t){var s;let e;if(this.readyState!=="complete"&&t.where!=="next"&&this.setReadyState("loading"),typeof t.where=="string"){let o;switch(t.where){case"next":o=this.pref.spreadView?this.opfView.nextSpread:this.opfView.nextPage;break;case"previous":o=this.pref.spreadView?this.opfView.previousSpread:this.opfView.previousPage;break;case"last":o=this.opfView.lastPage;break;case"first":o=this.opfView.firstPage;break;default:return v(!0)}o&&(e=()=>o.call(this.opfView,this.pagePosition,!this.renderAllPages))}else if(typeof t.epage=="number"){let o=t.epage;e=()=>this.opfView.navigateToEPage(o,this.pagePosition,!this.renderAllPages)}else if(typeof t.url=="string"){let o=t.url;e=()=>this.opfView.navigateTo(o,this.pagePosition,!this.renderAllPages)}else if(typeof((s=t.position)==null?void 0:s.spineIndex)=="number"){let o=t.position;e=()=>this.opfView.findPage(o,!this.renderAllPages)}else return v(!0);if(!this.opfView)return v(!0);let n=A("moveTo");return e.call(this.opfView).then(o=>{let i;if(o){this.pagePosition=o.position;let a=A("moveTo.showCurrent");i=a.result(),this.showCurrent(o.page,!this.renderAllPages).then(()=>{this.reportPosition().thenFinish(a)})}else i=v(!0);i.then(a=>{this.readyState==="loading"&&this.setReadyState("interactive"),n.finish(a)})}),n.result()}showTOC(t){let e=!!t.autohide,n=t.v,s=this.opfView.isTOCVisible(),o=e!=this.opfView.tocAutohide&&n!="hide";if(s){if(n=="show"&&!o)return v(!0)}else if(n=="hide")return v(!0);if(s&&n!="show")return this.opfView.hideTOC(),v(!0);{let i=A("showTOC");return this.opfView.showTOC(e).then(a=>{if(a){if(o&&(a.listeners={}),e){let l=()=>{this.opfView.hideTOC()};a.addEventListener("hyperlink",l,!1)}a.addEventListener("hyperlink",this.hyperlinkListener,!1)}i.finish(!0)}),i.result()}}runCommand(t){let e=t.a||"";return un("runCommand",n=>{let s=this.actions[e];s?s.call(this,t).then(()=>{this.callback({t:"done",a:e}),n.finish(!0)}):(V.error("No such action:",e),n.finish(!0))},(n,s)=>{V.error(s,"Error during action:",e),n.finish(!0)})}initEmbed(t){let e=cg(t),n=null,s=this;eh(()=>{let o=A("commandLoop"),i=Ko().getScheduler();return s.hyperlinkListener=a=>{let l=a,c=l.href.charAt(0)==="#"||s.packageURL.some(u=>l.href.substr(0,u.length)==u);if(c){a.preventDefault();let u={t:"hyperlink",href:l.href,internal:c};i.run(()=>(s.callback(u),v(!0)))}},o.loopWithFrame(a=>{if(s.needResize)s.resize().then(()=>{a.continueLoop()});else if(s.needRefresh)s.currentPage&&s.showCurrent(s.currentPage,!this.renderAllPages).then(()=>{a.continueLoop()});else if(e){let l=e;e=null,s.runCommand(l).then(()=>{a.continueLoop()})}else{let l=A("waitForCommand");n=l.suspend(this),l.result().then(()=>{a.continueLoop()})}}).thenFinish(o),o.result()}),s.kick=()=>{let o=n;o&&(n=null,o.schedule(!0))},s.sendCommand=o=>e?!1:(e=cg(o),s.kick(),!0),this.window.adapt_command=s.sendCommand}},fp=(t=>(t.FIT_INSIDE_VIEWPORT="fit inside viewport",t))(fp||{}),sl=class r extends Error{constructor(){super();d(this,"name","RenderingCanceledError");d(this,"message","Page rendering has been canceled");d(this,"stack");Object.setPrototypeOf(this,r.prototype),this.stack=new Error().stack}};function cg(r){return typeof r=="string"?Hs(r):r}var ug=ss;function Cb(){return{autoResize:!0,fontSize:16,pageBorderWidth:1,renderAllPages:!0,pageViewMode:"autoSpread",zoom:1,fitToScreen:!1,defaultPaperSize:void 0,allowScripts:!0,pixelRatio:8}}function dg(r){let t={};return Object.keys(r).forEach(e=>{let n=r[e];switch(e){case"autoResize":t.autoresize=n;break;case"pageBorderWidth":t.pageBorder=n;break;default:t[e]=n}}),t}var Wi=class{constructor(t,e){this.settings=t;d(this,"initialized",!1);d(this,"adaptViewer_");d(this,"options");d(this,"eventTarget");d(this,"readyState");ul(t.debug),this.adaptViewer_=new nl(t.window||window,t.viewportElement,"main",this.dispatcher.bind(this)),this.options=Cb(),e&&this.setOptions(e),this.eventTarget=new vn,Object.defineProperty(this,"readyState",{get(){return this.adaptViewer_.readyState}})}setOptions(t){let e=Object.assign({a:"configure"},dg(t));this.adaptViewer_.sendCommand(e),Object.assign(this.options,t)}dispatcher(t){let e={type:t.t},n=t;Object.keys(n).forEach(s=>{s!=="t"&&(e[s]=n[s])}),this.eventTarget.dispatchEvent(e)}addListener(t,e){this.eventTarget.addEventListener(t,e,!1)}removeListener(t,e){this.eventTarget.removeEventListener(t,e,!1)}loadDocument(t,e,n){if(!t||(Array.isArray(t)?!t[0]||typeof t[0]!="string"&&!t[0].url:typeof t!="string"&&!t.url)){this.eventTarget.dispatchEvent({type:"error",content:{error:new Error("No URL specified")}});return}this.loadDocumentOrPublication(t,null,e,n)}loadPublication(t,e,n){if(!t){this.eventTarget.dispatchEvent({type:"error",content:{error:new Error("No URL specified")}});return}this.loadDocumentOrPublication(null,t,e,n)}loadDocumentOrPublication(t,e,n,s){let o=n||{};function i(u){if(u)return u.map(p=>({url:p.url||null,text:p.text||null}))}let a=i(o.authorStyleSheet),l=i(o.userStyleSheet);s&&Object.assign(this.options,s);let c=Object.assign({a:t?"loadXML":"loadPublication",userAgentRootURL:this.settings.userAgentRootURL,url:bb(t)||e,document:o.documentObject,fragment:o.fragment,authorStyleSheet:a,userStyleSheet:l},dg(this.options));this.initialized?this.adaptViewer_.sendCommand(c):(this.initialized=!0,this.adaptViewer_.initEmbed(c))}getCurrentPageProgression(){return this.adaptViewer_.getCurrentPageProgression()}resolveNavigation(t){switch(t){case"left":return this.getCurrentPageProgression()===ug.LTR?"previous":"next";case"right":return this.getCurrentPageProgression()===ug.LTR?"next":"previous";default:return t}}navigateToPage(t,e){t==="epage"?this.adaptViewer_.sendCommand({a:"moveTo",epage:e}):this.adaptViewer_.sendCommand({a:"moveTo",where:this.resolveNavigation(t)})}navigateToInternalUrl(t){this.adaptViewer_.sendCommand({a:"moveTo",url:t})}navigateToPosition(t){var e,n;this.adaptViewer_.sendCommand({a:"moveTo",position:{spineIndex:t.spineIndex,pageIndex:(e=t.pageIndex)!=null?e:-1,offsetInItem:(n=t.offsetInItem)!=null?n:-1}})}isTOCVisible(){return this.adaptViewer_.opfView&&this.adaptViewer_.opfView.opf&&this.adaptViewer_.opfView.opf.toc?!!this.adaptViewer_.opfView.isTOCVisible():null}showTOC(t,e){let n=t==null?"toggle":t?"show":"hide";this.adaptViewer_.sendCommand({a:"toc",v:n,autohide:e})}queryZoomFactor(t){return this.adaptViewer_.queryZoomFactor(t)}getPageSizes(){return this.adaptViewer_.pageSizes}getTOC(){var t,e;return(e=(t=this.adaptViewer_.opfView)==null?void 0:t.tocView)==null?void 0:e.getTOC()}getMetadata(){return this.adaptViewer_.opf.getMetadata()}getCover(){return this.adaptViewer_.opf.cover}};function bb(r){function t(n){return typeof n=="number"?n:null}function e(n){return typeof n=="string"?{url:n,startPage:null,skipPagesBefore:null}:{url:n.url,startPage:t(n.startPage),skipPagesBefore:t(n.skipPagesBefore)}}return Array.isArray(r)?r.map(e):r?[e(r)]:null}var pg=(a=>(a.PREVIOUS="previous",a.NEXT="next",a.LEFT="left",a.RIGHT="right",a.FIRST="first",a.LAST="last",a.EPAGE="epage",a))(pg||{}),xb=fp,yb=hp;Ye.forceRegisterEndTiming("load_vivliostyle");var gp=class{constructor(t,{title:e="",printCallback:n=a=>a.print(),errorCallback:s=null,hideIframe:o=!0,removeIframe:i=!0}){d(this,"htmlDoc");d(this,"title");d(this,"printCallback");d(this,"errorCallback");d(this,"hideIframe");d(this,"removeIframe");d(this,"iframe");d(this,"iframeWin");d(this,"window");this.htmlDoc=t,this.title=e,this.printCallback=n,this.errorCallback=s,this.hideIframe=o,this.removeIframe=i}init(){this.iframe=document.createElement("iframe"),this.hideIframe&&(this.iframe.style.width="0",this.iframe.style.height="0",this.iframe.style.borderWidth="0"),this.window=window,this.window.printInstance=this,this.iframe.srcdoc=`
|
|
1517
|
+
`),n.toString()}},Da=class{constructor(t){this.deobfuscator=t;p(this,"familyMap",{})}registerFamily(t,e){let n=t.family,s=this.familyMap[n],o=e.family;if(s){if(s!=o)throw new Error(`E_FONT_FAMILY_INCONSISTENT ${t.family}`)}else this.familyMap[n]=o}filterFontFamily(t){if(t instanceof ge){let e=t.values,n=[];for(let s of e){let o=this.familyMap[s.stringValue()];o&&n.push(L(o)),n.push(s)}return new ge(n)}else{let e=this.familyMap[t.stringValue()];return e?new ge([L(e),t]):t}}},Ma=class{constructor(t,e,n){this.head=t;this.body=e;p(this,"srcURLMap",{});p(this,"familyPrefix");p(this,"familyCounter",0);this.familyPrefix=n||"Fnt_"}getViewFontFamily(t,e){let n=t.family,s=e.familyMap[n];return s||(s=this.familyPrefix+ ++this.familyCounter,e.familyMap[n]=s,s)}initFont(t,e,n){let s=A("initFont"),o=t.src,i={};for(let u of $d(t.properties))i[u]=t.properties[u];let a=this.getViewFontFamily(t,n);i["font-family"]=L(a);let l=new Fi(i),c=this.head.ownerDocument.createElement("style");return c.textContent=l.makeAtRule(o,e),this.head.appendChild(c),V.debug("Load font:",o),s.finish(l),s.result()}loadFont(t,e){let n=t.src,s=t.family+";"+n,o=this.srcURLMap[s];return o?o.piggyback(i=>{let a=i;a.traitsEqual(t)?(e.registerFamily(t,a),V.debug("Found already-loaded font:",n)):V.warn("E_FONT_FACE_INCOMPATIBLE",t.src)}):(o=new Qt(()=>{let i=A("loadFont"),a=n.replace(/^url\("([^"]+)"\).*$/,"$1"),l=e.deobfuscator?e.deobfuscator(a):null;return l?gs(a,"blob").then(c=>{if(!c.responseBlob){i.finish(null);return}l(c.responseBlob).then(u=>{this.initFont(t,u,e).thenFinish(i)})}):this.initFont(t,null,e).thenFinish(i),i.result()},`loadFont ${n}`),this.srcURLMap[s]=o,o.start()),o}findOrLoadFonts(t,e){let n=[];for(let s of t){if(!s.src||!s.family){V.warn("E_FONT_FACE_INVALID");continue}n.push(this.loadFont(s,e))}return Vn(n).thenAsync(()=>this.waitFontLoading())}waitFontLoading(){let t=this.head.ownerDocument.fonts,e=0;if(t.forEach(s=>{s.status==="unloaded"&&(e++,s.load().catch(o=>{}))}),e===0)return v(!0);let n=A("waitFontLoading");return n.loop(()=>n.sleep(20).thenAsync(()=>t.status==="loading"?v(!0):v(!1))).thenFinish(n),n.result()}};var JC=1,Ro=class{constructor(t,e,n,s,o){this.name=e;this.pseudoName=n;this.classes=s;this.parent=o;p(this,"specified",{});p(this,"children",[]);p(this,"pageMaster",null);p(this,"index",0);p(this,"key");p(this,"_scope");this._scope=t,this.key=`p${JC++}`,o&&(this.index=o.children.length,o.children.push(this))}get scope(){return this._scope}createInstance(t){throw new Error("E_UNEXPECTED_CALL")}clone(t){throw new Error("E_UNEXPECTED_CALL")}copySpecified(t){let e=this.specified,n=t.specified;for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}cloneChildren(t){for(let e=0;e<this.children.length;e++)this.children[e].clone({parent:t})}},_a=class extends Ro{constructor(t){super(t,null,null,[],null),this.specified.width=new H(Rn,0),this.specified.height=new H(In,0)}},Ua=class extends as{constructor(e,n){super(e,o);this.pageMaster=n;let s=this;function o(i,a){let l=i.match(/^([^.]+)\.([^.]+)$/);if(l){let c=s.pageMaster.keyMap[l[1]];if(c){let d=this.lookupInstance(c);if(d)return a?d.resolveFunc(l[2]):d.resolveName(l[2])}}return null}}},Io=class r extends Ro{constructor(e,n,s,o,i,a,l){super(e,n,s,o,i);this.condition=a;this.specificity=l;p(this,"keyMap",{});e instanceof Ua||(this._scope=new Ua(e,this)),this.pageMaster=this,this.specified.width=new H(Rn,0),this.specified.height=new H(In,0),this.specified["wrap-flow"]=new H(b.auto,0),this.specified.position=new H(b.relative,0),this.specified.overflow=new H(b.visible,0)}createInstance(e){return new Us(e,this)}clone(e){let n=new r(this.scope,this.name,e.pseudoName||this.pseudoName,this.classes,this.parent,this.condition,this.specificity);return this.copySpecified(n),this.cloneChildren(n),n}resetScope(){this.scope.pageMaster=this}},Ha=class r extends Ro{constructor(t,e,n,s,o){super(t,e,n,s,o),this.pageMaster=o.pageMaster,e&&(this.pageMaster.keyMap[e]=this.key),this.specified["wrap-flow"]=new H(b.auto,0)}createInstance(t){return new Xd(t,this)}clone(t){let e=new r(t.parent.scope,this.name,this.pseudoName,this.classes,t.parent);return this.copySpecified(e),this.cloneChildren(e),e}},Jn=class r extends Ro{constructor(t,e,n,s,o){super(t,e,n,s,o),this.pageMaster=o.pageMaster,e&&(this.pageMaster.keyMap[e]=this.key)}createInstance(t){return new rn(t,this)}clone(t){let e=new r(t.parent.scope,this.name,this.pseudoName,this.classes,t.parent);return this.copySpecified(e),this.cloneChildren(e),e}};function eb(r,t,e){return!t||U(t)?new ie(r,e):t.toExpr(r,r.zero)}function te(r,t,e){return!t||t===b.auto||U(t)?null:t.toExpr(r,e)}function tb(r,t,e){return!t||t===b.normal||U(t)?null:t.toExpr(r,e)}function ot(r,t,e){return!t||t===b.auto||U(t)?r.zero:t.toExpr(r,e)}function Yd(r,t,e){return!t||U(t)?r.zero:t===b.auto?null:t.toExpr(r,e)}function zt(r,t,e,n){return!t||e===b.none||U(t)?r.zero:t.toExpr(r,n)}function lg(r,t,e){return!t||U(t)?e:t===b._true?r._true:t===b._false?r._false:t.toExpr(r,r.zero)}var Vo=class{constructor(t,e){this.parentInstance=t;this.pageBox=e;p(this,"cascaded",{});p(this,"style",{});p(this,"autoWidth",null);p(this,"autoHeight",null);p(this,"children",[]);p(this,"isAutoWidth",!1);p(this,"isAutoHeight",!1);p(this,"isTopDependentOnAutoHeight",!1);p(this,"isRightDependentOnAutoWidth",!1);p(this,"calculatedWidth",0);p(this,"calculatedHeight",0);p(this,"pageMasterInstance",null);p(this,"namedValues",{});p(this,"namedFuncs",{});p(this,"vertical",!1);p(this,"rtl",!1);p(this,"suppressEmptyBoxGeneration",!1);p(this,"borderBoxSizing",!1);t&&t.children.push(this)}reset(){this.calculatedWidth=0,this.calculatedHeight=0}addNamedValues(t,e){let n=this.resolveName(t),s=this.resolveName(e);if(!n||!s)throw new Error("E_INTERNAL");return z(this.pageBox.scope,n,s)}resolveName(t){let e=this.namedValues[t];if(e)return e;let n=this.style[t];switch(n&&(e=n.toExpr(this.pageBox.scope,this.pageBox.scope.zero)),t){case"margin-left-edge":e=this.resolveName("left");break;case"margin-top-edge":e=this.resolveName("top");break;case"margin-right-edge":e=this.addNamedValues("border-right-edge","margin-right");break;case"margin-bottom-edge":e=this.addNamedValues("border-bottom-edge","margin-bottom");break;case"border-left-edge":e=this.addNamedValues("margin-left-edge","margin-left");break;case"border-top-edge":e=this.addNamedValues("margin-top-edge","margin-top");break;case"border-right-edge":e=this.addNamedValues("padding-right-edge","border-right-width");break;case"border-bottom-edge":e=this.addNamedValues("padding-bottom-edge","border-bottom-width");break;case"padding-left-edge":e=this.addNamedValues("border-left-edge","border-left-width");break;case"padding-top-edge":e=this.addNamedValues("border-top-edge","border-top-width");break;case"padding-right-edge":e=this.addNamedValues("right-edge","padding-right");break;case"padding-bottom-edge":e=this.addNamedValues("bottom-edge","padding-bottom");break;case"left-edge":e=this.addNamedValues("padding-left-edge","padding-left");break;case"top-edge":e=this.addNamedValues("padding-top-edge","padding-top");break;case"right-edge":e=this.addNamedValues("left-edge","width");break;case"bottom-edge":e=this.addNamedValues("top-edge","height");break}if(!e){let s;if(t=="extent")s=this.vertical?"width":"height";else if(t=="measure")s=this.vertical?"height":"width";else{let o=this.vertical?Uu:Hu;s=t;for(let i in o)s=s.replace(i,o[i])}s!=t&&(e=this.resolveName(s))}return e&&(this.namedValues[t]=e),e}resolveFunc(t){let e=this.namedFuncs[t];if(e)return e;switch(t){case"columns":{let n=this.pageBox.scope,s=new Zs(n,0),o=this.resolveName("column-count"),i=this.resolveName("column-width"),a=this.resolveName("column-gap");e=K(n,Qs(n,new un(n,"min",[s,o]),z(n,i,a)),a);break}}return e&&(this.namedFuncs[t]=e),e}initEnabled(){let t=this.pageBox.scope,e=this.style,n=lg(t,e.enabled,t._true),s=te(t,e.page,t.zero);if(s){let a=new ee(t,"page-number");n=tt(t,n,new An(t,s,a))}let o=te(t,e["min-page-width"],t.zero);o&&(n=tt(t,n,new ls(t,new ee(t,"page-width"),o)));let i=te(t,e["min-page-height"],t.zero);i&&(n=tt(t,n,new ls(t,new ee(t,"page-height"),i))),n=this.boxSpecificEnabled(n),e.enabled=new B(n)}boxSpecificEnabled(t){return t}initHorizontal(){let t=this.pageBox.scope,e=this.style,n=this.parentInstance?this.parentInstance.style.width.toExpr(t,null):null,s=te(t,e.left,n),o=te(t,e["margin-left"],n),i=zt(t,e["border-left-width"],e["border-left-style"],n),a=ot(t,e["padding-left"],n),l=te(t,e.width,n),c=te(t,e["max-width"],n),u=ot(t,e["padding-right"],n),d=zt(t,e["border-right-width"],e["border-right-style"],n),h=te(t,e["margin-right"],n),f=te(t,e.right,n),g=z(t,i,a),m=z(t,i,u);if(s&&f&&l){let C=K(t,n,z(t,l,z(t,z(t,s,g),m)));o?h?f=K(t,C,h):h=K(t,C,z(t,f,o)):(C=K(t,C,f),h?o=K(t,C,h):(o=Qs(t,C,new ie(t,.5)),h=o))}else{o||(o=t.zero),h||(h=t.zero),!s&&!f&&!l&&(s=t.zero),!s&&!l?(l=this.autoWidth,this.isAutoWidth=!0):!s&&!f?s=t.zero:!l&&!f&&(l=this.autoWidth,this.isAutoWidth=!0);let C=K(t,n,z(t,z(t,o,g),z(t,h,m)));this.isAutoWidth&&(c||(c=K(t,C,s||f)),!this.vertical&&(te(t,e["column-width"],null)||te(t,e["column-count"],null))&&(l=c,this.isAutoWidth=!1)),s?l?f||(f=K(t,C,z(t,s,l))):l=K(t,C,z(t,s,f)):s=K(t,C,z(t,f,l))}let y=e["snap-width"]||(this.parentInstance?this.parentInstance.style["snap-width"]:null),E=ot(t,y,n);e.left=new B(s),e["margin-left"]=new B(o),e["border-left-width"]=new B(i),e["padding-left"]=new B(a),e.width=new B(l),e["max-width"]=new B(c||l),e["padding-right"]=new B(u),e["border-right-width"]=new B(d),e["margin-right"]=new B(h),e.right=new B(f),e["snap-width"]=new B(E)}initVertical(){let t=this.pageBox.scope,e=this.style,n=this.parentInstance?this.parentInstance.style.width.toExpr(t,null):null,s=this.parentInstance?this.parentInstance.style.height.toExpr(t,null):null,o=te(t,e.top,s),i=te(t,e["margin-top"],n),a=zt(t,e["border-top-width"],e["border-top-style"],n),l=ot(t,e["padding-top"],n),c=te(t,e.height,s),u=te(t,e["max-height"],s),d=ot(t,e["padding-bottom"],n),h=zt(t,e["border-bottom-width"],e["border-bottom-style"],n),f=te(t,e["margin-bottom"],n),g=te(t,e.bottom,s),m=z(t,a,l),y=z(t,h,d);if(o&&g&&c){let x=K(t,s,z(t,c,z(t,z(t,o,m),y)));i?f?g=K(t,x,i):f=K(t,x,z(t,g,i)):(x=K(t,x,g),f?i=K(t,x,f):(i=Qs(t,x,new ie(t,.5)),f=i))}else{i||(i=t.zero),f||(f=t.zero),!o&&!g&&!c&&(o=t.zero),!o&&!c?(c=this.autoHeight,this.isAutoHeight=!0):!o&&!g?o=t.zero:!c&&!g&&(c=this.autoHeight,this.isAutoHeight=!0);let x=K(t,s,z(t,z(t,i,m),z(t,f,y)));this.isAutoHeight&&(u||(u=K(t,x,o||g)),this.vertical&&(te(t,e["column-width"],null)||te(t,e["column-count"],null))&&(c=u,this.isAutoHeight=!1)),o?c?g||(g=K(t,x,z(t,o,c))):c=K(t,x,z(t,g,o)):o=K(t,x,z(t,g,c))}let E=e["snap-height"]||(this.parentInstance?this.parentInstance.style["snap-height"]:null),C=ot(t,E,n);e.top=new B(o),e["margin-top"]=new B(i),e["border-top-width"]=new B(a),e["padding-top"]=new B(l),e.height=new B(c),e["max-height"]=new B(u||c),e["padding-bottom"]=new B(d),e["border-bottom-width"]=new B(h),e["margin-bottom"]=new B(f),e.bottom=new B(g),e["snap-height"]=new B(C)}initColumns(){let t=this.pageBox.scope,e=this.style,n=te(t,e[this.vertical?"height":"width"],null),s=te(t,e["column-width"],n),o=te(t,e["column-count"],null),i=tb(t,e["column-gap"],null);i||(i=new Ft(t,1,"em")),s&&!o&&(o=new un(t,"floor",[Yo(t,z(t,n,i),z(t,s,i))]),o=new un(t,"max",[t.one,o])),o||(o=t.one),s=K(t,Yo(t,z(t,n,i),o),i),e["column-width"]=new B(s),e["column-count"]=new B(o),e["column-gap"]=new B(i)}depends(t,e,n){return this.style[t].toExpr(this.pageBox.scope,null).depend(e,n)}init(t){var l;t.registerInstance(this.pageBox.key,this);let n=this.pageBox.scope,s=this.style,o=this.parentInstance?this.parentInstance.getActiveRegions(t):null,i=Ea(this.cascaded,t,o,!1,null);this.vertical=xa(i,t,this.parentInstance?this.parentInstance.vertical:!1),this.rtl=ya(i,t,this.parentInstance?this.parentInstance.rtl:!1),this.borderBoxSizing=((l=i["box-sizing"])==null?void 0:l.value)===b.border_box;let a=!!(t instanceof es&&t.currentLayoutPosition&&new ee(n,"left-page").evaluate(t));Sa(i,s,this.vertical,this.rtl,a,(c,u)=>u.value),this.autoWidth=new Z(n,()=>this.calculatedWidth,"autoWidth"),this.autoHeight=new Z(n,()=>this.calculatedHeight,"autoHeight"),this.initHorizontal(),this.initVertical(),this.initColumns(),this.initEnabled()}getProp(t,e){var s,o;let n=this.style[e];return!n&&Yn(e)&&this.pageMasterInstance instanceof an&&(e==="font-size"&&t.isRelativeRootFontSize&&t.rootFontSize?n=new P(t.rootFontSize,"px"):n=(o=((s=t.styler)==null?void 0:s.rootStyle)[e])==null?void 0:o.value),n&&(n=xi(t,n,e)),n}getPropAsNumber(t,e){var s,o;let n=this.style[e];if(n){let i=/\b(height|top|bottom)\b/.test(e)?(s=t.pageAreaHeight)!=null?s:t.pageHeight():(o=t.pageAreaWidth)!=null?o:t.pageWidth();n=xi(t,n,e,i)}return ke(n,t)}getSpecial(t,e){let n=zu(this.cascaded,e);if(n){let s=[];for(let o=0;o<n.length;o++){let i=n[o].evaluate(t,"");i&&i!==O&&s.push(i)}if(s.length)return s}return null}getActiveRegions(t){let e=this.getSpecial(t,"region-id");if(e){let n=[];for(let s=0;s<e.length;s++)n[s]=e[s].toString();return n}return null}propagateProperty(t,e,n,s){this.propagatePropertyToElement(t,e.element,n,s)}propagatePropertyToElement(t,e,n,s){let o=this.getProp(t,n);o&&(o.isNumeric()&&Nr(o.unit)&&(o=wr(o,t)),n==="font-family"&&(o=s.filterFontFamily(o)),(n.startsWith("background")||n==="z-index")&&e.parentElement.hasAttribute("data-vivliostyle-bleed-box")&&(e=e.parentElement),T(e,n,o.toString()))}propagateDelayedProperty(t,e,n,s){let o=this.getProp(t,n);o&&s.push(new _n(e.element,n,o))}assignLeftPosition(t,e){let n=this.getPropAsNumber(t,"left"),s=this.getPropAsNumber(t,"margin-left"),o=this.getPropAsNumber(t,"padding-left"),i=this.getPropAsNumber(t,"border-left-width"),a=this.getPropAsNumber(t,"width");e.setHorizontalPosition(n,a),T(e.element,"margin-left",`${s}px`),T(e.element,"padding-left",`${o}px`),T(e.element,"border-left-width",`${i}px`),e.marginLeft=s,e.borderLeft=i,e.paddingLeft=o}assignRightPosition(t,e){let n=this.getPropAsNumber(t,"right"),s=this.getPropAsNumber(t,"snap-height"),o=this.getPropAsNumber(t,"margin-right"),i=this.getPropAsNumber(t,"padding-right"),a=this.getPropAsNumber(t,"border-right-width");if(T(e.element,"margin-right",`${o}px`),T(e.element,"padding-right",`${i}px`),T(e.element,"border-right-width",`${a}px`),e.marginRight=o,e.borderRight=a,this.vertical&&s>0){let l=n+e.getInsetRight(),c=l-Math.floor(l/s)*s;c>0&&(e.snapOffsetX=s-c,i+=e.snapOffsetX)}e.paddingRight=i,e.snapWidth=s}assignTopPosition(t,e){let n=this.getPropAsNumber(t,"snap-height"),s=this.getPropAsNumber(t,"top"),o=this.getPropAsNumber(t,"margin-top"),i=this.getPropAsNumber(t,"padding-top"),a=this.getPropAsNumber(t,"border-top-width");if(e.top=s,e.marginTop=o,e.borderTop=a,e.snapHeight=n,!this.vertical&&n>0){let l=s+e.getInsetTop(),c=l-Math.floor(l/n)*n;c>0&&(e.snapOffsetY=n-c,i+=e.snapOffsetY)}e.paddingTop=i,T(e.element,"top",`${s}px`),T(e.element,"margin-top",`${o}px`),T(e.element,"padding-top",`${i}px`),T(e.element,"border-top-width",`${a}px`)}assignBottomPosition(t,e){let n=this.getPropAsNumber(t,"margin-bottom"),s=this.getPropAsNumber(t,"padding-bottom"),o=this.getPropAsNumber(t,"border-bottom-width"),i=this.getPropAsNumber(t,"height")-e.snapOffsetY;T(e.element,"height",`${i}px`),T(e.element,"margin-bottom",`${n}px`),T(e.element,"padding-bottom",`${s}px`),T(e.element,"border-bottom-width",`${o}px`),e.height=i-e.snapOffsetY,e.marginBottom=n,e.borderBottom=o,e.paddingBottom=s}assignBeforePosition(t,e){this.vertical?this.assignRightPosition(t,e):this.assignTopPosition(t,e)}assignAfterPosition(t,e){this.vertical?this.assignLeftPosition(t,e):this.assignBottomPosition(t,e)}assignStartEndPosition(t,e){this.vertical?(this.assignTopPosition(t,e),this.assignBottomPosition(t,e)):(this.assignRightPosition(t,e),this.assignLeftPosition(t,e))}sizeWithMaxHeight(t,e){T(e.element,"border-top-width","0px");let n=this.getPropAsNumber(t,"max-height");this.isTopDependentOnAutoHeight?e.setVerticalPosition(0,n):(this.assignTopPosition(t,e),n-=e.snapOffsetY,e.height=n,T(e.element,"height",`${n}px`))}sizeWithMaxWidth(t,e){T(e.element,"border-left-width","0px");let n=this.getPropAsNumber(t,"max-width");if(this.isRightDependentOnAutoWidth)e.setHorizontalPosition(0,n);else{this.assignRightPosition(t,e),n-=e.snapOffsetX,e.width=n;let s=this.getPropAsNumber(t,"right");T(e.element,"right",`${s}px`),T(e.element,"width",`${n}px`)}}prepareContainer(t,e,n,s,o){(!this.parentInstance||this.vertical!=this.parentInstance.vertical)&&T(e.element,"writing-mode",this.vertical?"vertical-rl":"horizontal-tb"),(!this.parentInstance||this.rtl!=this.parentInstance.rtl)&&T(e.element,"direction",this.rtl?"rtl":"ltr"),(this.vertical?this.isAutoWidth:this.isAutoHeight)?this.vertical?this.sizeWithMaxWidth(t,e):this.sizeWithMaxHeight(t,e):(this.assignBeforePosition(t,e),this.assignAfterPosition(t,e)),(this.vertical?this.isAutoHeight:this.isAutoWidth)?this.vertical?this.sizeWithMaxHeight(t,e):this.sizeWithMaxWidth(t,e):this.assignStartEndPosition(t,e);for(let i=0;i<sg.length;i++)this.propagateProperty(t,e,sg[i],s)}transferContentProps(t,e,n,s){for(let o=0;o<ig.length;o++)this.propagateProperty(t,e,ig[o],s);if(this.style["text-overflow"]){let o=e.element.firstElementChild;T(o,"text-overflow","inherit"),T(o,"overflow","inherit")}}transferSingleUriContentProps(t,e,n){let s=()=>{var a,l;let i=(l=(a=this.cascaded.width)!=null?a:this.cascaded[this.vertical?"block-size":"inline-size"])==null?void 0:l.value;return!!i&&i!==b.auto&&!U(i)},o=()=>{var a,l;let i=(l=(a=this.cascaded.height)!=null?a:this.cascaded[this.vertical?"inline-size":"block-size"])==null?void 0:l.value;return!!i&&i!==b.auto&&!U(i)};for(let i=0;i<rg.length;i++){let a=rg[i];if(a==="width"||a==="height"){if(a==="width"&&!s()||a==="height"&&!o())continue;T(e,a,"100%");continue}this.propagatePropertyToElement(t,e,a,n)}}finishContainer(t,e,n,s,o,i,a){this.vertical?this.calculatedWidth=e.computedBlockSize+e.snapOffsetX:this.calculatedHeight=e.computedBlockSize+e.snapOffsetY;let l=(this.vertical||!s)&&this.isAutoHeight,c=(!this.vertical||!s)&&this.isAutoWidth,u=null;if((c||l)&&(c&&T(e.element,"width","auto"),l&&T(e.element,"height","auto"),u=i.getElementClientRect(s?s.element:e.element),c&&(this.calculatedWidth=Math.ceil(u.right-u.left-e.paddingLeft-e.borderLeft-e.paddingRight-e.borderRight),this.vertical&&(this.calculatedWidth+=e.snapOffsetX)),l&&(this.calculatedHeight=u.bottom-u.top-e.paddingTop-e.borderTop-e.paddingBottom-e.borderBottom,this.vertical||(this.calculatedHeight+=e.snapOffsetY))),(this.vertical?this.isAutoHeight:this.isAutoWidth)&&this.assignStartEndPosition(t,e),(this.vertical?this.isAutoWidth:this.isAutoHeight)&&((this.vertical?this.isRightDependentOnAutoWidth:this.isTopDependentOnAutoHeight)&&this.assignBeforePosition(t,e),this.assignAfterPosition(t,e)),o>1){let d=this.getPropAsNumber(t,"column-rule-width"),h=this.getProp(t,"column-rule-style"),f=this.getProp(t,"column-rule-color");if(d>0&&h&&h!=b.none&&f!=b.transparent){let g=this.getPropAsNumber(t,"column-gap"),m=this.vertical?e.height:e.width,y=this.vertical?"border-top":"border-left";for(let E=1;E<o;E++){let C=this.vertical?(m+g)*E/o-g/2+e.paddingTop-d/2:(m+g)*E/o-g/2+e.paddingLeft-d/2,x=this.vertical?e.width+e.paddingLeft+e.paddingRight:e.height+e.paddingTop+e.paddingBottom,N=e.element.ownerDocument.createElement("div");T(N,"position","absolute"),T(N,this.vertical?"left":"top","0px"),T(N,this.vertical?"top":"left",`${C}px`),T(N,this.vertical?"height":"width","0px"),T(N,this.vertical?"width":"height",`${x}px`),T(N,y,`${d}px ${h.toString()}${f?` ${f.toString()}`:""}`),e.element.insertBefore(N,e.element.firstChild)}}}for(let d=0;d<og.length;d++)this.propagateProperty(t,e,og[d],a);for(let d=0;d<ag.length;d++)this.propagateDelayedProperty(t,e,ag[d],n.delayedItems)}applyCascadeAndInit(t,e){let n=this.cascaded,s=this.pageBox.specified;for(let i in s)this instanceof an&&this.pageBox.pseudoName=="vivliostyle-page-rule-master"&&(i==="writing-mode"||i==="direction")||As(i)&&xn(n,i,pe(s,i));if(this.pageBox.pseudoName==Oi)for(let i in e)(i.match(/^background-/)||i=="writing-mode")&&(n[i]=e[i]);if(this.pageBox.pseudoName=="layout-host")for(let i in e)!i.match(/^background-/)&&i!="writing-mode"&&(n[i]=e[i]);t.pushRule(this.pageBox.classes,null,n);let o=n.content;o&&(n.content=o.filterValue(new vo(t,null,t.counterResolver))),this.init(t.context);for(let i of this.pageBox.children)i.createInstance(this).applyCascadeAndInit(t,e);t.popRule()}resolveAutoSizing(t){this.isAutoWidth&&(this.isRightDependentOnAutoWidth=this.depends("right",this.autoWidth,t)||this.depends("margin-right",this.autoWidth,t)||this.depends("border-right-width",this.autoWidth,t)||this.depends("padding-right",this.autoWidth,t)),this.isAutoHeight&&(this.isTopDependentOnAutoHeight=this.depends("top",this.autoHeight,t)||this.depends("margin-top",this.autoHeight,t)||this.depends("border-top-width",this.autoHeight,t)||this.depends("padding-top",this.autoHeight,t));for(let e of this.children)e.resolveAutoSizing(t)}},sg=["border-left-style","border-right-style","border-top-style","border-bottom-style","border-left-color","border-right-color","border-top-color","border-bottom-color","box-sizing","outline-style","outline-color","outline-width","overflow","visibility"],og=["border-top-left-radius","border-top-right-radius","border-bottom-right-radius","border-bottom-left-radius","border-start-start-radius","border-start-end-radius","border-end-start-radius","border-end-end-radius","border-image-source","border-image-slice","border-image-width","border-image-outset","border-image-repeat","background-attachment","background-color","background-image","background-repeat","background-position","background-clip","background-origin","background-size","box-shadow","opacity","z-index","background-blend-mode","isolation","mix-blend-mode","filter"],ig=["color","font-family","font-size","font-style","font-weight","line-height","letter-spacing","text-align","text-align-last","text-decoration","text-indent","text-transform","white-space","text-wrap","text-wrap-mode","text-wrap-style","word-spacing","font-feature-settings","font-kerning","font-size-adjust","font-variant-ligatures","font-variant-caps","font-variant-numeric","font-variant-east-asian","font-stretch","text-combine-upright","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-fill-color","text-orientation","text-shadow","text-stroke-color","text-stroke-width","text-underline-offset","text-underline-position","text-overflow"],rg=["width","height","image-resolution","object-fit","object-position"],ag=["transform","transform-origin"],Oi="background-host",za=class extends Vo{constructor(t){super(null,t)}applyCascadeAndInit(t,e){super.applyCascadeAndInit(t,e),this.children.sort((s,o)=>o.pageBox.specificity-s.pageBox.specificity||s.pageBox.index-o.pageBox.index)}},Us=class extends Vo{constructor(t,e){super(t,e),this.pageMasterInstance=this}boxSpecificEnabled(t){let e=this.pageBox.pageMaster;return e.condition&&(t=tt(e.scope,t,e.condition)),t}adjustPageLayout(t,e,n){}},Xd=class extends Vo{constructor(t,e){super(t,e),this.pageMasterInstance=t.pageMasterInstance}},rn=class extends Vo{constructor(t,e){super(t,e),this.pageMasterInstance=t.pageMasterInstance}processPartitionList(t,e,n){let s=null;if(e instanceof be&&(s=[e]),e instanceof ge&&(s=e.values),s){let o=this.pageBox.scope;for(let i=0;i<s.length;i++)if(s[i]instanceof be){let a=jo(s[i].name,"enabled"),l=new ee(o,a);n&&(l=new Ct(o,l)),t=tt(o,t,l)}}return t}boxSpecificEnabled(t){let e=this.pageBox.scope,n=this.style,s=lg(e,n.required,e._false)!==e._false;if(s||this.isAutoHeight){let o=eb(e,n["flow-from"],"body"),i=new un(e,"has-content",[o]);t=tt(e,t,i)}if(t=this.processPartitionList(t,n["required-partitions"],!1),t=this.processPartitionList(t,n["conflicting-partitions"],!0),s){let o=this.pageMasterInstance.style.enabled,i=o?o.toExpr(e,null):e._true;i=tt(e,i,t),this.pageMasterInstance.style.enabled=new B(i)}return t}prepareContainer(t,e,n,s,o){var i;this.pageBox.pageMaster instanceof Di||(T(e.element,"overflow","hidden"),e.element.setAttribute("data-vivliostyle-page-partition",(i=this.pageBox.name)!=null?i:"")),super.prepareContainer(t,e,n,s,o)}},Bi=class extends Jt{constructor(e,n,s,o){super(e,n,!1);this.target=s;this.validatorSet=o}property(e,n,s){this.validatorSet.validatePropertyAndHandleShorthand(e,n,s,this)}unknownProperty(e,n){this.report(`E_INVALID_PROPERTY ${e}: ${n.toString()}`)}invalidPropertyValue(e,n){this.report(`E_INVALID_PROPERTY_VALUE ${e}: ${n.toString()}`)}simpleProperty(e,n,s){this.target.specified[e]=new H(n,s?Mr:_r)}},Ga=class extends Bi{constructor(t,e,n,s){super(t,e,n,s)}},jd=class r extends Bi{constructor(t,e,n,s){super(t,e,n,s),n.specified.width=new H(zl,0),n.specified.height=new H(zl,0)}startPartitionRule(t,e,n){let s=new Jn(this.scope,t,e,n,this.target),o=new Ga(this.scope,this.owner,s,this.validatorSet);this.owner.pushHandler(o)}startPartitionGroupRule(t,e,n){let s=new Ha(this.scope,t,e,n,this.target),o=new r(this.scope,this.owner,s,this.validatorSet);this.owner.pushHandler(o)}},Wa=class extends Bi{constructor(t,e,n,s){super(t,e,n,s)}startPartitionRule(t,e,n){let s=new Jn(this.scope,t,e,n,this.target),o=new Ga(this.scope,this.owner,s,this.validatorSet);this.owner.pushHandler(o)}startPartitionGroupRule(t,e,n){let s=new Ha(this.scope,t,e,n,this.target),o=new jd(this.scope,this.owner,s,this.validatorSet);this.owner.pushHandler(o)}};function pp(r){var n,s;let t=(n=r["writing-mode"])==null?void 0:n.value,e=(s=r.direction)==null?void 0:s.value;return t===b.vertical_lr||t!==b.vertical_rl&&e!==b.rtl?"ltr":"rtl"}var nb={a10:{width:new P(26,"mm"),height:new P(37,"mm")},a9:{width:new P(37,"mm"),height:new P(52,"mm")},a8:{width:new P(52,"mm"),height:new P(74,"mm")},a7:{width:new P(74,"mm"),height:new P(105,"mm")},a6:{width:new P(105,"mm"),height:new P(148,"mm")},a5:{width:new P(148,"mm"),height:new P(210,"mm")},a4:{width:new P(210,"mm"),height:new P(297,"mm")},a3:{width:new P(297,"mm"),height:new P(420,"mm")},a2:{width:new P(420,"mm"),height:new P(594,"mm")},a1:{width:new P(594,"mm"),height:new P(841,"mm")},a0:{width:new P(841,"mm"),height:new P(1189,"mm")},b10:{width:new P(31,"mm"),height:new P(44,"mm")},b9:{width:new P(44,"mm"),height:new P(62,"mm")},b8:{width:new P(62,"mm"),height:new P(88,"mm")},b7:{width:new P(88,"mm"),height:new P(125,"mm")},b6:{width:new P(125,"mm"),height:new P(176,"mm")},b5:{width:new P(176,"mm"),height:new P(250,"mm")},b4:{width:new P(250,"mm"),height:new P(353,"mm")},b3:{width:new P(353,"mm"),height:new P(500,"mm")},b2:{width:new P(500,"mm"),height:new P(707,"mm")},b1:{width:new P(707,"mm"),height:new P(1e3,"mm")},b0:{width:new P(1e3,"mm"),height:new P(1414,"mm")},c10:{width:new P(28,"mm"),height:new P(40,"mm")},c9:{width:new P(40,"mm"),height:new P(57,"mm")},c8:{width:new P(57,"mm"),height:new P(81,"mm")},c7:{width:new P(81,"mm"),height:new P(114,"mm")},c6:{width:new P(114,"mm"),height:new P(162,"mm")},c5:{width:new P(162,"mm"),height:new P(229,"mm")},c4:{width:new P(229,"mm"),height:new P(324,"mm")},c3:{width:new P(324,"mm"),height:new P(458,"mm")},c2:{width:new P(458,"mm"),height:new P(648,"mm")},c1:{width:new P(648,"mm"),height:new P(917,"mm")},c0:{width:new P(917,"mm"),height:new P(1297,"mm")},"jis-b10":{width:new P(32,"mm"),height:new P(45,"mm")},"jis-b9":{width:new P(45,"mm"),height:new P(64,"mm")},"jis-b8":{width:new P(64,"mm"),height:new P(91,"mm")},"jis-b7":{width:new P(91,"mm"),height:new P(128,"mm")},"jis-b6":{width:new P(128,"mm"),height:new P(182,"mm")},"jis-b5":{width:new P(182,"mm"),height:new P(257,"mm")},"jis-b4":{width:new P(257,"mm"),height:new P(364,"mm")},"jis-b3":{width:new P(364,"mm"),height:new P(515,"mm")},"jis-b2":{width:new P(515,"mm"),height:new P(728,"mm")},"jis-b1":{width:new P(728,"mm"),height:new P(1030,"mm")},"jis-b0":{width:new P(1030,"mm"),height:new P(1456,"mm")},letter:{width:new P(8.5,"in"),height:new P(11,"in")},legal:{width:new P(8.5,"in"),height:new P(14,"in")},ledger:{width:new P(11,"in"),height:new P(17,"in")}},sb=new P(.24,"pt"),ay=new P(3,"mm"),ob=new P(10,"mm"),ib=new P(13,"mm");function Gi(r){let t={width:Rn,height:In,bleed:ne,bleedOffset:ne,cropOffset:ne},e=r.size;if(!(!e||e.value===b.auto)){let c=e.value,u,d;if(c.isSpaceList()?(u=c.values[0],d=c.values[1]):(u=c,d=null),u.isNumeric())t.width=u,t.height=d||u;else{let h=u.name&&nb[u.name.toLowerCase()];h&&(d&&d===b.landscape?(t.width=h.height,t.height=h.width):(t.width=h.width,t.height=h.height))}}let n=r.marks,s=r.bleed,o=n&&!U(n.value)?n.value:b.none,i=s&&!U(s.value)?s.value:b.auto;if(i===b.auto){if(o!==b.none){let c=!1;o.isSpaceList()?c=o.values.some(u=>u===b.crop):c=o===b.crop,c&&(t.bleed=new P(6,"pt"))}}else i.isNumeric()&&(t.bleed=i);let a=r["crop-offset"],l=a&&!U(a.value)?a.value:b.auto;return l===b.auto?o!==b.none&&(t.bleedOffset=ib):l.isNumeric()&&(t.cropOffset=l),t}function hp(r,t){let e={},n=Math.max(0,r.bleed.num)*t.queryUnitSize(r.bleed.unit,!1),s=!r.cropOffset.num&&r.bleedOffset.num?r.bleedOffset.num*t.queryUnitSize(r.bleedOffset.unit,!1):Math.max(0,r.cropOffset.num*t.queryUnitSize(r.cropOffset.unit,!1)-n),o=n+s,i=r.width;i===Rn?t.pref.defaultPaperSize?e.pageWidth=t.pref.defaultPaperSize.width*t.queryUnitSize("px",!1):e.pageWidth=(t.pref.spreadView?Math.floor(t.viewportWidth/2)-t.pref.pageBorder:t.viewportWidth)-o*2:e.pageWidth=i.num*t.queryUnitSize(i.unit,!1);let a=r.height;return a===In?t.pref.defaultPaperSize?e.pageHeight=t.pref.defaultPaperSize.height*t.queryUnitSize("px",!1):e.pageHeight=t.viewportHeight-o*2:e.pageHeight=a.num*t.queryUnitSize(a.unit,!1),e.bleed=n,e.bleedOffset=s,e.cropOffset=o,e}function ug(r,t,e){let n=r.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",t),n.setAttribute("height",e),n.style.position="absolute",n}function Mi(r,t,e,n){n=n||"polyline";let s=r.createElementNS("http://www.w3.org/2000/svg",n);return s.setAttribute("stroke",e===b.auto?"#010101":e.toString()),s.setAttribute("stroke-width",t),s.setAttribute("fill","none"),s}var qd=(s=>(s.TOP_LEFT="top left",s.TOP_RIGHT="top right",s.BOTTOM_LEFT="bottom left",s.BOTTOM_RIGHT="bottom right",s))(qd||{});function rb(r,t,e,n,s,o,i){let a=s;a<=o+2*Y.mm&&(a=o+s/2);let l=Math.max(s,a),c=o+l+e/2,u=ug(r,c,c),d=[[0,o+s],[s,o+s],[s,o+s-a]],h=d.map(m=>[m[1],m[0]]);(t==="top right"||t==="bottom right")&&(d=d.map(m=>[o+l-m[0],m[1]]),h=h.map(m=>[o+l-m[0],m[1]])),(t==="bottom left"||t==="bottom right")&&(d=d.map(m=>[m[0],o+l-m[1]]),h=h.map(m=>[m[0],o+l-m[1]]));let f=Mi(r,e,n);f.setAttribute("points",d.map(m=>m.join(",")).join(" ")),u.appendChild(f);let g=Mi(r,e,n);return g.setAttribute("points",h.map(m=>m.join(",")).join(" ")),u.appendChild(g),t.split(" ").forEach(m=>{u.style[m]=`${i}px`}),u}var _i=(s=>(s.TOP="top",s.BOTTOM="bottom",s.LEFT="left",s.RIGHT="right",s))(_i||{});function ab(r,t,e,n,s,o){let i=s*2,a,l;t==="top"||t==="bottom"?(a=i,l=s):(a=s,l=i);let c=ug(r,a,l),u=Mi(r,e,n);u.setAttribute("points",`0,${l/2} ${a},${l/2}`),c.appendChild(u);let d=Mi(r,e,n);d.setAttribute("points",`${a/2},0 ${a/2},${l}`),c.appendChild(d);let h=Mi(r,e,n,"circle");h.setAttribute("cx",a/2),h.setAttribute("cy",l/2),h.setAttribute("r",s/4),c.appendChild(h);let f;switch(t){case"top":f="bottom";break;case"bottom":f="top";break;case"left":f="right";break;case"right":f="left";break}return Object.keys(_i).forEach(g=>{let m=_i[g];m===t?c.style[m]=`${o}px`:m!==f&&(c.style[m]="0",c.style[`margin-${m}`]="auto")}),c}function dg(r,t,e,n){let s=!1,o=!1,i=r.marks;if(i){let m=i.value;m instanceof q?m.values.forEach(y=>{y===b.crop?s=!0:y===b.cross&&(o=!0)}):m===b.crop?s=!0:m===b.cross&&(o=!0)}let a=t.bleed;if(!s&&!o)return;let l=e.container,c=l.ownerDocument;let u=ke(sb,n),d=Math.max(0,t.bleedOffset-ke(ob,n)),h=t.bleedOffset-d,f=r["crop-marks-line-color"],g=f&&!U(f.value)?f.value:b.auto;s&&Object.keys(qd).forEach(m=>{let y=qd[m],E=rb(c,y,u,g,h,a,d);l.appendChild(E)}),o&&Object.keys(_i).forEach(m=>{let y=_i[m],E=ab(c,y,u,g,h,d);l.appendChild(E)})}var Kd=(()=>{let r=["left","right","top","bottom","before","after","start","end","block-start","block-end","inline-start","inline-end","inside","outside"],t={width:!0,height:!0,"block-size":!0,"inline-size":!0,margin:!0,padding:!0,border:!0,outline:!0,"outline-width":!0,"outline-style":!0,"outline-color":!0,"border-radius":!0,"border-top-left-radius":!0,"border-top-right-radius":!0,"border-bottom-right-radius":!0,"border-bottom-left-radius":!0,"border-start-start-radius":!0,"border-start-end-radius":!0,"border-end-start-radius":!0,"border-end-end-radius":!0,"box-shadow":!0,"box-sizing":!0};return r.forEach(e=>{t[`margin-${e}`]=!0,t[`padding-${e}`]=!0,t[`border-${e}-width`]=!0,t[`border-${e}-style`]=!0,t[`border-${e}-color`]=!0}),t})();var fp={"top-left-corner":{order:1,isInTopRow:!0,isInBottomRow:!1,isInLeftColumn:!0,isInRightColumn:!1,positionAlongVariableDimension:null},"top-left":{order:2,isInTopRow:!0,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:"start"},"top-center":{order:3,isInTopRow:!0,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:"center"},"top-right":{order:4,isInTopRow:!0,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:"end"},"top-right-corner":{order:5,isInTopRow:!0,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!0,positionAlongVariableDimension:null},"right-top":{order:6,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!0,positionAlongVariableDimension:"start"},"right-middle":{order:7,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!0,positionAlongVariableDimension:"center"},"right-bottom":{order:8,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!0,positionAlongVariableDimension:"end"},"bottom-right-corner":{order:9,isInTopRow:!1,isInBottomRow:!0,isInLeftColumn:!1,isInRightColumn:!0,positionAlongVariableDimension:null},"bottom-right":{order:10,isInTopRow:!1,isInBottomRow:!0,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:"end"},"bottom-center":{order:11,isInTopRow:!1,isInBottomRow:!0,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:"center"},"bottom-left":{order:12,isInTopRow:!1,isInBottomRow:!0,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:"start"},"bottom-left-corner":{order:13,isInTopRow:!1,isInBottomRow:!0,isInLeftColumn:!0,isInRightColumn:!1,positionAlongVariableDimension:null},"left-bottom":{order:14,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!0,isInRightColumn:!1,positionAlongVariableDimension:"end"},"left-middle":{order:15,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!0,isInRightColumn:!1,positionAlongVariableDimension:"center"},"left-top":{order:16,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!0,isInRightColumn:!1,positionAlongVariableDimension:"start"}},lb=(()=>{let r=fp;return Object.keys(r).sort((t,e)=>r[t].order-r[e].order)})(),Ya="vivliostyle-page-rule-master",Ui="_marginBoxes",Di=class extends Io{constructor(e,n,s){super(e,null,Ya,[],n,null,0);p(this,"pageMarginBoxes",{});let o=Gi(s),i=new Zd(this.scope,this,s,o);this.createPageMarginBoxes(s),this.applySpecified(s,o)}createPageMarginBoxes(e){let n=e[Ui];n&&lb.forEach(s=>{n[s]&&(this.pageMarginBoxes[s]=new Jd(this.scope,this,s,e))})}applySpecified(e,n){this.specified.position=new H(b.relative,0),this.specified.width=new H(n.width,0),this.specified.height=new H(n.height,0);for(let s in e)!Kd[s]&&s!=="background-clip"&&(this.specified[s]=e[s])}createInstance(e){return new an(e,this)}},Zd=class extends Jn{constructor(e,n,s,o){super(e,null,null,[],n);this.pageSize=o;let i=new Qd(this.scope,this);this.applySpecified(s)}applySpecified(e){this.specified["wrap-flow"]=new H(b.auto,0),this.specified["z-index"]=new H(new ut(0),0),this.specified.position=new H(b.absolute,0),this.specified.overflow=new H(b.visible,0);for(let n in Kd)Kd.hasOwnProperty(n)&&(this.specified[n]=e[n])}createInstance(e){return new tp(e,this)}},Qd=class extends Jn{constructor(t,e){super(t,null,null,[],e),this.specified["flow-from"]=new H(L("body"),0)}createInstance(t){return new Hi(t,this)}},Jd=class extends Jn{constructor(e,n,s,o){super(e,null,null,[],n);this.marginBoxName=s;this.applySpecified(o)}applySpecified(e){let n=e[Ui][this.marginBoxName];for(let s in e){let o=e[s],i=n[s];(_u[s]||i&&i.value===b.inherit)&&(this.specified[s]=o)}for(let s in n)if(Object.prototype.hasOwnProperty.call(n,s)){let o=n[s];o&&o.value!==O&&o.value!==b.inherit&&o.value!==b.unset&&o.value!==b.revert&&(this.specified[s]=o)}}createInstance(e){return new zi(e,this)}},an=class extends Us{constructor(e,n){super(e,n);p(this,"pageAreaDimension",null);p(this,"pageMarginBoxInstances",{})}applyCascadeAndInit(e,n){let s=this.cascaded;for(let o in n)if(Object.prototype.hasOwnProperty.call(n,o))switch(o){case"writing-mode":case"direction":s[o]=n[o]}super.applyCascadeAndInit(e,n)}initHorizontal(){let e=this.style;e.left=ne,e["margin-left"]=ne,e["border-left-width"]=ne,e["padding-left"]=ne,e["padding-right"]=ne,e["border-right-width"]=ne,e["margin-right"]=ne,e.right=ne}initVertical(){let e=this.style;e.top=ne,e["margin-top"]=ne,e["border-top-width"]=ne,e["padding-top"]=ne,e["padding-bottom"]=ne,e["border-bottom-width"]=ne,e["margin-bottom"]=ne,e.bottom=ne}setPageAreaDimension(e){this.pageAreaDimension=e;let n=this.style;n.width=new B(e.borderBoxWidth),n.height=new B(e.borderBoxHeight),n["padding-left"]=new B(e.marginLeft),n["padding-right"]=new B(e.marginRight),n["padding-top"]=new B(e.marginTop),n["padding-bottom"]=new B(e.marginBottom)}adjustPageLayout(e,n,s){let o=n.marginBoxes,i={start:this.pageAreaDimension.marginLeft,end:this.pageAreaDimension.marginRight,extent:this.pageAreaDimension.borderBoxWidth},a={start:this.pageAreaDimension.marginTop,end:this.pageAreaDimension.marginBottom,extent:this.pageAreaDimension.borderBoxHeight};this.sizeMarginBoxesAlongVariableDimension(o.top,!0,i,e,s),this.sizeMarginBoxesAlongVariableDimension(o.bottom,!0,i,e,s),this.sizeMarginBoxesAlongVariableDimension(o.left,!1,a,e,s),this.sizeMarginBoxesAlongVariableDimension(o.right,!1,a,e,s)}sizeMarginBoxesAlongVariableDimension(e,n,s,o,i){let a="start",l="center",c="end",u=this.pageBox.scope,d={},h={},f={};for(let S in e){let w=fp[S];if(w){let k=e[S],R=this.pageMarginBoxInstances[S],G=new Fo(k,R.style,n,u,i);d[w.positionAlongVariableDimension]=k,h[w.positionAlongVariableDimension]=R,f[w.positionAlongVariableDimension]=G}}let g={start:s.start.evaluate(o),end:s.end.evaluate(o),extent:s.extent.evaluate(o)},m=this.getSizesOfMarginBoxesAlongVariableDimension(f,g.extent),y=!1,E={};Object.keys(d).forEach(S=>{let w=S,k=te(u,h[w].style[n?"max-width":"max-height"],s.extent);if(k){let R=k.evaluate(o);if(m[w]>R){let G=f[w]=new $a(d[w],h[w].style,n,u,i,R);E[w]=G.getOuterSize(),y=!0}}}),y&&(m=this.getSizesOfMarginBoxesAlongVariableDimension(f,g.extent),y=!1,[a,l,c].forEach(S=>{var w;m[S]=(w=E[S])!=null?w:m[S]}));let C={};Object.keys(d).forEach(S=>{let w=S,k=te(u,h[w].style[n?"min-width":"min-height"],s.extent);if(k){let R=k.evaluate(o);if(m[w]<R){let G=f[w]=new $a(d[w],h[w].style,n,u,i,R);C[w]=G.getOuterSize(),y=!0}}}),y&&(m=this.getSizesOfMarginBoxesAlongVariableDimension(f,g.extent),[a,l,c].forEach(S=>{m[S]=C[S]||m[S]}));let x=g.start+g.extent,N=g.start+(g.start+g.extent);[a,l,c].forEach(S=>{let w=m[S];if(w!=null){let k=d[S],R=0;switch(S){case a:R=n?k.left:k.top;break;case l:R=(N-w)/2;break;case c:R=x-w;break}n?k.setHorizontalPosition(R,w-k.getInsetLeft()-k.getInsetRight()):k.setVerticalPosition(R,w-k.getInsetTop()-k.getInsetBottom())}})}getSizesOfMarginBoxesAlongVariableDimension(e,n){var l;let s=e.start,o=e.center,i=e.end,a={};if(o){let c=[s,i],u=new ep(c),d=this.distributeAutoMarginBoxSizes(o,u,n);d.xSize!=null&&(a.center=d.xSize);let h=(l=d.xSize)!=null?l:o.getOuterSize(),f=Math.max((n-h)/2,0);s&&(a.start=s.hasAutoSize()?f:s.getOuterSize()),i&&(a.end=i.hasAutoSize()?f:i.getOuterSize())}else{let c=this.distributeAutoMarginBoxSizes(s,i,n);c.xSize!=null&&(a.start=c.xSize),c.ySize!=null&&(a.end=c.ySize)}return a}distributeAutoMarginBoxSizes(e,n,s){let o={xSize:null,ySize:null};if(e instanceof Fo&&e.minMaxFitContent&&(o.xSize=e.getOuterSize()),n instanceof Fo&&n.minMaxFitContent&&(o.ySize=n.getOuterSize()),e&&n)if(e.hasAutoSize()&&n.hasAutoSize()){let i=e.getOuterMaxContentSize(),a=n.getOuterMaxContentSize();if(i>0&&a>0){let l=i+a;if(l<s)o.xSize=s*i/l;else{let c=e.getOuterMinContentSize(),u=n.getOuterMinContentSize(),d=c+u;d<s?o.xSize=c+(s-d)*(i-c)/(l-d):d>0&&(o.xSize=s*c/d)}o.xSize>0&&(o.ySize=s-o.xSize)}else i>0?o.xSize=s:a>0&&(o.ySize=s)}else e.hasAutoSize()?o.xSize=Math.max(s-n.getOuterSize(),0):n.hasAutoSize()&&(o.ySize=Math.max(s-e.getOuterSize(),0));else e?e.hasAutoSize()&&(o.xSize=s):n&&n.hasAutoSize()&&(o.ySize=s);return o}prepareContainer(e,n,s,o,i){n.element.setAttribute("data-vivliostyle-page-box",!0),super.prepareContainer(e,n,s,o,i)}},Fo=class{constructor(t,e,n,s,o){this.container=t;this.isHorizontal=n;this.clientLayout=o;p(this,"hasAutoSize_");p(this,"size",null);p(this,"minMaxFitContent",null);let i=e[n?"width":"height"];if(this.hasAutoSize_=!i||i===b.auto||U(i),this.minMaxFitContent=i instanceof be&&(i.name==="min-content"||i.name==="max-content"||i.name==="fit-content")?i.name:null,this.minMaxFitContent){let a=this.getSize();if(this.isHorizontal){let l=a[this.minMaxFitContent==="min-content"?"min-content width":this.minMaxFitContent==="max-content"?"max-content width":"fit-content width"];this.container.setHorizontalPosition(this.container.left,l)}else{let l=a[this.minMaxFitContent==="min-content"?"min-content height":this.minMaxFitContent==="max-content"?"max-content height":"fit-content height"];this.container.setVerticalPosition(this.container.top,l)}}}hasAutoSize(){return this.hasAutoSize_}getSize(){if(!this.size){let t=this.isHorizontal?["max-content width","min-content width","fit-content width"]:["max-content height","min-content height","fit-content height"];this.size=uo(this.clientLayout,this.container.element,t)}return this.size}getOuterMaxContentSize(){let t=this.getSize();return this.isHorizontal?this.container.getInsetLeft()+t["max-content width"]+this.container.getInsetRight():this.container.getInsetTop()+t["max-content height"]+this.container.getInsetBottom()}getOuterMinContentSize(){let t=this.getSize();return this.isHorizontal?this.container.getInsetLeft()+t["min-content width"]+this.container.getInsetRight():this.container.getInsetTop()+t["min-content height"]+this.container.getInsetBottom()}getOuterSize(){return this.isHorizontal?this.container.getInsetLeft()+this.container.width+this.container.getInsetRight():this.container.getInsetTop()+this.container.height+this.container.getInsetBottom()}},ep=class{constructor(t){this.params=t}hasAutoSize(){return this.params.some(t=>{var e;return(e=t==null?void 0:t.hasAutoSize())!=null?e:!1})}getOuterMaxContentSize(){let t=this.params.map(e=>{var n;return(n=e==null?void 0:e.getOuterMaxContentSize())!=null?n:0});return Math.max.apply(null,t)*t.length}getOuterMinContentSize(){let t=this.params.map(e=>{var n;return(n=e==null?void 0:e.getOuterMinContentSize())!=null?n:0});return Math.max.apply(null,t)*t.length}getOuterSize(){let t=this.params.map(e=>{var n;return(n=e==null?void 0:e.getOuterSize())!=null?n:0});return Math.max.apply(null,t)*t.length}},$a=class extends Fo{constructor(e,n,s,o,i,a){super(e,n,s,o,i);p(this,"fixedSize");this.fixedSize=a}hasAutoSize(){return!1}getOuterMaxContentSize(){return this.getOuterSize()}getOuterMinContentSize(){return this.getOuterSize()}getOuterSize(){return this.isHorizontal?this.container.getInsetLeft()+this.fixedSize+this.container.getInsetRight():this.container.getInsetTop()+this.fixedSize+this.container.getInsetBottom()}},tp=class extends rn{constructor(e,n){super(e,n);p(this,"borderBoxWidth",null);p(this,"borderBoxHeight",null);p(this,"contentBoxWidth",null);p(this,"contentBoxHeight",null);p(this,"marginTop",null);p(this,"marginRight",null);p(this,"marginBottom",null);p(this,"marginLeft",null)}applyCascadeAndInit(e,n){for(let o in n)o.match(/^background-/)&&(this.cascaded[o]=n[o]);super.applyCascadeAndInit(e,n),this.parentInstance.setPageAreaDimension({borderBoxWidth:this.borderBoxWidth,borderBoxHeight:this.borderBoxHeight,marginTop:this.marginTop,marginRight:this.marginRight,marginBottom:this.marginBottom,marginLeft:this.marginLeft})}initHorizontal(){let e=this.resolvePageBoxDimensions({start:"left",end:"right",extent:"width"});this.borderBoxWidth=e.borderBoxExtent,this.contentBoxWidth=e.contentBoxExtent,this.marginLeft=e.marginStart,this.marginRight=e.marginEnd}initVertical(){let e=this.resolvePageBoxDimensions({start:"top",end:"bottom",extent:"height"});this.borderBoxHeight=e.borderBoxExtent,this.contentBoxHeight=e.contentBoxExtent,this.marginTop=e.marginStart,this.marginBottom=e.marginEnd}resolvePageBoxDimensions(e){let n=this.style,s=this.pageBox.pageSize,o=this.pageBox.scope,i=e.start,a=e.end,l=e.extent,c=s[l].toExpr(o,null),u=te(o,n[l],c),d=te(o,n[`margin-${i}`],c),h=te(o,n[`margin-${a}`],c),f=ot(o,n[`padding-${i}`],c),g=ot(o,n[`padding-${a}`],c),m=zt(o,n[`border-${i}-width`],n[`border-${i}-style`],c),y=zt(o,n[`border-${a}-width`],n[`border-${a}-style`],c),E=z(o,z(o,m,f),z(o,y,g)),C,x,N;return u?(this.borderBoxSizing?(x=u,N=K(o,x,E)):(N=u,x=z(o,N,E)),C=K(o,c,x),!d&&!h?(d=Qs(o,C,new ie(o,.5)),h=d):d?h=K(o,C,d):d=K(o,C,h)):(d||(d=o.zero),h||(h=o.zero),C=z(o,d,h),x=K(o,c,C),N=K(o,x,E),u=this.borderBoxSizing?x:N),n[i]=new B(d),n[a]=new B(h),n[`margin-${i}`]=ne,n[`margin-${a}`]=ne,n[`border-${i}-width`]=new B(m),n[`border-${a}-width`]=new B(y),n[`padding-${i}`]=new B(f),n[`padding-${a}`]=new B(g),n[l]=new B(u),n[`max-${l}`]=new B(u),{borderBoxExtent:x,contentBoxExtent:N,marginStart:d,marginEnd:h}}prepareContainer(e,n,s,o,i){n.element.setAttribute("data-vivliostyle-page-area-container",!0),super.prepareContainer(e,n,s,o,i),T(n.element,"position","relative"),T(n.element,"inset",""),T(n.element,"display","flow-root")}},Hi=class extends rn{constructor(t,e){super(t,e)}applyCascadeAndInit(t,e){for(let n in e)n.match(/^column.*$/)&&(this.cascaded[n]=e[n]);super.applyCascadeAndInit(t,{})}initHorizontal(){let t=this.style,e=this.parentInstance.style,n=this.pageBox.scope;t.left=e["padding-left"],t.width=new B(this.parentInstance.contentBoxWidth),t["margin-left"]=new B(new qt(n,e.left.toExpr(n,null))),t["margin-right"]=new B(new qt(n,e.right.toExpr(n,null))),t["border-left-width"]=e.left,t["border-right-width"]=e.right,t["border-left-style"]=b.solid,t["border-right-style"]=b.solid,t["border-left-color"]=b.transparent,t["border-right-color"]=b.transparent}initVertical(){let t=this.style,e=this.parentInstance.style,n=this.pageBox.scope;t.top=e["padding-top"],t.height=new B(this.parentInstance.contentBoxHeight),t["margin-top"]=new B(new qt(n,e.top.toExpr(n,null))),t["margin-bottom"]=new B(new qt(n,e.bottom.toExpr(n,null))),t["border-top-width"]=e.top,t["border-bottom-width"]=e.bottom,t["border-top-style"]=b.solid,t["border-bottom-style"]=b.solid,t["border-top-color"]=b.transparent,t["border-bottom-color"]=b.transparent}prepareContainer(t,e,n,s,o){e.element.setAttribute("data-vivliostyle-page-area",!0),n.pageAreaElement=e.element,super.prepareContainer(t,e,n,s,o),t.pageAreaWidth=parseFloat(n.pageAreaElement.style.width),t.pageAreaHeight=parseFloat(n.pageAreaElement.style.height),T(e.element,"position","relative"),T(e.element,"inset",""),T(e.element,"display","flow-root")}},zi=class extends rn{constructor(e,n){super(e,n);p(this,"boxInfo");p(this,"suppressEmptyBoxGeneration",!0);let s=n.marginBoxName;this.boxInfo=fp[s];let o=e;o.pageMarginBoxInstances[s]=this}prepareContainer(e,n,s,o,i){n.element.setAttribute("data-vivliostyle-page-margin-box",this.pageBox.marginBoxName),this.applyVerticalAlign(e,n.element),super.prepareContainer(e,n,s,o,i)}applyVerticalAlign(e,n){T(n,"display","flex"),T(n,"flex-flow",this.vertical?this.rtl?"row-reverse":"row":"column");let s=this.getProp(e,"vertical-align"),o=null;s===L("middle")?o="center":s===L("top")?o="flex-start":s===L("bottom")&&(o="flex-end"),o&&T(n,"justify-content",o);let i=this.getProp(e,"content");if(this.vertical||i instanceof Oe||i instanceof B&&i.expr instanceof Z&&i.expr.str.startsWith("running-element-")){let a="center";(this.boxInfo.isInTopRow||this.boxInfo.isInBottomRow)&&(this.boxInfo.isInLeftColumn||this.boxInfo.positionAlongVariableDimension==="end"?a=this.vertical||this.rtl?"start":"end":(this.boxInfo.isInRightColumn||this.boxInfo.positionAlongVariableDimension==="start")&&(a=this.vertical||this.rtl?"end":"start")),T(n,"align-items",a)}}positionAlongVariableDimension(e,n){let s=this.style,o=this.pageBox.scope,i=e.start,a=e.end,l=e.extent,c=i==="left",u=c?n.borderBoxWidth:n.borderBoxHeight,d=te(o,s[l],u),h=c?n.marginLeft:n.marginTop;if(this.boxInfo.positionAlongVariableDimension==="start")s[i]=new B(h);else if(d){let f=ot(o,s[`margin-${i}`],u),g=ot(o,s[`margin-${a}`],u),m=ot(o,s[`padding-${i}`],u),y=ot(o,s[`padding-${a}`],u),E=zt(o,s[`border-${i}-width`],s[`border-${i}-style`],u),C=zt(o,s[`border-${a}-width`],s[`border-${a}-style`],u),x=z(o,d,z(o,this.borderBoxSizing?o.zero:z(o,z(o,m,y),z(o,E,C)),z(o,f,g)));switch(this.boxInfo.positionAlongVariableDimension){case"center":s[i]=new B(z(o,h,Yo(o,K(o,u,x),new ie(o,2))));break;case"end":s[i]=new B(K(o,z(o,h,u),x));break}}}positionAndSizeAlongFixedDimension(e,n){let s=this.style,o=this.pageBox.scope,i=this.borderBoxSizing,a=e.inside,l=e.outside,c=e.extent,u=n[`margin${l.charAt(0).toUpperCase()}${l.substring(1)}`],d=Yd(o,s[`margin-${a}`],u),h=Yd(o,s[`margin-${l}`],u),f=ot(o,s[`padding-${a}`],u),g=ot(o,s[`padding-${l}`],u),m=zt(o,s[`border-${a}-width`],s[`border-${a}-style`],u),y=zt(o,s[`border-${l}-width`],s[`border-${l}-style`],u),E=te(o,s[c],u),C=null;function x(N){if(C)return C;C={extent:E?E.evaluate(N):null,marginInside:d?d.evaluate(N):null,marginOutside:h?h.evaluate(N):null};let S=u.evaluate(N),w=0;return i||[m,f,g,y].forEach(k=>{k&&(w+=k.evaluate(N))}),(C.marginInside===null||C.marginOutside===null)&&w+C.extent+C.marginInside+C.marginOutside>S&&(C.marginInside===null&&(C.marginInside=0),C.marginOutside===null&&(C.marginOutside=0)),C.extent!==null&&C.marginInside!==null&&C.marginOutside!==null&&(C.marginOutside=null),C.extent===null?(C.extent=S-w-C.marginInside-C.marginOutside,C.marginInside===null&&(C.marginInside=0),C.marginOutside===null&&(C.marginOutside=0)):typeof C.extent=="number"&&(C.marginInside===null&&typeof C.marginOutside=="number"?C.marginInside=S-w-C.extent-C.marginOutside:typeof C.marginInside=="number"&&C.marginOutside===null?C.marginOutside=S-w-C.extent-C.marginInside:C.marginInside=C.marginOutside=(S-w-C.extent)/2),C}s[c]=new B(new Z(o,function(){let N=x(this).extent;return N===null?"auto":N},c)),s[`margin-${a}`]=new B(new Z(o,function(){let N=x(this).marginInside;return N===null?"auto":N},`margin-${a}`)),s[`margin-${l}`]=new B(new Z(o,function(){let N=x(this).marginOutside;return N===null?"auto":N},`margin-${l}`)),a==="left"?s.left=new B(z(o,n.marginLeft,n.borderBoxWidth)):a==="top"&&(s.top=new B(z(o,n.marginTop,n.borderBoxHeight)))}initHorizontal(){let n=this.parentInstance.pageAreaDimension;this.boxInfo.isInLeftColumn?this.positionAndSizeAlongFixedDimension({inside:"right",outside:"left",extent:"width"},n):this.boxInfo.isInRightColumn?this.positionAndSizeAlongFixedDimension({inside:"left",outside:"right",extent:"width"},n):this.positionAlongVariableDimension({start:"left",end:"right",extent:"width"},n)}initVertical(){let n=this.parentInstance.pageAreaDimension;this.boxInfo.isInTopRow?this.positionAndSizeAlongFixedDimension({inside:"bottom",outside:"top",extent:"height"},n):this.boxInfo.isInBottomRow?this.positionAndSizeAlongFixedDimension({inside:"top",outside:"bottom",extent:"height"},n):this.positionAlongVariableDimension({start:"top",end:"bottom",extent:"height"},n)}finishContainer(e,n,s,o,i,a,l){super.finishContainer(e,n,s,o,i,a,l);let c=s.marginBoxes,u=this.pageBox.marginBoxName,d=this.boxInfo;!d.isInLeftColumn&&!d.isInRightColumn?d.isInTopRow?c.top[u]=n:d.isInBottomRow&&(c.bottom[u]=n):!d.isInTopRow&&!d.isInBottomRow&&(d.isInLeftColumn?c.left[u]=n:d.isInRightColumn&&(c.right[u]=n));let h=this.parentInstance.pageAreaDimension,f=this.getProp(e,"width"),g=f instanceof be&&(f.name==="min-content"||f.name==="max-content"||f.name==="fit-content")?f.name:null,m=this.getPropAsNumber(e,"min-width"),y=this.getPropAsNumber(e,"max-width");if(g||m||y){g&&T(n.element,"width",g),m&&T(n.element,"min-width",`${m}px`),y&&T(n.element,"max-width",`${y}px`);let S=this.getProp(e,"margin-left"),w=this.getProp(e,"margin-right");if(d.isInLeftColumn){let k=h.borderBoxWidth.evaluate(e)+h.marginRight.evaluate(e);T(n.element,"right",`${k}px`),(S===b.auto||w!==b.auto)&&T(n.element,"margin-left","auto"),w===b.auto&&T(n.element,"margin-right","auto")}else d.isInRightColumn&&(T(n.element,"right","0"),(w===b.auto||S!==b.auto)&&T(n.element,"margin-right","auto"),S===b.auto&&T(n.element,"margin-left","auto"))}let E=this.getProp(e,"height"),C=E instanceof be&&(E.name==="min-content"||E.name==="max-content"||E.name==="fit-content")?E.name:null,x=this.getPropAsNumber(e,"min-height"),N=this.getPropAsNumber(e,"max-height");if(C||x||N){C&&T(n.element,"height",C),x&&T(n.element,"min-height",`${x}px`),N&&T(n.element,"max-height",`${N}px`);let S=this.getProp(e,"margin-top"),w=this.getProp(e,"margin-bottom");if(d.isInTopRow){let k=h.borderBoxHeight.evaluate(e)+h.marginBottom.evaluate(e);T(n.element,"bottom",`${k}px`),(S===b.auto||w!==b.auto)&&T(n.element,"margin-top","auto"),w===b.auto&&T(n.element,"margin-bottom","auto")}else d.isInBottomRow&&(T(n.element,"bottom","0"),(w===b.auto||S!==b.auto)&&T(n.element,"margin-bottom","auto"),S===b.auto&&T(n.element,"margin-top","auto"))}}},Xa=class{constructor(t,e,n,s,o){this.cascadeInstance=t;this.pageScope=e;this.rootPageBoxInstance=n;this.context=s;this.docElementStyle=o;p(this,"pageMasterCache",{});this.definePageProgression()}definePageProgression(){let t=this.pageScope,e=this.context,n=e.isVersoFirstPage,s=new ee(t,"page-number"),o=new An(t,new Ks(t,s,new ie(t,2)),n?t.one:t.zero);t.defineName("recto-page",new Ct(t,o)),t.defineName("verso-page",o),(e.pageProgression||pp(this.docElementStyle))==="ltr"?(t.defineName("left-page",o),t.defineName("right-page",new Ct(t,o))):(t.defineName("left-page",new Ct(t,o)),t.defineName("right-page",o))}getCascadedPageStyle(t){let e={};return this.cascadeInstance.pushRule([],t,e),this.cascadeInstance.popRule(),e}getPageRulePageMaster(t,e){let n=t.pageBox;if(Object.keys(e).length===0)return n.resetScope(),t;let s=this.makeCacheKey(e,n),o=this.pageMasterCache[s];return o||(n.pseudoName===Oi?o=this.generatePageRuleMaster(e):o=this.generateCascadedPageMaster(e,n),this.pageMasterCache[s]=o),o.pageBox.resetScope(),o}makeCacheKey(t,e){var o;let n=this.makeCascadeValueObjectKey(t),s=((o=this.context.currentLayoutPosition)==null?void 0:o.page)%2;return`${e.key}^${n}^${s}`}makeCascadeValueObjectKey(t){let e=[];for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let s=t[n],o;s instanceof H?o=`${s.value}`:o=this.makeCascadeValueObjectKey(s),e.push(n+o+(s.priority||""))}return e.sort().join("^")}generatePageRuleMaster(t){let n=new Di(this.pageScope,this.rootPageBoxInstance.pageBox,t).createInstance(this.rootPageBoxInstance);return n.applyCascadeAndInit(this.cascadeInstance,this.docElementStyle),n.resolveAutoSizing(this.context),n}generateCascadedPageMaster(t,e){let n=e.clone({pseudoName:Ya}),s=n.specified,o=t.size;if(o&&!U(o.value)){let a=Gi(t),l=o.priority;on(s,"width",new H(a.width,l),this.context),on(s,"height",new H(a.height,l),this.context)}["counter-reset","counter-increment"].forEach(a=>{s[a]&&(t[a]=s[a])});let i=n.createInstance(this.rootPageBoxInstance);return i.applyCascadeAndInit(this.cascadeInstance,this.docElementStyle),i.resolveAutoSizing(this.context),i}},np=class extends Q{constructor(e){super();this.pageType=e}apply(e){e.currentPageType===this.pageType&&this.chained.apply(e)}getPriority(){return 3}makePrimary(e){return this.chained&&e.insertInTable(e.pagetypes,this.pageType,this.chained),!0}},sp=class extends Q{constructor(e){super();this.scope=e}apply(e){new ee(this.scope,"page-number").evaluate(e.context)===1&&this.chained.apply(e)}getPriority(){return 2}},op=class extends Q{constructor(e){super();this.scope=e}apply(e){new ee(this.scope,"blank-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 2}},ip=class extends Q{constructor(e){super();this.scope=e}apply(e){new ee(this.scope,"left-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},rp=class extends Q{constructor(e){super();this.scope=e}apply(e){new ee(this.scope,"right-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},ap=class extends Q{constructor(e){super();this.scope=e}apply(e){new ee(this.scope,"recto-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},lp=class extends Q{constructor(e){super();this.scope=e}apply(e){new ee(this.scope,"verso-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},cp=class extends jn{constructor(e,n,s){super(n,s);this.scope=e;this.a=n;this.b=s}apply(e){let n=e.context,s=n.layoutPositionAtPageStart.page;n.blankPageAtStart&&s--,s&&this.matchANPlusB(s)&&this.chained.apply(e)}getPriority(){return 2}},up=class extends Ls{constructor(t,e){super(t,e,null,null,null)}apply(t){cb(t.context,t.currentStyle,this.style,this.specificity,t)}};function cb(r,t,e,n,s){bi(r,t,e,n,null,null,null);let o=e[Ui];if(o){let i=wo(t,Ui);for(let a in o)if(o.hasOwnProperty(a)){let l=i[a];l||(l={},i[a]=l),bi(r,l,o[a],n,null,null,null)}}}var ja=class extends En{constructor(e,n,s,o,i){super(e,n,s==null?void 0:s.condition,s,null,o,!1);this.pageProps=i;p(this,"currentPageSelectors",[]);p(this,"currentNamedPageSelector","");p(this,"currentPseudoPageClassSelectors",[])}startPageRule(){this.startSelectorRule()}tagSelector(e,n){this.currentNamedPageSelector=n,n&&(this.chain.push(new np(n)),this.specificity+=65536)}pseudoclassSelector(e,n){if(e=e.toLowerCase(),n)switch(e){case"nth":{let[s,o]=n;this.currentPseudoPageClassSelectors.push(`:${e}(${s}n${o<0?o:"+"+o})`),this.chain.push(new cp(this.scope,s,o)),this.specificity+=256}break;default:this.reportAndSkip(`E_INVALID_PAGE_SELECTOR :${e}(${n.join("")})`);break}else switch(this.currentPseudoPageClassSelectors.push(`:${e}`),e){case"first":this.chain.push(new sp(this.scope)),this.specificity+=256;break;case"blank":this.chain.push(new op(this.scope)),this.specificity+=256;break;case"left":this.chain.push(new ip(this.scope)),this.specificity+=1;break;case"right":this.chain.push(new rp(this.scope)),this.specificity+=1;break;case"recto":this.chain.push(new ap(this.scope)),this.specificity+=1;break;case"verso":this.chain.push(new lp(this.scope)),this.specificity+=1;break;default:this.reportAndSkip(`E_INVALID_PAGE_SELECTOR :${e}`);break}}finishSelector(){let e;!this.currentNamedPageSelector&&!this.currentPseudoPageClassSelectors.length?e=null:e=[this.currentNamedPageSelector].concat(this.currentPseudoPageClassSelectors.sort()),this.currentPageSelectors.push({selectors:e,specificity:this.specificity}),this.currentNamedPageSelector="",this.currentPseudoPageClassSelectors=[]}nextSelector(){this.finishSelector(),super.nextSelector()}startRuleBody(){this.finishSelector(),super.startRuleBody()}simpleProperty(e,n,s){if((e==="bleed"||e==="marks")&&!this.currentPageSelectors.some(a=>a.selectors===null))return;super.simpleProperty(e,n,s);let o=pe(this.elementStyle,e),i=this.pageProps;if(e==="bleed"||e==="marks")i[""]||(i[""]={}),Object.keys(i).forEach(a=>{xn(i[a],e,o)});else if(e==="size"){let a=i[""];this.currentPageSelectors.forEach(l=>{let c=new H(o.value,o.priority+l.specificity),u=l.selectors?l.selectors.join(""):"",d=i[u];d?on(d,e,c):(d=i[u]={},xn(d,e,c),a&&["bleed","marks"].forEach(h=>{a[h]&&xn(d,h,a[h])}))})}}insertNonPrimary(e){this.cascade.insertInTable(this.cascade.pagetypes,"*",e)}makeApplyRuleAction(e){return new up(this.elementStyle,e)}startPageMarginBoxRule(e){let n=wo(this.elementStyle,Ui),s=n[e];s||(s={},n[e]=s);let o=new dp(this.scope,this.owner,this.validatorSet,s);this.owner.pushHandler(o)}},dp=class extends Jt{constructor(e,n,s,o){super(e,n,!1);this.validatorSet=s;this.boxStyle=o}property(e,n,s){this.validatorSet.validatePropertyAndHandleShorthand(e,n,s,this)}invalidPropertyValue(e,n){this.report(`E_INVALID_PROPERTY_VALUE ${e}: ${n.toString()}`)}unknownProperty(e,n){this.report(`E_INVALID_PROPERTY ${e}: ${n.toString()}`)}simpleProperty(e,n,s){let o=s?this.getImportantSpecificity():this.getBaseSpecificity(),i=new H(n,o);xn(this.boxStyle,e,i)}};var Gt=!0;function hg(r){Gt=r}var Hs=[];function pg(r,t){return r===t||(r.src||t.src?r.src===t.src:r.textContent===t.textContent)}function fg(r){let t=Array.from(r.querySelectorAll("body > :not(script):not(link):not(style) ~ script"));return Array.from(r.querySelectorAll("head > script, body > script")).filter(e=>!t.includes(e))}function qa(r,t,e){var u,d;if(!Gt)return v(!1);if(!(e!=null&&e.inHead)&&!(e!=null&&e.atEnd)&&fg(r.ownerDocument).includes(r))return v(!1);let n=r.textContent,s=r.src,o=r.type==="module",i=(o||s)&&r.async,a=o&&!i||s&&r.defer,l=!(e!=null&&e.atEnd)&&((e==null?void 0:e.forceDefer)||a||i);if(gp(t)||(t.onload=null),l)return Hs.some(h=>pg(h,r))||Hs.push(r),v(!0);if(s.includes("/mathjax")){let h=t.document.head.querySelector("script[src*='MathJax.js']:not([data-vivliostyle-scripting])");if(h){if(s.includes("/mathjax@3"))t.document.head.removeChild(h),(d=(u=t.MathJax)==null?void 0:u.version)!=null&&d.startsWith("2.")&&delete t.MathJax;else if(s.includes("/MathJax.js"))return v(!0)}}for(let h of t.document.head.getElementsByTagName("script"))h.hasAttribute("data-vivliostyle-scripting")&&pg(h,r)&&t.document.head.removeChild(h);let c=t.document.createElement("script");c.textContent=n,s&&(c.src=s),c.async=i,c.defer=a,c.setAttribute("data-vivliostyle-scripting","true");for(let h of r.attributes)["src","async","defer"].includes(h.name)||c.setAttribute(h.name,h.value);if(V.debug("script:",s),s){let h=Fn(c);return t.document.head.appendChild(c),Vn([h])}else return t.document.head.appendChild(c),v(!0)}function db(r,t){var o;let e={},n=i=>{var c;let a=(c=i["font-family"])==null?void 0:c.value;if(a)if(a.values)for(let u of a.values)e[u.stringValue()]=!0;else e[a.stringValue()]=!0;let l=i._marginBoxes;if(l)for(let u of Object.values(l))n(u)},s=i=>{if(i instanceof Ls)n(i.style);else if(i instanceof yn||Array.isArray(i))for(let a of Object.values(i))s(a)};for(let i of Object.values(t.cascade.code))for(let a of Object.values(i!=null?i:{}))s(a);for(let i of r.querySelectorAll("[style]"))(o=i.style)!=null&&o.fontFamily&&(e[i.style.fontFamily]=!0);return Object.keys(e).join(",")}function pb(r,t,e){var s;let n=(s=t.document.querySelector("[data-vivliostyle-textcontent]"))!=null?s:t.document.createElement("div");return n.style.position="fixed",n.style.fontSize="0",n.setAttribute("data-vivliostyle-textcontent","true"),n.setAttribute("aria-hidden","true"),n.style.fontFamily=db(r,e),n.textContent=r.documentElement.textContent,t.document.body.appendChild(n),n}function gg(r,t,e){if(!Gt)return v(!1);let n=fg(r);if(n.length===0)return v(!1);let s=n.some(u=>!(u.async||u.defer||u.type==="module")),o=s?pb(r,t,e):null,i=t.document.fonts,a=t.$,l=!1,c=A("loadScripts");return c.loop(()=>{if(n.length===0)return s?c.sleep(20).thenAsync(()=>{var d,h;return i.status==="loading"||t.document.documentElement.classList.contains("wf-loading")||(d=t.FontJSON)!=null&&d.Font&&((h=t.ret)!=null&&h.readyState)&&t.ret.readyState<4?v(!0):v(!1)}):v(!1);let u=n.shift();return qa(u,t,{inHead:!0,forceDefer:l}).thenAsync(()=>(!l&&t.$!==a&&(Hs.push(u),l=!0),n.length===0&&s&&(V.debug("dispatchEvent: DOMContentLoaded (document)"),t.document.dispatchEvent(new Event("DOMContentLoaded"))),v(!0)))}).then(()=>{o&&o.remove(),c.finish(!0)}),c.result()}function mg(r){if(!Gt)return v(!1);let t=A("loadScripts");return t.loop(()=>Hs.length===0?v(!1):qa(Hs.shift(),r,{atEnd:!0}).thenReturn(Hs.length>0)).then(()=>{V.debug("dispatchEvent: DOMContentLoaded (window)"),r.dispatchEvent(new Event("DOMContentLoaded")),V.debug("dispatchEvent: load (window)"),r.dispatchEvent(new Event("load")),t.finish(!0)}),t.result()}function gp(r){return Gt?Hs.length>0||!!r.document.head.querySelector("script[data-vivliostyle-scripting]"):!1}var Cg=(r,t,e)=>r.replace(/[uU][rR][lL]\(\s*"((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^"\r\n])+)"/gm,(n,s)=>`url("${e.transformURL(s,t)}"`).replace(/[uU][rR][lL]\(\s*'((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^'\r\n])+)'/gm,(n,s)=>`url('${e.transformURL(s,t)}'`).replace(/[uU][rR][lL]\(\s*((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^"'\r\n\)\s])+)/gm,(n,s)=>`url(${e.transformURL(s,t)}`);var fb={};function gb(r){r.addEventListener("load",()=>{r.contentWindow.navigator.epubReadingSystem={name:"adapt",version:"0.1",layoutStyle:"paginated",hasFeature:function(t,e){switch(t){case"mouse-events":return!0}return!1}}},!1)}var Wi=class Wi extends wn{constructor(e,n,s,o,i,a,l,c,u,d,h,f,g){super();this.flowName=e;this.context=n;this.viewport=s;this.styler=o;this.regionIds=i;this.xmldoc=a;this.docFaces=l;this.footnoteStyle=c;this.stylerProducer=u;this.page=d;this.customRenderer=h;this.fallbackMap=f;this.documentURLTransformer=g;p(this,"document");p(this,"exprContentListener");p(this,"nodeContext",null);p(this,"viewRoot",null);p(this,"isFootnote",!1);p(this,"sourceNode",null);p(this,"offsetInNode",0);p(this,"viewNode",null);this.document=s.document,this.exprContentListener=o.counterListener.getExprContentListener()}clone(){return new Wi(this.flowName,this.context,this.viewport,this.styler,this.regionIds,this.xmldoc,this.docFaces,this.footnoteStyle,this.stylerProducer,this.page,this.customRenderer,this.fallbackMap,this.documentURLTransformer)}createPseudoelementShadow(e,n,s,o,i,a,l,c){let u=this.getPseudoMap(s,this.regionIds,this.isFootnote,this.nodeContext,a);if(!u)return c;let d=[],h=ko.createElementNS("http://www.pyroxy.com/ns/shadow","root"),f=h;for(let m of Rf){let y;if(m){if(!u[m]||m=="footnote-marker"&&!(n&&this.isFootnote))continue;if(m.match(/^first-/)){let E=o.display;if(!E||E===b.inline)continue;let C=e.firstElementChild;if(C&&ue(C.previousSibling)){let x=i.getStyle(C,!1);if(x){let N=pe(x,"display");if(N!=null&&N.value&&N.value!==b.inline)continue}}}if(m==="before"||m==="after"){let E=u[m].content;if(!E||!Nt(E.value))continue}d.push(m),y=ko.createElementNS("http://www.w3.org/1999/xhtml","span"),Ei(y,m)}else y=ko.createElementNS("http://www.pyroxy.com/ns/shadow","content");f.appendChild(y),m.match(/^first-/)&&(f=y)}if(!d.length)return c;let g=new yi(e,s,i,a,this.exprContentListener);return new ys(e,h,null,l,c,St.ROOTLESS,g)}getPseudoMap(e,n,s,o,i){let a=vt(e,"_pseudos");if(!a)return null;let l={};for(let c in a){let u=l[c]={};Po(u,a[c],i),ga(u,i,a[c]),Xu(a[c],n,s,(d,h)=>{Po(u,h,i),$u(h,f=>{Po(u,f,i)})})}return l}createRefShadow(e,n,s,o,i){let a=A("createRefShadow");return this.xmldoc.store.load(e).then(l=>{let c=l;if(c){let u=c.getElement(e);if(u){let d=this.stylerProducer.getStylerForDoc(c);i=new ys(s,u,c,o,i,n,d)}}a.finish(i)}),a.result()}createShadows(e,n,s,o,i,a,l){let c=A("createShadows"),u=null,d=o.template,h;if(d instanceof Oe||d===b.footnote){let f=d instanceof Oe?d.url:J("user-agent.xml#footnote",Xt);h=this.createRefShadow(f,St.ROOTLESS,e,l,u)}else h=v(u);return h.then(f=>{let g=null;if(e.namespaceURI=="http://www.pyroxy.com/ns/shadow"&&e.localName=="include"){let y=e.getAttribute("href"),E=null;y?E=l?l.xmldoc:this.xmldoc:l&&(l.owner.namespaceURI=="http://www.w3.org/1999/xhtml"?y=l.owner.getAttribute("href"):y=l.owner.getAttributeNS("http://www.w3.org/1999/xlink","href"),E=l.parentShadow?l.parentShadow.xmldoc:this.xmldoc),y&&(y=J(y,E.url),g=this.createRefShadow(y,St.ROOTED,e,l,f))}g==null&&(g=v(f));let m=null;g.then(y=>{if(o.display===b.table_cell){let E=J("user-agent.xml#table-cell",Xt);m=this.createRefShadow(E,St.ROOTLESS,e,l,y)}else m=v(y);m.then(E=>{E=this.createPseudoelementShadow(e,n,s,o,i,a,l,E),c.finish(E)})})}),c.result()}setViewRoot(e,n){this.viewRoot=e,this.isFootnote=n}computeStyle(e,n,s,o){var E;let i=this.context,a=Ea(s,i,this.regionIds,this.isFootnote,this.nodeContext),l=!((E=this.nodeContext)!=null&&E.parent);l&&(!a["writing-mode"]&&this.styler.rootStyle["writing-mode"]&&(a["writing-mode"]=this.styler.rootStyle["writing-mode"]),!a.direction&&this.styler.rootStyle.direction&&(a.direction=this.styler.rootStyle.direction));let c=e;e=xa(a,i,e);let u=!l&&e!==c;n=ya(a,i,n);let d=(C,x)=>{let N;u&&(e?/^(min-|max-)?(height|inline-size)$/.test(C)&&(N=i.pageAreaHeight):/^(min-|max-)?(width|inline-size)$/.test(C)&&(N=i.pageAreaWidth));let S=x.evaluate(i,C,N,e);return C=="font-family"&&(S=this.docFaces.filterFontFamily(S)),S},h=!!new ee(i.style.pageScope,"left-page").evaluate(i);if(Sa(a,o,e,n,h,d),u){let C=o[e?"height":"width"];(!C||C===b.auto)&&(o[e?"height":"width"]=b.max_content)}if(ci(o.position))return o.position=b.fixed,o.visibility=b.hidden,e;let f=o.position,g=o.float,m=o.display||(this.sourceNode.namespaceURI==="http://www.w3.org/1999/xhtml"?b.inline:void 0),y=Gc(m,f,g,this.sourceNode===this.xmldoc.root);return["display","position","float"].forEach(C=>{y[C]&&(o[C]=y[C])}),e}inheritFromSourceParent(e){let n=this.nodeContext.sourceNode,s=[],o=null,i=this.nodeContext.shadowContext,a=-1;for(;n&&n.nodeType==1;){let h=i&&i.root==n;if(!h||i.type==St.ROOTLESS){let g=(i?i.styler:this.styler).getStyle(n,!1);s.push(g),o=o||_o(n)}h?(n=i.owner,i=i.parentShadow):(n=n.parentNode,a++)}let l=a===0,c=this.context.queryUnitSize("em",l),u={"font-size":new H(new P(c,"px"),0)},d=new ua(u,this.context);for(let h=s.length-1;h>=0;--h){let f=s[h],g=[];for(let E in f)Yn(E)&&g.push(E);g.sort(Gl);let m,y;for(let E of g){d.setPropName(E);let C=pe(f,E),x=C;U(C.value)||(E==="font-size"&&h===s.length-1&&this.context.isRelativeRootFontSize&&this.context.rootFontSize?x=new H(new P(this.context.rootFontSize,"px"),C.priority):E==="line-height"&&h===s.length-1&&this.context.rootLineHeight&&C.value instanceof P&&(C.value.unit==="lh"||C.value.unit==="rlh")?x=new H(new P(this.context.rootLineHeight,"px"),C.priority):h===0&&C.value instanceof P&&C.value.unit==="lh"?x=new H(new P(C.value.num*this.getLineHeightUnitSize(E,m,y),"px"),C.priority):xt(E)||(x=C.filterValue(d)),E==="font-size"?m=x.value:E==="line-height"&&(y=x.value),u[E]=x)}}for(let h in e)Yn(h)||(u[h]=e[h]);return{lang:o,elementStyle:u}}resolveURL(e){return e=J(e,this.xmldoc.url),this.fallbackMap[e]||e}inheritLangAttribute(){this.nodeContext.lang=_o(this.nodeContext.sourceNode)||this.nodeContext.parent&&this.nodeContext.parent.lang||this.nodeContext.lang}transferPolyfilledInheritedProps(e){let n=df().filter(s=>e[s]);if(n.length){let s=this.nodeContext.inheritedProps;if(this.nodeContext.parent){s=this.nodeContext.inheritedProps={};for(let o in this.nodeContext.parent.inheritedProps)s[o]=this.nodeContext.parent.inheritedProps[o]}n.forEach(o=>{let i=e[o];if(i){if(U(i))i===b.initial&&(s[o]=void 0);else if(i instanceof ut)s[o]=i.num;else if(i instanceof be)s[o]=i.name;else if(i instanceof P){let a=i;switch(a.unit){case"dpi":case"dpcm":case"dppx":s[o]=a.num*Y[a.unit];break;default:s[o]=i}}else s[o]=i;["widows","orphans"].includes(o)||delete e[o]}})}}resolveFormattingContext(e,n,s,o,i,a){let l=Ge("RESOLVE_FORMATTING_CONTEXT");for(let c=0;c<l.length;c++){let u=l[c](e,n,s,o,i,a);if(u){e.formattingContext=u;return}}}createElementView(e,n){var E,C,x,N;let s=!0,o=A("createElementView"),i=this.sourceNode,a=this.nodeContext.shadowContext?this.nodeContext.shadowContext.styler:this.styler,l=a.getStyle(i,!1);if(!this.nodeContext.shadowContext){let S=this.xmldoc.getElementOffset(i);Xn.registerFragmentIndex(S,this.nodeContext.fragmentIndex,0)}let c={};if(!this.nodeContext.parent){let S=this.inheritFromSourceParent(l);l=S.elementStyle,this.nodeContext.lang=S.lang}let u=l.position,d=l.float,h=l["float-reference"],f=d&&!U(d.value)&&d.value!==b.none&&h&&!U(h.value)?jh(h.value.toString()):null;if(this.nodeContext.parent&&(ci(u==null?void 0:u.value)||f&&Hn(f))){let S=this.inheritFromSourceParent(l);l=S.elementStyle,this.nodeContext.lang=S.lang}this.nodeContext.vertical=this.computeStyle(this.nodeContext.vertical,this.nodeContext.direction==="rtl",l,c),f&&Hn(f)&&c.display===b.block&&(c.display=b.flow_root),a.processContent(i,c,(C=this.nodeContext.viewNode)!=null?C:(E=this.nodeContext.parent)==null?void 0:E.viewNode),this.transferPolyfilledInheritedProps(c),this.inheritLangAttribute(),c.direction&&(this.nodeContext.direction=c.direction.toString());let g=c["flow-into"];if(g&&g.toString()!=this.flowName)return o.finish(!1),o.result();if(Gt&&i.localName==="script"&&i.namespaceURI==="http://www.w3.org/1999/xhtml")return qa(i,this.viewport.window).thenFinish(o),o.result();let m=c.display;if(U(m)&&(m===b.initial||m===b.unset?m=b.inline:m===b.inherit?m=((x=this.nodeContext.parent)==null?void 0:x.display)&&L((N=this.nodeContext.parent)==null?void 0:N.display):m=null),m===b.none)return o.finish(!1),o.result();let y=this.nodeContext.parent==null;return this.nodeContext.flexContainer=m===b.flex,this.createShadows(i,y,l,c,a,this.context,this.nodeContext.shadowContext).then(S=>{var Ap,Lp;this.nodeContext.nodeShadow=S;let w=c.position,k=c.float,R=c.clear,G=this.nodeContext.vertical?b.vertical_rl:b.horizontal_tb,de=this.nodeContext.parent?this.nodeContext.parent.vertical?b.vertical_rl:b.horizontal_tb:G,Xe=qh(i),Je=c["column-count"],_e=c["column-width"],Fe=Je&&Je!==b.auto&&!U(Je)||_e&&_e!==b.auto&&!U(_e);this.nodeContext.establishesBFC=Kh(m,w,k,c.overflow,G,de,Fe||Xe),this.nodeContext.containingBlockForAbsolute=Zh(w),this.nodeContext.isInsideBFC()&&k!==b.footnote&&!(f&&Hn(f))&&(k=null,R=null);let $=k instanceof q||k===b.left||k===b.right||k===b.top||k===b.bottom||k===b.inline_start||k===b.inline_end||k===b.block_start||k===b.block_end||k===b.snap_block||k===b.snap_inline||k===b.inside||k===b.outside||k===b.footnote;k&&(delete c.float,k===b.footnote&&(this.isFootnote?($=!1,c.display=b.block):c.display=b.inline)),R&&(R===b.inherit&&this.nodeContext.parent&&this.nodeContext.parent.clearSide&&(R=L(this.nodeContext.parent.clearSide)),(R===b.left||R===b.right||R===b.top||R===b.bottom||R===b.inline_start||R===b.inline_end||R===b.block_start||R===b.block_end||R===b.inside||R===b.outside||R===b.both||R===b.all||R===b.same||R===b.column||R===b.region||R===b.page)&&(delete c.clear,c.display&&c.display!=b.inline&&(this.nodeContext.clearSide=R.toString())));let I=m===b.list_item&&c["ua-list-item-count"],M=c["break-inside"];($||M&&!U(M)&&M!==b.auto)&&this.nodeContext.breakPenalty++,m&&m!==b.inline&&gn(m)&&this.nodeContext.breakPenalty++,this.nodeContext.inline=!$&&!m||gn(m)||sa(m),this.nodeContext.display=m?m.toString():"inline",this.nodeContext.floatSide=$?k.toString():null,this.nodeContext.floatReference=f||ae.INLINE;let F=c["float-min-wrap-block"];this.nodeContext.floatMinWrapBlock=F&&!U(F)?F:null;let _=this.isInsideNonRootMultiColumn();!y&&Fe&&c["column-fill"]===b.auto&&(c["--viv--saved-column-fill"]=b.auto,c["column-fill"]=b.balance);let W=c["column-span"];if(this.nodeContext.columnSpan=!_&&W&&!U(W)?W:null,!this.nodeContext.inline){let D=c["break-after"];D&&!U(D)&&!(_&&D===b.column)&&(this.nodeContext.breakAfter=D.toString(),zr[this.nodeContext.breakAfter]&&(c["break-after"]=b.column));let it=c["break-before"];it&&!U(it)&&!(_&&it===b.column)&&(this.nodeContext.breakBefore=it.toString(),zr[this.nodeContext.breakBefore]&&(c["break-before"]=b.column),this.nodeContext.fragmentIndex!==1&&(this.nodeContext.breakBefore=null));let Tt=c.page,rt=Tt&&!U(Tt)&&Tt.toString();!rt&&!this.nodeContext.parent&&(this.nodeContext.shadowContext||m===b.table_header_group||m===b.table_footer_group)&&(rt=this.styler.cascade.currentPageType),!rt||rt.toLowerCase()==="auto"?rt=this.nodeContext.pageType:this.nodeContext.pageType=rt,this.styler.cascade.currentPageType!==rt&&!(!rt&&c.position===b.fixed)&&(this.nodeContext.fragmentIndex===1&&!On(this.nodeContext.breakBefore)&&(this.nodeContext.breakBefore="page"),rt!==this.styler.cascade.previousPageType&&(this.styler.cascade.previousPageType=this.styler.cascade.currentPageType),this.styler.cascade.currentPageType=rt)}this.nodeContext.verticalAlign=c["vertical-align"]&&c["vertical-align"].toString()||"baseline",this.nodeContext.captionSide=c["caption-side"]&&c["caption-side"].toString()||"top";let he=c["border-collapse"];if(!he||he===L("separate")){let D=c["border-spacing"],it,Tt;D&&(D instanceof q?(it=D.values[0],Tt=D.values[1]):it=Tt=D,it.isNumeric()&&(this.nodeContext.inlineBorderSpacing=ke(it,this.context)),Tt.isNumeric()&&(this.nodeContext.blockBorderSpacing=ke(Tt,this.context)))}let Tn=c["footnote-policy"];this.nodeContext.footnotePolicy=Tn&&!U(Tn)?Tn:null;let Ki=c["x-first-pseudo"];if(Ki){let D=this.nodeContext.parent?this.nodeContext.parent.firstPseudo:null;this.nodeContext.firstPseudo=new Yr(D,Ki.num)}this.nodeContext.inline||this.processAfterIfcontinues(i,l,a,this.context);let Pp=c["white-space"];if(Pp){let D=Qr(Pp.toString());D!==null&&(this.nodeContext.whitespace=D)}let dl=c["hyphenate-character"];dl&&dl instanceof ce&&(this.nodeContext.hyphenateCharacter=dl.str);let Ag=c["word-break"],Lg=c["line-break"],kp=c["overflow-wrap"];(Ag===b.break_all||Lg===b.anywhere||kp===b.break_word||kp===b.anywhere)&&(this.nodeContext.breakWord=!0),this.resolveFormattingContext(this.nodeContext,e,m,w,k,y),this.nodeContext.parent&&this.nodeContext.parent.formattingContext&&(e=this.nodeContext.parent.formattingContext.isFirstTime(this.nodeContext,e)),this.nodeContext.inline||(this.nodeContext.repeatOnBreak=this.processRepeatOnBreak(c),this.findAndProcessRepeatingElements(i,a));let ns=!1,pl=null,Bo=[],It=i.namespaceURI,X=i.localName,Zi=X;if(It=="http://www.w3.org/1999/xhtml"?(X=="html"||X=="body"||X=="script"||X=="link"||X=="meta"?X="div":X=="vide_"?X="video":X=="audi_"?X="audio":X=="object"&&(ns=!!this.customRenderer),i.getAttribute(Na)&&(Lp=(Ap=l.content)==null?void 0:Ap.value)!=null&&Lp.url&&(X="img")):It=="http://www.idpf.org/2007/ops"?(X="span",It="http://www.w3.org/1999/xhtml"):It=="http://www.pyroxy.com/ns/shadow"?(It="http://www.w3.org/1999/xhtml",X=this.nodeContext.inline?"span":"div"):ns=!!this.customRenderer,I)e?X="li":(X="div",m=b.block,c.display=m);else if(X=="body"||X=="li")X="div";else if(X=="q")X="span";else if(X=="a"){let D=c["hyperlink-processing"];D&&D.toString()!="normal"&&(X="span")}c.behavior&&c.behavior.toString()!="none"&&this.customRenderer&&(ns=!0),i.dataset&&i.getAttribute("data-math-typeset")==="true"&&(ns=!0);let hl;if(ns){let D=this.nodeContext.parent?this.nodeContext.parent.viewNode:null;hl=this.customRenderer(i,D,c)}else hl=v(null);hl.then(D=>{if(D)ns&&(s=D.getAttribute("data-adapt-process-children")=="true");else if(c.display===b.none){o.finish(!1);return}else D=this.createElement(It,X);X!=Zi&&(D.setAttribute("data-vivliostyle-original-tag",Zi),(Zi==="html"||Zi==="body")&&(D.role="presentation")),X=="a"&&D.addEventListener("click",this.page.hrefHandler,!1),pl&&(this.applyPseudoelementStyle(this.nodeContext,"inner",pl),D.appendChild(pl)),D.localName=="iframe"&&D.namespaceURI=="http://www.w3.org/1999/xhtml"&&gb(D);let it=this.nodeContext.inheritedProps["image-resolution"],Tt=[],rt=c.width,fl=c.height,Rg=i.getAttribute("width"),Ig=i.getAttribute("height"),gl=rt===b.auto||!rt&&!Rg,ml=fl===b.auto||!fl&&!Ig,Rp=i.attributes,Vg=Rp.length,Qi=null,Ip=null;for(let et=0;et<Vg;et++){let Wt=Rp[et],at=Wt.namespaceURI,oe=Wt.localName,fe=Wt.nodeValue;if(at){if(at=="http://www.w3.org/2000/xmlns/")continue;at=="http://www.w3.org/1999/xlink"&&oe=="href"&&(fe=this.documentURLTransformer.transformURL(this.resolveURL(fe),this.xmldoc.url))}else{if(!Gt&&oe.match(/^on/)||oe=="style")continue;if((oe=="id"||oe=="name")&&e){let je=this.documentURLTransformer.transformFragment(fe,this.xmldoc.url);D.setAttribute(oe,fe),D.setAttribute("data-vivliostyle-id",je);let wt=D.ownerDocument.createElement("a");wt.setAttribute(oe,je),wt.setAttribute(_t,"1"),D.appendChild(wt),this.page.registerElementWithId(D,je);continue}if(oe=="src"||oe=="href"||oe=="poster")fe=this.resolveURL(fe),oe==="href"&&(fe=this.documentURLTransformer.transformURL(fe,this.xmldoc.url));else if(oe=="srcset")fe=fe.split(",").map(je=>this.resolveURL(je.trim())).join(",");else if(oe==="data"&&ns&&X==="object"&&D.hasAttribute("data"))continue;if(oe==="poster"&&X==="video"&&It==="http://www.w3.org/1999/xhtml"&&gl&&ml){let je=new Image,wt=Fn(je,fe);Bo.push(wt),Tt.push({image:je,element:D,fetcher:wt})}}if(It=="http://www.w3.org/2000/svg"&&/^[A-Z\-]+$/.test(oe)&&(oe=oe.toLowerCase()),this.isSVGUrlAttribute(oe)&&(fe=Cg(fe,this.xmldoc.url,this.documentURLTransformer)),at){let je=fb[at];je&&(oe=`${je}:${oe}`)}if(oe=="src"&&!at&&(X=="img"||X=="input")&&It=="http://www.w3.org/1999/xhtml")Qi=fe;else if(oe=="alt"&&!at&&X=="img"&&It=="http://www.w3.org/1999/xhtml")Ip=fe;else if(oe=="href"&&X=="image"&&It=="http://www.w3.org/2000/svg"&&at=="http://www.w3.org/1999/xlink")this.page.fetchers.push(Fn(D,fe));else if(at)D.setAttributeNS(at,oe,fe);else try{D.setAttribute(oe,fe)}catch(je){V.warn(je)}}if(Qi){let et=X==="input"?new Image:D,Wt=Fn(et,Qi,Ip);et!==D&&(D.src=Qi);let at=()=>{var fe,je;if(c.position===b.fixed)return!0;for(let wt=(fe=this.nodeContext.parent)==null?void 0:fe.viewNode;wt&&wt!==this.viewRoot;wt=wt.parentElement)if(((je=wt.style)==null?void 0:je.position)==="fixed")return!0;return!1};!gl&&!ml&&!(()=>{let fe=this.nodeContext.vertical?rt:fl;return fe instanceof P&&fe.unit==="%"})()&&!at()?this.page.fetchers.push(Wt):(gl&&ml&&it&&it!==1&&Tt.push({image:et,element:D,fetcher:Wt}),Bo.push(Wt))}delete c.content;let Cl=c["list-style-image"];if(Cl&&Cl instanceof Oe){let et=Cl.url;Bo.push(Fn(new Image,et))}if(this.preprocessElementStyle(c),this.applyComputedStyles(D,c),this.nodeContext.inline)e||(pt(D,"inline-start"),bs(D)&&pt(D,"clone"));else if(e){if(!ta(c.position)){let et=c["margin-break"],Wt=this.getBreakTypeAt(this.nodeContext),at=Wt!==null,oe=Wt==="auto";(et===b.discard&&at||et!==b.keep&&oe&&!this.nodeContext.floatSide)&&Hr(D,"block-start")}}else{let et=this.nodeContext.vertical?"width":"height";gt(D,et)&&T(D,et,this.nodeContext.display==="table-row"?"0.01px":""),pt(D,"block-start"),bs(D)&&pt(D,"clone"),Hr(D,"block-start")}I&&D.setAttribute("value",c["ua-list-item-count"].stringValue()),this.viewNode=D,Bo.length?Vn(Bo).then(()=>{it>0&&this.modifyElemDimensionWithImageResolution(Tt,it,c,this.nodeContext.vertical),o.finish(s)}):o.timeSlice().then(()=>{o.finish(s)})})}),o.result()}isInsideNonRootMultiColumn(){var n;let e=(n=this.nodeContext.parent)==null?void 0:n.viewNode;return!!(e&&Xc(e))}getBreakTypeAt(e){var s,o,i,a,l;if(this.isInsideTable(e))return null;for(let c=e;c&&!c.after;c=c.parent){if(Ie(c.breakBefore))return c.breakBefore;if(c.fragmentIndex===1&&!c.parent)return c.sourceNode===c.sourceNode.ownerDocument.documentElement?"page":null;if((s=c.parent)!=null&&s.floatSide)return null;let u=(o=c.parent)==null?void 0:o.viewNode;if(u){let d=this.viewport.window.getComputedStyle(u),h=parseFloat(d.paddingBlockStart),f=parseFloat(d.borderBlockStartWidth);if(h||f)return null;let g=u==null?void 0:u.firstChild;for(;g&&(ue(g,c.parent.whitespace)||!c.floatSide&&Ns(g));)g=g.nextSibling;if(g&&g!==c.viewNode)return null}}let n=(l=(a=(i=this.context)==null?void 0:i.currentLayoutPosition)==null?void 0:a.flowPositions[this.flowName])==null?void 0:l.startBreakType;return Ie(n)?n:"auto"}isInsideTable(e){for(let n=e;n&&!n.after;n=n.parent)if(n.display&&n.display.startsWith("table"))return!0;return!1}processAfterIfcontinues(e,n,s,o){let i=this.getPseudoMap(n,this.regionIds,this.isFootnote,this.nodeContext,o);if(i&&i["after-if-continues"]&&i["after-if-continues"].content){let a=new yi(e,n,s,o,this.exprContentListener);this.nodeContext.afterIfContinues=new va(e,a)}}isSVGUrlAttribute(e){return Wi.SVG_URL_ATTRIBUTES.includes(e.toLowerCase())}modifyElemDimensionWithImageResolution(e,n,s,o){e.forEach(i=>{if(i.fetcher.get().get()==="load"){let a=i.image,l=a.width/n,c=a.height/n,u=i.element;if(l>0&&c>0){if(s["box-sizing"]===b.border_box&&(s["border-left-style"]!==b.none&&(l+=ke(s["border-left-width"],this.context)),s["border-right-style"]!==b.none&&(l+=ke(s["border-right-width"],this.context)),s["border-top-style"]!==b.none&&(c+=ke(s["border-top-width"],this.context)),s["border-bottom-style"]!==b.none&&(c+=ke(s["border-bottom-width"],this.context))),n>1){let d=s["max-width"]||b.none,h=s["max-height"]||b.none;if(d===b.none&&h===b.none)T(u,"max-width",`${l}px`);else if(d!==b.none&&h===b.none)T(u,"width",`${l}px`);else if(d===b.none&&h!==b.none)T(u,"height",`${c}px`);else{d.isNumeric(),h.isNumeric();let f=d,g=h;f.unit!=="%"?T(u,"max-width",`${Math.min(l,ke(f,this.context))}px`):g.unit!=="%"?T(u,"max-height",`${Math.min(c,ke(g,this.context))}px`):o?T(u,"height",`${c}px`):T(u,"width",`${l}px`)}}else if(n<1){let d=s["min-width"]||ne,h=s["min-height"]||ne;d.isNumeric(),d.isNumeric();let f=d,g=h;f.num===0&&g.num===0?T(u,"min-width",`${l}px`):f.num!==0&&g.num===0?T(u,"width",`${l}px`):f.num===0&&g.num!==0?T(u,"height",`${c}px`):f.unit!=="%"?T(u,"min-width",`${Math.max(l,ke(f,this.context))}px`):g.unit!=="%"?T(u,"min-height",`${Math.max(c,ke(g,this.context))}px`):o?T(u,"height",`${c}px`):T(u,"width",`${l}px`)}}}})}preprocessElementStyle(e){Ge("PREPROCESS_ELEMENT_STYLE").forEach(s=>{s(this.nodeContext,e)})}findAndProcessRepeatingElements(e,n){for(let s=e.firstChild;s;s=s.nextSibling){if(s.nodeType!==1)continue;let o={},i=n.getStyle(s,!1);if(this.computeStyle(this.nodeContext.vertical,this.nodeContext.direction==="rtl",i,o),!this.processRepeatOnBreak(o))continue;if(this.nodeContext.formattingContext instanceof Ht&&!this.nodeContext.belongsTo(this.nodeContext.formattingContext))return;let l=this.nodeContext.parent,c=l&&l.formattingContext;this.nodeContext.formattingContext=new Ht(c,this.nodeContext.sourceNode),this.nodeContext.formattingContext.initializeRepetitiveElements(this.nodeContext.vertical);return}}processRepeatOnBreak(e){let n=e["repeat-on-break"];return n!==b.none&&((n===b.auto||U(n))&&(e.display===b.table_header_group?n=b.header:e.display===b.table_footer_group?n=b.footer:n=b.none),n&&n!==b.none)?n.toString():null}createTextNodeView(){let e=A("createTextNodeView");return this.preprocessTextContent().then(()=>{let n=this.offsetInNode||0,s=Bc(this.nodeContext.preprocessedTextContent).substr(n);this.viewNode=document.createTextNode(s),e.finish(!0)}),e.result()}preprocessTextContent(){if(this.nodeContext.preprocessedTextContent!=null)return v(!0);let e,n=e=this.sourceNode.textContent,s=A("preprocessTextContent"),o=Ge("PREPROCESS_TEXT_CONTENT"),i=0;return s.loop(()=>i>=o.length?v(!1):o[i++](this.nodeContext,n).thenAsync(a=>(n=a,v(!0)))).then(()=>{this.nodeContext.preprocessedTextContent=Oh(e,n),s.finish(!0)}),s.result()}createNodeView(e,n){let s=A("createNodeView"),o,i=!0;return this.sourceNode.nodeType==1?o=this.createElementView(e,n):this.sourceNode.nodeType==8?(this.viewNode=null,o=v(!0)):o=this.createTextNodeView(),o.then(a=>{var l,c;if(i=a,this.nodeContext.viewNode=this.viewNode,this.viewNode){let u=(f,g)=>(f==null?void 0:f.nodeType)===1&&Vs(f)===g,d=this.nodeContext.parent,h=d?u(this.viewNode,"after")&&u(d.viewNode,"first-letter")&&((l=d.viewNode)!=null&&l.hasChildNodes())?d.parent.viewNode:d.viewNode:this.viewRoot;if(h&&(this.nodeContext.inline&&!(this.viewNode.nodeType===3&&ue(this.viewNode))&&!h.hasChildNodes()&&Ac(h).includes("block-start")&&pt(h,"text-start"),h.appendChild(this.viewNode),ef(this.viewNode),this.viewNode.nodeType===1&&this.viewNode.hasAttribute("data-vivliostyle-id"))){let f=this.viewNode,g=f.querySelector(":scope > a:empty[id^='viv-id-']");if(g&&(f.closest("[style*='position: absolute']")||/(table|flex|grid|ruby)/.test(f.style.display))){let m=g.getAttribute("id");g.ownerDocument.querySelectorAll(`a[id="${m}"]`).forEach(E=>{var C;(C=E.parentElement)==null||C.removeChild(E)});let y=h.closest("[data-vivliostyle-bleed-box]");(c=y==null?void 0:y.parentElement)==null||c.insertBefore(g,y)}}}s.finish(i)}),s.result()}setCurrent(e,n,s){return this.nodeContext=e,e?(this.sourceNode=e.sourceNode,this.offsetInNode=e.offsetInNode):(this.sourceNode=null,this.offsetInNode=-1),this.viewNode=null,this.nodeContext?this.createNodeView(n,!!s):v(!0)}processShadowContent(e){if(e.shadowContext==null||e.sourceNode.localName!="content"||e.sourceNode.namespaceURI!="http://www.pyroxy.com/ns/shadow")return e;let n=e.boxOffset,s=e.shadowContext,o=e.parent,i,a,l=s.subShadow||s.parentShadow;s.subShadow?(i=s.root,a=s.type,a==St.ROOTLESS&&(i=i.firstChild)):(i=s.owner.firstChild,a=St.ROOTLESS);let c=e.sourceNode.nextSibling;if(c?(e.sourceNode=c,e.resetView()):e.shadowSibling?e=e.shadowSibling:i?e=null:(e=e.parent.modify(),e.after=!0),i){let u=new Un(i,o,n);return u.shadowContext=l,u.shadowType=a,u.shadowSibling=e,u}return e.boxOffset=n,e}nextPositionInTree(e){let n=e.boxOffset+1;if(e.after){if(!e.parent)return null;if(e.shadowType!=St.ROOTED){let s=e.sourceNode.nextSibling;if(s)return e=e.modify(),e.boxOffset=n,e.sourceNode=s,e.resetView(),this.processShadowContent(e)}return e.shadowSibling?(e=e.shadowSibling.modify(),e.boxOffset=n,e):(e=e.parent.modify(),e.boxOffset=n,e.after=!0,e)}else{if(e.nodeShadow){let o=e.nodeShadow.root;if(e.nodeShadow.type==St.ROOTLESS&&(o=o.firstChild),o){let i=new Un(o,e,n);return i.shadowContext=e.nodeShadow,i.shadowType=e.nodeShadow.type,this.processShadowContent(i)}}let s=e.sourceNode.firstChild;if(s)return this.processShadowContent(new Un(s,e,n));if(e.sourceNode.nodeType!=1){let o=Bc(e.preprocessedTextContent);n+=o.length-1-e.offsetInNode}return e=e.modify(),e.boxOffset=n,e.after=!0,e}}isTransclusion(e,n,s){let o=pe(n,"hyperlink-processing");if(!o)return!1;let i=o.evaluate(this.context,"hyperlink-processing");return i?i.toString()==s:!1}nextInTree(e,n){let s=this.nextPositionInTree(e);if(!s||s.after)return v(s);let o=A("nextInTree");return this.setCurrent(s,!0,n).then(i=>{(!s.viewNode||!i)&&(s=s.modify(),s.after=!0,s.viewNode||(s.inline=!0)),this.dispatchEvent({type:"nextInTree",nodeContext:s}),o.finish(s)}),o.result()}addImageFetchers(e){if(e instanceof ge){let n=e.values;for(let s=0;s<n.length;s++)this.addImageFetchers(n[s])}else if(e instanceof Oe){let n=e.url;this.page.fetchers.push(Fn(new Image,n))}}applyComputedStyles(e,n){var u,d,h;let s=n["background-image"];s&&this.addImageFetchers(s);let o=n.position===b.relative,i=((u=this.nodeContext)==null?void 0:u.parent)===null&&((d=this.sourceNode)==null?void 0:d.parentElement)===null&&!!((h=this.viewRoot)!=null&&h.parentElement),a=Object.keys(n);a.sort(Gl);let l,c;for(let f of a){if(mb[f])continue;let g=n[f];if(!(!g||g===O&&!xt(f))){if(g=g.visit(new Lr(this.xmldoc.url,this.documentURLTransformer)),g instanceof P&&Nr(g.unit)&&(g.unit==="lh"?g=new P(g.num*this.getLineHeightUnitSize(f,l,c),"px"):g=wr(g,this.context)),f==="font-size"?l=g:f==="line-height"&&(c=g),Uh[f]||o&&Hh[f]){this.page.delayedItems.push(new _n(e,f,g));continue}i&&this.page.pageAreaElement&&Yn(f)?T(this.page.pageAreaElement.parentElement.parentElement,f,g.toString()):T(e,f,g.toString())}}}getLineHeightUnitSize(e,n,s){var u,d,h,f;let o=Y.lh/Y.em,i=((d=(u=this.nodeContext.parent)==null?void 0:u.viewNode)==null?void 0:d.nodeType)===1?this.viewport.window.getComputedStyle(this.nodeContext.parent.viewNode):null,a=i?parseFloat(i.fontSize):this.context.fontSize(),l=i?i.lineHeight==="normal"?a*o:parseFloat(i.lineHeight):this.context.rootLineHeight;if(e==="line-height"||e==="font-size")return l;let c=null;if(s){if(s instanceof nt||s instanceof P&&(s.unit==="em"||s.unit==="%"))c=s instanceof P&&s.unit==="%"?s.num/100:s.num;else if(s instanceof P)return s.num*this.context.queryUnitSize(s.unit,!1)}else for(let g=(h=this.nodeContext.parent)==null?void 0:h.viewNode;;g=g.parentNode){if(!g||g.nodeType!==1){c=o;break}let m=(f=g==null?void 0:g.style)==null?void 0:f.lineHeight;if(m){/^[0-9.]+$/.test(m)&&(c=parseFloat(m)),m==="normal"&&(c=o);break}}return c!==null?n instanceof P?c*Gu(n,a,this.context).num:c*a:l}applyPseudoelementStyle(e,n,s){if(e.after)return;let o=this.sourceNode,a=(e.shadowContext?e.shadowContext.styler:this.styler).getStyle(o,!1),l=vt(a,"_pseudos");if(!l||(a=l[n],!a))return;let c={};e.vertical=this.computeStyle(e.vertical,e.direction==="rtl",a,c);let u=c.content;Nt(u)&&(u.visit(new hn(s,this.context,u,this.exprContentListener)),delete c.content),this.applyComputedStyles(s,c)}peelOff(e,n){let s=A("peelOff"),o=e.firstPseudo,i=e.offsetInNode,a=e.after;if(n>0){let h=e.viewNode.textContent;e.viewNode.textContent=h.substr(0,n),i+=n}else if(!a&&e.viewNode&&i==0){let h=e.viewNode.parentNode;h&&h.removeChild(e.viewNode)}let l=e.boxOffset+n,c=[];for(;e.firstPseudo===o;)c.push(e),e=e.parent;let u=c.pop(),d=u.shadowSibling;return s.loop(()=>{for(;c.length>0;){u=c.pop(),e=new Un(u.sourceNode,e,l),c.length==0&&(e.offsetInNode=i,e.after=a),e.shadowType=u.shadowType,e.shadowContext=u.shadowContext,e.nodeShadow=u.nodeShadow,e.shadowSibling=u.shadowSibling?u.shadowSibling:d,d=null;let h=this.setCurrent(e,!1);if(h.isPending())return h}return v(!1)}).then(()=>{s.finish(e)}),s.result()}createElement(e,n){return e=="http://www.w3.org/1999/xhtml"?this.document.createElement(n):this.document.createElementNS(e,n)}applyFootnoteStyle(e,n,s){let o={},i=vt(this.footnoteStyle,"_pseudos");if(e=this.computeStyle(e,n,this.footnoteStyle,o),i&&i.before){let a={},l=this.createElement("http://www.w3.org/1999/xhtml","span");Ei(l,"before"),s.appendChild(l),this.computeStyle(e,n,i.before,a),delete a.content,this.applyComputedStyles(l,a)}return delete o.content,this.applyComputedStyles(s,o),e}processFragmentedBlockEdge(e){var i,a,l;let n=!e.inline&&e.after?e.parent:e,s=!1;if(e.inline&&e.after&&!e.shadowContext&&((i=e.sourceNode.nextSibling)==null?void 0:i.nodeType)===1){let c=e.sourceNode.nextSibling,u=(a=pe(this.styler.getStyle(c,!1),"display"))==null?void 0:a.value.toString();s=u&&!gn(u)||c.getAttribute("data-math-typeset")==="true"&&/^\s*(\$\$|\\\[)/.test(c.textContent)}let o=0;for(let c=n;c;c=c.parent){if(((l=c.viewNode)==null?void 0:l.nodeType)!==1)continue;let u=c.viewNode;if(u.style)if(c.inline){if(pt(u,"inline-end"),bs(u)){let d=c.vertical?u.offsetWidth:u.offsetHeight;pt(u,"clone"),(c.vertical?u.offsetWidth:u.offsetHeight)>d&&this.fixClonedBoxDecorationOverflow(u)}}else{let d=this.nodeContext.vertical?"width":"height";if(gt(u,d)&&T(u,d,""),pt(u,"block-end"),!o++&&c!==n){let{textAlign:h}=this.viewport.window.getComputedStyle(u);if(h==="justify"&&!s){let f=this.createChildAnonymousBlockIfNeeded(u);f?f!==u?Lc(f,["block-start","text-start","block-end","text-end","justify"]):(pt(u,"text-end"),pt(u,"justify")):pt(u,"text-end")}else pt(u,"text-end")}bs(u)&&pt(u,"clone"),Hr(u,"block-end")}}}fixClonedBoxDecorationOverflow(e){let n=this.viewport.window.getComputedStyle(e),s=parseFloat(n.paddingInlineEnd),o=parseFloat(n.borderInlineEndWidth),i=-(s+o);isNaN(i)||(e.style.marginInlineEnd=`${i}px`)}createChildAnonymousBlockIfNeeded(e){let n=i=>{let{display:a,position:l,float:c}=this.viewport.window.getComputedStyle(i);if(i.localName==="ruby"||Yt[i.localName])return!1;if(i.localName==="br")return!0;if((a==="inline"||a==="contents")&&i.hasChildNodes()){let u=i.lastElementChild;if(u&&(!u.nextSibling||u.nextSibling===i.lastChild&&ue(u.nextSibling))){let d=n(u);if(d||d===null)return d}for(let d=u==null?void 0:u.previousElementSibling;d;d=d.previousElementSibling){let h=n(d);if(h||h===null)return null}return!1}if(a==="none"||l==="absolute"||l==="fixed"||c&&c!=="none"||i.hasAttribute(_t)){let u=i.previousElementSibling;return u&&(u.nextSibling===i||u.nextSibling===i.previousSibling&&ue(u.nextSibling))?n(u):!1}return!(!a||gn(a))},s=null;for(let i=e.lastElementChild;i;i=i.previousElementSibling){let a=n(i);if(a){s=i;break}if(a===null)return null}if(!s)return e;if(s===e.lastElementChild&&(!s.nextSibling||s.nextSibling===e.lastChild&&ue(s.nextSibling)))return null;let o=e.ownerDocument.createElement("span");o.className="viv-anonymous-block";for(let i=s.nextSibling,a=null;i;i=a)a=i.nextSibling,o.appendChild(i);return e.appendChild(o),o}convertLengthToPx(e,n,s){let o=e.num,i=e.unit;if(Yp(i)){let a=n;for(;a&&a.nodeType!==1;)a=a.parentNode;let l=parseFloat(s.getElementComputedStyle(a)["font-size"]);return this.context,Ca(e,l,this.context).num}else{let a=this.context.queryUnitSize(i,!1);return a?o*a:e}}isSameNodePositionStep(e,n){if(e.shadowContext){if(!n.shadowContext)return!1;let s=e.node.nodeType===1?e.node:e.node.parentElement,o=n.node.nodeType===1?n.node:n.node.parentElement;return e.shadowContext.owner===n.shadowContext.owner&&Vs(s)===Vs(o)}else return e.node===n.node}isSameNodePosition(e,n){return e.offsetInNode===n.offsetInNode&&e.after==n.after&&e.steps.length===n.steps.length&&e.steps.every((s,o)=>{let i=n.steps[o];return this.isSameNodePositionStep(s,i)})}isPseudoelement(e){return!!Vs(e)}};p(Wi,"SVG_URL_ATTRIBUTES",["color-profile","clip-path","cursor","filter","marker","marker-start","marker-end","marker-mid","fill","stroke","mask"]);var Za=Wi,mb={"float-min-wrap-block":!0,"float-reference":!0,"flow-into":!0,"flow-linger":!0,"flow-options":!0,"flow-priority":!0,"footnote-policy":!0,"margin-break":!0,page:!0},Ka=null,Qa=class{constructor(t){p(this,"layoutBox");p(this,"window");p(this,"scaleRatio");this.layoutBox=t.layoutBox,this.window=t.window,this.scaleRatio=t.scaleRatio}scaleRect(t){return Ka?{left:t.left*this.scaleRatio,top:t.top*this.scaleRatio,right:t.right*this.scaleRatio,bottom:t.bottom*this.scaleRatio,width:t.width*this.scaleRatio,height:t.height*this.scaleRatio}:t}subtractOffsets(t,e){let n=e.left,s=e.top;return{left:t.left-n,top:t.top-s,right:t.right-n,bottom:t.bottom-s,width:t.width,height:t.height}}getRangeClientRects(t){let e=t.getClientRects(),n=this.layoutBox.getBoundingClientRect();return Array.from(e).map(s=>this.scaleRect(this.subtractOffsets(s,n)))}getElementClientRect(t){let n=t.getBoundingClientRect();if(n.left===0&&n.top===0&&n.right===0&&n.bottom===0)return n;let s=this.layoutBox.getBoundingClientRect();return this.scaleRect(this.subtractOffsets(n,s))}getElementComputedStyle(t){return this.window.getComputedStyle(t,null)}adjustLengthValue(t){let e=64*(this.scaleRatio||1);return Math.floor(t*e)/e}},vn=class{constructor(t,e,n,s,o,i){this.window=t;this.fontSize=e;this.pixelRatio=n;p(this,"document");p(this,"root");p(this,"outerZoomBox");p(this,"contentContainer");p(this,"layoutBox");p(this,"width");p(this,"height");p(this,"scaleRatio",1);this.document=t.document,this.root=s||this.document.body;let a=this.root.firstElementChild;a||(a=this.document.createElement("div"),a.setAttribute("data-vivliostyle-outer-zoom-box","true"),a.role="presentation",this.root.appendChild(a));let l=a.firstElementChild;l||(l=this.document.createElement("div"),l.setAttribute("data-vivliostyle-spread-container","true"),l.role="presentation",a.appendChild(l)),n>0&&CSS.supports("zoom","8")&&(T(this.root,"--viv-outputPixelRatio",`${n}`),T(this.root,"--viv-devicePixelRatio",`${t.devicePixelRatio}`),this.scaleRatio=n/t.devicePixelRatio,Ka===null&&(Ka=!("currentCSSZoom"in l)),Ka&&T(this.root,"--viv-scaleRectRatio",`${this.scaleRatio}`));let c=a.nextElementSibling;c||(c=this.document.createElement("div"),c.setAttribute("data-vivliostyle-layout-box","true"),c.role="presentation",this.root.appendChild(c)),this.outerZoomBox=a,this.contentContainer=l,this.layoutBox=c,this.width=o||parseFloat(t.getComputedStyle(this.root).width)||this.root.offsetWidth||t.innerWidth,this.height=i||parseFloat(t.getComputedStyle(this.root).height)||this.root.offsetHeight||t.innerHeight;let u={width:794,height:1056},d=!t.outerWidth&&!t.outerHeight||/Headless/.test(navigator.userAgent)||navigator.webdriver&&t.innerWidth===800&&t.innerHeight===600;(!this.width||!o&&d)&&(this.width=u.width),(!this.height||!i&&d)&&(this.height=u.height)}resetZoom(){T(this.outerZoomBox,"width",""),T(this.outerZoomBox,"height",""),T(this.contentContainer,"width",""),T(this.contentContainer,"height",""),T(this.contentContainer,"transform","")}zoom(t,e,n){T(this.root,"--viv-outputScale",`${n}`),T(this.outerZoomBox,"width",`${t*n}px`),T(this.outerZoomBox,"height",`${e*n}px`),T(this.contentContainer,"width",`${t}px`),T(this.contentContainer,"height",`${e}px`)}clear(){let t=this.root;for(;t.lastChild;)t.removeChild(t.lastChild)}};var $i=class{constructor(t,e,n){this.store=t;this.url=e;this.document=n;p(this,"lang",null);p(this,"totalOffset",-1);p(this,"root");p(this,"body");p(this,"head");p(this,"last");p(this,"lastOffset",1);p(this,"idMap");this.root=n.documentElement;let s=null,o=null;if(this.root.namespaceURI=="http://www.w3.org/1999/xhtml"){for(let i=this.root.firstChild;i;i=i.nextSibling){if(i.nodeType!=1)continue;let a=i;if(a.namespaceURI=="http://www.w3.org/1999/xhtml")switch(a.localName){case"head":o=a;break;case"body":s=a;break}}this.lang=this.root.getAttribute("lang")}this.body=s,this.head=o,this.last=this.root,this.last.setAttribute(Vt,"0")}doc(){return new tl([this.document])}getElementOffset(t){let e=t.getAttribute(Vt);if(e)return parseInt(e,10);let n=this.lastOffset,s=this.last;for(;s!=t;){let o=s.firstChild;if(!o){for(;o=s.nextSibling,!o;)if(s=s.parentNode,s==null)throw new Error("Internal error")}s=o,o.nodeType==1?(o.setAttribute(Vt,n.toString()),++n):n+=o.textContent.length}return this.lastOffset=n,this.last=t,n-1}getNodeOffset(t,e,n){let s=0,o=t,i=null;if(o.nodeType==1){if(!n)return this.getElementOffset(o)}else{if(s=e,i=o.previousSibling,!i)return o=o.parentNode,s+=1,this.getElementOffset(o)+s;o=i}for(;;){for(;o.lastChild;)o=o.lastChild;if(o.nodeType==1)break;if(s+=o.textContent.length,i=o.previousSibling,!i){o=o.parentNode;break}o=i}return s+=1,this.getElementOffset(o)+s}getTotalOffset(){return this.totalOffset<0&&(this.totalOffset=this.getNodeOffset(this.root,0,!0)),this.totalOffset}getNodeByOffset(t){let e,n=this.root;for(;;){if(e=this.getElementOffset(n),e>=t)return n;let l=n.children;if(!l)break;let c=mt(l.length,u=>{let d=l[u];return this.getElementOffset(d)>t});if(c==0)break;n=l[c-1]}let s=e+1,o=n,i=o.firstChild||o.nextSibling,a=null;for(;;){if(i){if(i.nodeType==1||(o=i,a=o,s+=i.textContent.length,s>t&&!/^\s*$/.test(i.textContent)))break}else if(o=o.parentNode,!o)break;i=o.nextSibling}return i&&a&&/^\s*$/.test(a.textContent)&&(a=i),a||n}buildIdMap(t){let e=t.getAttribute("id");e&&!this.idMap[e]&&(this.idMap[e]=t);let n=t.getAttributeNS("http://www.w3.org/XML/1998/namespace","id");n&&!this.idMap[n]&&(this.idMap[n]=t);for(let s=t.firstElementChild;s;s=s.nextElementSibling)this.buildIdMap(s)}getElement(t){let e=t.match(/([^#]*)#(.+)$/);if(!e||e[1]&&e[1]!=this.url)return null;let n=e[2],s=this.document.getElementById(n);return!s&&this.document.getElementsByName&&(s=this.document.getElementsByName(n)[0]),s||(this.idMap||(this.idMap={},this.buildIdMap(this.document.documentElement)),s=this.idMap[n]),s}},Cp=(o=>(o.TEXT_HTML="text/html",o.TEXT_XML="text/xml",o.APPLICATION_XML="application/xml",o.APPLICATION_XHTML_XML="application/xhtml+xml",o.IMAGE_SVG_XML="image/svg+xml",o))(Cp||{});function el(r,t,e){let n=e||new DOMParser,s;try{s=n.parseFromString(r,t)}catch(o){}if(s){let o=s.documentElement,i="parsererror";if(o.localName===i)return null;for(let a=o.firstElementChild;a;a=a.nextElementSibling)if(a.localName===i)return null}else return null;return s}function Cb(r){let t=r.contentType;if(t){let n=Object.keys(Cp);for(let s=0;s<n.length;s++)if(Cp[n[s]]===t)return t;if(t.match(/\+xml$/))return"application/xml"}let e=r.url.match(/\.([^./]+)$/);if(e)switch(e[1]){case"html":case"htm":return"text/html";case"xhtml":case"xht":return"application/xhtml+xml";case"svg":case"svgz":return"image/svg+xml";case"opf":case"xml":return"application/xml"}return null}function xp(r,t){let e=r.responseXML;if(!e){let s=new DOMParser,o=r.responseText;if(o){let i=Cb(r);if(e=el(o,i||"application/xml",s),e&&!i){let a=e.documentElement;a.localName.toLowerCase()==="html"&&!a.namespaceURI?e=el(o,"text/html",s):a.localName.toLowerCase()==="svg"&&e.contentType!=="image/svg+xml"&&(e=el(o,"image/svg+xml",s))}e||(e=el(o,"text/html",s))}}let n=e?new $i(t,r.url,e):null;return v(n)}function bg(){return new fs(xp,"document")}var bp=class r{constructor(t){this.fn=t}check(t){return this.fn(t)}withAttribute(t,e){return new r(n=>this.check(n)&&n.nodeType==1&&n.getAttribute(t)==e)}withChild(t,e){return new r(n=>{if(!this.check(n))return!1;let s=new tl([n]);return s=s.child(t),e&&(s=s.predicate(e)),s.size()>0})}},yp=new bp(r=>!0),tl=class r{constructor(t){this.nodes=t}asArray(){return this.nodes}size(){return this.nodes.length}predicate(t){let e=[];for(let n of this.nodes)t.check(n)&&e.push(n);return new r(e)}forEachNode(t){let e=[],n=s=>{e.push(s)};for(let s=0;s<this.nodes.length;s++)t(this.nodes[s],n);return new r(e)}forEach(t){let e=[];for(let n=0;n<this.nodes.length;n++)e.push(t(this.nodes[n]));return e}forEachNonNull(t){let e=[];for(let n=0;n<this.nodes.length;n++){let s=t(this.nodes[n]);s!=null&&e.push(s)}return e}child(t){return this.forEachNode((e,n)=>{for(let s=e.firstChild;s;s=s.nextSibling)s.nodeType==1&&s.localName==t&&n(s)})}childElements(){return this.forEachNode((t,e)=>{for(let n=t.firstChild;n;n=n.nextSibling)n.nodeType==1&&e(n)})}attribute(t){return this.forEachNonNull(e=>e.nodeType==1?e.getAttribute(t):null)}textContent(){return this.forEach(t=>t.textContent)}};var bb=new Qt(()=>{let r=A("uaStylesheetBase"),t=Wd(),e=J("user-agent-base.css",Xt),n=new En(null,null,null,null,null,t,!0);return n.startStylesheet("UA"),Cf(n.cascade),Ur(yc,n,e,null,null).thenFinish(r),r.result()},"uaStylesheetBaseFetcher");function xb(){return bb.get()}var Ep=class{constructor(t,e,n,s,o,i,a,l,c,u){this.store=t;this.rootScope=e;this.pageScope=n;this.cascade=s;this.rootBox=o;this.fontFaces=i;this.footnoteProps=a;this.flowProps=l;this.viewportProps=c;this.pageProps=u;p(this,"fontDeobfuscator");p(this,"validatorSet");this.fontDeobfuscator=t.fontDeobfuscator,this.validatorSet=t.validatorSet,this.pageScope.defineBuiltIn("has-content",function(d){d=d;let h=this,f=h.currentLayoutPosition,g=f.firstFlowChunkOfFlow(d);return h.matchPageSide(f.startSideOfFlow(d))&&f.hasContent(d,h.lookupOffset)&&!!g&&!h.flowChunkIsAfterParentFlowForcedBreak(g)}),this.pageScope.defineName("page-number",new Z(this.pageScope,function(){let d=this;return d.pageNumberOffset+d.currentLayoutPosition.page},"page-number")),this.pageScope.defineName("blank-page",new Z(this.pageScope,function(){let h=this.currentLayoutPosition;return h==null?void 0:h.isBlankPage},"blank-page"))}sizeViewport(t,e,n,s){if(this.viewportProps.length){let o=new Xs(this.rootScope,t,e,n),i=gf(o,this.viewportProps),a=i.width,l=i.height,c=i["text-zoom"],u=1;if(a&&l||c){let d=Y.em;if((c?c.evaluate(o,"text-zoom"):null)===b.scale&&(u=d/n,n=d,t*=u,e*=u),a&&l){let f=ke(a.evaluate(o,"width"),o),g=ke(l.evaluate(o,"height"),o);if(f>0&&g>0)return{width:s&&s.spreadView?(f+s.pageBorder)*2:f,height:g,fontSize:n}}}}return{width:t,height:e,fontSize:n}}},es=class extends Xs{constructor(e,n,s,o,i,a,l,c,u,d,h,f,g){super(e.rootScope,o.width,o.height,o.fontSize);this.style=e;this.xmldoc=n;this.viewport=o;this.clientLayout=i;this.fontMapper=a;this.customRenderer=l;this.fallbackMap=c;this.pageNumberOffset=u;this.documentURLTransformer=d;this.counterStore=h;p(this,"lang");p(this,"primaryFlows",{body:!0});p(this,"rootPageBoxInstance",null);p(this,"styler",null);p(this,"stylerMap",null);p(this,"currentLayoutPosition",null);p(this,"layoutPositionAtPageStart",null);p(this,"lookupOffset",0);p(this,"faces");p(this,"pageBoxInstances",{});p(this,"pageManager",null);p(this,"rootPageFloatLayoutContext");p(this,"pageBreaks",{});p(this,"pageProgression",null);p(this,"isVersoFirstPage",!1);p(this,"blankPageAtStart",!1);p(this,"pageSheetSize",{});p(this,"pageSheetHeight",0);p(this,"pageSheetWidth",0);this.lang=n.lang||s,this.faces=new Da(this.style.fontDeobfuscator),this.rootPageFloatLayoutContext=new fn(null,null,null,null,null,null,null),this.pageProgression=f||null,this.isVersoFirstPage=!!g;for(let m in e.flowProps){let y=e.flowProps[m],E=pe(y,"flow-consume");E&&(E.evaluate(this,"flow-consume")==b.all?this.primaryFlows[m]=!0:delete this.primaryFlows[m])}}init(){let e=A("StyleInstance.init"),n=this.counterStore.createCounterListener(this.xmldoc.url),s=this.counterStore.createCounterResolver(this.xmldoc.url,this.style.rootScope,this.style.pageScope);this.styler=new ki(this.xmldoc,this.style.cascade,this.style.rootScope,this,this.primaryFlows,this.style.validatorSet,n,s),s.setStyler(this.styler),this.styler.resetFlowChunkStream(this),this.stylerMap={},this.stylerMap[this.xmldoc.url]=this.styler;let o=this.styler.getTopContainerStyle();this.pageProgression||(this.pageProgression=pp(o)),this.matchStartPageSide(this.styler.breakBeforeValues[0])||(this.pageNumberOffset===0?this.isVersoFirstPage=!0:this.blankPageAtStart=!0);let i=this.style.rootBox;this.rootPageBoxInstance=new za(i);let a=this.style.cascade.createInstance(this,n,s,this.lang);this.styler.cascade.currentPageType=this.styler.cascade.firstPageType,this.rootPageBoxInstance.applyCascadeAndInit(a,o),this.rootPageBoxInstance.resolveAutoSizing(this),this.pageManager=new Xa(a,this.style.pageScope,this.rootPageBoxInstance,this,o);let l=[];for(let u of this.style.fontFaces){if(u.condition&&!u.condition.evaluate(this))continue;let d=tg(u.properties,this),h=new Fi(d);l.push(h)}this.fontMapper.findOrLoadFonts(l,this.faces).then(()=>{gg(this.xmldoc.document,this.viewport.window,this.styler).thenFinish(e)});let c=this.style.pageProps;return c[""]||(c[""]={}),Object.keys(c).forEach(u=>{let d=c[u];this.styler.cascade.applyVarFilter([d],this.styler,null),this.styler.cascade.applyCalcFilter(d,this.styler.context);let h=hp(Gi(d),this);this.pageSheetSize[u]={width:h.pageWidth+h.cropOffset*2,height:h.pageHeight+h.cropOffset*2}}),e.result()}matchStartPageSide(e){let n=this.pageNumberOffset%2==(this.isVersoFirstPage?1:0),s=this.pageProgression=="ltr";switch(e){case"left":return n!==s;case"right":return n===s;case"recto":return n;case"verso":return!n;default:return!0}}getStylerForDoc(e){let n=this.stylerMap[e.url];if(!n){let s=this.style.store.getStyleForDoc(e),o=new Xs(s.rootScope,this.pageWidth(),this.pageHeight(),this.initialFontSize),i=this.counterStore.createCounterListener(e.url),a=this.counterStore.createCounterResolver(e.url,s.rootScope,s.pageScope);n=new ki(e,s.cascade,s.rootScope,o,this.primaryFlows,s.validatorSet,i,a),this.stylerMap[e.url]=n}return n}registerInstance(e,n){this.pageBoxInstances[e]=n}lookupInstance(e){return this.pageBoxInstances[e]}encounteredFlowChunk(e,n){let s=this.currentLayoutPosition;if(s){s.flows[e.flowName]?n=s.flows[e.flowName]:s.flows[e.flowName]=n;let o=s.flowPositions[e.flowName];o||(o=new Kr,s.flowPositions[e.flowName]=o);let i=$h(e.element),a=new ht(i),l=new qr(a,e);o.positions.push(l)}}evalSupportsTest(e,n,s){if(s)return e==="selector"?this.evalSupportsSelector(n):!1;if(!e)return!1;let o=!0;class i{unknownProperty(d,h){o=!1}invalidPropertyValue(d,h){o=!1}simpleProperty(d,h,f){}}let a=new i,l=en(this.style.rootScope,new De(n,null),"");return l?(this.xmldoc.store.validatorSet.validatePropertyAndHandleShorthand(e,l,!1,a),o):!1}evalSupportsSelector(e){let n=new nl(null),s=new De(e+"{}",n);return new Bn(me,s,n,"").runParser(Number.POSITIVE_INFINITY,!1,!1,!1,!1)?!n.cascadeParserHandler.invalid:!1}getConsumedOffset(e){let n=Number.POSITIVE_INFINITY;for(let s=0;s<e.positions.length;s++){let o=e.positions[s].chunkPosition.primary,i=o.steps[0].node,a=o.offsetInNode,l=o.after,c=0;for(;i.ownerDocument!=this.xmldoc.document;)c++,i=o.steps[c].node,l=!1,a=0;let u=this.xmldoc.getNodeOffset(i,a,l);u<n&&(n=u)}return n}getPosition(e,n){if(!e)return 0;let s=Number.POSITIVE_INFINITY;for(let o in this.primaryFlows){let i=e.flowPositions[o];if(!n&&(!i||i.positions.length==0)&&this.currentLayoutPosition&&(this.styler.styleUntilFlowIsReached(o),i=this.currentLayoutPosition.flowPositions[o],e!=this.currentLayoutPosition&&i&&(i=i.clone(),e.flowPositions[o]=i)),i){let a=this.getConsumedOffset(i);a<s&&(s=a)}}return s}dumpLocation(e){V.debug("Location - page",this.currentLayoutPosition.page),V.debug(" current:",e),V.debug(" lookup:",this.lookupOffset);for(let n in this.currentLayoutPosition.flowPositions){let s=this.currentLayoutPosition.flowPositions[n];for(let o of s.positions)V.debug(" Chunk",`${n}:`,o.flowChunk.startOffset)}}matchPageSide(e){switch(e){case"left":case"right":case"recto":case"verso":return new ee(this.style.pageScope,`${e}-page`).evaluate(this);default:return!0}}updateStartSide(e){for(let n in e.flowPositions){let s=e.flowPositions[n];if(s&&s.positions.length>0){let o=s.positions[0].flowChunk;if(this.getConsumedOffset(s)===o.startOffset){let i=s.positions[0].flowChunk.breakBefore,a=s.startBreakType;s.startBreakType=Rc(Ve(a,i))}}}}selectPageMaster(e){let n=this.currentLayoutPosition,s=this.getPosition(n);if(s==Number.POSITIVE_INFINITY)return null;let o=this.rootPageBoxInstance.children,i;for(let a=0;a<o.length;a++){if(i=o[a],i.pageBox.pseudoName===Ya)continue;let l=1;i.pageBox.pseudoName===Oi&&!(this.actualPageWidth&&this.actualPageHeight)&&(l=1/0);let c=i.getProp(this,"utilization");c&&c.isNum()&&(l=c.num);let u=this.queryUnitSize("em",!1),d=this.pageWidth()*this.pageHeight(),h=Math.ceil(l*d/(u*u)),f=this.styler.cascade.currentPageType;this.lookupOffset=this.styler.styleUntil(s,h),this.styler.cascade.currentPageType=f,this.updateStartSide(n),this.layoutPositionAtPageStart=n.clone(),this.initLingering(),this.clearScope(this.style.pageScope);let g=i.getProp(this,"enabled");if(!g||g===b._true){if(n.page===1&&this.blankPageAtStart){i.style={};let m=e.size;e={},m&&(e.size=m)}return this.pageManager.getPageRulePageMaster(i,e)}}throw new Error("No enabled page masters")}flowChunkIsAfterParentFlowForcedBreak(e){let n=this.layoutPositionAtPageStart.flows,s=n[e.flowName].parentFlowName;if(s){let o=e.startOffset,i=n[s].forcedBreakOffsets;if(!i.length||o<i[0])return!1;let a=mt(i.length,d=>i[d]>o)-1,l=i[a],c=this.layoutPositionAtPageStart.flowPositions[s],u=this.getConsumedOffset(c);return l<u?!1:u<l?!0:!this.matchPageSide(c.startBreakType)}return!1}setFormattingContextToColumn(e,n){let s=this.currentLayoutPosition.flows[n];s.formattingContext||(s.formattingContext=new xo(null)),e.flowRootFormattingContext=s.formattingContext}layoutDeferredPageFloats(e){let n=e.pageFloatLayoutContext,s=n.getDeferredPageFloatContinuations(),o=c=>{if(c.floatReference!==ae.PAGE)return!1;let u=this.layoutPositionAtPageStart.flowPositions.body,d=u&&this.getConsumedOffset(u),h=this.xmldoc.getNodeOffset(c.nodePosition.steps[0].node,0,!1);return h!=null&&d!=null&&h>d},i=A("layoutDeferredPageFloats"),a=!1,l=0;return i.loopWithFrame(c=>{if(l===s.length){c.breakLoop();return}let u=s[l++],d=u.float;if(o(d)){c.breakLoop();return}let h=new Ut().findByFloat(d),f=h.findPageFloatFragment(d,n);if(f&&f.hasFloat(d)){c.continueLoop();return}else if(n.isForbidden(d)||n.hasPrecedingFloatsDeferredToNext(d)){n.deferPageFloat(u),c.breakLoop();return}e.layoutPageFloatInner(u,h,null,f).then(g=>{if(!g){c.breakLoop();return}let m=n.parent.isInvalidated();if(m){c.breakLoop();return}else n.isInvalidated()&&!m&&(a=!0,n.validate());c.continueLoop()})}).then(()=>{a&&n.invalidate(),i.finish(!0)}),i.result()}getLastAfterPositionIfDeferredFloatsExists(e,n){if(e.pageFloatLayoutContext.getPageFloatContinuationsDeferredToNext().length>0)if(e.lastAfterPosition){let i;return n?(i=n.clone(),i.primary=e.lastAfterPosition):i=new ht(e.lastAfterPosition),i}else return null;else return null}layoutColumn(e,n){let s=this.currentLayoutPosition.flowPositions[n];if(!s||!this.matchPageSide(s.startBreakType))return v(!0);this.setFormattingContextToColumn(e,n),e.init(),this.primaryFlows[n]&&e.bands.length>0&&(e.forceNonfitting=!1);let o=A("layoutColumn");return this.layoutDeferredPageFloats(e).then(()=>{if(e.pageFloatLayoutContext.isInvalidated()){o.finish(!0);return}let i=[],a=[],l=!0;o.loopWithFrame(c=>{if(e.pageFloatLayoutContext.hasContinuingFloatFragmentsInFlow(n)){c.breakLoop();return}for(;s.positions.length-a.length>0;){let u=0;for(;a.includes(u);)u++;let d=s.positions[u];if(d.flowChunk.startOffset>this.lookupOffset||this.flowChunkIsAfterParentFlowForcedBreak(d.flowChunk))break;for(let g=u+1;g<s.positions.length;g++){if(a.includes(g))continue;let m=s.positions[g];if(m.flowChunk.startOffset>this.lookupOffset||this.flowChunkIsAfterParentFlowForcedBreak(m.flowChunk))break;m.flowChunk.isBetter(d.flowChunk)&&(d=m,u=g)}let h=d.flowChunk,f=!0;if(e.layout(d.chunkPosition,l,s.breakAfter).then(g=>{if(e.pageFloatLayoutContext.isInvalidated()){c.breakLoop();return}if(l=!1,d.flowChunk.repeated&&(g===null||h.exclusive)&&i.push(u),h.exclusive){a.push(u),c.breakLoop();return}else{let m=!!g||!!e.pageBreakType,y=this.getLastAfterPositionIfDeferredFloatsExists(e,g);if(e.pageBreakType&&y?(d.chunkPosition=y,s.breakAfter=e.pageBreakType,e.pageBreakType=null):(a.push(u),(g||y)&&(d.chunkPosition=g||y,i.push(u)),s.startBreakType=Rc(e.pageBreakType)),m){c.breakLoop();return}}e.forceNonfitting=!1,f?f=!1:c.continueLoop()}),f){f=!1;return}}c.breakLoop()}).then(()=>{if(!e.pageFloatLayoutContext.isInvalidated()){s.positions=s.positions.filter((u,d)=>i.includes(d)||!a.includes(d)),s.breakAfter==="column"&&(s.breakAfter=null),e.saveDistanceToBlockEndFloats();let c=e.pageFloatLayoutContext.getMaxReachedAfterEdge();e.updateMaxReachedAfterEdge(c)}o.finish(!0)})}),o.result()}createLayoutConstraint(e){let n=this.currentLayoutPosition.page-1,s=this.counterStore.createLayoutConstraint(n);return new Ta([s].concat(e.getLayoutConstraints()))}createAndLayoutColumn(e,n,s,o,i,a,l,c,u,d,h,f,g,m){let y=e.vertical?e.isAutoWidth&&e.isRightDependentOnAutoWidth:e.isAutoHeight&&e.isTopDependentOnAutoHeight,E=i.element,C=new fn(c,ae.COLUMN,null,l,null,null,null),x=this.currentLayoutPosition.clone(),N=A("createAndLayoutColumn"),S;return N.loopWithFrame(w=>{let k=this.createLayoutConstraint(C);if(u>1){let R=this.viewport.document.createElement("div");if(T(R,"position","absolute"),E.appendChild(R),S=new Bs(R,g,this.clientLayout,k,C),S.forceNonfitting=m,S.vertical=i.vertical,S.rtl=i.rtl,S.snapHeight=i.snapHeight,S.snapWidth=i.snapWidth,i.vertical){let G=(i.rtl?u-a-1:a)*(h+d)+i.paddingTop,de=parseFloat(E.style.width);S.setHorizontalPosition(i.paddingLeft+de-i.width,i.width),S.setVerticalPosition(G,h)}else{let G=(i.rtl?u-a-1:a)*(h+d)+i.paddingLeft;S.setVerticalPosition(i.paddingTop,i.height),S.setHorizontalPosition(G,h)}S.originX=n,S.originY=s}else S=new Bs(E,g,this.clientLayout,k,C),S.copyFrom(i);S.exclusions=y?[]:o.concat(),S.innerShape=f,C.setContainer(S),(S.vertical?S.height:S.width)>=0?this.layoutColumn(S,l).then(()=>{C.isInvalidated()||C.finish(),S.pageFloatLayoutContext.isInvalidated()&&!c.isInvalidated()?(S.pageFloatLayoutContext.validate(),this.currentLayoutPosition=x.clone(),S.element!==E&&E.removeChild(S.element),w.continueLoop()):w.breakLoop()}):(C.finish(),w.breakLoop())}).then(()=>{N.finish(S)}),N.result()}setPagePageFloatLayoutContextContainer(e,n,s){(n instanceof Hi||n instanceof Us&&!(n instanceof an))&&e.setContainer(s)}getRegionPageFloatLayoutContext(e,n,s,o){n instanceof rn;let i=n.getProp(this,"writing-mode")||null,a=n.getProp(this,"direction")||null;return new fn(e,ae.REGION,s,o,null,i,a)}layoutFlowColumnsWithBalancing(e,n,s,o,i,a,l,c,u){let d=this.currentLayoutPosition.clone(),h=this.getRegionPageFloatLayoutContext(a,n,l,c),f=!0,g=()=>(this.currentLayoutPosition=d.clone(),this.layoutFlowColumns(e,n,s,o,i,a,h,l,c,u,f).thenAsync(m=>m?v({columns:m,position:this.currentLayoutPosition}):v(null)));return g().thenAsync(m=>{if(!m)return v(null);if(u<=1)return v(m.columns);let y=n.getProp(this,"column-fill")||b.balance,E=this.currentLayoutPosition.flowPositions[c];let C=Wf(u,y,g,h,l,m.columns,E);return C?(f=!1,a.lock(),h.lock(),C.balanceColumns(m).thenAsync(x=>(a.unlock(),a.validate(),h.unlock(),this.currentLayoutPosition=x.position,v(x.columns)))):v(m.columns)})}layoutFlowColumns(e,n,s,o,i,a,l,c,u,d,h){let f=A("layoutFlowColumns"),g=this.currentLayoutPosition.clone(),m=n.getPropAsNumber(this,"column-gap"),y=d>1?n.getPropAsNumber(this,"column-width"):c.vertical?c.height:c.width,E=n.getActiveRegions(this),C=n.getProp(this,"shape-inside"),x=Rr(C,0,0,c.width,c.height,this),N=new Za(u,this,this.viewport,this.styler,E,this.xmldoc,this.faces,this.style.footnoteProps,this,e,this.customRenderer,this.fallbackMap,this.documentURLTransformer),S=0,w=null,k=[];return f.loopWithFrame(R=>{this.createAndLayoutColumn(n,s,o,i,c,S++,u,l,d,m,y,x,N,h).then(G=>{if(a.isInvalidated()){k=null,R.breakLoop();return}if((!!G.pageBreakType&&G.pageBreakType!=="column"||S===d)&&!l.isInvalidated()&&l.finish(),l.isInvalidated()){S=0,this.currentLayoutPosition=g.clone(),l.validate(),l.isLocked()?(k=null,R.breakLoop()):R.continueLoop();return}w=G,k[S-1]=w,w.pageBreakType&&w.pageBreakType!="column"&&(S=d,w.pageBreakType!="region"&&(this.pageBreaks[u]=!0)),S<d?R.continueLoop():R.breakLoop()})}).then(()=>{f.finish(k)}),f.result()}layoutContainer(e,n,s,o,i,a,l){n.reset();let c=n.getProp(this,"enabled");if(c&&c!==b._true)return v(!0);let u=A("layoutContainer"),h=n.getProp(this,"wrap-flow")===b.auto,f=n.getProp(this,"flow-from"),g=this.viewport.document.createElement("div");g.role=n instanceof zi?"complementary":"presentation";let m=n.getProp(this,"position");T(g,"position",m?m.name:"absolute");let y=n instanceof an;n instanceof rn?s.appendChild(g):s.insertBefore(g,s.firstChild);let C=new go(g);C.vertical=n.vertical,C.rtl=n.rtl,C.borderBoxSizing=n.borderBoxSizing,C.exclusions=a,n.prepareContainer(this,C,e,this.faces,this.clientLayout),n instanceof an&&(C.width<=0||C.height<=0)&&V.warn("Negative or zero page area size"),C.originX=o,C.originY=i,o+=C.left+C.marginLeft+C.borderLeft,i+=C.top+C.marginTop+C.borderTop,this.setPagePageFloatLayoutContextContainer(l,n,C);let x,N=!1;if(!f||!f.isIdent()){let S=n.getProp(this,"content");if(S instanceof B&&S.expr instanceof Z&&S.expr.str.startsWith("running-element-"))S.visit(new hn(g,this,S,this.counterStore.getExprContentListener()));else if(S&&Nt(S)){let w="span";S.url&&(w="img");let k=this.viewport.document.createElement(w);S.visit(new hn(k,this,S,this.counterStore.getExprContentListener())),g.appendChild(k),w=="img"&&n.transferSingleUriContentProps(this,k,this.faces),n.transferContentProps(this,C,e,this.faces),w=="span"&&Af(k,n.getProp(this,"text-autospace"),n.getProp(this,"text-spacing-trim"),n.getProp(this,"hanging-punctuation"),this.lang,n.vertical)}else n.suppressEmptyBoxGeneration&&(s.removeChild(g),N=!0);N||n.finishContainer(this,C,e,null,1,this.clientLayout,this.faces),x=v(!0)}else if(this.pageBreaks[f.toString()])l.isInvalidated()||n.finishContainer(this,C,e,null,1,this.clientLayout,this.faces),x=v(!0);else{let S=A("layoutContainer.inner"),w=f.toString(),k=n.getPropAsNumber(this,"column-count");this.layoutFlowColumnsWithBalancing(e,n,o,i,a,l,C,w,k).then(R=>{if(!l.isInvalidated()){let G=R[0];G.element===g&&(C=G),C.computedBlockSize=Math.max.apply(null,R.map(Xe=>Xe.computedBlockSize)),n.finishContainer(this,C,e,G,k,this.clientLayout,this.faces);let de=this.currentLayoutPosition.flowPositions[w];de&&de.breakAfter==="region"&&(de.breakAfter=null)}S.finish(!0)}),x=S.result()}return x.then(()=>{if(l.isInvalidated()){u.finish(!0);return}if(!n.isAutoHeight||Math.floor(C.computedBlockSize)>0){if(!N&&!h){let w=n.getProp(this,"shape-outside"),k=C.getOuterShape(w,this);a.push(k)}}else if(n.children.length==0){s.removeChild(g),u.finish(!0);return}let S=y?0:n.children.length-1;u.loop(()=>{for(;S>=0&&S<n.children.length;){let w=n.children[y?S++:S--],k=this.layoutContainer(e,w,g,o,i,a,l);if(k.isPending())return k.thenAsync(()=>v(!l.isInvalidated()));if(l.isInvalidated())break}return v(!1)}).then(()=>{u.finish(!0)})}),u.result()}processLinger(){let e=this.currentLayoutPosition.page;for(let n in this.currentLayoutPosition.flowPositions){let s=this.currentLayoutPosition.flowPositions[n];for(let o=s.positions.length-1;o>=0;o--){let i=s.positions[o];i.flowChunk.startPage>=0&&i.flowChunk.startPage+i.flowChunk.linger-1<=e&&s.positions.splice(o,1)}}}initLingering(){let e=this.currentLayoutPosition.page;for(let n in this.currentLayoutPosition.flowPositions){let s=this.currentLayoutPosition.flowPositions[n];for(let o=s.positions.length-1;o>=0;o--){let i=s.positions[o];i.flowChunk.startPage<0&&i.flowChunk.startOffset<this.lookupOffset&&(i.flowChunk.startPage=e)}}}noMorePrimaryFlows(e){for(let n in this.primaryFlows){let s=e.flowPositions[n];if(s&&s.positions.length>0)return!1}return!0}layoutNextPage(e,n){var g;let s=e.container===e.bleedBox;this.pageBreaks={},n?(this.currentLayoutPosition=n.clone(),this.styler.replayFlowElementsFromOffset(n.highestSeenOffset)):(this.currentLayoutPosition=new Zr,this.styler.replayFlowElementsFromOffset(-1)),this.lang&&e.bleedBox.setAttribute("lang",this.lang),n=this.currentLayoutPosition;let o=1e4;if(n.page>o)throw new Error(`Too many pages generated (over ${o} pages)`);let i=n.startSideOfFlow("body");n.isBlankPage=On(i)&&this.matchPageSide(i),e.isBlankPage=n.isBlankPage,n.page++,e.pageType==null&&(e.pageType=(g=e.isBlankPage?this.styler.cascade.previousPageType:this.styler.cascade.currentPageType)!=null?g:"",this.styler.cascade.previousPageType=this.styler.cascade.currentPageType),this.clearScope(this.style.pageScope),this.layoutPositionAtPageStart=n.clone();let a=s?{}:this.pageManager.getCascadedPageStyle(e.pageType);if(this.styler.cascade.applyVarFilter([a],this.styler,null),this.styler.cascade.applyCalcFilter(a,this.styler.context),!s){let m=new ee(this.style.pageScope,"left-page");e.side=m.evaluate(this)?"left":"right",e.container.setAttribute("data-vivliostyle-page-side",e.side)}let l=this.selectPageMaster(a);if(!l)return v(null);let c=0;if(!s){e.setAutoPageWidth(l.pageBox.specified.width.value===Rn),e.setAutoPageHeight(l.pageBox.specified.height.value===In),this.counterStore.setCurrentPage(e),this.counterStore.updatePageCounters(a,this);let m=hp(Gi(a),this);this.setPageSizeAndBleed(m,e),dg(a,m,e,this),c=m.bleedOffset+m.bleed}let u=!s&&l.getProp(this,"writing-mode")||b.horizontal_tb;this.pageVertical=u!=b.horizontal_tb;let d=l.getProp(this,"direction")||b.ltr,h=new fn(this.rootPageFloatLayoutContext,ae.PAGE,null,null,null,u,d),f=A("layoutNextPage");return f.loopWithFrame(m=>{this.layoutContainer(e,l,e.bleedBox,c,c,[],h).then(()=>{h.isInvalidated()||h.finish(),h.isInvalidated()?(this.currentLayoutPosition=this.layoutPositionAtPageStart.clone(),h.validate(),m.continueLoop()):m.breakLoop()})}).then(()=>{l.adjustPageLayout(this,e,this.clientLayout),s||(this.processLinger(),n=this.currentLayoutPosition,Object.keys(n.flowPositions).forEach(y=>{let E=n.flowPositions[y],C=E.breakAfter;C&&(C==="page"||!this.matchPageSide(C))&&(E.breakAfter=null)})),this.currentLayoutPosition=this.layoutPositionAtPageStart=null,n.highestSeenOffset=this.styler.getReachedOffset();let m=this.style.store.getTriggersForDoc(this.xmldoc);e.finish(m,this.clientLayout),this.noMorePrimaryFlows(n)&&(n=null),f.finish(n)}),f.result()}setPageSizeAndBleed(e,n){this.actualPageWidth=e.pageWidth,this.actualPageHeight=e.pageHeight,this.pageSheetWidth=e.pageWidth+e.cropOffset*2,this.pageSheetHeight=e.pageHeight+e.cropOffset*2,n.container.style.width=`${this.pageSheetWidth}px`,n.container.style.height=`${this.pageSheetHeight}px`,n.bleedBox.style.left=`${e.bleedOffset}px`,n.bleedBox.style.width=`${e.pageWidth}px`,n.bleedBox.style.top=`${e.bleedOffset}px`,n.bleedBox.style.height=`${e.pageHeight}px`,n.bleedBox.style.padding=`${e.bleed}px`}},Sp=class r extends En{constructor(e,n,s,o){super(e.rootScope,e,n,s,o,e.validatorSet,!s);this.masterHandler=e;p(this,"insideRegion",!1)}startPageTemplateRule(){}startPageMasterRule(e,n,s){let o=new Io(this.masterHandler.pageScope,e,n,s,this.masterHandler.rootBox,this.condition,this.owner.getBaseSpecificity());this.masterHandler.pushHandler(new Wa(o.scope,this.masterHandler,o,this.validatorSet))}startWhenRule(e){let n=e.expr;this.condition!=null&&(n=tt(this.scope,this.condition,n)),this.masterHandler.pushHandler(new r(this.masterHandler,n,this,this.regionId))}startDefineRule(){this.masterHandler.pushHandler(new fa(this.scope,this.owner))}startFontFaceRule(){let e={};this.masterHandler.fontFaces.push({properties:e,condition:this.condition}),this.masterHandler.pushHandler(new Is(this.scope,this.owner,null,e,this.masterHandler.validatorSet,"font-face"))}startFlowRule(e){let n=this.masterHandler.flowProps[e];n||(n={},this.masterHandler.flowProps[e]=n),this.masterHandler.pushHandler(new Is(this.scope,this.owner,null,n,this.masterHandler.validatorSet))}startViewportRule(){let e={};this.masterHandler.viewportProps.push(e),this.masterHandler.pushHandler(new Is(this.scope,this.owner,this.condition,e,this.masterHandler.validatorSet))}startFootnoteRule(e){let n=this.masterHandler.footnoteProps;if(e){let s=wo(n,"_pseudos");n=s[e],n||(n={},s[e]=n)}this.masterHandler.pushHandler(new Is(this.scope,this.owner,null,n,this.masterHandler.validatorSet))}startRegionRule(){this.insideRegion=!0,this.startSelectorRule()}startPageRule(){let e=new ja(this.masterHandler.pageScope,this.masterHandler,this,this.validatorSet,this.masterHandler.pageProps);this.masterHandler.pushHandler(e),e.startPageRule()}startRuleBody(){if(En.prototype.startRuleBody.call(this),this.insideRegion){this.insideRegion=!1;let e=`R${this.masterHandler.regionCount++}`;this.special("region-id",L(e)),this.endRule();let n=new r(this.masterHandler,this.condition,this,e);this.masterHandler.pushHandler(n),n.startRuleBody()}}},nl=class extends Br{constructor(e){super();this.validatorSet=e;p(this,"rootScope");p(this,"pageScope");p(this,"rootBox");p(this,"cascadeParserHandler");p(this,"regionCount",0);p(this,"fontFaces",[]);p(this,"footnoteProps",{});p(this,"flowProps",{});p(this,"viewportProps",[]);p(this,"pageProps",{});this.rootScope=new as(null),this.pageScope=new as(this.rootScope),this.rootBox=new _a(this.rootScope),this.cascadeParserHandler=new Sp(this,null,null,null),this.slave=this.cascadeParserHandler}};function yb(r,t){return t.parseOPSResource(r)}var sl=class extends fs{constructor(e){super(yb,"document");this.fontDeobfuscator=e;p(this,"styleByKey",{});p(this,"styleFetcherByKey",{});p(this,"styleByDocURL",{});p(this,"triggersByDocURL",{});p(this,"validatorSet",null);p(this,"styleSheets",[]);p(this,"triggerSingleDocumentPreprocessing",!1)}init(e,n){this.setStyleSheets(e,n);let s=A("OPSDocStore.init");return this.validatorSet=Wd(),xb().then(()=>{this.triggerSingleDocumentPreprocessing=!0,s.finish(!0)}),s.result()}getStyleForDoc(e){return this.styleByDocURL[e.url]}getTriggersForDoc(e){return this.triggersByDocURL[e.url]}setStyleSheets(e,n){this.clearStyleSheets(),e&&e.forEach(this.addAuthorStyleSheet,this),n&&n.forEach(this.addUserStyleSheet,this)}clearStyleSheets(){this.styleSheets.splice(0)}addAuthorStyleSheet(e){let n=e.url;n&&(n=J(Pn(n),ln)),this.styleSheets.push({url:n,text:e.text,flavor:"Author",classes:null,media:null})}addUserStyleSheet(e){let n=e.url;n&&(n=J(Pn(n),ln)),this.styleSheets.push({url:n,text:e.text,flavor:"User",classes:null,media:null})}parseOPSResource(e){let n=A("OPSDocStore.load"),s=e.url,o=s.endsWith("?viv-toc-box");return xp(e,this).then(i=>{var f;if(!i){n.finish(null);return}if(this.triggerSingleDocumentPreprocessing){let g=Ge("PREPROCESS_SINGLE_DOCUMENT");for(let m=0;m<g.length;m++)try{g[m](i.document)}catch(y){V.warn("Error during single document preprocessing:",y)}}let a=[],l=i.document.getElementsByTagNameNS("http://www.idpf.org/2007/ops","trigger");for(let g=0;g<l.length;g++){let m=l[g],y=m.getAttributeNS("http://www.w3.org/2001/xml-events","observer"),E=m.getAttributeNS("http://www.w3.org/2001/xml-events","event"),C=m.getAttribute("action"),x=m.getAttribute("ref");y&&E&&C&&x&&a.push({observer:y,event:E,action:C,ref:x})}this.triggersByDocURL[s]=a;let c=[];if(c.push({url:J("user-agent-page.css",Xt),text:xc,flavor:"UA",classes:null,media:null}),o)c.push({url:J("user-agent-toc.css",Xt),text:Ec,flavor:"UA",classes:null,media:null});else{let g=i.document.querySelectorAll("style, link, meta");for(let m of g){let y=m.namespaceURI,E=m.localName;if(y=="http://www.w3.org/1999/xhtml")if(E=="style"){let C=m.getAttribute("class"),x=m.getAttribute("media"),N=m.getAttribute("title");c.push({url:s,text:m.textContent,flavor:"Author",classes:N?C:null,media:x})}else if(E=="link"){let C=m.getAttribute("href"),x=(f=m.getAttribute("rel"))==null?void 0:f.split(/\s+/),N=m.getAttribute("class"),S=m.getAttribute("media");if(C&&(x!=null&&x.includes("stylesheet"))&&(!x.includes("alternate")||N)){let w=J(C,s),k=m.getAttribute("title");c.push({url:w,text:null,classes:k?N:null,media:S,flavor:"Author"})}}else E=="meta"&&m.getAttribute("name")=="viewport"&&c.push({url:s,text:this.processViewportMeta(m),flavor:"Author",classes:null,media:null})}for(let m=0;m<this.styleSheets.length;m++)c.push(this.styleSheets[m])}let u="";for(let g=0;g<c.length;g++)u+=c[g].url,u+="^",c[g].text&&(u+=c[g].text),u+="^";let d=this.styleByKey[u];if(d){this.styleByDocURL[s]=d,n.finish(i);return}let h=this.styleFetcherByKey[u];h||(h=new Qt(()=>{let g=A("fetchStylesheet"),m=0,y=new nl(this.validatorSet);return g.loop(()=>{if(m<c.length){let E=c[m++];return y.startStylesheet(E.flavor),E.text!==null?Ur(E.text,y,E.url,E.classes,E.media).thenReturn(!0):Tc(E.url,y,E.classes,E.media)}return v(!1)}).then(()=>{let E=y.cascadeParserHandler.finish();d=new Ep(this,y.rootScope,y.pageScope,E,y.rootBox,y.fontFaces,y.footnoteProps,y.flowProps,y.viewportProps,y.pageProps),this.styleByKey[u]=d,delete this.styleFetcherByKey[u],g.finish(d)}),g.result()},`FetchStylesheet ${s}`),this.styleFetcherByKey[u]=h,h.start()),h.get().then(g=>{this.styleByDocURL[s]=g,n.finish(i)})}),n.result()}processViewportMeta(e){return""}};var Xi="\u25B8",Eg="\u25BE",Eb="\u25B9";function il(r){let t=Array.from(r.querySelectorAll("nav[*|type],nav[epub\\:type]"));if(t.length>0||(t=Array.from(r.querySelectorAll("[role=doc-toc]")),t.length>0))return t;let e="nav,.toc,#toc,#table-of-contents,#contents,[role=directory]";for(let n of r.querySelectorAll(e)){if(t.find(o=>o.contains(n)))continue;let s=n;/^h[1-6]$/.test(s.localName)&&(s.previousElementSibling?s=s.nextElementSibling:s=s.parentElement),s&&s.querySelector("li a[href]")&&t.push(s)}return t}function Sg(r){let t=il(r),e=[];for(let n of t)for(let s of n.querySelectorAll("li a[href]"))e.push(s);return e}var ol=class{constructor(t,e,n,s,o,i,a,l,c,u){this.store=t;this.url=e;this.lang=n;this.clientLayout=s;this.fontMapper=o;this.rendererFactory=a;this.fallbackMap=l;this.documentURLTransformer=c;this.counterStore=u;p(this,"pref");p(this,"page",null);p(this,"instance",null);this.pref=Sr(i),this.pref.spreadView=!1}setAutoHeight(t,e){if(e--!=0){for(let n=t.firstChild;n;n=n.nextSibling)if(n.nodeType==1){let s=n;gt(s,"height","auto")!="auto"&&(T(s,"height","auto"),this.setAutoHeight(s,e)),gt(s,"position","static")=="absolute"&&(T(s,"position","relative"),this.setAutoHeight(s,e))}}}makeCustomRenderer(t){let e=this.rendererFactory.makeCustomRenderer(t);return(n,s,o)=>{let i=o.behavior;if(i)switch(i.toString()){case"toc-node-anchor":o.color=b.inherit,o["text-decoration"]=b.none;break;case"toc-node":o.display=b.block,o.margin=ne,o.padding=ne,o["padding-inline-start"]=new P(1.25,"em");break;case"toc-node-first-child":o.display=b.inline_block,o.margin=new P(.2,"em"),o["vertical-align"]=b.top,o.color=b.inherit,o["text-decoration"]=b.none;break;case"toc-container":o.padding=ne;break}if(!i||i.toString()!="toc-node"&&i.toString()!="toc-container")return e(n,s,o);let a=n.firstChild;a&&a.nodeType!==1&&ue(a)&&n.replaceChild(n.ownerDocument.createComment(a.textContent),a);let l=s.getAttribute("data-adapt-class");if(l=="toc-node"){let u=s.firstChild;u.textContent!=Xi&&(u.textContent=Xi,T(u,"cursor","pointer"),u.addEventListener("click",Sb,!1),u.setAttribute("role","button"),u.setAttribute("aria-expanded","false"),s.setAttribute("aria-expanded","false"),s.style.height!=="0px"&&(u.tabIndex=0))}let c=s.ownerDocument.createElement("div");if(c.setAttribute("data-adapt-process-children","true"),i.toString()=="toc-node"){let u=s.ownerDocument.createElement("div");if(u.textContent=Eb,T(u,"margin","0.2em 0 0 -1em"),T(u,"margin-inline-start","-1em"),T(u,"margin-inline-end","0"),T(u,"display","inline-block"),T(u,"width","1em"),T(u,"text-align","center"),T(u,"vertical-align","top"),T(u,"cursor","default"),T(u,"font-family","Menlo,sans-serif"),c.appendChild(u),T(c,"overflow","hidden"),c.setAttribute("data-adapt-class","toc-node"),c.setAttribute("role","treeitem"),l=="toc-node"||l=="toc-container"){T(c,"height","0px");let d=n.firstElementChild;d&&d.localName==="a"&&(d.tabIndex=-1)}else s.setAttribute("role","tree")}else l=="toc-node"&&(c.setAttribute("data-adapt-class","toc-container"),c.setAttribute("role","group"),c.setAttribute("aria-hidden","true"));return v(c)}}showTOC(t,e,n,s,o){if(this.page)return v(this.page);let i=A("showTOC"),a=new fo(t,t);this.page=a;let l=Pt(this.url)+"?viv-toc-box";return this.store.load(l).then(c=>{for(let g of il(c.document))g.setAttribute("data-vivliostyle-role","doc-toc");let u=this.store.getStyleForDoc(c),d=u.sizeViewport(n,1e5,o);e=new vn(e.window,d.fontSize,0,e.root,d.width,d.height);let h=this.makeCustomRenderer(c),f=new es(u,c,this.lang,e,this.clientLayout,this.fontMapper,h,this.fallbackMap,0,this.documentURLTransformer,this.counterStore);this.instance=f,f.pref=this.pref,f.init().then(()=>{f.layoutNextPage(a,null).then(()=>{this.setAutoHeight(t,2),i.finish(a)})})}),i.result()}hideTOC(){this.page&&(this.page.container.style.visibility="hidden",this.page.container.setAttribute("aria-hidden","true"))}isTOCVisible(){return!!this.page&&this.page.container.style.visibility==="visible"}getTOC(){if(!this.page)return[];function t(s){if(!s)return[];let o=s.querySelectorAll(":scope > [role=treeitem] > a[href]");return Array.from(o).map(e)}function e(s){let o=new URL(s.href),[,i]=o.hash.match(/^#?(.*)$/),a=s.innerText,l=s.parentElement.querySelector("[role=group]"),c=t(l);return{id:i,title:a,children:c}}let n=this.page.container.querySelector("[role=tree]");return t(n)}};function Sb(r){let t=r.target,e=t.textContent==Xi;t.textContent=e?Eg:Xi;let n=t.parentNode;t.setAttribute("aria-expanded",e?"true":"false"),n.setAttribute("aria-expanded",e?"true":"false");let s=n.firstChild;for(;s;){if(s.nodeType===1){let o=s,i=o.getAttribute("data-adapt-class");if(i==="toc-container"){if(o.setAttribute("aria-hidden",e?"false":"true"),o.firstChild){s=o.firstChild;continue}}else if(i==="toc-node"&&(o.style.height=e?"auto":"0px",o.children.length>=2&&(o.children[1].tabIndex=e?0:-1),o.children.length>=3&&(o.children[0].tabIndex=e?0:-1,!e))){let a=o.children[0];if(a.textContent==Eg){a.textContent=Xi,a.setAttribute("aria-expanded","false"),o.setAttribute("aria-expanded","false"),s=o.children[2];continue}}}for(;!s.nextSibling&&s.parentNode!==n;)s=s.parentNode;s=s.nextSibling}r.stopPropagation()}var Yi=class extends sl{constructor(){super(null);p(this,"plainXMLStore");p(this,"jsonStore");p(this,"opfByURL",{});p(this,"primaryOPFByEPubURL",{});p(this,"deobfuscators",{});p(this,"documents",{});this.fontDeobfuscator=this.makeDeobfuscatorFactory(),this.plainXMLStore=bg(),this.jsonStore=mh()}makeDeobfuscatorFactory(){return e=>this.deobfuscators[e]}loadAsPlainXML(e,n,s){return this.plainXMLStore.load(e,n,s)}startLoadingAsPlainXML(e){this.plainXMLStore.fetch(e)}loadAsJSON(e,n,s){return this.jsonStore.load(e,n,s)}loadPubDoc(e){let n=A("loadPubDoc");return gs(e,null,"HEAD").then(s=>{if(s.status>=400)this.loadEPUBDoc(e).then(o=>{if(o){n.finish(o);return}V.error(`Failed to fetch a source document from ${e} (${s.status}${s.statusText?" "+s.statusText:""})`),n.finish(null)});else if(!s.status&&!s.responseXML&&!s.responseText&&!s.responseBlob&&!s.contentType&&/\/[^/.]+(?:[#?]|$)/.test(e)&&(e=e.replace(/([#?]|$)/,"/$1")),s.contentType=="application/oebps-package+xml"||/\.opf(?:[#?]|$)/.test(e)){let[,o,i]=e.match(/^((?:.*\/)?)([^/]*)$/);this.loadOPF(o,i).thenFinish(n)}else s.contentType=="application/ld+json"||s.contentType=="application/webpub+json"||s.contentType=="application/audiobook+json"||s.contentType=="application/json"||/\.json(?:ld)?(?:[#?]|$)/.test(e)?this.loadAsJSON(e,!0).then(o=>{if(!o){this.reportLoadError(e),n.finish(null);return}let i=new zs(this,e);i.initWithWebPubManifest(o,void 0,e).then(()=>{n.finish(i)})}):this.loadWebPub(e).then(o=>{if(o){n.finish(o);return}this.loadEPUBDoc(e).then(i=>{if(i){n.finish(i);return}V.error(`Failed to load ${e}.`),n.finish(null)})})}),n.result()}loadEPUBDoc(e){let n=A("loadEPUBDoc");e.endsWith("/")||(e=e+"/"),this.startLoadingAsPlainXML(e+"META-INF/encryption.xml");let s=e+"META-INF/container.xml";return this.loadAsPlainXML(s).then(o=>{if(o){let i=o.doc().child("container").child("rootfiles").child("rootfile").attribute("full-path");for(let a of i)if(a){this.loadOPF(e,a).thenFinish(n);return}}n.finish(null)}),n.result()}loadOPF(e,n){let s=e+n,o=this.opfByURL[s];if(o)return v(o);let i=A("loadOPF");return this.loadAsPlainXML(s,!0,`Failed to fetch EPUB OPF ${s}`).then(a=>{a?(o=new zs(this,e),this.opfByURL[s]=o,this.primaryOPFByEPubURL[e]=o,this.plainXMLStore.resources[e+"META-INF/container.xml"]?this.loadAsPlainXML(e+"META-INF/encryption.xml").then(l=>{o.initWithXMLDoc(a,l).then(()=>{i.finish(o)})}):o.initWithXMLDoc(a,null).then(()=>{i.finish(o)})):this.reportLoadError(s)}),i.result()}loadWebPub(e){let n=A("loadWebPub");return this.load(e).then(s=>{if(!s)this.reportLoadError(e);else if(s.document.querySelector("a[href='META-INF/'],a[href$='/META-INF/']"))n.finish(null);else{let o=s.document,i=new zs(this,e),a=o.querySelector("link[rel='publication'],link[rel='manifest'][type='application/webpub+json']");if(a){let l=a.getAttribute("href");if(/^#/.test(l)){let c=$s(o.getElementById(l.substr(1)).textContent);i.initWithWebPubManifest(c,o).then(()=>{n.finish(i)})}else{let c=J(a.getAttribute("href"),e);this.loadAsJSON(c,!0,`Failed to fetch Publication Manifest ${c}`).then(u=>{i.initWithWebPubManifest(u,o,c).then(()=>{n.finish(i)})})}}else i.initWithWebPubManifest({},o).then(()=>{i.toc&&i.toc.src===s.url&&il(o).length===0&&(i.toc=null),n.finish(i)})}}),n.result()}addDocument(e,n){let s=A("EPUBDocStore.load"),o=Pt(e);return(this.documents[o]=this.parseOPSResource({status:200,statusText:"",url:o,contentType:n.contentType,responseText:null,responseXML:n,responseBlob:null})).thenFinish(s),s.result()}reportLoadError(e){let n=o=>o.replace(/([^:/?#]|^)[/?#].*/,"$1"),s=()=>{let o=n(e);return!(o===n(ln)||Object.keys(this.resources).find(a=>this.resources[a]&&n(a)===o)||!/^https?:?\/\/[^/]/.test(e)||/\.(xhtml|xht|xml|opf)$/i.test(e))};e.startsWith("data:")?V.error(`Failed to load ${e}. Invalid data.`):e.startsWith("http:")&&ln.startsWith("https:")?V.error(`Failed to load ${e}. Mixed Content ("http:" content on "https:" context) is not allowed.`):s()?V.error(`Failed to load ${e}. This may be caused by the server not allowing cross-origin resource sharing (CORS).`):V.error(`Failed to load ${e}. The target resource is invalid.`)}load(e){let n=Pt(e),s=this.documents[n];if(s)return s.isPending()?s:v(s.get());{let o=A("EPUBDocStore.load");return s=super.load(n,!0,`Failed to fetch a source document from ${n}`),s.then(i=>{i?o.finish(i):this.reportLoadError(n)}),o.result()}}processViewportMeta(e){let n=e.getAttribute("content");if(!n)return"";let s={},o;for(;(o=n.match(/^,?\s*([-A-Za-z_.][-A-Za-z_0-9.]*)\s*=\s*([-+A-Za-z_0-9.]*)\s*/))!=null;)n=n.substr(o[0].length),s[o[1]]=o[2];let i=s.width-0,a=s.height-0;if(i&&a){let l=!!Object.values(this.primaryOPFByEPubURL).find(c=>c.prePaginated);return`@-epubx-viewport{width:${i}px;height:${a}px;}`+(l?`@page{size:${i}px ${a}px;margin:0;}`:"@page{margin:0;}")}return""}},al=class{constructor(){p(this,"id",null);p(this,"src","");p(this,"mediaType",null);p(this,"title",null);p(this,"itemRefElement",null);p(this,"spineIndex",-1);p(this,"compressedSize",0);p(this,"compressed",null);p(this,"epage",0);p(this,"epageCount",0);p(this,"startPage",null);p(this,"skipPagesBefore",null);p(this,"itemProperties");this.itemProperties=Dp}initWithElement(t,e){this.id=t.getAttribute("id"),this.src=J(t.getAttribute("href"),e),this.mediaType=t.getAttribute("media-type");let n=t.getAttribute("properties");n&&(this.itemProperties=Up(n.split(/\s+/)))}initWithParam(t){this.spineIndex=t.index,this.id=`item${t.index+1}`,this.src=t.url,this.startPage=t.startPage,this.skipPagesBefore=t.skipPagesBefore}};function vb(r){return r.id}function Tb(r){return t=>{let e=A("deobfuscator");return wb("SHA-1",r).then(n=>{let s=t.slice(0,1040),o=t.slice(1040,t.size);fh(s).then(i=>{let a=new DataView(i);for(let l=0;l<a.byteLength;l++){let c=a.getUint8(l);c^=n[l%20],a.setUint8(l,c)}e.finish(Nc([a,o]))})}),e.result()}}function wb(r,t){let e=A("makeDigest"),n=e.suspend();return window.crypto.subtle.digest(r,new TextEncoder().encode(t)).then(s=>{n.schedule(new Uint8Array(s))}),e.result()}var ts={dcterms:"http://purl.org/dc/terms/",marc:"http://id.loc.gov/vocabulary/",media:"http://www.idpf.org/epub/vocab/overlays/#",rendition:"http://www.idpf.org/vocab/rendition/#",onix:"http://www.editeur.org/ONIX/book/codelists/current.html#",xsd:"http://www.w3.org/2001/XMLSchema#",opf:"http://www.idpf.org/2007/opf"},ji="http://idpf.org/epub/vocab/package/meta/#",ve={language:`${ts.dcterms}language`,title:`${ts.dcterms}title`,creator:`${ts.dcterms}creator`,layout:`${ts.rendition}layout`,titleType:`${ji}title-type`,displaySeq:`${ji}display-seq`,alternateScript:`${ji}alternate-script`,role:`${ji}role`};function Pb(r,t){let e={};return(n,s)=>{var d,h,f,g,m,y;let o,i,a=n.r||e,l=s.r||e;if(r==ve.title&&(o=((d=a[ve.titleType])==null?void 0:d[0].v)=="main",i=((h=l[ve.titleType])==null?void 0:h[0].v)=="main",o!=i))return o?-1:1;let c=parseInt((f=a[ve.displaySeq])==null?void 0:f[0].v,10);isNaN(c)&&(c=Number.MAX_VALUE);let u=parseInt((g=l[ve.displaySeq])==null?void 0:g[0].v,10);return isNaN(u)&&(u=Number.MAX_VALUE),c!=u?c-u:r!=ve.language&&t&&(o=((m=a[ve.language]||a[ve.alternateScript])==null?void 0:m[0].v)==t,i=((y=l[ve.language]||l[ve.alternateScript])==null?void 0:y[0].v)==t,o!=i)?o?-1:1:n.o-s.o}}function kb(r,t){let e;if(!t)e=ts;else{e={};for(let h in ts)e[h]=ts[h];let d;for(;(d=t.match(/^\s*([A-Z_a-z\u007F-\uFFFF][-.A-Z_a-z0-9\u007F-\uFFFF]*):\s*(\S+)/))!=null;)t=t.substr(d[0].length),e[d[1]]=d[2]}let n=d=>{if(d){let h=d.match(/^\s*(([^:]*):)?(\S+)\s*$/);if(h){let f=h[2]?e[h[2]]:ji;if(f)return f+h[3]}}return null},s=1,o=r.childElements().forEachNonNull(d=>{if(d.localName=="meta"){let h=n(d.getAttribute("property"));if(h)return{name:h,value:d.textContent,id:d.getAttribute("id"),order:s++,refines:d.getAttribute("refines"),lang:null,scheme:n(d.getAttribute("scheme")),role:null}}else if(d.namespaceURI=="http://purl.org/dc/elements/1.1/")return{name:ts.dcterms+d.localName,order:s++,lang:d.getAttribute("xml:lang"),value:d.textContent,id:d.getAttribute("id"),refines:null,scheme:null,role:d.getAttribute("role")||d.getAttribute("opf:role")};return null}),i=ir(o,d=>d.refines),a=d=>Hp(d,(h,f)=>h.map(g=>{let m={v:g.value,o:g.order};g.scheme&&(m.s=g.scheme);let y=i[`#${g.id}`]||[];if(y.length||g.lang||g.role){g.lang&&y.push({name:ve.language,value:g.lang,lang:null,id:null,refines:g.id,scheme:null,order:g.order,role:null}),g.role&&y.push({name:ve.role,value:g.role,lang:null,id:null,refines:g.id,scheme:null,order:g.order,role:null});let E=ir(y,C=>C.name);m.r=a(E)}return m})),l=a(ir(o,d=>d.refines?null:d.name)),c=null;l[ve.language]&&(c=l[ve.language][0].v);let u=d=>{for(let h in d){let f=d[h];f.sort(Pb(h,c));for(let g=0;g<f.length;g++){let m=f[g].r;m&&u(m)}}};return u(l),l}function Ab(){let r=window.MathJax;return r?r.Hub:null}var Ng={"application/xhtml+xml":!0,"image/jpeg":!0,"image/png":!0,"image/svg+xml":!0,"image/gif":!0,"audio/mp3":!0},Np="viv-id-",zs=class{constructor(t,e){this.store=t;this.pubURL=e;p(this,"opfXML",null);p(this,"encXML",null);p(this,"items",null);p(this,"spine",null);p(this,"itemMap",null);p(this,"itemMapByPath",null);p(this,"uid",null);p(this,"bindings",{});p(this,"lang",null);p(this,"epageCount",0);p(this,"prePaginated",!1);p(this,"epageIsRenderedPage",!0);p(this,"epageCountCallback",null);p(this,"metadata",{});p(this,"toc",null);p(this,"cover",null);p(this,"fallbackMap",{});p(this,"pageProgression",null);p(this,"documentURLTransformer");this.documentURLTransformer=this.createDocumentURLTransformer()}createDocumentURLTransformer(){let t=this;class e{transformFragment(s,o){let i=o+(s?`#${s}`:"");return Np+Rl(i,":")}transformURL(s,o){let i=s.match(/^([^#]*)#?(.*)$/);if(i){let a=i[1]||o.replace(/\?viv-toc-box$/,""),l=decodeURIComponent(i[2]);if(a&&t.spine.some(c=>c.src===a))return`#${this.transformFragment(l,a)}`}return s}restoreURL(s){s.charAt(0)==="#"&&(s=s.substring(1)),s.indexOf(Np)===0&&(s=s.substring(Np.length));let i=_p(s,":").match(/^([^#]*)#?(.*)$/);return i?[i[1],i[2]]:[]}}return new e}getMetadata(){return this.metadata}getPathFromURL(t){if(t.startsWith("data:"))return t===this.pubURL?"":t;if(this.pubURL){let e=J("",this.pubURL);return t===e||t+"/"===e?"":(e.charAt(e.length-1)!="/"&&(e+="/"),t.substr(0,e.length)==e?decodeURIComponent(t.substr(e.length)):null)}else return t}initWithXMLDoc(t,e){this.opfXML=t,this.encXML=e;let n=t.doc().child("package"),s=n.attribute("unique-identifier")[0];if(s){let c=t.getElement(`${t.url}#${s}`);c&&(this.uid=c.textContent.replace(/[ \n\r\t]/g,""))}let o={};this.items=n.child("manifest").child("item").asArray().map(c=>{let u=new al,d=c;u.initWithElement(d,t.url);let h=d.getAttribute("fallback");return h&&!Ng[u.mediaType]&&(o[u.src]=h),!this.toc&&u.itemProperties.nav&&(this.toc=u),!this.cover&&u.itemProperties["cover-image"]&&(this.cover=u),u}),this.itemMap=Il(this.items,vb),this.itemMapByPath=Il(this.items,c=>this.getPathFromURL(c.src));for(let c in o){let u=c;for(;;){let d=this.itemMap[o[u]];if(!d)break;if(Ng[d.mediaType]){this.fallbackMap[c]=d.src;break}u=d.src}}this.spine=n.child("spine").child("itemref").asArray().map((c,u)=>{let d=c,h=d.getAttribute("idref"),f=this.itemMap[h];return f&&(f.itemRefElement=d,f.spineIndex=u),f});let i=n.child("spine").attribute("page-progression-direction")[0];i&&(this.pageProgression=xl(i));let a=e?e.doc().child("encryption").child("EncryptedData").predicate(yp.withChild("EncryptionMethod",yp.withAttribute("Algorithm","http://www.idpf.org/2008/embedding"))).child("CipherData").child("CipherReference").attribute("URI"):[],l=n.child("bindings").child("mediaType").asArray();for(let c=0;c<l.length;c++){let u=l[c].getAttribute("handler"),d=l[c].getAttribute("media-type");d&&u&&this.itemMap[u]&&(this.bindings[d]=this.itemMap[u].src)}if(this.metadata=kb(n.child("metadata"),n.attribute("prefix")[0]),this.metadata[ve.language]&&(this.lang=this.metadata[ve.language][0].v),this.metadata[ve.layout]&&(this.prePaginated=this.metadata[ve.layout][0].v==="pre-paginated"),a.length>0&&this.uid){let c=Tb(this.uid);for(let u=0;u<a.length;u++)this.store.deobfuscators[this.pubURL+a[u]]=c}return this.prePaginated&&this.assignAutoPages(),v(!0)}assignAutoPages(){let t=0;for(let e of this.spine){let n=this.prePaginated?1:Math.ceil(e.compressedSize/1024);e.epage=t,e.epageCount=n,t+=n}this.epageCount=t,this.epageCountCallback&&this.epageCountCallback(this.epageCount)}setEPageCountMode(t){this.epageIsRenderedPage=t||this.prePaginated}countEPages(t){if(this.epageCountCallback=t,this.epageIsRenderedPage)return this.prePaginated&&this.epageCount==0&&this.assignAutoPages(),v(!0);let e=0,n=0,s=A("countEPages");return s.loopWithFrame(o=>{if(n===this.spine.length){o.breakLoop();return}let i=this.spine[n++];i.epage=e,this.store.load(i.src).then(a=>{let l=1800,c=a.lang||this.lang;c&&c.match(/^(ja|ko|zh)/)&&(l/=3),i.epageCount=Math.ceil(a.getTotalOffset()/l),e+=i.epageCount,this.epageCount=e,this.epageCountCallback&&this.epageCountCallback(this.epageCount),o.continueLoop()})}).thenFinish(s),s.result()}initWithChapters(t,e){this.itemMap={},this.itemMapByPath={},this.items=[],this.spine=this.items;let n=this.opfXML=new $i(null,"",new DOMParser().parseFromString("<spine></spine>","text/xml"));return t.forEach(s=>{let o=new al;o.initWithParam(s),o.id;let i=n.document.createElement("itemref");i.setAttribute("idref",o.id),n.root.appendChild(i),o.itemRefElement=i,this.itemMap[o.id]=o;let a=this.getPathFromURL(s.url);a==null&&(a=s.url),this.itemMapByPath[a]=o,this.items.push(o)}),e?this.store.addDocument(t[0].url,e):v(null)}initWithWebPubManifest(t,e,n){var h,f,g,m;t.readingProgression&&(this.pageProgression=t.readingProgression),this.metadata===void 0&&(this.metadata={});let s=t.name||((h=t.metadata)==null?void 0:h.title)||(e==null?void 0:e.title);s&&(this.metadata[ve.title]=(Array.isArray(s)?s:[s]).map(y=>{var E;return{v:(E=y.value)!=null?E:y}}));let o=t.author||t.creator||((f=t.metadata)==null?void 0:f.author)||Array.from((g=e==null?void 0:e.querySelectorAll("meta[name='author'], meta[name='DC.Creator']"))!=null?g:[]).map(y=>y.content);o&&o.length!==0&&(this.metadata[ve.creator]=(Array.isArray(o)?o:[o]).map(y=>{var E;return{v:(E=y.name)!=null?E:y}}));let i=t.inLanguage||((m=t.metadata)==null?void 0:m.language)||(e==null?void 0:e.documentElement.lang)||(e==null?void 0:e.documentElement.getAttribute("xml:lang"));i&&(this.metadata[ve.language]=(Array.isArray(i)?i:[i]).map(y=>({v:y})));let a=this.getPathFromURL(this.pubURL);if(!t.readingOrder&&e&&a!==null){t.readingOrder=[encodeURI(a)];for(let y of Sg(e)){let E=y.getAttribute("href");if(/^(https?:)?\/\//.test(E)||/\.(jpe?g|png|gif|pdf|svg|mml)([#?]|$)/.test(E))continue;let C=Pt(J(E,this.pubURL)),x=this.getPathFromURL(C),N=x!==null?encodeURI(x):C;t.readingOrder.indexOf(N)==-1&&t.readingOrder.push(N)}}let l=[],c=0,u=-1;[t.readingOrder,t.resources].forEach(y=>{y instanceof Array&&y.forEach(E=>{let C=y===t.readingOrder,x=typeof E=="string"?E:E.url||E.href,N=typeof E=="string"?"":E.encodingFormat||E.href&&E.type||"";if(C||N==="text/html"||N==="application/xhtml+xml"||!N&&E.rel!=="stylesheet"&&/(^|\/)([^/]+\.(x?html|htm|xht)|[^/.]*)([#?]|$)/.test(x)){let S=n?n.replace(/\/[^/]+$/,"/"):this.pubURL,w={url:J(Pn(x),S),index:c++,startPage:null,skipPagesBefore:null};E.rel==="contents"&&u===-1&&(u=w.index),l.push(w)}})});let d=A("initWithWebPubManifest");return this.initWithChapters(l).then(()=>{var E,C;u!==-1&&(this.toc=this.items[u]),this.toc||(this.toc=n?(E=this.items)==null?void 0:E[0]:this.itemMapByPath[a]);let y=(C=t.readingOrder)==null?void 0:C.length;y&&y<this.items.length&&this.items.splice(y),d.finish(!0)}),d.result()}getCFI(t,e){let n=this.spine[t],s=A("getCFI");return this.store.load(n.src).then(o=>{let i=o.getNodeByOffset(e),a=null;if(i){let l=o.getNodeOffset(i,0,!1),c=e-l,u=new Uo;u.prependPathFromNode(i,c,!1,null),n.itemRefElement&&u.prependPathFromNode(n.itemRefElement,0,!1,null),a=u.toString()}s.finish(a)}),s.result()}resolveFragment(t){return pn("resolveFragment",e=>{if(!t){e.finish(null);return}let n=new Uo;n.fromString(t);let s;if(this.opfXML){let o=n.navigate(this.opfXML.document);if(o.node.nodeType!=1||o.after||!o.ref){e.finish(null);return}let i=o.node,a=i.getAttribute("idref");if(i.localName!="itemref"||!a||!this.itemMap[a]){e.finish(null);return}s=this.itemMap[a],n=o.ref}else s=this.spine[0];this.store.load(s.src).then(o=>{let i=n.navigate(o.document),a=o.getNodeOffset(i.node,i.offset,i.after);e.finish({spineIndex:s.spineIndex,offsetInItem:a,pageIndex:-1})})},(e,n)=>{V.warn(n,"Cannot resolve fragment:",t),e.finish(null)})}resolveEPage(t){return pn("resolveEPage",e=>{if(t<=0){e.finish({spineIndex:0,offsetInItem:0,pageIndex:-1});return}if(this.epageIsRenderedPage){let o=this.spine.findIndex(l=>l.epage==0&&l.epageCount==0||l.epage<=t&&l.epage+l.epageCount>t);o==-1&&(o=this.spine.length-1);let i=this.spine[o];(!i||i.epageCount==0)&&(i=this.spine[--o]);let a=Math.floor(t-i.epage);e.finish({spineIndex:o,offsetInItem:-1,pageIndex:a});return}let n=mt(this.spine.length,o=>{let i=this.spine[o];return i.epage+i.epageCount>t});n==this.spine.length&&n--;let s=this.spine[n];this.store.load(s.src).then(o=>{t-=s.epage,t>s.epageCount&&(t=s.epageCount);let i=0;if(t>0){let a=o.getTotalOffset();i=Math.round(a*t/s.epageCount),i==a&&i--}e.finish({spineIndex:n,offsetInItem:i,pageIndex:-1})})},(e,n)=>{V.warn(n,"Cannot resolve epage:",t),e.finish(null)})}getEPageFromPosition(t){let e=this.spine[t.spineIndex];if(this.epageIsRenderedPage){let s=e.epage+t.pageIndex;return v(s)}if(t.offsetInItem<=0)return v(e.epage);let n=A("getEPage");return this.store.load(e.src).then(s=>{let o=s.getTotalOffset(),i=Math.min(o,t.offsetInItem);n.finish(e.epage+i*e.epageCount/o)}),n.result()}},rl=(r,t)=>({page:r,position:{spineIndex:r.spineIndex,pageIndex:t,offsetInItem:r.offset}}),ll=class{constructor(t,e,n,s,o){this.opf=t;this.viewport=e;this.fontMapper=n;this.pageSheetSizeReporter=o;p(this,"spineItems",[]);p(this,"spineItemLoadingContinuations",[]);p(this,"pref");p(this,"clientLayout");p(this,"counterStore");p(this,"tocAutohide",!1);p(this,"tocVisible",!1);p(this,"tocView");this.pref=Sr(s),this.clientLayout=new Qa(e),this.counterStore=new Ir(t.documentURLTransformer)}getPage(t){let e=this.spineItems[t.spineIndex];return e?e.pages[t.pageIndex]:null}getCurrentPageProgression(t){if(this.opf.pageProgression)return this.opf.pageProgression;{let e=this.spineItems[t?t.spineIndex:0];return e?e.instance.pageProgression:null}}finishPageContainer(t,e,n){e.container.style.display="none",e.container.style.visibility="visible",e.container.style.position="",e.container.style.top="",e.container.style.left="",e.container.setAttribute("data-vivliostyle-page-side",e.side);let s=t.pages[n];if(e.isFirstPage=t.item.spineIndex==0&&n==0,t.pages[n]=e,this.opf.epageIsRenderedPage){if(n==0&&t.item.spineIndex>0){let o=this.opf.spine[t.item.spineIndex-1];t.item.epage=o.epage+o.epageCount}t.item.epageCount=t.pages.length,this.opf.epageCount=this.opf.spine.reduce((o,i)=>o+i.epageCount,0),this.opf.epageCountCallback&&this.opf.epageCountCallback(this.opf.epageCount)}if(s)t.instance.viewport.contentContainer.replaceChild(e.container,s.container),s.dispatchEvent({type:"replaced",target:null,currentTarget:null,preventDefault:null,newPage:e});else{let o=null;if(n>0)o=t.pages[n-1].container.nextElementSibling;else for(let i=t.item.spineIndex+1;i<this.spineItems.length;i++){let a=this.spineItems[i];if(a&&a.pages[0]){o=a.pages[0].container;break}}t.instance.viewport.contentContainer.insertBefore(e.container,o)}this.pageSheetSizeReporter({width:t.instance.pageSheetWidth,height:t.instance.pageSheetHeight},t.instance.pageSheetSize,t.item.spineIndex,t.instance.pageNumberOffset+n)}renderSinglePage(t,e){let n=A("renderSinglePage"),s=t.pages[e?e.page:0],o=this.makePage(t,e);return s&&(o.pageType=s.pageType),t.instance.layoutNextPage(o,e).then(i=>{e=i;let a=e?e.page-1:t.layoutPositions.length-1;this.finishPageContainer(t,o,a),this.counterStore.finishPage(o.spineIndex,a);let l=null;if(e){let c=t.layoutPositions[e.page];t.layoutPositions[e.page]=e,c&&t.pages[e.page]&&(e.isSamePosition(c)||(l=this.renderSinglePage(t,e)))}l||(l=v(!0)),l.then(()=>{let c=this.counterStore.getUnresolvedRefsToPage(o),u=0;n.loopWithFrame(d=>{if(u++,u>c.length){d.breakLoop();return}let h=c[u-1];if(h.refs=h.refs.filter(f=>!f.isResolved()),h.refs.length===0){d.continueLoop();return}this.getPageViewItem(h.spineIndex).then(f=>{if(!f){d.continueLoop();return}let{currentPageType:g,previousPageType:m}=f.instance.styler.cascade,y=f.instance.scopes;f.instance.scopes={},this.counterStore.pushPageCounters(h.pageCounters),this.counterStore.pushReferencesToSolve(h.refs);let E=f.layoutPositions[h.pageIndex];this.renderSinglePage(f,E).then(C=>{f.instance.styler.cascade.currentPageType=g,f.instance.styler.cascade.previousPageType=m,f.instance.scopes=y,this.counterStore.popPageCounters(),this.counterStore.popReferencesToSolve();let x=C.pageAndPosition.position;x.spineIndex===o.spineIndex&&x.pageIndex===a&&(o=C.pageAndPosition.page),d.continueLoop()})})}).then(()=>{o.container.parentElement||(o=t.pages[a]),o.isLastPage=!e&&t.item.spineIndex===this.opf.spine.length-1,o.isLastPage&&(this.viewport,this.counterStore.finishLastPage(this.viewport)),o.container.setAttribute("data-vivliostyle-page-index",a),o.container.setAttribute("data-vivliostyle-spine-index",o.spineIndex),n.finish({pageAndPosition:rl(o,a),nextLayoutPosition:e})})})}),n.result()}normalizeSeekPosition(t,e){let n=t.pageIndex,s=-1;if(n<0){s=t.offsetInItem;let o=mt(e.layoutPositions.length,i=>e.instance.getPosition(e.layoutPositions[i],!0)>s);o===e.layoutPositions.length?e.complete?n=e.layoutPositions.length-1:n=Number.POSITIVE_INFINITY:n=o-1}else n===Number.POSITIVE_INFINITY&&t.offsetInItem!==-1&&(s=t.offsetInItem);return{spineIndex:t.spineIndex,pageIndex:n,offsetInItem:s}}findPage(t,e){let n=A("findPage");return this.getPageViewItem(t.spineIndex).then(s=>{if(!s){n.finish(null);return}let o=null,i;n.loopWithFrame(a=>{let l=this.normalizeSeekPosition(t,s);i=l.pageIndex,o=s.pages[i],o?a.breakLoop():s.complete?(i=s.layoutPositions.length-1,o=s.pages[i],a.breakLoop()):e?this.renderPage(l).then(c=>{c&&(o=c.page,i=c.position.pageIndex),a.breakLoop()}):n.sleep(100).then(()=>{a.continueLoop()})}).then(()=>{n.finish(rl(o,i))})}),n.result()}renderPage(t){let e=A("renderPage");return this.getPageViewItem(t.spineIndex).then(n=>{if(!n){e.finish(null);return}let s=this.normalizeSeekPosition(t,n),o=s.pageIndex,i=s.offsetInItem,a=n.pages[o];if(a){e.finish(rl(a,o));return}e.loopWithFrame(l=>{if(o<n.layoutPositions.length){l.breakLoop();return}if(n.complete){o=n.layoutPositions.length-1,l.breakLoop();return}let c=n.layoutPositions[n.layoutPositions.length-1];this.renderSinglePage(n,c).then(u=>{let d=u.pageAndPosition.page;if(c=u.nextLayoutPosition,c){if(i>=0&&n.instance.getPosition(c)>i){a=d,o=n.layoutPositions.length-2,l.breakLoop();return}l.continueLoop()}else a=d,o=u.pageAndPosition.position.pageIndex,n.complete=!0,l.breakLoop()})}).then(()=>{a=a||n.pages[o];let l=n.layoutPositions[o];if(a){e.finish(rl(a,o));return}this.renderSinglePage(n,l).then(c=>{c.nextLayoutPosition||(n.complete=!0),e.finish(c.pageAndPosition)})})}),e.result()}renderAllPages(){let t=A("renderAllPages");return this.renderPagesUpto({spineIndex:this.opf.spine.length-1,pageIndex:Number.POSITIVE_INFINITY,offsetInItem:-1},!1).then(e=>{t.loopWithFrame(n=>{this.spineItems.some(s=>s==null?void 0:s.pages.some(o=>o==null?void 0:o.fetchers.some(i=>!i.arrived)))?t.sleep(100).then(()=>{n.continueLoop()}):n.breakLoop()}).then(()=>{t.finish(e)})}),t.result()}renderPagesUpto(t,e){let n=A("renderPagesUpto");t||(t={spineIndex:0,pageIndex:0,offsetInItem:0});let s=t.spineIndex,o=t.pageIndex,i=0;e&&(i=s);let a;return n.loopWithFrame(l=>{let c={spineIndex:i,pageIndex:i===s?o:Number.POSITIVE_INFINITY,offsetInItem:i===s?t.offsetInItem:-1};this.renderPage(c).then(u=>{a=u,++i>s?l.breakLoop():l.continueLoop()})}).then(()=>{n.finish(a)}),n.result()}firstPage(t,e){return this.findPage({spineIndex:0,pageIndex:0,offsetInItem:-1},e)}lastPage(t,e){return this.findPage({spineIndex:this.opf.spine.length-1,pageIndex:Number.POSITIVE_INFINITY,offsetInItem:-1},e)}nextPage(t,e){let n=t.spineIndex,s=t.pageIndex,o=A("nextPage");return this.getPageViewItem(n).then(i=>{if(!i){o.finish(null);return}if(i.complete&&s==i.layoutPositions.length-1){if(n>=this.opf.spine.length-1){o.finish(null);return}n++,s=0;let a=this.spineItems[n],l=a&&a.pages[0],c=i.pages[i.pages.length-1];l&&c&&l.side==c.side&&(a.pages.forEach(u=>{u.container&&u.container.remove()}),this.spineItems[n]=null,this.spineItemLoadingContinuations[n]=null)}else s++;this.findPage({spineIndex:n,pageIndex:s,offsetInItem:-1},e).thenFinish(o)}),o.result()}previousPage(t,e){let n=t.spineIndex,s=t.pageIndex;if(s==0){if(n==0)return v(null);n--,s=Number.POSITIVE_INFINITY}else s--;return this.findPage({spineIndex:n,pageIndex:s,offsetInItem:-1},e)}isRectoPage(t,e){let n=t.side==="left",s=this.getCurrentPageProgression(e)==="ltr";return!n&&s||n&&!s}getSpread(t,e){let n=this.getPage(t);if(!n)return v({left:null,right:null});let s=A("getSpread"),o=n.side==="left",i;return this.isRectoPage(n,t)?i=this.previousPage(t,e):i=this.nextPage(t,e),i.then(a=>{let l=this.getPage(t),c=a&&a.page;c&&c.side===l.side&&(c=null),o?s.finish({left:l,right:c}):s.finish({left:c,right:l})}),s.result()}nextSpread(t,e){let n=this.getPage(t);if(!n)return v(null);let s=this.isRectoPage(n,t),o=this.nextPage(t,e);return s?o:o.thenAsync(i=>{if(i){if(i.page.side===n.side)return o;let a=this.nextPage(i.position,e);return a.thenAsync(l=>l?a:o)}else return v(null)})}previousSpread(t,e){let n=this.getPage(t);if(!n)return v(null);let s=this.isRectoPage(n,t),o=this.previousPage(t,e),i=n.container.previousElementSibling;return s?o.thenAsync(a=>a?a.page.side===n.side||a.page.container!==i?o:this.previousPage(a.position,e):v(null)):o}navigateToEPage(t,e,n){let s=A("navigateToEPage");return this.opf.resolveEPage(t).then(o=>{o?this.findPage(o,n).thenFinish(s):s.finish(null)}),s.result()}navigateToFragment(t,e,n){let s=A("navigateToCFI");return this.opf.resolveFragment(t).then(o=>{o?this.findPage(o,n).thenFinish(s):s.finish(null)}),s.result()}navigateTo(t,e,n){V.debug("Navigate to",t);let s=this.opf.getPathFromURL(Pt(t));if(!s){if(this.opf.opfXML&&t.match(/^#epubcfi\(/))s=this.opf.getPathFromURL(this.opf.opfXML.url);else if(t.charAt(0)==="#"){let a=this.opf.documentURLTransformer.restoreURL(t);this.opf.opfXML?(s=this.opf.getPathFromURL(a[0]),s==null&&(s=a[0])):s=a[0],t=a[0]+(a[1]?`#${a[1]}`:"")}if(s==null)return v(null)}let o=this.opf.itemMapByPath[s];if(!o){if(this.opf.opfXML&&s==this.opf.getPathFromURL(this.opf.opfXML.url)){let a=t.indexOf("#");if(a>=0)return this.navigateToFragment(t.substr(a+1),e,n)}return v(null)}let i=A("navigateTo");return this.getPageViewItem(o.spineIndex).then(a=>{if(!a){i.finish(null);return}let l=a.xmldoc.getElement(t);this.findPage({spineIndex:o.spineIndex,pageIndex:-1,offsetInItem:l?a.xmldoc.getElementOffset(l):0},n).thenFinish(i)}),i.result()}makePage(t,e){let n=t.instance.viewport,s=n.document.createElement("div");s.setAttribute("data-vivliostyle-page-container","true"),s.role="presentation",ss||(s.style.visibility="hidden"),n.layoutBox.appendChild(s);let o=n.document.createElement("div");o.setAttribute("data-vivliostyle-bleed-box","true"),o.role="presentation",s.appendChild(o);let i=new fo(s,o);if(i.spineIndex=t.item.spineIndex,i.position=e,i.offset=t.instance.getPosition(e),i.offset===0&&!(t.instance.blankPageAtStart&&t.pages.length===0)){let a=this.opf.documentURLTransformer.transformFragment("",t.item.src);o.setAttribute("id",a),i.registerElementWithId(o,a)}if(n!==this.viewport){let a=Ol(this.viewport.width,this.viewport.height,n.width,n.height),l=en(null,new De(a,null),"");i.delayedItems.push(new _n(s,"transform",l))}return i}makeObjectView(t,e,n,s){let o=e.getAttribute("data"),i=null;if(o){o=J(o,t.url);let a=e.getAttribute("media-type");if(!a){let l=this.opf.getPathFromURL(o);if(l){let c=this.opf.itemMapByPath[l];c&&(a=c.mediaType)}}if(a){let l=this.opf.bindings[a];if(l){i=this.viewport.document.createElement("iframe"),i.style.border="none";let c=Al(o),u=Al(a),d=new $e;d.append(l),d.append("?src="),d.append(c),d.append("&type="),d.append(u);for(let g=e.firstChild;g;g=g.nextSibling)if(g.nodeType==1){let m=g;if(m.localName=="param"&&m.namespaceURI=="http://www.w3.org/1999/xhtml"){let y=m.getAttribute("name"),E=m.getAttribute("value");y&&E&&(d.append("&"),d.append(encodeURIComponent(y)),d.append("="),d.append(encodeURIComponent(E)))}}i.setAttribute("src",d.toString());let h=e.getAttribute("width");h&&i.setAttribute("width",h);let f=e.getAttribute("height");f&&i.setAttribute("height",f)}}}return i||(i=this.viewport.document.createElement("object"),o&&i.setAttribute("data",o),i.setAttribute("data-adapt-process-children","true")),v(i)}makeMathJaxView(t,e,n,s){let o=Ab();if(o){let i=n.ownerDocument,a=i.createElement("span");n.appendChild(a);let l=i.importNode(e,!0);this.resolveURLsInMathML(l,t),a.appendChild(l);let c=o.queue;c.Push(["Typeset",o,a]);let u=A("makeMathJaxView"),d=u.suspend();return c.Push(()=>{d.schedule(a)}),u.result()}return v(null)}resolveURLsInMathML(t,e){if(t!=null){if(t.nodeType===1&&t.tagName==="mglyph"){let n=Array.from(t.attributes);for(let s of n){if(s.name!=="src")continue;let o=J(s.nodeValue,e.url);s.namespaceURI?t.setAttributeNS(s.namespaceURI,s.name,o):t.setAttribute(s.name,o)}}t.firstChild&&this.resolveURLsInMathML(t.firstChild,e),t.nextSibling&&this.resolveURLsInMathML(t.nextSibling,e)}}makeCustomRenderer(t){return(e,n,s)=>e.localName=="object"&&e.namespaceURI=="http://www.w3.org/1999/xhtml"?this.makeObjectView(t,e,n,s):e.namespaceURI=="http://www.w3.org/1998/Math/MathML"?this.makeMathJaxView(t,e,n,s):e.dataset&&e.dataset.mathTypeset=="true"?this.makeMathJaxView(t,e,n,s):v(null)}getPageViewItem(t){if(t===-1||t>=this.opf.spine.length)return v(null);let e=this.spineItems[t];if(e)return v(e);let n=A("getPageViewItem"),s=this.spineItemLoadingContinuations[t];if(s){let a=n.suspend();return s.push(a),n.result()}else s=this.spineItemLoadingContinuations[t]=[];let o=this.opf.spine[t],i=this.opf.store;return i.load(o.src).then(a=>{var x;let l=o.itemRefElement.getAttribute("properties");l&&a.root.setAttribute("data-vivliostyle-epub-spine-properties",l),o.title=a.document.title;let c=i.getStyleForDoc(a),u=this.makeCustomRenderer(a),d=this.viewport,h=c.sizeViewport(d.width,d.height,d.fontSize,this.pref);(h.width!=d.width||h.height!=d.height||h.fontSize!=d.fontSize)&&(d=new vn(d.window,h.fontSize,d.pixelRatio,d.root,h.width,h.height));let f=(x=this.spineItems[0])==null?void 0:x.instance.isVersoFirstPage,g=this.spineItems[t-1],m,y;if(o.startPage!==null)m=o.startPage-1,y=m;else{if(t>0&&(!g||!g.complete))m=o.epage||t,!this.opf.prePaginated&&m%2==(f?1:0)&&m++,y=m;else{m=g?g.instance.pageNumberOffset+g.pages.length:0;let N=this.counterStore.currentPageCounters.page;y=!N||!N.length?m:N[N.length-1]}o.skipPagesBefore!==null&&(m+=o.skipPagesBefore,y+=o.skipPagesBefore)}this.counterStore.forceSetPageCounter(y);let E=new es(c,a,this.opf.lang,d,this.clientLayout,this.fontMapper,u,this.opf.fallbackMap,m,this.opf.documentURLTransformer,this.counterStore,this.opf.pageProgression,f);E.pref=this.pref;let C=this.opf.metadata&&this.opf.metadata[ve.title];E.pubTitle=C&&C[0]&&C[0].v||"",E.docTitle=o.title||"",E.init().then(()=>{!this.opf.pageProgression&&E.pageProgression&&(this.opf.pageProgression=E.pageProgression),e={item:o,xmldoc:a,instance:E,layoutPositions:[null],pages:[],complete:!1},this.spineItems[t]=e,n.finish(e),s.forEach(N=>{N.schedule(e)})})}),n.result()}removeRenderedPages(){let t=this.spineItems;for(let e of t)e&&e.pages.splice(0);this.viewport.clear()}hasAutoSizedPages(){let t=this.spineItems;for(let e of t)if(e){let n=e.pages;for(let s of n)if(s.isAutoPageWidth&&s.isAutoPageHeight)return!0}return!1}hasPages(){return this.spineItems.some(t=>t&&t.pages.length>0)}showTOC(t){let e=this.opf,n=e.toc;if(this.tocAutohide=t,!n)return v(null);if(this.tocVisible=!0,this.tocView&&this.tocView.page)return this.tocView.page.container.style.visibility="visible",this.tocView.page.container.setAttribute("aria-hidden","false"),v(this.tocView.page);let s=A("showTOC");this.tocView||(this.tocView=new ol(e.store,n.src,e.lang,this.clientLayout,this.fontMapper,this.pref,this,e.fallbackMap,e.documentURLTransformer,this.counterStore));let o=this.viewport,i=Math.min(344,Math.round(.67*o.width)-16),a=o.height-6,l=o.document.createElement("div");return o.root.appendChild(l),ss||(l.style.visibility="hidden"),l.style.width=`${i+16}px`,l.style.maxHeight=`${a}px`,l.setAttribute("data-vivliostyle-toc-box","true"),l.setAttribute("role","navigation"),this.tocView.showTOC(l,o,i,a,this.viewport.fontSize).then(c=>{l.style.visibility="visible",l.setAttribute("aria-hidden","false"),s.finish(c)}),s.result()}hideTOC(){this.tocVisible=!1,this.tocView&&this.tocView.hideTOC()}isTOCVisible(){return this.tocVisible&&!!this.tocView&&this.tocView.isTOCVisible()}};var vg="data-vivliostyle-viewer-status",Rb="data-vivliostyle-spread-view",vp=(n=>(n.SINGLE_PAGE="singlePage",n.SPREAD="spread",n.AUTO_SPREAD="autoSpread",n))(vp||{}),cl=class{constructor(t,e,n,s){this.window=t;this.viewportElement=e;this.instanceId=n;this.callbackFn=s;p(this,"fontMapper");p(this,"kick");p(this,"sendCommand");p(this,"resizeListener");p(this,"hyperlinkListener");p(this,"pageRuleStyleElement");p(this,"pageSheetSizeAlreadySet",!1);p(this,"renderTask",null);p(this,"actions");p(this,"readyState");p(this,"packageURL");p(this,"opf");p(this,"touchActive");p(this,"touchX");p(this,"touchY");p(this,"needResize");p(this,"resized");p(this,"needRefresh");p(this,"viewportSize");p(this,"currentPage");p(this,"currentSpread");p(this,"pagePosition");p(this,"fontSize");p(this,"zoom");p(this,"fitToScreen");p(this,"pageViewMode");p(this,"waitForLoading");p(this,"renderAllPages");p(this,"pref");p(this,"pageSizes");p(this,"pixelRatio");p(this,"pixelRatioLimit");p(this,"viewport");p(this,"opfView");let o=e.ownerDocument,i=(a,l)=>{let c=o.getElementById(a);return c||(c=o.createElement("style"),c.id=a,l&&(c.textContent=l),o.head.appendChild(c)),c};i("vivliostyle-viewport-screen-css",gc),i("vivliostyle-viewport-css",mc),i("vivliostyle-polyfill-css",Sc),e.setAttribute("data-vivliostyle-viewer-viewport",!0),ss&&e.setAttribute("data-vivliostyle-debug",!0),e.setAttribute(vg,"loading"),this.fontMapper=new Ma(o.head,e),this.init(),this.kick=()=>{},this.sendCommand=()=>{},this.resizeListener=()=>{this.needResize=!0,this.resized=!0,this.kick()},this.pageReplacedListener=this.pageReplacedListener.bind(this),this.hyperlinkListener=a=>{},this.pageRuleStyleElement=i("vivliostyle-page-rules"),this.actions={loadPublication:this.loadPublication,loadXML:this.loadXML,configure:this.configure,moveTo:this.moveTo,toc:this.showTOC},this.addLogListeners()}init(){this.readyState="loading",this.packageURL=[],this.opf=null,this.touchActive=!1,this.touchX=0,this.touchY=0,this.needResize=!1,this.resized=!1,this.needRefresh=!1,this.viewportSize=null,this.currentPage=null,this.currentSpread=null,this.pagePosition=null,this.fontSize=16,this.zoom=1,this.fitToScreen=!1,this.pageViewMode="singlePage",this.waitForLoading=!1,this.renderAllPages=!0,this.pref=Bl(),this.pageSizes=[],this.pixelRatioLimit=/Chrome/.test(navigator.userAgent)?16:0,this.pixelRatio=Math.min(8,this.pixelRatioLimit)}addLogListeners(){let t=Sl;V.addListener(t.DEBUG,e=>{this.callback({t:"debug",content:e})}),V.addListener(t.INFO,e=>{this.callback({t:"info",content:e})}),V.addListener(t.WARN,e=>{this.callback({t:"warn",content:e})}),V.addListener(t.ERROR,e=>{this.callback({t:"error",content:e})})}callback(t){t.i=this.instanceId,this.callbackFn(t)}setReadyState(t){this.readyState!==t&&(this.readyState=t,this.viewportElement.setAttribute(vg,t),this.callback({t:"readystatechange"}))}loadPublication(t){Ye.registerStartTiming("beforeRender"),this.setReadyState("loading");let e=t.url,n=t.fragment,s=t.authorStyleSheet,o=t.userStyleSheet;this.viewport=null;let i=A("loadPublication");return this.configure(t).then(()=>{let a=new Yi;a.init(s,o).then(()=>{let l=J(Pn(e),this.window.location.href);this.packageURL=[l],a.loadPubDoc(l).then(c=>{c?(this.opf=c,this.render(n).then(()=>{i.finish(!0)})):i.finish(!1)})})}),i.result()}loadXML(t){Ye.registerStartTiming("beforeRender"),this.setReadyState("loading");let e=t.url,n=t.document,s=t.fragment,o=t.authorStyleSheet,i=t.userStyleSheet;this.viewport=null;let a=A("loadXML");return this.configure(t).then(()=>{let l=new Yi;l.init(o,i).then(()=>{let c=e.map((u,d)=>({url:J(Pn(u.url),this.window.location.href),index:d,startPage:u.startPage,skipPagesBefore:u.skipPagesBefore}));this.packageURL=c.map(u=>u.url),this.opf=new zs(l,""),this.opf.initWithChapters(c,n).then(()=>{this.render(s).then(()=>{a.finish(!0)})})})}),a.result()}render(t){this.cancelRenderingTask();let e;return t?e=this.opf.resolveFragment(t).thenAsync(n=>(this.pagePosition=n,v(!0))):e=v(!0),e.thenAsync(()=>(Ye.registerEndTiming("beforeRender"),this.resize()))}resolveLength(t){let e=parseFloat(t),n=/[a-z]+$/,s;if(typeof t=="string"&&(s=t.match(n))){let o=s[0];if(o==="em"||o==="rem")return e*this.fontSize;if(o==="ex")return e*Y.ex*this.fontSize/Y.em;let i=Y[o];if(i)return e*i}return e}configure(t){if(typeof t.autoresize=="boolean"&&(t.autoresize?(this.viewportSize=null,this.window.addEventListener("resize",this.resizeListener,!1),this.needResize=!0):this.window.removeEventListener("resize",this.resizeListener,!1)),typeof t.fontSize=="number"){let e=t.fontSize;e>=5&&e<=72&&this.fontSize!=e&&(this.fontSize=e,this.needResize=!0)}if(typeof t.viewport=="object"&&t.viewport){let e=t.viewport,n={marginLeft:this.resolveLength(e["margin-left"])||0,marginRight:this.resolveLength(e["margin-right"])||0,marginTop:this.resolveLength(e["margin-top"])||0,marginBottom:this.resolveLength(e["margin-bottom"])||0,width:this.resolveLength(e.width)||0,height:this.resolveLength(e.height)||0};(n.width>=200||n.height>=200)&&(this.window.removeEventListener("resize",this.resizeListener,!1),this.viewportSize=n,this.needResize=!0)}if(typeof t.hyphenate=="boolean"&&(this.pref.hyphenate=t.hyphenate,this.needResize=!0),typeof t.horizontal=="boolean"&&(this.pref.horizontal=t.horizontal,this.needResize=!0),typeof t.nightMode=="boolean"&&(this.pref.nightMode=t.nightMode,this.needResize=!0),typeof t.lineHeight=="number"&&(this.pref.lineHeight=t.lineHeight,this.needResize=!0),typeof t.columnWidth=="number"&&(this.pref.columnWidth=t.columnWidth,this.needResize=!0),typeof t.fontFamily=="string"&&(this.pref.fontFamily=t.fontFamily,this.needResize=!0),typeof t.load=="boolean"&&(this.waitForLoading=t.load),typeof t.renderAllPages=="boolean"&&(this.renderAllPages=t.renderAllPages),typeof t.userAgentRootURL=="string"&&(Tl(t.userAgentRootURL.replace(/resources\/?$/,"")),wl(t.userAgentRootURL)),typeof t.rootURL=="string"&&(Tl(t.rootURL),wl(`${ln}resources/`)),typeof t.pageViewMode=="string"&&t.pageViewMode!==this.pageViewMode&&(this.pageViewMode=t.pageViewMode,this.needResize=!0),typeof t.pageBorder=="number"&&t.pageBorder!==this.pref.pageBorder&&(this.viewport=null,this.pref.pageBorder=t.pageBorder,this.needResize=!0),typeof t.zoom=="number"&&t.zoom!==this.zoom&&(this.zoom=t.zoom,this.needRefresh=!0),typeof t.fitToScreen=="boolean"&&t.fitToScreen!==this.fitToScreen&&(this.fitToScreen=t.fitToScreen,this.needRefresh=!0),typeof t.defaultPaperSize=="object"&&typeof t.defaultPaperSize.width=="number"&&typeof t.defaultPaperSize.height=="number"&&(this.viewport=null,this.pref.defaultPaperSize=t.defaultPaperSize,this.needResize=!0),typeof t.allowScripts=="boolean"&&t.allowScripts!==Gt&&(hg(t.allowScripts),this.needResize=!0),typeof t.pixelRatio=="number"){let e=Math.min(t.pixelRatio,this.pixelRatioLimit);e!==this.pixelRatio&&(this.pixelRatio=e,this.needResize=!0)}return this.configurePlugins(t),v(!0)}configurePlugins(t){Ge("CONFIGURATION").forEach(n=>{let s=n(t);this.needResize=s.needResize||this.needResize,this.needRefresh=s.needRefresh||this.needRefresh})}pageReplacedListener(t){let e=this.currentPage,n=this.currentSpread,s=t.target;n?(n.left===s||n.right===s)&&this.showCurrent(t.newPage):e===t.target&&this.showCurrent(t.newPage)}forCurrentPages(t){let e=[];this.currentPage&&e.push(this.currentPage),this.currentSpread&&(e.push(this.currentSpread.left),e.push(this.currentSpread.right)),e.forEach(n=>{n&&t(n)})}removePageListeners(){this.forCurrentPages(t=>{t.removeEventListener("hyperlink",this.hyperlinkListener,!1),t.removeEventListener("replaced",this.pageReplacedListener,!1)})}hidePages(){this.removePageListeners(),this.forCurrentPages(t=>{T(t.container,"display","none")}),this.currentPage=null,this.currentSpread=null}showSinglePage(t){t.addEventListener("hyperlink",this.hyperlinkListener,!1),t.addEventListener("replaced",this.pageReplacedListener,!1),T(t.container,"visibility","visible"),T(t.container,"display","block")}showPage(t){this.hidePages(),this.currentPage=t,t.container.style.marginLeft="",t.container.style.marginRight="",this.showSinglePage(t)}showSpread(t){if(this.hidePages(),this.currentSpread=t,t.left&&t.right){let e=parseFloat(t.left.container.style.width),n=parseFloat(t.right.container.style.width);e&&n&&e!==n&&(e<n?t.left.container.style.marginLeft=`${n-e}px`:t.right.container.style.marginRight=`${e-n}px`)}t.left&&(this.showSinglePage(t.left),t.right?t.left.container.removeAttribute("data-vivliostyle-unpaired-page"):t.left.container.setAttribute("data-vivliostyle-unpaired-page",!0)),t.right&&(this.showSinglePage(t.right),t.left?t.right.container.removeAttribute("data-vivliostyle-unpaired-page"):t.right.container.setAttribute("data-vivliostyle-unpaired-page",!0))}reportPosition(){let t=A("reportPosition");return this.pagePosition,this.opf.getCFI(this.pagePosition.spineIndex,this.pagePosition.offsetInItem).then(e=>{let n=this.currentPage;(this.waitForLoading&&n.fetchers.length>0?Vn(n.fetchers):v(!0)).then(()=>{this.sendLocationNotification(n,e).thenFinish(t)})}),t.result()}createViewport(){let t=this.viewportElement;if(this.viewportSize){let e=this.viewportSize;return t.style.marginLeft=`${e.marginLeft}px`,t.style.marginRight=`${e.marginRight}px`,t.style.marginTop=`${e.marginTop}px`,t.style.marginBottom=`${e.marginBottom}px`,new vn(this.window,this.fontSize,this.pixelRatio,t,e.width,e.height)}else return new vn(this.window,this.fontSize,this.pixelRatio,t)}resolveSpreadView(t,e){switch(this.pageViewMode){case"singlePage":return!1;case"spread":return!0;case"autoSpread":default:return(t.width-this.pref.pageBorder)/t.height>=(e?e.width*2/e.height:1.45)&&(!!e||t.width>800)}}updateSpreadView(t){this.pref.spreadView=t,this.viewportElement.setAttribute(Rb,t.toString())}sizeIsGood(){var i;let t=this.createViewport(),e=((i=this.opfView)==null?void 0:i.hasPages())&&!this.opfView.hasAutoSizedPages(),n=this.resolveSpreadView(t,this.resized&&e?this.pageSizes[0]:null);this.resized=!1;let s=this.pref.spreadView!==n;return this.updateSpreadView(n),this.pixelRatio&&this.opfView&&this.pixelRatio/this.window.devicePixelRatio!==this.opfView.clientLayout.scaleRatio||this.viewportSize||!this.viewport||this.viewport.fontSize!=this.fontSize?!1:!s&&t.width==this.viewport.width&&t.height==this.viewport.height||!s&&t.width==this.viewport.width&&t.height!=this.viewport.height&&/Android|iPhone|iPad|iPod/.test(navigator.userAgent)?!0:e?(this.viewport.width=t.width,this.viewport.height=t.height,this.needRefresh=!0,!0):!1}setPageSize(t,e,n,s){this.pageSizes[s]=t,this.setPageSizePageRules(e,n,s),s===0&&this.pageViewMode==="autoSpread"&&!this.opfView.hasAutoSizedPages()&&this.updateSpreadView(this.resolveSpreadView(this.viewport,t))}setPageSizePageRules(t,e,n){var o,i;if(this.pageRuleStyleElement&&(!this.pageSheetSizeAlreadySet||this.pageSizes[n].width!==((o=this.pageSizes[n-1])==null?void 0:o.width)||this.pageSizes[n].height!==((i=this.pageSizes[n-1])==null?void 0:i.height))){let c=function(m){let y=m*.75;return Math.ceil(y)};var s=c;let a=Math.max(...this.pageSizes.map(m=>m.width)),l=Math.max(...this.pageSizes.map(m=>m.height)),u=c(a),d=c(l),h=u*((this.pixelRatio||1)-1)+2,f=d*((this.pixelRatio||1)-1)+2,g=`@page {size: ${u}pt ${d}pt; margin: 0 ${-h}pt ${-f}pt 0;}`;this.pageRuleStyleElement.textContent=g,this.pageSheetSizeAlreadySet=!0}}removePageSizePageRules(){this.pageRuleStyleElement&&(this.pageRuleStyleElement.textContent="",this.pageSheetSizeAlreadySet=!1)}reset(){let t=!1,e=!1;this.opfView&&(t=this.opfView.tocVisible,e=this.opfView.tocAutohide,this.opfView.removeRenderedPages()),this.pageSizes=[],this.removePageSizePageRules(),this.viewport=this.createViewport(),this.viewport.resetZoom(),this.opfView=new ll(this.opf,this.viewport,this.fontMapper,this.pref,this.setPageSize.bind(this)),t&&this.sendCommand({a:"toc",v:"show",autohide:e})}showCurrent(t,e){this.needRefresh=!1,this.removePageListeners();let n=this.resolveSpreadView(this.viewport,t.dimensions);return n!==this.pref.spreadView&&this.updateSpreadView(n),n?this.opfView.getSpread(this.pagePosition,e).thenAsync(s=>!s.left&&!s.right?v(null):s.left&&s.right&&(!this.resolveSpreadView(this.viewport,s.left.dimensions)||!this.resolveSpreadView(this.viewport,s.right.dimensions))?(this.updateSpreadView(!1),this.showPage(t),this.setPageZoom(t),this.currentPage=t,v(null)):(this.showSpread(s),this.setSpreadZoom(s),this.currentPage=t.side==="left"?s.left:s.right,v(null))):(this.showPage(t),this.setPageZoom(t),this.currentPage=t,v(null))}setPageZoom(t){let e=this.getAdjustedZoomFactor(t.dimensions);this.viewport.zoom(t.dimensions.width,t.dimensions.height,e)}setSpreadZoom(t){let e=this.getSpreadDimensions(t);this.viewport.zoom(e.width,e.height,this.getAdjustedZoomFactor(e))}getAdjustedZoomFactor(t){return this.fitToScreen?this.calculateZoomFactorToFitInsideViewPort(t):this.zoom}getSpreadDimensions(t){let e=0,n=0;return t.left&&(e+=t.left.dimensions.width,n=t.left.dimensions.height),t.right&&(e+=t.right.dimensions.width,n=Math.max(n,t.right.dimensions.height)),t.left&&t.right&&(e+=this.pref.pageBorder*2,e+=Math.abs(t.left.dimensions.width-t.right.dimensions.width)),{width:e,height:n}}queryZoomFactor(t){if(!this.currentPage)throw new Error("no page exists.");switch(t){case"fit inside viewport":{let e;return this.pref.spreadView?(this.currentSpread,e=this.getSpreadDimensions(this.currentSpread)):e=this.currentPage.dimensions,this.calculateZoomFactorToFitInsideViewPort(e)}default:throw new Error(`unknown zoom type: ${t}`)}}calculateZoomFactorToFitInsideViewPort(t){if(!this.viewport)return this.zoom;let e=this.viewport.width/t.width,n=this.viewport.height/t.height;return Math.min(e,n)}cancelRenderingTask(){this.renderTask&&this.renderTask.interrupt(new ul),this.renderTask=null}resize(){if(this.needResize=!1,this.needRefresh=!1,this.sizeIsGood())return v(!0);this.setReadyState("loading"),this.cancelRenderingTask();let t=Jo().getScheduler().run(()=>pn("resize",e=>{if(!this.opf){e.finish(!1);return}this.renderTask=t,Ye.registerStartTiming("render (resize)"),this.reset(),this.pagePosition&&(this.pagePosition.pageIndex==0&&this.pagePosition.offsetInItem==0||(this.pagePosition.pageIndex=-1)),this.opf.setEPageCountMode(this.renderAllPages),this.opfView.renderPagesUpto(this.pagePosition,!this.renderAllPages).then(n=>{if(!n){e.finish(!1);return}this.pagePosition=n.position,this.showCurrent(n.page,!0).then(()=>{this.setReadyState("interactive"),this.opf.countEPages(s=>{let o={t:"nav",epageCount:s,first:this.currentPage.isFirstPage,last:this.currentPage.isLastPage,metadata:this.opf.metadata,docTitle:this.opf.spine[this.pagePosition.spineIndex].title};(this.currentPage.isFirstPage||this.pagePosition.pageIndex==0&&this.opf.spine[this.pagePosition.spineIndex].epage)&&(o.epage=this.opf.spine[this.pagePosition.spineIndex].epage),this.callback(o)}).then(()=>{this.reportPosition().then(s=>{(this.renderAllPages?this.opfView.renderAllPages():v(null)).then(()=>{this.renderTask===t&&(this.renderTask=null),Ye.registerEndTiming("render (resize)"),Gt&&gp(this.window)?mg(this.window).then(()=>{this.renderAllPages&&this.setReadyState("complete"),this.callback({t:"loaded"}),e.finish(s)}):(this.renderAllPages&&this.setReadyState("complete"),this.callback({t:"loaded"}),e.finish(s))})})})})})},(e,n)=>{if(n instanceof ul)Ye.registerEndTiming("render (resize)"),V.debug(n.message);else throw n}));return v(!0)}sendLocationNotification(t,e){let n=A("sendLocationNotification"),s={t:"nav",first:t.isFirstPage,last:t.isLastPage,metadata:this.opf.metadata,docTitle:this.opf.spine[t.spineIndex].title};return this.opf.getEPageFromPosition(this.pagePosition).then(o=>{s.epage=o,s.epageCount=this.opf.epageCount,e&&(s.cfi=e),this.callback(s),n.finish(!0)}),n.result()}getCurrentPageProgression(){return this.opfView?this.opfView.getCurrentPageProgression(this.pagePosition):null}moveTo(t){var s;let e;if(this.readyState!=="complete"&&t.where!=="next"&&this.setReadyState("loading"),typeof t.where=="string"){let o;switch(t.where){case"next":o=this.pref.spreadView?this.opfView.nextSpread:this.opfView.nextPage;break;case"previous":o=this.pref.spreadView?this.opfView.previousSpread:this.opfView.previousPage;break;case"last":o=this.opfView.lastPage;break;case"first":o=this.opfView.firstPage;break;default:return v(!0)}o&&(e=()=>o.call(this.opfView,this.pagePosition,!this.renderAllPages))}else if(typeof t.epage=="number"){let o=t.epage;e=()=>this.opfView.navigateToEPage(o,this.pagePosition,!this.renderAllPages)}else if(typeof t.url=="string"){let o=t.url;e=()=>this.opfView.navigateTo(o,this.pagePosition,!this.renderAllPages)}else if(typeof((s=t.position)==null?void 0:s.spineIndex)=="number"){let o=t.position;e=()=>this.opfView.findPage(o,!this.renderAllPages)}else return v(!0);if(!this.opfView)return v(!0);let n=A("moveTo");return e.call(this.opfView).then(o=>{let i;if(o){this.pagePosition=o.position;let a=A("moveTo.showCurrent");i=a.result(),this.showCurrent(o.page,!this.renderAllPages).then(()=>{this.reportPosition().thenFinish(a)})}else i=v(!0);i.then(a=>{this.readyState==="loading"&&this.setReadyState("interactive"),n.finish(a)})}),n.result()}showTOC(t){let e=!!t.autohide,n=t.v,s=this.opfView.isTOCVisible(),o=e!=this.opfView.tocAutohide&&n!="hide";if(s){if(n=="show"&&!o)return v(!0)}else if(n=="hide")return v(!0);if(s&&n!="show")return this.opfView.hideTOC(),v(!0);{let i=A("showTOC");return this.opfView.showTOC(e).then(a=>{if(a){if(o&&(a.listeners={}),e){let l=()=>{this.opfView.hideTOC()};a.addEventListener("hyperlink",l,!1)}a.addEventListener("hyperlink",this.hyperlinkListener,!1)}i.finish(!0)}),i.result()}}runCommand(t){let e=t.a||"";return pn("runCommand",n=>{let s=this.actions[e];s?s.call(this,t).then(()=>{this.callback({t:"done",a:e}),n.finish(!0)}):(V.error("No such action:",e),n.finish(!0))},(n,s)=>{V.error(s,"Error during action:",e),n.finish(!0)})}initEmbed(t){let e=Tg(t),n=null,s=this;hh(()=>{let o=A("commandLoop"),i=Jo().getScheduler();return s.hyperlinkListener=a=>{let l=a,c=l.href.charAt(0)==="#"||s.packageURL.some(u=>l.href.substr(0,u.length)==u);if(c){a.preventDefault();let u={t:"hyperlink",href:l.href,internal:c};i.run(()=>(s.callback(u),v(!0)))}},o.loopWithFrame(a=>{if(s.needResize)s.resize().then(()=>{a.continueLoop()});else if(s.needRefresh)s.currentPage&&s.showCurrent(s.currentPage,!this.renderAllPages).then(()=>{a.continueLoop()});else if(e){let l=e;e=null,s.runCommand(l).then(()=>{a.continueLoop()})}else{let l=A("waitForCommand");n=l.suspend(this),l.result().then(()=>{a.continueLoop()})}}).thenFinish(o),o.result()}),s.kick=()=>{let o=n;o&&(n=null,o.schedule(!0))},s.sendCommand=o=>e?!1:(e=Tg(o),s.kick(),!0),this.window.adapt_command=s.sendCommand}},Tp=(t=>(t.FIT_INSIDE_VIEWPORT="fit inside viewport",t))(Tp||{}),ul=class r extends Error{constructor(){super();p(this,"name","RenderingCanceledError");p(this,"message","Page rendering has been canceled");p(this,"stack");Object.setPrototypeOf(this,r.prototype),this.stack=new Error().stack}};function Tg(r){return typeof r=="string"?$s(r):r}var wg=os;function Vb(){return{autoResize:!0,fontSize:16,pageBorderWidth:1,renderAllPages:!0,pageViewMode:"autoSpread",zoom:1,fitToScreen:!1,defaultPaperSize:void 0,allowScripts:!0,pixelRatio:8}}function Pg(r){let t={};return Object.keys(r).forEach(e=>{let n=r[e];switch(e){case"autoResize":t.autoresize=n;break;case"pageBorderWidth":t.pageBorder=n;break;default:t[e]=n}}),t}var qi=class{constructor(t,e){this.settings=t;p(this,"initialized",!1);p(this,"adaptViewer_");p(this,"options");p(this,"eventTarget");p(this,"readyState");bl(t.debug),this.adaptViewer_=new cl(t.window||window,t.viewportElement,"main",this.dispatcher.bind(this)),this.options=Vb(),e&&this.setOptions(e),this.eventTarget=new wn,Object.defineProperty(this,"readyState",{get(){return this.adaptViewer_.readyState}})}setOptions(t){let e=Object.assign({a:"configure"},Pg(t));this.adaptViewer_.sendCommand(e),Object.assign(this.options,t)}dispatcher(t){let e={type:t.t},n=t;Object.keys(n).forEach(s=>{s!=="t"&&(e[s]=n[s])}),this.eventTarget.dispatchEvent(e)}addListener(t,e){this.eventTarget.addEventListener(t,e,!1)}removeListener(t,e){this.eventTarget.removeEventListener(t,e,!1)}loadDocument(t,e,n){if(!t||(Array.isArray(t)?!t[0]||typeof t[0]!="string"&&!t[0].url:typeof t!="string"&&!t.url)){this.eventTarget.dispatchEvent({type:"error",content:{error:new Error("No URL specified")}});return}this.loadDocumentOrPublication(t,null,e,n)}loadPublication(t,e,n){if(!t){this.eventTarget.dispatchEvent({type:"error",content:{error:new Error("No URL specified")}});return}this.loadDocumentOrPublication(null,t,e,n)}loadDocumentOrPublication(t,e,n,s){let o=n||{};function i(u){if(u)return u.map(d=>({url:d.url||null,text:d.text||null}))}let a=i(o.authorStyleSheet),l=i(o.userStyleSheet);s&&Object.assign(this.options,s);let c=Object.assign({a:t?"loadXML":"loadPublication",userAgentRootURL:this.settings.userAgentRootURL,url:Fb(t)||e,document:o.documentObject,fragment:o.fragment,authorStyleSheet:a,userStyleSheet:l},Pg(this.options));this.initialized?this.adaptViewer_.sendCommand(c):(this.initialized=!0,this.adaptViewer_.initEmbed(c))}getCurrentPageProgression(){return this.adaptViewer_.getCurrentPageProgression()}resolveNavigation(t){switch(t){case"left":return this.getCurrentPageProgression()===wg.LTR?"previous":"next";case"right":return this.getCurrentPageProgression()===wg.LTR?"next":"previous";default:return t}}navigateToPage(t,e){t==="epage"?this.adaptViewer_.sendCommand({a:"moveTo",epage:e}):this.adaptViewer_.sendCommand({a:"moveTo",where:this.resolveNavigation(t)})}navigateToInternalUrl(t){this.adaptViewer_.sendCommand({a:"moveTo",url:t})}navigateToPosition(t){var e,n;this.adaptViewer_.sendCommand({a:"moveTo",position:{spineIndex:t.spineIndex,pageIndex:(e=t.pageIndex)!=null?e:-1,offsetInItem:(n=t.offsetInItem)!=null?n:-1}})}isTOCVisible(){return this.adaptViewer_.opfView&&this.adaptViewer_.opfView.opf&&this.adaptViewer_.opfView.opf.toc?!!this.adaptViewer_.opfView.isTOCVisible():null}showTOC(t,e){let n=t==null?"toggle":t?"show":"hide";this.adaptViewer_.sendCommand({a:"toc",v:n,autohide:e})}queryZoomFactor(t){return this.adaptViewer_.queryZoomFactor(t)}getPageSizes(){return this.adaptViewer_.pageSizes}getTOC(){var t,e;return(e=(t=this.adaptViewer_.opfView)==null?void 0:t.tocView)==null?void 0:e.getTOC()}getMetadata(){return this.adaptViewer_.opf.getMetadata()}getCover(){return this.adaptViewer_.opf.cover}};function Fb(r){function t(n){return typeof n=="number"?n:null}function e(n){return typeof n=="string"?{url:n,startPage:null,skipPagesBefore:null}:{url:n.url,startPage:t(n.startPage),skipPagesBefore:t(n.skipPagesBefore)}}return Array.isArray(r)?r.map(e):r?[e(r)]:null}var kg=(a=>(a.PREVIOUS="previous",a.NEXT="next",a.LEFT="left",a.RIGHT="right",a.FIRST="first",a.LAST="last",a.EPAGE="epage",a))(kg||{}),Bb=Tp,Ob=vp;Ye.forceRegisterEndTiming("load_vivliostyle");var wp=class{constructor(t,{title:e="",printCallback:n=a=>a.print(),errorCallback:s=null,hideIframe:o=!0,removeIframe:i=!0}){p(this,"htmlDoc");p(this,"title");p(this,"printCallback");p(this,"errorCallback");p(this,"hideIframe");p(this,"removeIframe");p(this,"iframe");p(this,"iframeWin");p(this,"window");this.htmlDoc=t,this.title=e,this.printCallback=n,this.errorCallback=s,this.hideIframe=o,this.removeIframe=i}init(){this.iframe=document.createElement("iframe"),this.hideIframe&&(this.iframe.style.width="0",this.iframe.style.height="0",this.iframe.style.borderWidth="0"),this.window=window,this.window.printInstance=this,this.iframe.srcdoc=`
|
|
1511
1518
|
<!DOCTYPE html>
|
|
1512
1519
|
<html data-vivliostyle-paginated="true">
|
|
1513
1520
|
<head>
|
|
@@ -1535,6 +1542,6 @@ span[data-viv-leader] {
|
|
|
1535
1542
|
<body onload='parent.printInstance.runInIframe(window)'>
|
|
1536
1543
|
<div id="vivliostyle-viewer-viewport"></div>
|
|
1537
1544
|
</body>
|
|
1538
|
-
</html>`,document.body.appendChild(this.iframe)}runInIframe(t){return this.iframeWin=t,this.preparePrint().then(()=>this.browserPrint()).then(()=>this.cleanUp())}preparePrint(){this.iframeWin.document.title=this.title;let t=new Blob([this.htmlDoc],{type:"text/html"}),e=URL.createObjectURL(t),n=new
|
|
1539
|
-
`);this.errorCallback(i)}),n.loadDocument({url:e})})}browserPrint(){this.printCallback(this.iframeWin)}cleanUp(){delete this.window.printInstance,this.removeIframe&&this.iframe.parentElement.removeChild(this.iframe)}};function
|
|
1545
|
+
</html>`,document.body.appendChild(this.iframe)}runInIframe(t){return this.iframeWin=t,this.preparePrint().then(()=>this.browserPrint()).then(()=>this.cleanUp())}preparePrint(){this.iframeWin.document.title=this.title;let t=new Blob([this.htmlDoc],{type:"text/html"}),e=URL.createObjectURL(t),n=new qi({viewportElement:this.iframeWin.document.body.firstElementChild,window:this.iframeWin,debug:!0});return new Promise(s=>{n.addListener("readystatechange",()=>{n.readyState==="complete"&&s()}),this.errorCallback&&n.addListener("error",o=>{var a,l;let i=(l=(a=o.content.error)==null?void 0:a.toString())!=null?l:o.content.messages.join(`
|
|
1546
|
+
`);this.errorCallback(i)}),n.loadDocument({url:e})})}browserPrint(){this.printCallback(this.iframeWin)}cleanUp(){delete this.window.printInstance,this.removeIframe&&this.iframe.parentElement.removeChild(this.iframe)}};function Db(r,t){new wp(r,t).init()}
|
|
1540
1547
|
//# sourceMappingURL=vivliostyle.js.map
|