@vivliostyle/print 2.44.0 → 2.44.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es6.js CHANGED
@@ -1,12 +1,12 @@
1
- var Pg=Object.create;var kh=Object.defineProperty;var Ng=Object.getOwnPropertyDescriptor;var Tg=Object.getOwnPropertyNames;var Ag=Object.getPrototypeOf,Ig=Object.prototype.hasOwnProperty;var Fg=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var Rg=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Tg(t))!Ig.call(e,o)&&o!==i&&kh(e,o,{get:()=>t[o],enumerable:!(n=Ng(t,o))||n.enumerable});return e};var Lg=(e,t,i)=>(i=e!=null?Pg(Ag(e)):{},Rg(t||!e||!e.__esModule?kh(i,"default",{value:e,enumerable:!0}):i,e));var Sg=Fg((dC,xg)=>{"use strict";var Og=Object.create,Go=Object.defineProperty,Bg=Object.getOwnPropertyDescriptor,Mg=Object.getOwnPropertyNames,_g=Object.getPrototypeOf,Dg=Object.prototype.hasOwnProperty,cc=e=>{throw TypeError(e)},zg=(e,t,i)=>t in e?Go(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Vg=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}},Ug=(e,t)=>{for(var i in t)Go(e,i,{get:t[i],enumerable:!0})},dc=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Mg(t))!Dg.call(e,o)&&o!==i&&Go(e,o,{get:()=>t[o],enumerable:!(n=Bg(t,o))||n.enumerable});return e},$g=(e,t,i)=>(i=e!=null?Og(_g(e)):{},dc(t||!e||!e.__esModule?Go(i,"default",{value:e,enumerable:!0}):i,e)),Hg=e=>dc(Go({},"__esModule",{value:!0}),e),u=(e,t,i)=>zg(e,typeof t!="symbol"?t+"":t,i),xl=(e,t,i)=>t.has(e)||cc("Cannot "+i),H=(e,t,i)=>(xl(e,t,"read from private field"),i?i.call(e):t.get(e)),ie=(e,t,i)=>t.has(e)?cc("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),de=(e,t,i,n)=>(xl(e,t,"write to private field"),n?n.call(e,i):t.set(e,i),i),le=(e,t,i)=>(xl(e,t,"access private method"),i),Wg=Vg((e,t)=>{var i=-1,n=1,o=0;function r(k,_,F,D,E){if(k===_)return k?[[o,k]]:[];if(F!=null){var N=X(k,_,F);if(N)return N}var R=l(k,_),$=k.substring(0,R);k=k.substring(R),_=_.substring(R),R=d(k,_);var V=k.substring(k.length-R);k=k.substring(0,k.length-R),_=_.substring(0,_.length-R);var q=s(k,_);return $&&q.unshift([o,$]),V&&q.push([o,V]),b(q,E),D&&f(q),q}function s(k,_){var F;if(!k)return[[n,_]];if(!_)return[[i,k]];var D=k.length>_.length?k:_,E=k.length>_.length?_:k,N=D.indexOf(E);if(N!==-1)return F=[[n,D.substring(0,N)],[o,E],[n,D.substring(N+E.length)]],k.length>_.length&&(F[0][0]=F[2][0]=i),F;if(E.length===1)return[[i,k],[n,_]];var R=p(k,_);if(R){var $=R[0],V=R[1],q=R[2],Q=R[3],ee=R[4],pe=r($,q),re=r(V,Q);return pe.concat([[o,ee]],re)}return a(k,_)}function a(k,_){for(var F=k.length,D=_.length,E=Math.ceil((F+D)/2),N=E,R=2*E,$=new Array(R),V=new Array(R),q=0;q<R;q++)$[q]=-1,V[q]=-1;$[N+1]=0,V[N+1]=0;for(var Q=F-D,ee=Q%2!==0,pe=0,re=0,se=0,De=0,Te=0;Te<E;Te++){for(var fe=-Te+pe;fe<=Te-re;fe+=2){var Ce=N+fe,ge;fe===-Te||fe!==Te&&$[Ce-1]<$[Ce+1]?ge=$[Ce+1]:ge=$[Ce-1]+1;for(var Ie=ge-fe;ge<F&&Ie<D&&k.charAt(ge)===_.charAt(Ie);)ge++,Ie++;if($[Ce]=ge,ge>F)re+=2;else if(Ie>D)pe+=2;else if(ee){var Oe=N+Q-fe;if(Oe>=0&&Oe<R&&V[Oe]!==-1){var Fe=F-V[Oe];if(ge>=Fe)return h(k,_,ge,Ie)}}}for(var He=-Te+se;He<=Te-De;He+=2){var Oe=N+He,Fe;He===-Te||He!==Te&&V[Oe-1]<V[Oe+1]?Fe=V[Oe+1]:Fe=V[Oe-1]+1;for(var gt=Fe-He;Fe<F&&gt<D&&k.charAt(F-Fe-1)===_.charAt(D-gt-1);)Fe++,gt++;if(V[Oe]=Fe,Fe>F)De+=2;else if(gt>D)se+=2;else if(!ee){var Ce=N+Q-He;if(Ce>=0&&Ce<R&&$[Ce]!==-1){var ge=$[Ce],Ie=N+ge-Ce;if(Fe=F-Fe,ge>=Fe)return h(k,_,ge,Ie)}}}}return[[i,k],[n,_]]}function h(k,_,F,D){var E=k.substring(0,F),N=_.substring(0,D),R=k.substring(F),$=_.substring(D),V=r(E,N),q=r(R,$);return V.concat(q)}function l(k,_){if(!k||!_||k.charAt(0)!==_.charAt(0))return 0;for(var F=0,D=Math.min(k.length,_.length),E=D,N=0;F<E;)k.substring(N,E)==_.substring(N,E)?(F=E,N=F):D=E,E=Math.floor((D-F)/2+F);return C(k.charCodeAt(E-1))&&E--,E}function c(k,_){var F=k.length,D=_.length;if(F==0||D==0)return 0;F>D?k=k.substring(F-D):F<D&&(_=_.substring(0,F));var E=Math.min(F,D);if(k==_)return E;for(var N=0,R=1;;){var $=k.substring(E-R),V=_.indexOf($);if(V==-1)return N;R+=V,(V==0||k.substring(E-R)==_.substring(0,R))&&(N=R,R++)}}function d(k,_){if(!k||!_||k.slice(-1)!==_.slice(-1))return 0;for(var F=0,D=Math.min(k.length,_.length),E=D,N=0;F<E;)k.substring(k.length-E,k.length-N)==_.substring(_.length-E,_.length-N)?(F=E,N=F):D=E,E=Math.floor((D-F)/2+F);return P(k.charCodeAt(k.length-E))&&E--,E}function p(k,_){var F=k.length>_.length?k:_,D=k.length>_.length?_:k;if(F.length<4||D.length*2<F.length)return null;function E(re,se,De){for(var Te=re.substring(De,De+Math.floor(re.length/4)),fe=-1,Ce="",ge,Ie,Oe,Fe;(fe=se.indexOf(Te,fe+1))!==-1;){var He=l(re.substring(De),se.substring(fe)),gt=d(re.substring(0,De),se.substring(0,fe));Ce.length<gt+He&&(Ce=se.substring(fe-gt,fe)+se.substring(fe,fe+He),ge=re.substring(0,De-gt),Ie=re.substring(De+He),Oe=se.substring(0,fe-gt),Fe=se.substring(fe+He))}return Ce.length*2>=re.length?[ge,Ie,Oe,Fe,Ce]:null}var N=E(F,D,Math.ceil(F.length/4)),R=E(F,D,Math.ceil(F.length/2)),$;if(!N&&!R)return null;R?N?$=N[4].length>R[4].length?N:R:$=R:$=N;var V,q,Q,ee;k.length>_.length?(V=$[0],q=$[1],Q=$[2],ee=$[3]):(Q=$[0],ee=$[1],V=$[2],q=$[3]);var pe=$[4];return[V,q,Q,ee,pe]}function f(k){for(var _=!1,F=[],D=0,E=null,N=0,R=0,$=0,V=0,q=0;N<k.length;)k[N][0]==o?(F[D++]=N,R=V,$=q,V=0,q=0,E=k[N][1]):(k[N][0]==n?V+=k[N][1].length:q+=k[N][1].length,E&&E.length<=Math.max(R,$)&&E.length<=Math.max(V,q)&&(k.splice(F[D-1],0,[i,E]),k[F[D-1]+1][0]=n,D--,D--,N=D>0?F[D-1]:-1,R=0,$=0,V=0,q=0,E=null,_=!0)),N++;for(_&&b(k),S(k),N=1;N<k.length;){if(k[N-1][0]==i&&k[N][0]==n){var Q=k[N-1][1],ee=k[N][1],pe=c(Q,ee),re=c(ee,Q);pe>=re?(pe>=Q.length/2||pe>=ee.length/2)&&(k.splice(N,0,[o,ee.substring(0,pe)]),k[N-1][1]=Q.substring(0,Q.length-pe),k[N+1][1]=ee.substring(pe),N++):(re>=Q.length/2||re>=ee.length/2)&&(k.splice(N,0,[o,Q.substring(0,re)]),k[N-1][0]=n,k[N-1][1]=ee.substring(0,ee.length-re),k[N+1][0]=i,k[N+1][1]=Q.substring(re),N++),N++}N++}}var g=/[^a-zA-Z0-9]/,v=/\s/,w=/[\r\n]/,x=/\n\r?\n$/,m=/^\r?\n\r?\n/;function S(k){function _(re,se){if(!re||!se)return 6;var De=re.charAt(re.length-1),Te=se.charAt(0),fe=De.match(g),Ce=Te.match(g),ge=fe&&De.match(v),Ie=Ce&&Te.match(v),Oe=ge&&De.match(w),Fe=Ie&&Te.match(w),He=Oe&&re.match(x),gt=Fe&&se.match(m);return He||gt?5:Oe||Fe?4:fe&&!ge&&Ie?3:ge||Ie?2:fe||Ce?1:0}for(var F=1;F<k.length-1;){if(k[F-1][0]==o&&k[F+1][0]==o){var D=k[F-1][1],E=k[F][1],N=k[F+1][1],R=d(D,E);if(R){var $=E.substring(E.length-R);D=D.substring(0,D.length-R),E=$+E.substring(0,E.length-R),N=$+N}for(var V=D,q=E,Q=N,ee=_(D,E)+_(E,N);E.charAt(0)===N.charAt(0);){D+=E.charAt(0),E=E.substring(1)+N.charAt(0),N=N.substring(1);var pe=_(D,E)+_(E,N);pe>=ee&&(ee=pe,V=D,q=E,Q=N)}k[F-1][1]!=V&&(V?k[F-1][1]=V:(k.splice(F-1,1),F--),k[F][1]=q,Q?k[F+1][1]=Q:(k.splice(F+1,1),F--))}F++}}function b(k,_){k.push([o,""]);for(var F=0,D=0,E=0,N="",R="",$;F<k.length;){if(F<k.length-1&&!k[F][1]){k.splice(F,1);continue}switch(k[F][0]){case n:E++,R+=k[F][1],F++;break;case i:D++,N+=k[F][1],F++;break;case o:var V=F-E-D-1;if(_){if(V>=0&&A(k[V][1])){var q=k[V][1].slice(-1);if(k[V][1]=k[V][1].slice(0,-1),N=q+N,R=q+R,!k[V][1]){k.splice(V,1),F--;var Q=V-1;k[Q]&&k[Q][0]===n&&(E++,R=k[Q][1]+R,Q--),k[Q]&&k[Q][0]===i&&(D++,N=k[Q][1]+N,Q--),V=Q}}if(L(k[F][1])){var q=k[F][1].charAt(0);k[F][1]=k[F][1].slice(1),N+=q,R+=q}}if(F<k.length-1&&!k[F][1]){k.splice(F,1);break}if(N.length>0||R.length>0){N.length>0&&R.length>0&&($=l(R,N),$!==0&&(V>=0?k[V][1]+=R.substring(0,$):(k.splice(0,0,[o,R.substring(0,$)]),F++),R=R.substring($),N=N.substring($)),$=d(R,N),$!==0&&(k[F][1]=R.substring(R.length-$)+k[F][1],R=R.substring(0,R.length-$),N=N.substring(0,N.length-$)));var ee=E+D;N.length===0&&R.length===0?(k.splice(F-ee,ee),F=F-ee):N.length===0?(k.splice(F-ee,ee,[n,R]),F=F-ee+1):R.length===0?(k.splice(F-ee,ee,[i,N]),F=F-ee+1):(k.splice(F-ee,ee,[i,N],[n,R]),F=F-ee+2)}F!==0&&k[F-1][0]===o?(k[F-1][1]+=k[F][1],k.splice(F,1)):F++,E=0,D=0,N="",R="";break}}k[k.length-1][1]===""&&k.pop();var pe=!1;for(F=1;F<k.length-1;)k[F-1][0]===o&&k[F+1][0]===o&&(k[F][1].substring(k[F][1].length-k[F-1][1].length)===k[F-1][1]?(k[F][1]=k[F-1][1]+k[F][1].substring(0,k[F][1].length-k[F-1][1].length),k[F+1][1]=k[F-1][1]+k[F+1][1],k.splice(F-1,1),pe=!0):k[F][1].substring(0,k[F+1][1].length)==k[F+1][1]&&(k[F-1][1]+=k[F+1][1],k[F][1]=k[F][1].substring(k[F+1][1].length)+k[F+1][1],k.splice(F+1,1),pe=!0)),F++;pe&&b(k,_)}function C(k){return k>=55296&&k<=56319}function P(k){return k>=56320&&k<=57343}function L(k){return P(k.charCodeAt(0))}function A(k){return C(k.charCodeAt(k.length-1))}function z(k){for(var _=[],F=0;F<k.length;F++)k[F][1].length>0&&_.push(k[F]);return _}function U(k,_,F,D){return A(k)||L(D)?null:z([[o,k],[i,_],[n,F],[o,D]])}function X(k,_,F){var D=typeof F=="number"?{index:F,length:0}:F.oldRange,E=typeof F=="number"?null:F.newRange,N=k.length,R=_.length;if(D.length===0&&(E===null||E.length===0)){var $=D.index,V=k.slice(0,$),q=k.slice($),Q=E?E.index:null;e:{var ee=$+R-N;if(Q!==null&&Q!==ee||ee<0||ee>R)break e;var pe=_.slice(0,ee),re=_.slice(ee);if(re!==q)break e;var se=Math.min($,ee),De=V.slice(0,se),Te=pe.slice(0,se);if(De!==Te)break e;var fe=V.slice(se),Ce=pe.slice(se);return U(De,fe,Ce,q)}e:{if(Q!==null&&Q!==$)break e;var ge=$,pe=_.slice(0,ge),re=_.slice(ge);if(pe!==V)break e;var Ie=Math.min(N-ge,R-ge),Oe=q.slice(q.length-Ie),Fe=re.slice(re.length-Ie);if(Oe!==Fe)break e;var fe=q.slice(0,q.length-Ie),Ce=re.slice(0,re.length-Ie);return U(V,fe,Ce,Oe)}}if(D.length>0&&E&&E.length===0)e:{var De=k.slice(0,D.index),Oe=k.slice(D.index+D.length),se=De.length,Ie=Oe.length;if(R<se+Ie)break e;var Te=_.slice(0,se),Fe=_.slice(R-Ie);if(De!==Te||Oe!==Fe)break e;var fe=k.slice(se,N-Ie),Ce=_.slice(se,R-Ie);return U(De,fe,Ce,Oe)}return null}function oe(k,_,F,D){return r(k,_,F,D,!0)}oe.INSERT=n,oe.DELETE=i,oe.EQUAL=o,t.exports=oe}),pc={};Ug(pc,{CoreViewer:()=>wg,HOOKS:()=>Ts,Navigation:()=>bg,PageProgression:()=>Sl,PageSide:()=>mc,PageViewMode:()=>tC,Profiler:()=>wc,ReadyState:()=>yc,UserAgentBaseCss:()=>Nd,UserAgentCounterStylesCss:()=>Id,UserAgentPageCss:()=>Pd,UserAgentTocCss:()=>Td,UserAgentXml:()=>Ed,ValidationTxt:()=>kd,VivliostylePolyfillCss:()=>Ad,VivliostyleViewportCss:()=>Cd,VivliostyleViewportScreenCss:()=>Sd,ZoomType:()=>eC,getHooksForName:()=>_t,isDebug:()=>Io,pageProgressionOf:()=>gc,plugin:()=>jg,printHTML:()=>nC,profile:()=>Zg,profiler:()=>Nt,registerHook:()=>Ft,removeHook:()=>Cl,setDebug:()=>fc});xg.exports=Hg(pc);var Io=!1;function fc(e){Io=e}var Sl=(e=>(e.LTR="ltr",e.RTL="rtl",e))(Sl||{});function gc(e){switch(e){case"ltr":return"ltr";case"rtl":return"rtl";default:throw new Error(`unknown PageProgression: ${e}`)}}var mc=(e=>(e.LEFT="left",e.RIGHT="right",e))(mc||{}),yc=(e=>(e.LOADING="loading",e.INTERACTIVE="interactive",e.COMPLETE="complete",e))(yc||{}),vc=(e=>(e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e))(vc||{}),Gg=class{constructor(e){u(this,"opt_console",e),u(this,"listeners",{})}consoleDebug(e){this.opt_console?this.opt_console.debug?this.opt_console.debug(...e):this.opt_console.log(...e):console.debug(...e)}consoleInfo(e){this.opt_console?this.opt_console.info?this.opt_console.info(...e):this.opt_console.log(...e):console.info(...e)}consoleWarn(e){this.opt_console?this.opt_console.warn?this.opt_console.warn(...e):this.opt_console.log(...e):console.warn(...e)}consoleError(e){this.opt_console?this.opt_console.error?this.opt_console.error(...e):this.opt_console.log(...e):console.error(...e)}triggerListeners(e,t){let i=this.listeners[e];i&&i(t)}addListener(e,t){this.listeners[e]=t}debug(...e){let t=hr(arguments);this.consoleDebug(ur(t)),this.triggerListeners(1,t)}info(...e){let t=hr(arguments);this.consoleInfo(ur(t)),this.triggerListeners(2,t)}warn(...e){let t=hr(arguments);this.consoleWarn(ur(t)),this.triggerListeners(3,t)}error(...e){let t=hr(arguments);this.consoleError(ur(t)),this.triggerListeners(4,t)}};function hr(e){let t=Array.from(e),i=null;return t[0]instanceof Error&&(i=t.shift()),{error:i,messages:t}}function ur(e){let t=e.error,i=t&&(t.frameTrace||t.stack),n=[].concat(e.messages);return t&&(n.length>0&&(n=n.concat([`
1
+ var Pg=Object.create;var kh=Object.defineProperty;var Ng=Object.getOwnPropertyDescriptor;var Tg=Object.getOwnPropertyNames;var Ag=Object.getPrototypeOf,Ig=Object.prototype.hasOwnProperty;var Fg=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var Rg=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Tg(t))!Ig.call(e,r)&&r!==i&&kh(e,r,{get:()=>t[r],enumerable:!(n=Ng(t,r))||n.enumerable});return e};var Lg=(e,t,i)=>(i=e!=null?Pg(Ag(e)):{},Rg(t||!e||!e.__esModule?kh(i,"default",{value:e,enumerable:!0}):i,e));var Sg=Fg((dC,xg)=>{"use strict";var Og=Object.create,Wr=Object.defineProperty,Bg=Object.getOwnPropertyDescriptor,Mg=Object.getOwnPropertyNames,_g=Object.getPrototypeOf,Dg=Object.prototype.hasOwnProperty,cc=e=>{throw TypeError(e)},zg=(e,t,i)=>t in e?Wr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Vg=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}},Ug=(e,t)=>{for(var i in t)Wr(e,i,{get:t[i],enumerable:!0})},dc=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Mg(t))!Dg.call(e,r)&&r!==i&&Wr(e,r,{get:()=>t[r],enumerable:!(n=Bg(t,r))||n.enumerable});return e},$g=(e,t,i)=>(i=e!=null?Og(_g(e)):{},dc(t||!e||!e.__esModule?Wr(i,"default",{value:e,enumerable:!0}):i,e)),Hg=e=>dc(Wr({},"__esModule",{value:!0}),e),u=(e,t,i)=>zg(e,typeof t!="symbol"?t+"":t,i),xl=(e,t,i)=>t.has(e)||cc("Cannot "+i),H=(e,t,i)=>(xl(e,t,"read from private field"),i?i.call(e):t.get(e)),ie=(e,t,i)=>t.has(e)?cc("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),de=(e,t,i,n)=>(xl(e,t,"write to private field"),n?n.call(e,i):t.set(e,i),i),le=(e,t,i)=>(xl(e,t,"access private method"),i),Wg=Vg((e,t)=>{var i=-1,n=1,r=0;function o(k,_,F,D,E){if(k===_)return k?[[r,k]]:[];if(F!=null){var N=X(k,_,F);if(N)return N}var R=l(k,_),$=k.substring(0,R);k=k.substring(R),_=_.substring(R),R=d(k,_);var V=k.substring(k.length-R);k=k.substring(0,k.length-R),_=_.substring(0,_.length-R);var q=s(k,_);return $&&q.unshift([r,$]),V&&q.push([r,V]),b(q,E),D&&f(q),q}function s(k,_){var F;if(!k)return[[n,_]];if(!_)return[[i,k]];var D=k.length>_.length?k:_,E=k.length>_.length?_:k,N=D.indexOf(E);if(N!==-1)return F=[[n,D.substring(0,N)],[r,E],[n,D.substring(N+E.length)]],k.length>_.length&&(F[0][0]=F[2][0]=i),F;if(E.length===1)return[[i,k],[n,_]];var R=p(k,_);if(R){var $=R[0],V=R[1],q=R[2],Q=R[3],ee=R[4],pe=o($,q),oe=o(V,Q);return pe.concat([[r,ee]],oe)}return a(k,_)}function a(k,_){for(var F=k.length,D=_.length,E=Math.ceil((F+D)/2),N=E,R=2*E,$=new Array(R),V=new Array(R),q=0;q<R;q++)$[q]=-1,V[q]=-1;$[N+1]=0,V[N+1]=0;for(var Q=F-D,ee=Q%2!==0,pe=0,oe=0,se=0,De=0,Te=0;Te<E;Te++){for(var fe=-Te+pe;fe<=Te-oe;fe+=2){var Ce=N+fe,ge;fe===-Te||fe!==Te&&$[Ce-1]<$[Ce+1]?ge=$[Ce+1]:ge=$[Ce-1]+1;for(var Ie=ge-fe;ge<F&&Ie<D&&k.charAt(ge)===_.charAt(Ie);)ge++,Ie++;if($[Ce]=ge,ge>F)oe+=2;else if(Ie>D)pe+=2;else if(ee){var Be=N+Q-fe;if(Be>=0&&Be<R&&V[Be]!==-1){var Fe=F-V[Be];if(ge>=Fe)return h(k,_,ge,Ie)}}}for(var He=-Te+se;He<=Te-De;He+=2){var Be=N+He,Fe;He===-Te||He!==Te&&V[Be-1]<V[Be+1]?Fe=V[Be+1]:Fe=V[Be-1]+1;for(var gt=Fe-He;Fe<F&&gt<D&&k.charAt(F-Fe-1)===_.charAt(D-gt-1);)Fe++,gt++;if(V[Be]=Fe,Fe>F)De+=2;else if(gt>D)se+=2;else if(!ee){var Ce=N+Q-He;if(Ce>=0&&Ce<R&&$[Ce]!==-1){var ge=$[Ce],Ie=N+ge-Ce;if(Fe=F-Fe,ge>=Fe)return h(k,_,ge,Ie)}}}}return[[i,k],[n,_]]}function h(k,_,F,D){var E=k.substring(0,F),N=_.substring(0,D),R=k.substring(F),$=_.substring(D),V=o(E,N),q=o(R,$);return V.concat(q)}function l(k,_){if(!k||!_||k.charAt(0)!==_.charAt(0))return 0;for(var F=0,D=Math.min(k.length,_.length),E=D,N=0;F<E;)k.substring(N,E)==_.substring(N,E)?(F=E,N=F):D=E,E=Math.floor((D-F)/2+F);return C(k.charCodeAt(E-1))&&E--,E}function c(k,_){var F=k.length,D=_.length;if(F==0||D==0)return 0;F>D?k=k.substring(F-D):F<D&&(_=_.substring(0,F));var E=Math.min(F,D);if(k==_)return E;for(var N=0,R=1;;){var $=k.substring(E-R),V=_.indexOf($);if(V==-1)return N;R+=V,(V==0||k.substring(E-R)==_.substring(0,R))&&(N=R,R++)}}function d(k,_){if(!k||!_||k.slice(-1)!==_.slice(-1))return 0;for(var F=0,D=Math.min(k.length,_.length),E=D,N=0;F<E;)k.substring(k.length-E,k.length-N)==_.substring(_.length-E,_.length-N)?(F=E,N=F):D=E,E=Math.floor((D-F)/2+F);return P(k.charCodeAt(k.length-E))&&E--,E}function p(k,_){var F=k.length>_.length?k:_,D=k.length>_.length?_:k;if(F.length<4||D.length*2<F.length)return null;function E(oe,se,De){for(var Te=oe.substring(De,De+Math.floor(oe.length/4)),fe=-1,Ce="",ge,Ie,Be,Fe;(fe=se.indexOf(Te,fe+1))!==-1;){var He=l(oe.substring(De),se.substring(fe)),gt=d(oe.substring(0,De),se.substring(0,fe));Ce.length<gt+He&&(Ce=se.substring(fe-gt,fe)+se.substring(fe,fe+He),ge=oe.substring(0,De-gt),Ie=oe.substring(De+He),Be=se.substring(0,fe-gt),Fe=se.substring(fe+He))}return Ce.length*2>=oe.length?[ge,Ie,Be,Fe,Ce]:null}var N=E(F,D,Math.ceil(F.length/4)),R=E(F,D,Math.ceil(F.length/2)),$;if(!N&&!R)return null;R?N?$=N[4].length>R[4].length?N:R:$=R:$=N;var V,q,Q,ee;k.length>_.length?(V=$[0],q=$[1],Q=$[2],ee=$[3]):(Q=$[0],ee=$[1],V=$[2],q=$[3]);var pe=$[4];return[V,q,Q,ee,pe]}function f(k){for(var _=!1,F=[],D=0,E=null,N=0,R=0,$=0,V=0,q=0;N<k.length;)k[N][0]==r?(F[D++]=N,R=V,$=q,V=0,q=0,E=k[N][1]):(k[N][0]==n?V+=k[N][1].length:q+=k[N][1].length,E&&E.length<=Math.max(R,$)&&E.length<=Math.max(V,q)&&(k.splice(F[D-1],0,[i,E]),k[F[D-1]+1][0]=n,D--,D--,N=D>0?F[D-1]:-1,R=0,$=0,V=0,q=0,E=null,_=!0)),N++;for(_&&b(k),S(k),N=1;N<k.length;){if(k[N-1][0]==i&&k[N][0]==n){var Q=k[N-1][1],ee=k[N][1],pe=c(Q,ee),oe=c(ee,Q);pe>=oe?(pe>=Q.length/2||pe>=ee.length/2)&&(k.splice(N,0,[r,ee.substring(0,pe)]),k[N-1][1]=Q.substring(0,Q.length-pe),k[N+1][1]=ee.substring(pe),N++):(oe>=Q.length/2||oe>=ee.length/2)&&(k.splice(N,0,[r,Q.substring(0,oe)]),k[N-1][0]=n,k[N-1][1]=ee.substring(0,ee.length-oe),k[N+1][0]=i,k[N+1][1]=Q.substring(oe),N++),N++}N++}}var g=/[^a-zA-Z0-9]/,v=/\s/,w=/[\r\n]/,x=/\n\r?\n$/,m=/^\r?\n\r?\n/;function S(k){function _(oe,se){if(!oe||!se)return 6;var De=oe.charAt(oe.length-1),Te=se.charAt(0),fe=De.match(g),Ce=Te.match(g),ge=fe&&De.match(v),Ie=Ce&&Te.match(v),Be=ge&&De.match(w),Fe=Ie&&Te.match(w),He=Be&&oe.match(x),gt=Fe&&se.match(m);return He||gt?5:Be||Fe?4:fe&&!ge&&Ie?3:ge||Ie?2:fe||Ce?1:0}for(var F=1;F<k.length-1;){if(k[F-1][0]==r&&k[F+1][0]==r){var D=k[F-1][1],E=k[F][1],N=k[F+1][1],R=d(D,E);if(R){var $=E.substring(E.length-R);D=D.substring(0,D.length-R),E=$+E.substring(0,E.length-R),N=$+N}for(var V=D,q=E,Q=N,ee=_(D,E)+_(E,N);E.charAt(0)===N.charAt(0);){D+=E.charAt(0),E=E.substring(1)+N.charAt(0),N=N.substring(1);var pe=_(D,E)+_(E,N);pe>=ee&&(ee=pe,V=D,q=E,Q=N)}k[F-1][1]!=V&&(V?k[F-1][1]=V:(k.splice(F-1,1),F--),k[F][1]=q,Q?k[F+1][1]=Q:(k.splice(F+1,1),F--))}F++}}function b(k,_){k.push([r,""]);for(var F=0,D=0,E=0,N="",R="",$;F<k.length;){if(F<k.length-1&&!k[F][1]){k.splice(F,1);continue}switch(k[F][0]){case n:E++,R+=k[F][1],F++;break;case i:D++,N+=k[F][1],F++;break;case r:var V=F-E-D-1;if(_){if(V>=0&&A(k[V][1])){var q=k[V][1].slice(-1);if(k[V][1]=k[V][1].slice(0,-1),N=q+N,R=q+R,!k[V][1]){k.splice(V,1),F--;var Q=V-1;k[Q]&&k[Q][0]===n&&(E++,R=k[Q][1]+R,Q--),k[Q]&&k[Q][0]===i&&(D++,N=k[Q][1]+N,Q--),V=Q}}if(L(k[F][1])){var q=k[F][1].charAt(0);k[F][1]=k[F][1].slice(1),N+=q,R+=q}}if(F<k.length-1&&!k[F][1]){k.splice(F,1);break}if(N.length>0||R.length>0){N.length>0&&R.length>0&&($=l(R,N),$!==0&&(V>=0?k[V][1]+=R.substring(0,$):(k.splice(0,0,[r,R.substring(0,$)]),F++),R=R.substring($),N=N.substring($)),$=d(R,N),$!==0&&(k[F][1]=R.substring(R.length-$)+k[F][1],R=R.substring(0,R.length-$),N=N.substring(0,N.length-$)));var ee=E+D;N.length===0&&R.length===0?(k.splice(F-ee,ee),F=F-ee):N.length===0?(k.splice(F-ee,ee,[n,R]),F=F-ee+1):R.length===0?(k.splice(F-ee,ee,[i,N]),F=F-ee+1):(k.splice(F-ee,ee,[i,N],[n,R]),F=F-ee+2)}F!==0&&k[F-1][0]===r?(k[F-1][1]+=k[F][1],k.splice(F,1)):F++,E=0,D=0,N="",R="";break}}k[k.length-1][1]===""&&k.pop();var pe=!1;for(F=1;F<k.length-1;)k[F-1][0]===r&&k[F+1][0]===r&&(k[F][1].substring(k[F][1].length-k[F-1][1].length)===k[F-1][1]?(k[F][1]=k[F-1][1]+k[F][1].substring(0,k[F][1].length-k[F-1][1].length),k[F+1][1]=k[F-1][1]+k[F+1][1],k.splice(F-1,1),pe=!0):k[F][1].substring(0,k[F+1][1].length)==k[F+1][1]&&(k[F-1][1]+=k[F+1][1],k[F][1]=k[F][1].substring(k[F+1][1].length)+k[F+1][1],k.splice(F+1,1),pe=!0)),F++;pe&&b(k,_)}function C(k){return k>=55296&&k<=56319}function P(k){return k>=56320&&k<=57343}function L(k){return P(k.charCodeAt(0))}function A(k){return C(k.charCodeAt(k.length-1))}function z(k){for(var _=[],F=0;F<k.length;F++)k[F][1].length>0&&_.push(k[F]);return _}function U(k,_,F,D){return A(k)||L(D)?null:z([[r,k],[i,_],[n,F],[r,D]])}function X(k,_,F){var D=typeof F=="number"?{index:F,length:0}:F.oldRange,E=typeof F=="number"?null:F.newRange,N=k.length,R=_.length;if(D.length===0&&(E===null||E.length===0)){var $=D.index,V=k.slice(0,$),q=k.slice($),Q=E?E.index:null;e:{var ee=$+R-N;if(Q!==null&&Q!==ee||ee<0||ee>R)break e;var pe=_.slice(0,ee),oe=_.slice(ee);if(oe!==q)break e;var se=Math.min($,ee),De=V.slice(0,se),Te=pe.slice(0,se);if(De!==Te)break e;var fe=V.slice(se),Ce=pe.slice(se);return U(De,fe,Ce,q)}e:{if(Q!==null&&Q!==$)break e;var ge=$,pe=_.slice(0,ge),oe=_.slice(ge);if(pe!==V)break e;var Ie=Math.min(N-ge,R-ge),Be=q.slice(q.length-Ie),Fe=oe.slice(oe.length-Ie);if(Be!==Fe)break e;var fe=q.slice(0,q.length-Ie),Ce=oe.slice(0,oe.length-Ie);return U(V,fe,Ce,Be)}}if(D.length>0&&E&&E.length===0)e:{var De=k.slice(0,D.index),Be=k.slice(D.index+D.length),se=De.length,Ie=Be.length;if(R<se+Ie)break e;var Te=_.slice(0,se),Fe=_.slice(R-Ie);if(De!==Te||Be!==Fe)break e;var fe=k.slice(se,N-Ie),Ce=_.slice(se,R-Ie);return U(De,fe,Ce,Be)}return null}function re(k,_,F,D){return o(k,_,F,D,!0)}re.INSERT=n,re.DELETE=i,re.EQUAL=r,t.exports=re}),pc={};Ug(pc,{CoreViewer:()=>wg,HOOKS:()=>Ts,Navigation:()=>bg,PageProgression:()=>Sl,PageSide:()=>mc,PageViewMode:()=>tC,Profiler:()=>wc,ReadyState:()=>yc,UserAgentBaseCss:()=>Nd,UserAgentCounterStylesCss:()=>Id,UserAgentPageCss:()=>Pd,UserAgentTocCss:()=>Td,UserAgentXml:()=>Ed,ValidationTxt:()=>kd,VivliostylePolyfillCss:()=>Ad,VivliostyleViewportCss:()=>Cd,VivliostyleViewportScreenCss:()=>Sd,ZoomType:()=>eC,getHooksForName:()=>_t,isDebug:()=>Ar,pageProgressionOf:()=>gc,plugin:()=>jg,printHTML:()=>nC,profile:()=>Zg,profiler:()=>Nt,registerHook:()=>Ft,removeHook:()=>Cl,setDebug:()=>fc});xg.exports=Hg(pc);var Ar=!1;function fc(e){Ar=e}var Sl=(e=>(e.LTR="ltr",e.RTL="rtl",e))(Sl||{});function gc(e){switch(e){case"ltr":return"ltr";case"rtl":return"rtl";default:throw new Error(`unknown PageProgression: ${e}`)}}var mc=(e=>(e.LEFT="left",e.RIGHT="right",e))(mc||{}),yc=(e=>(e.LOADING="loading",e.INTERACTIVE="interactive",e.COMPLETE="complete",e))(yc||{}),vc=(e=>(e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e))(vc||{}),Gg=class{constructor(e){u(this,"opt_console",e),u(this,"listeners",{})}consoleDebug(e){this.opt_console?this.opt_console.debug?this.opt_console.debug(...e):this.opt_console.log(...e):console.debug(...e)}consoleInfo(e){this.opt_console?this.opt_console.info?this.opt_console.info(...e):this.opt_console.log(...e):console.info(...e)}consoleWarn(e){this.opt_console?this.opt_console.warn?this.opt_console.warn(...e):this.opt_console.log(...e):console.warn(...e)}consoleError(e){this.opt_console?this.opt_console.error?this.opt_console.error(...e):this.opt_console.log(...e):console.error(...e)}triggerListeners(e,t){let i=this.listeners[e];i&&i(t)}addListener(e,t){this.listeners[e]=t}debug(...e){let t=lo(arguments);this.consoleDebug(ho(t)),this.triggerListeners(1,t)}info(...e){let t=lo(arguments);this.consoleInfo(ho(t)),this.triggerListeners(2,t)}warn(...e){let t=lo(arguments);this.consoleWarn(ho(t)),this.triggerListeners(3,t)}error(...e){let t=lo(arguments);this.consoleError(ho(t)),this.triggerListeners(4,t)}};function lo(e){let t=Array.from(e),i=null;return t[0]instanceof Error&&(i=t.shift()),{error:i,messages:t}}function ho(e){let t=e.error,i=t&&(t.frameTrace||t.stack),n=[].concat(e.messages);return t&&(n.length>0&&(n=n.concat([`
2
2
  `])),n=n.concat([t.toString()]),i&&(n=n.concat([`
3
- `]).concat(i))),n}var Y=new Gg,Ts=(e=>(e.SIMPLE_PROPERTY="SIMPLE_PROPERTY",e.PREPROCESS_SINGLE_DOCUMENT="PREPROCESS_SINGLE_DOCUMENT",e.PREPROCESS_TEXT_CONTENT="PREPROCESS_TEXT_CONTENT",e.PREPROCESS_ELEMENT_STYLE="PREPROCESS_ELEMENT_STYLE",e.POLYFILLED_INHERITED_PROPS="POLYFILLED_INHERITED_PROPS",e.CONFIGURATION="CONFIGURATION",e.RESOLVE_TEXT_NODE_BREAKER="RESOLVE_TEXT_NODE_BREAKER",e.RESOLVE_FORMATTING_CONTEXT="RESOLVE_FORMATTING_CONTEXT",e.RESOLVE_LAYOUT_PROCESSOR="RESOLVE_LAYOUT_PROCESSOR",e.POST_LAYOUT_BLOCK="POST_LAYOUT_BLOCK",e.PAGINATION_PROGRESS="PAGINATION_PROGRESS",e))(Ts||{}),Kr={};function Ft(e,t,i){if(!Ts[e])Y.warn(new Error(`Skipping unknown plugin hook '${e}'.`));else{let n=Kr[e];n||(n=Kr[e]=[]),i?n.unshift(t):n.push(t)}}function Cl(e,t){if(!Ts[e])Y.warn(new Error(`Ignoring unknown plugin hook '${e}'.`));else{let i=Kr[e];if(i){let n=i.indexOf(t);n>=0&&i.splice(n,1)}}}function _t(e){return Kr[e]||[]}var jg={registerHook:Ft,removeHook:Cl},wc=class{constructor(e){u(this,"performanceInstance",e),u(this,"timestamps",{}),u(this,"registerTiming"),u(this,"registerStartTiming"),u(this,"registerEndTiming"),this.registerTiming=ln,this.registerStartTiming=this.registerStartTiming=ln,this.registerEndTiming=this.registerEndTiming=ln}forceRegisterStartTiming(e,t){Qs.call(this,e,"start",t)}forceRegisterEndTiming(e,t){Qs.call(this,e,"end",t)}printTimings(){let e=this.timestamps,t="";Object.keys(e).forEach(i=>{let n=e[i],o=n.length;for(let r=0;r<o;r++){let s=n[r];t+=i,o>1&&(t+=`(${r})`),t+=` => start: ${s.start}, end: ${s.end}, duration: ${s.end-s.start}
4
- `}}),Y.info(t)}disable(){this.registerTiming=ln,this.registerStartTiming=this.registerStartTiming=ln,this.registerEndTiming=this.registerEndTiming=ln}enable(){this.registerTiming=Qs,this.registerStartTiming=this.registerStartTiming=Eh,this.registerEndTiming=this.registerEndTiming=Xg}isEnabled(){return this.registerStartTiming===Eh}};function ln(){}function Qs(e,t,i){i||(i=this.performanceInstance.now());let n=this.timestamps[e];n||(n=this.timestamps[e]=[]);let o,r=n.length;for(let s=r-1;s>=0&&(o=n[s],!(o&&!o[t]));s--)o=null;o||(o={},n.push(o)),o[t]=i}function Eh(e,t){this.registerTiming(e,"start",t)}function Xg(e,t){this.registerTiming(e,"end",t)}var qg={now:Date.now},Yg=window&&window.performance,Nt=new wc(Yg||qg);Nt.forceRegisterStartTiming("load_vivliostyle");var Zg={profiler:{registerStartTiming:Nt.registerStartTiming,registerEndTiming:Nt.registerEndTiming,printTimings:Nt.printTimings,disable:Nt.disable,enable:Nt.enable}},jo=navigator.userAgent.includes("Chrome")?"chromium":navigator.userAgent.includes("Firefox")?"firefox":navigator.userAgent.includes("AppleWebKit")?"webkit":"unknown",Jr=/^[\s\p{Zs}\p{P}\p{Mn}]*[\p{L}\p{N}]\p{Mn}*(?:[\s\p{Zs}]*\p{P}\p{Mn}*)*/u,Ht="data-adapt-eloff",Kg={};function kl(e){return JSON.parse(e)}function pt(e){let t=e.match(/^([^#]*)/);return t?t[1]:e}function bc(e){let t=e.match(/^([^#?]*)/);return t?t[1]:e}var El="?viv-toc-box";function As(e){return e.endsWith(El)}function dn(e){return As(e)?e.slice(0,-El.length):e}function xa(e){return As(e)?e:pt(e)+El}var Ji=window.location.href;function Ph(e){Ji=e}var Ni=window.location.href;function Nh(e){Ni=e}function Jg(e){let t=bc(e).match(/^(https?:\/\/raw\.githack\.com\/web-platform-tests\/wpt\/[^/]+)(?:\/|$)/);return t?t[1]:null}function Fo(e){return e.replace(/^(https?:)\/\/raw\.githack\.com\/web-platform-tests\/wpt\/[^/]+\//,"$1//wpt.live/")}function Ae(e,t){if(/^data:/i.test(t))return e||t;if(!t||e.match(/^\w{2,}:/))return e.toLowerCase().match("^javascript:")?"#":(e.match(/^\w{2,}:\/\/[^\/]+$/)&&(e=`${e}/`),e);t.match(/^\w{2,}:\/\/[^\/]+$/)&&(t=`${t}/`);let i;if(e.match(/^\/\//))return i=t.match(/^(\w{2,}:)\/\//),i?i[1]+e:e;if(e.match(/^\//)){let s=Jg(t);return s?s+e:(i=t.match(/^(\w{2,}:\/\/[^\/]+)\//),i?i[1]+e:e)}if(e.match(/^\.(\/|$)/)&&(e=e.substr(2)),t=bc(t),e.match(/^#/))return t+e;let n=t.lastIndexOf("/");if(n<0)return e;let o=t.substr(0,n+1)+e,r="";for(i=o.match(/^([^?#]*)([?#].*)$/),i&&(o=i[1],r=i[2]);n=o.indexOf("/../"),!(n<=0);){let s=o.lastIndexOf("/",n-1);if(s<=0)break;o=o.substr(0,s)+o.substr(n+3)}return o.replace(/\/(\.\/)+/g,"/")+r}function Qr(e,t){return e.match(/^#/)&&t?pt(t)+e:Ae(e,t)}function xc(e){return/^about:blank($|[?#])/i.test(e)?"data:text/html,":e}function Fn(e){let t;return(e=xc(e))!==e||((t=/^(https?:)\/\/github\.com\/web-platform-tests\/wpt\/(blob\/|tree\/|raw\/)?(.*)$/.exec(e))?e=`${t[1]}//raw.githack.com/web-platform-tests/wpt/${t[2]?"":"master/"}${t[3]}`:(t=/^(https?:)\/\/github\.com\/([^/]+\/[^/]+)\/(blob\/|tree\/|raw\/)?(.*)$/.exec(e))?e=`${t[1]}//raw.githubusercontent.com/${t[2]}/${t[3]?"":"master/"}${t[4]}`:(t=/^(https?:)\/\/wpt\.live\/(.*)$/.exec(e))?/\.sub\.[^/]+(?:[?#].*)?$/.test(t[2])||(e=`${t[1]}//raw.githack.com/web-platform-tests/wpt/master/${t[2]}`):(t=/^(https?:)\/\/www\.aozora\.gr\.jp\/(cards\/[^/]+\/files\/[^/.]+\.html)$/.exec(e))?e=`${t[1]}//raw.githubusercontent.com/aozorabunko/aozorabunko/master/${t[2]}`:(t=/^(https?:)\/\/gist\.github\.com\/([^/]+\/\w+)(\/|$)(raw(\/|$))?(.*)$/.exec(e))?e=`${t[1]}//gist.githubusercontent.com/${t[2]}/raw/${t[6]}`:(t=/^(https?:)\/\/gist\.github\.com\/([^/]+\/\w+)(?:#|%23)file-(.*)-(\w+)$/.exec(e))?e=`${t[1]}//gist.githubusercontent.com/${t[2]}/raw/${t[3]}.${t[4]}`:(t=/^(https?:)\/\/(?:[^/.]+\.)?jsbin\.com\/(?!(?:blog|help)\b)(\w+)((\/\d+)?).*$/.exec(e))&&(e=`${t[1]}//output.jsbin.com/${t[2]}${t[3]}/`)),e}function Th(e){return e==null?e:e.toString()}var Qg=class{constructor(){u(this,"queue",[null])}length(){return this.queue.length-1}add(e){let t=this.queue.length;for(;t>1;){let i=Math.floor(t/2),n=this.queue[i];if(n.compare(e)>0){this.queue[t]=e;return}this.queue[t]=n,t=i}this.queue[1]=e}peek(){return this.queue[1]}remove(){let e=this.queue[1],t=this.queue.pop(),i=this.queue.length;if(i>1){let n=1;for(;;){let o=n*2;if(o>=i)break;if(this.queue[o].compare(t)>0)o+1<i&&this.queue[o+1].compare(this.queue[o])>0&&o++;else if(o+1<i&&this.queue[o+1].compare(t)>0)o++;else break;this.queue[n]=this.queue[o],n=o}this.queue[n]=t}return e}},Sc=["","-webkit-","-moz-"],pn={};function Rr(e,t){return CSS.supports(e+t,"unset")}function em(e){let t=pn[e];if(t||t===null)return t;switch(e){case"behavior":case"template":case"ua-list-item-count":case"x-first-pseudo":return pn[e]=null,null;case"text-combine-upright":if(Rr("-webkit-","text-combine")&&!Rr("","text-combine-upright"))return pn[e]=["-webkit-text-combine"],["-webkit-text-combine"];break}for(let i of Sc)if(Rr(i,e))return t=[i+e],pn[e]=t,t;return Y.warn("Property not supported by the browser: ",e),pn[e]=null,null}function I(e,t,i){let n=e?.style;if(!n)return;if(t.startsWith("--")){n.setProperty(t,i||" ");return}let o=em(t);if(o)for(let r of o){switch(r){case"-webkit-text-combine":i==="all"&&(i="horizontal");break;case"text-combine-upright":i==="all"&&n.setProperty("text-indent","0");break}n.setProperty(r,i)}}function ki(e,t,i){try{let n=pn[t];return e.style.getPropertyValue(n?n[0]:t)}catch{}return i||""}function Sa(e){let t=e.getAttributeNS("http://www.w3.org/XML/1998/namespace","lang");return!t&&e.namespaceURI=="http://www.w3.org/1999/xhtml"&&(t=e.getAttribute("lang")),t}var gi=class{constructor(){u(this,"list",[])}append(e){return this.list.push(e),this}clear(){this.list=[]}toString(){let e=this.list.join("");return this.list=[e],e}};function Pl(e){return`\\${e.charCodeAt(0).toString(16)} `}function Ti(e){return e.replace(/[^-_a-zA-Z0-9\u0080-\uFFFF]/g,Pl)}function Xo(e){return e.replace(/[\u0000-\u001F"\\]/g,Pl)}function Ah(e){return e.replace(/[\s+&?=#\u007F-\uFFFF]+/g,encodeURIComponent)}function Ih(e){return!!e.match(/^[a-zA-Z\u009E\u009F\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u024F\u037B-\u037D\u0386\u0388-\u0482\u048A-\u0527]$/)}function tm(e,t){return t=typeof t=="string"?t:"\\u",t+(65536|e.charCodeAt(0)).toString(16).substr(1)}function Cc(e,t){function i(n){return tm(n,t)}return e.replace(/[^-a-zA-Z0-9_]/g,i)}function es(e){return Cc(e)}function im(e,t){return t=typeof t=="string"?t:"\\u",e.indexOf(t)===0?String.fromCharCode(parseInt(e.substring(t.length),16)):e}function nm(e,t){t=typeof t=="string"?t:"\\u";function i(o){return im(o,t)}let n=new RegExp(`${es(t)}[0-9a-fA-F]{4}`,"g");return e.replace(n,i)}function mi(e,t){let i=0,n=e;for(;;){if(i<=n,i==0||t(i-1),n==e||t(n),i==n)return i;let o=i+n>>1;t(o)?n=o:i=o+1}}function kc(e,t){return e-t}function Fh(e,t){let i={};for(let n of e){let o=t(n);o&&!i[o]&&(i[o]=n)}return i}function om(e){let t={};for(let i=0;i<e.length;i++)t[e[i]]=!0;return t}function ea(e,t){let i={};for(let n of e){let o=t(n);o&&(i[o]?i[o].push(n):i[o]=[n])}return i}function rm(e,t){let i={};for(let n in e)i[n]=t(e[n],n);return i}var Nl=class{constructor(){u(this,"listeners",{})}dispatchEvent(e){let t=this.listeners[e.type];if(t){e.target=this,e.currentTarget=this;for(let i=0;i<t.length;i++)t[i](e)}}addEventListener(e,t,i){if(i)return;let n=this.listeners[e];n?n.includes(t)||n.push(t):this.listeners[e]=[t]}removeEventListener(e,t,i){if(i)return;let n=this.listeners[e];if(n){let o=n.indexOf(t);o>=0&&n.splice(o,1)}}},ji={audio:!0,canvas:!0,embed:!0,iframe:!0,img:!0,math:!0,object:!0,picture:!0,svg:!0,video:!0};function Ec(){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 Pc(e){return{fontFamily:e.fontFamily,lineHeight:e.lineHeight,margin:e.margin,hyphenate:e.hyphenate,columnWidth:e.columnWidth,horizontal:e.horizontal,nightMode:e.nightMode,spreadView:e.spreadView,pageBorder:e.pageBorder,enabledMediaTypes:Object.assign({},e.enabledMediaTypes),defaultPaperSize:e.defaultPaperSize?Object.assign({},e.defaultPaperSize):void 0}}var sm=Ec(),Rh={PENDING:{}};function Nc(e,t,i,n){let o=Math.min((e-0)/i,(t-0)/n);return`matrix(${o},0,0,${o},0,0)`}function am(e){return`"${Xo(`${e}`)}"`}function lm(e){return Ti(`${e}`)}function Ca(e,t){return e?`${Ti(e)}.${Ti(t)}`:Ti(t)}var Tc=0,ts=class{constructor(e,t){if(u(this,"parent",e),u(this,"resolver",t),u(this,"scopeKey"),u(this,"children",[]),u(this,"zero"),u(this,"one"),u(this,"_true"),u(this,"_false"),u(this,"values",{}),u(this,"funcs",{}),u(this,"builtIns",{}),this.scopeKey=`S${Tc++}`,this.zero=new it(this,0),this.one=new it(this,1),this._true=new it(this,!0),this._false=new it(this,!1),e&&e.children.push(this),!e){let i=this.builtIns;i.floor=Math.floor,i.ceil=Math.ceil,i.round=Math.round,i.sqrt=Math.sqrt,i.min=Math.min,i.max=Math.max,i.letterbox=Nc,i["css-string"]=am,i["css-name"]=lm,i.typeof=n=>typeof n,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 this.pubTitle?this.pubTitle:""}),this.defineBuiltInName("doc-title",function(){return this.docTitle?this.docTitle:""})}}defineBuiltInName(e,t){this.values[e]=new we(this,t,e)}defineName(e,t){this.values[e]=t}defineFunc(e,t){this.funcs[e]=t}defineBuiltIn(e,t){this.builtIns[e]=t}};function hm(e){switch(e?.toLowerCase()){case"px":case"in":case"pt":case"pc":case"cm":case"mm":case"q":return!0;default:return!1}}function Ac(e){switch(e?.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 um(e){switch(e?.toLowerCase()){case"em":case"rem":case"lh":case"rlh":return!0;default:return!1}}function cm(e){switch(e?.toLowerCase()){case"rem":case"rlh":return!0;default:return!1}}var Zt={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,lh:20,rlh:20,dppx:1,dpi:1/96,dpcm:2.54/96};function Ic(e){switch(e){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 ka=class{constructor(e,t,i,n){u(this,"rootScope",e),u(this,"viewportWidth",t),u(this,"viewportHeight",i),u(this,"actualPageWidth",null),u(this,"pageWidth"),u(this,"actualPageHeight",null),u(this,"pageHeight"),u(this,"initialFontSize"),u(this,"rootFontSize",null),u(this,"isRelativeRootFontSize",null),u(this,"fontSize"),u(this,"rootLineHeight",null),u(this,"pref"),u(this,"scopes",{}),u(this,"pageAreaWidth",null),u(this,"pageAreaHeight",null),u(this,"pageVertical",null),u(this,"pubTitle",null),u(this,"docTitle",null),this.pageWidth=function(){return this.actualPageWidth?this.actualPageWidth:this.pref.spreadView?Math.floor(t/2)-this.pref.pageBorder:t},this.pageHeight=function(){return this.actualPageHeight?this.actualPageHeight:i},this.initialFontSize=n,this.fontSize=function(){return this.rootFontSize?this.rootFontSize:n},this.pref=sm}getScopeContext(e){let t=this.scopes[e.scopeKey];return t||(t={},this.scopes[e.scopeKey]=t),t}clearScope(e){this.scopes[e.scopeKey]={};for(let t=0;t<e.children.length;t++)this.clearScope(e.children[t])}queryUnitSize(e,t,i){if(Ac(e)){let n=this.pageWidth()/100,o=this.pageHeight()/100,r=this.pageAreaWidth!=null?this.pageAreaWidth/100:n,s=this.pageAreaHeight!=null?this.pageAreaHeight/100:o,a=i??this.pageVertical;switch(e){case"vw":return r;case"vh":return s;case"vi":return a?s:r;case"vb":return a?r:s;case"vmin":return r<s?r:s;case"vmax":return r>s?r:s;case"pvw":return n;case"pvh":return o;case"pvi":return a?o:n;case"pvb":return a?n:o;case"pvmin":return n<o?n:o;case"pvmax":return n>o?n:o}}return e=="em"||e=="rem"?t?this.initialFontSize:this.fontSize():e=="lh"||e=="rlh"?this.rootLineHeight:Zt[e]}evalName(e,t){do{let i=e.values[t];if(i||e.resolver&&(i=e.resolver.call(this,t,!1),i))return i;e=e.parent}while(e);throw new Error(`Name '${t}' is undefined`)}evalCall(e,t,i,n){do{let o=e.funcs[t];if(o||e.resolver&&(o=e.resolver.call(this,t,!0),o))return o;let r=e.builtIns[t];if(r){if(n)return e.zero;let s=Array(i.length);for(let a=0;a<i.length;a++)s[a]=i[a].evaluate(this);return new it(e,r.apply(this,s))}e=e.parent}while(e);throw new Error(`Function '${t}' is undefined`)}evalMediaName(e,t){let i=e==="all"||!!this.pref.enabledMediaTypes[e];return t?!i:i}evalMediaTest(e,t){let i="",n=e.match(/^(min|max)-(.*)$/);n&&(i=n[1],e=n[2]);let o=null,r=null;switch(e){case"width":case"height":case"device-width":case"device-height":case"color":t&&(o=t.evaluate(this));break}switch(e){case"width":r=this.pageWidth();break;case"height":r=this.pageHeight();break;case"device-width":r=window.screen.availWidth;break;case"device-height":r=window.screen.availHeight;break;case"color":r=window.screen.pixelDepth;break}if(r!=null&&o!=null)switch(i){case"min":return r>=Number(o);case"max":return r<=Number(o);default:return r==o}else if(r!=null&&t==null)return r!==0;return!1}evalSupportsTest(e,t,i){return!1}queryVal(e,t){let i=e&&this.scopes[e.scopeKey];return i?i[t]:void 0}storeVal(e,t,i){this.getScopeContext(e)[t]=i}},Xt=class{constructor(e){u(this,"scope",e),u(this,"key"),this.scope=e,this.key=`_${Tc++}`}toString(){let e=new gi;return this.appendTo(e,0),e.toString()}appendTo(e,t){throw new Error("F_ABSTRACT")}evaluateCore(e){throw new Error("F_ABSTRACT")}expand(e,t){return this}dependCore(e,t,i){return e===this}dependOuter(e,t,i){let n=i[this.key];if(n!=null)return n===Rh.PENDING?!1:n;{i[this.key]=Rh.PENDING;let o=this.dependCore(e,t,i);return i[this.key]=o,o}}depend(e,t){return this.dependOuter(e,t,{})}evaluate(e){let t=e.queryVal(this.scope,this.key);return typeof t<"u"||(t=this.evaluateCore(e),this.scope&&e.storeVal(this.scope,this.key,t)),t}isMediaName(){return!1}},Fc=class extends Xt{constructor(e,t){super(e),u(this,"val",t)}getOp(){throw new Error("F_ABSTRACT")}evalPrefix(e){throw new Error("F_ABSTRACT")}evaluateCore(e){let t=this.val.evaluate(e);return this.evalPrefix(t)}dependCore(e,t,i){return e===this||this.val.dependOuter(e,t,i)}appendTo(e,t){10<t&&e.append("("),e.append(this.getOp()),this.val.appendTo(e,10),10<t&&e.append(")")}expand(e,t){let i=this.val.expand(e,t);return i===this.val?this:new this.constructor(this.scope,i)}},Is=class extends Xt{constructor(e,t,i){super(e),u(this,"lhs",t),u(this,"rhs",i)}getPriority(){throw new Error("F_ABSTRACT")}getOp(){throw new Error("F_ABSTRACT")}evalInfix(e,t){throw new Error("F_ABSTRACT")}evaluateCore(e){let t=this.lhs.evaluate(e),i=this.rhs.evaluate(e);return this.evalInfix(t,i)}dependCore(e,t,i){return e===this||this.lhs.dependOuter(e,t,i)||this.rhs.dependOuter(e,t,i)}appendTo(e,t){let i=this.getPriority();i<=t&&e.append("("),this.lhs.appendTo(e,i),e.append(this.getOp()),this.rhs.appendTo(e,i),i<=t&&e.append(")")}expand(e,t){let i=this.lhs.expand(e,t),n=this.rhs.expand(e,t);return i===this.lhs&&n===this.rhs?this:new this.constructor(this.scope,i,n)}},Rc=class extends Is{constructor(e,t,i){super(e,t,i)}getPriority(){return 1}},Gn=class extends Is{constructor(e,t,i){super(e,t,i)}getPriority(){return 2}},Lc=class extends Is{constructor(e,t,i){super(e,t,i)}getPriority(){return 3}},Tl=class extends Is{constructor(e,t,i){super(e,t,i)}getPriority(){return 4}},Ai=class extends Fc{constructor(e,t){super(e,t)}getOp(){return"!"}evalPrefix(e){return!e}},dm=class extends Ai{constructor(e,t){super(e,t)}getOp(){return"not "}},Cn=class extends Fc{constructor(e,t){super(e,t)}getOp(){return"-"}evalPrefix(e){return-e}},Al=class extends Rc{constructor(e,t,i){super(e,t,i)}getOp(){return"&&"}evaluateCore(e){return this.lhs.evaluate(e)&&this.rhs.evaluate(e)}},pm=class extends Al{constructor(e,t,i){super(e,t,i)}getOp(){return" and "}},Il=class extends Rc{constructor(e,t,i){super(e,t,i)}getOp(){return"||"}evaluateCore(e){return this.lhs.evaluate(e)||this.rhs.evaluate(e)}},fm=class extends Il{constructor(e,t,i){super(e,t,i)}getOp(){return", "}},gm=class extends Il{constructor(e,t,i){super(e,t,i)}getOp(){return" or "}},mm=class extends Gn{constructor(e,t,i){super(e,t,i)}getOp(){return"<"}evalInfix(e,t){return e<t}},ym=class extends Gn{constructor(e,t,i){super(e,t,i)}getOp(){return"<="}evalInfix(e,t){return e<=t}},vm=class extends Gn{constructor(e,t,i){super(e,t,i)}getOp(){return">"}evalInfix(e,t){return e>t}},Ea=class extends Gn{constructor(e,t,i){super(e,t,i)}getOp(){return">="}evalInfix(e,t){return e>=t}},Fl=class extends Gn{constructor(e,t,i){super(e,t,i)}getOp(){return"=="}evalInfix(e,t){return e==t}},wm=class extends Gn{constructor(e,t,i){super(e,t,i)}getOp(){return"!="}evalInfix(e,t){return e!=t}},Oc=class extends Lc{constructor(e,t,i){super(e,t,i)}getOp(){return"+"}evalInfix(e,t){return e+t}},Bc=class extends Lc{constructor(e,t,i){super(e,t,i)}getOp(){return" - "}evalInfix(e,t){return e-t}},Rl=class extends Tl{constructor(e,t,i){super(e,t,i)}getOp(){return"*"}evalInfix(e,t){return e*t}},Mc=class extends Tl{constructor(e,t,i){super(e,t,i)}getOp(){return"/"}evalInfix(e,t){return e/t}},_c=class extends Tl{constructor(e,t,i){super(e,t,i)}getOp(){return"%"}evalInfix(e,t){return e%t}},qo=class extends Xt{constructor(e,t,i){var n;super(e),u(this,"num",t),u(this,"unit"),this.unit=(n=i?.toLowerCase())!=null?n:""}appendTo(e,t){e.append(this.num.toString()),e.append(Ti(this.unit))}evaluateCore(e){return this.num*e.queryUnitSize(this.unit,!1)}},Je=class extends Xt{constructor(e,t){super(e),u(this,"qualifiedName",t)}appendTo(e,t){e.append(this.qualifiedName)}evaluateCore(e){return e.evalName(this.scope,this.qualifiedName).evaluate(e)}dependCore(e,t,i){return e===this||t.evalName(this.scope,this.qualifiedName).dependOuter(e,t,i)}},Lh=class extends Xt{constructor(e,t,i){super(e),u(this,"not",t),u(this,"name",i)}appendTo(e,t){this.not&&e.append("not "),e.append(Ti(this.name))}evaluateCore(e){return e.evalMediaName(this.name,this.not)}isMediaName(){return!0}},we=class extends Xt{constructor(e,t,i){super(e),u(this,"fn",t),u(this,"str",i)}appendTo(e,t){e.append(this.str)}evaluateCore(e){return this.fn.call(e)}};function bm(e,t){e.append("(");for(let i=0;i<t.length;i++)i&&e.append(","),t[i].appendTo(e,0);e.append(")")}function xm(e,t,i){let n=t;for(let o=0;o<t.length;o++){let r=t[o].expand(e,i);if(t!==n)n[o]=r;else if(r!==t[o]){n=Array(t.length);for(let s=0;s<o;s++)n[s]=t[s];n[o]=r}}return n}var vo=class Dc extends Xt{constructor(t,i,n){super(t),u(this,"qualifiedName",i),u(this,"params",n)}appendTo(t,i){t.append(this.qualifiedName),bm(t,this.params)}evaluateCore(t){return t.evalCall(this.scope,this.qualifiedName,this.params,!1).expand(t,this.params).evaluate(t)}dependCore(t,i,n){if(t===this)return!0;for(let o=0;o<this.params.length;o++)if(this.params[o].dependOuter(t,i,n))return!0;return i.evalCall(this.scope,this.qualifiedName,this.params,!0).dependOuter(t,i,n)}expand(t,i){let n=xm(t,this.params,i);return n===this.params?this:new Dc(this.scope,this.qualifiedName,n)}},Sm=class zc extends Xt{constructor(t,i,n,o){super(t),u(this,"cond",i),u(this,"ifTrue",n),u(this,"ifFalse",o)}appendTo(t,i){i>0&&t.append("("),this.cond.appendTo(t,0),t.append("?"),this.ifTrue.appendTo(t,0),t.append(":"),this.ifFalse.appendTo(t,0),i>0&&t.append(")")}evaluateCore(t){return this.cond.evaluate(t)?this.ifTrue.evaluate(t):this.ifFalse.evaluate(t)}dependCore(t,i,n){return t===this||this.cond.dependOuter(t,i,n)||this.ifTrue.dependOuter(t,i,n)||this.ifFalse.dependOuter(t,i,n)}expand(t,i){let n=this.cond.expand(t,i),o=this.ifTrue.expand(t,i),r=this.ifFalse.expand(t,i);return n===this.cond&&o===this.ifTrue&&r===this.ifFalse?this:new zc(this.scope,n,o,r)}},it=class extends Xt{constructor(e,t){super(e),u(this,"val",t)}appendTo(e,t){switch(typeof this.val){case"number":case"boolean":e.append(this.val.toString());break;case"string":e.append('"'),e.append(Xo(this.val)),e.append('"');break;default:throw new Error("F_UNEXPECTED_STATE")}}evaluateCore(e){return this.val}},Oh=class Vc extends Xt{constructor(t,i,n){super(t),u(this,"name",i),u(this,"value",n)}appendTo(t,i){t.append("("),t.append(Xo(this.name.name)),t.append(":"),this.value.appendTo(t,0),t.append(")")}evaluateCore(t){return t.evalMediaTest(this.name.name,this.value)}dependCore(t,i,n){return t===this||this.value.dependOuter(t,i,n)}expand(t,i){let n=this.value.expand(t,i);return n===this.value?this:new Vc(this.scope,this.name,n)}},Cm=class extends Xt{constructor(e,t,i,n){super(e),u(this,"name",t),u(this,"value",i),u(this,"isFunc",n)}appendTo(e,t){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)}},Uc=class extends Xt{constructor(e,t){super(e),u(this,"index",t)}appendTo(e,t){e.append("$"),e.append(this.index.toString())}expand(e,t){let i=t[this.index];if(!i)throw new Error(`Parameter missing: ${this.index}`);return i}};function Wt(e,t,i){return t===e._false||t===e.zero||i==e._false||i==e.zero?e._false:t===e._true||t===e.one?i:i===e._true||i===e.one?t:new Al(e,t,i)}function ne(e,t,i){return t===e.zero?i:i===e.zero?t:new Oc(e,t,i)}function ye(e,t,i){return t===e.zero?new Cn(e,i):i===e.zero?t:new Bc(e,t,i)}function Lr(e,t,i){return t===e.zero||i===e.zero?e.zero:t===e.one?i:i===e.one?t:new Rl(e,t,i)}function Pa(e,t,i){return t===e.zero?e.zero:i===e.one?t:new Mc(e,t,i)}var Kt=class{visitValues(e){for(let t=0;t<e.length;t++)e[t].visit(this);return null}visitEmpty(e){return null}visitSlash(e){return null}visitStr(e){return null}visitIdent(e){return null}visitNumeric(e){return null}visitNum(e){return null}visitInt(e){return this.visitNum(e)}visitHexColor(e){return null}visitURL(e){return null}visitURange(e){return null}visitSpaceList(e){return this.visitValues(e.values),null}visitCommaList(e){return this.visitValues(e.values),null}visitFunc(e){return this.visitValues(e.values),null}visitExpr(e){return null}},nn=class extends Kt{constructor(){super(),u(this,"error",!1)}visitValues(e){let t=null;for(let i=0;i<e.length;i++){let n=e[i],o=n.visit(this);if(this.error)return[];if(t)t[i]=o;else if(n!==o){t=new Array(e.length);for(let r=0;r<i;r++)t[r]=e[r];t[i]=o}}return t||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 t=this.visitValues(e.values);return this.error?Be:t===e.values?e:new J(t)}visitCommaList(e){let t=this.visitValues(e.values);return this.error?Be:t===e.values?e:new _e(t)}visitFunc(e){let t=this.visitValues(e.values);return this.error?Be:t===e.values?e:new ai(e.name,t)}visitExpr(e){return e}},rt=class{toString(){let e=new gi;return this.appendTo(e,!0),e.toString()}stringValue(){let e=new gi;return this.appendTo(e,!1),e.toString()}toExpr(e,t){return null}appendTo(e,t){e.append("[error]")}isExpr(){return!1}isNumeric(){return!1}isNum(){return!1}isIdent(){return!1}isSpaceList(){return!1}visit(e){return this}},$c=class Hc extends rt{static get instance(){return this.empty||(this.empty=new Hc),this.empty}constructor(){super()}toExpr(t,i){return new it(t,"")}appendTo(t,i){}visit(t){return t.visitEmpty(this)}};u($c,"empty");var km=$c,Be=km.instance,Wc=class Gc extends rt{static get instance(){return this.slash||(this.slash=new Gc),this.slash}constructor(){super()}toExpr(t,i){return new it(t,"/")}appendTo(t,i){t.append("/")}visit(t){return t.visitSlash(this)}};u(Wc,"slash");var Em=Wc,jn=Em.instance,K=class extends rt{constructor(e){super(),u(this,"str",e)}toExpr(e,t){return new it(e,this.str)}appendTo(e,t){t?(e.append('"'),e.append(Xo(this.str)),e.append('"')):e.append(this.str)}visit(e){return e.visitStr(this)}},Na=Object.create(null),he=class extends rt{constructor(e){if(super(),u(this,"name",e),Na[e])throw new Error("E_INVALID_CALL");Na[e]=this}toExpr(e,t){return new it(e,this.name)}appendTo(e,t){t?e.append(Ti(this.name)):e.append(this.name)}visit(e){return e.visitIdent(this)}isIdent(){return!0}};function B(e){let t=Na[e];return t||(t=new he(e)),t}var O=class extends rt{constructor(e,t){var i;super(),u(this,"num",e),u(this,"unit"),this.unit=(i=t?.toLowerCase())!=null?i:""}toExpr(e,t){return this.num==0?e.zero:t&&this.unit=="%"?this.num==100?t:new Rl(e,t,new it(e,this.num/100)):new qo(e,this.num,this.unit)}appendTo(e,t){e.append(this.num.toString()),e.append(this.unit)}visit(e){return e.visitNumeric(this)}isNumeric(){return!0}},At=class extends rt{constructor(e){super(),u(this,"num",e)}toExpr(e,t){return this.num==0?e.zero:this.num==1?e.one:new it(e,this.num)}appendTo(e,t){e.append(this.num.toString())}visit(e){return e.visitNum(this)}isNum(){return!0}},lt=class extends At{constructor(e){super(e)}visit(e){return e.visitInt(this)}},jc=class extends rt{constructor(e){super(),u(this,"hex",e)}appendTo(e,t){e.append("#"),e.append(this.hex)}visit(e){return e.visitHexColor(this)}},Qe=class extends rt{constructor(e){super(),u(this,"url",e)}appendTo(e,t){e.append('url("'),e.append(Xo(this.url)),e.append('")')}visit(e){return e.visitURL(this)}},Xc=class extends rt{constructor(e){super(),u(this,"urangeText",e)}appendTo(e,t){e.append(this.urangeText)}visit(e){return e.visitURange(this)}};function Ll(e,t,i,n){var o,r;let s=t.length;if(s>0){(o=t[0])==null||o.appendTo(e,n);for(let a=1;a<s;a++)e.append(i),(r=t[a])==null||r.appendTo(e,n)}}var J=class extends rt{constructor(e){super(),u(this,"values",e)}appendTo(e,t){Ll(e,this.values," ",t)}visit(e){return e.visitSpaceList(this)}isSpaceList(){return!0}},_e=class extends rt{constructor(e){super(),u(this,"values",e)}appendTo(e,t){Ll(e,this.values,",",t)}visit(e){return e.visitCommaList(this)}},ai=class extends rt{constructor(e,t){super(),u(this,"name",e),u(this,"values",t)}appendTo(e,t){e.append(Ti(this.name)),e.append("("),Ll(e,this.values,",",t),e.append(")")}visit(e){return e.visitFunc(this)}},j=class extends rt{constructor(e){super(),u(this,"expr",e)}toExpr(){return this.expr}appendTo(e,t){this.expr instanceof it||this.expr instanceof qo?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}},fn=class extends rt{constructor(e){super(),u(this,"text",e)}appendTo(e,t){e.append(this.text||" ")}};function ut(e,t){if(e){if(e.isNumeric()){let i=e;return t.queryUnitSize(i.unit,!1)*i.num}if(e.isNum())return e.num}return 0}function qc(e,t){return new O(ut(e,t),"px")}var y={absolute:B("absolute"),all:B("all"),always:B("always"),anywhere:B("anywhere"),auto:B("auto"),avoid:B("avoid"),balance:B("balance"),balance_all:B("balance-all"),block:B("block"),block_end:B("block-end"),block_start:B("block-start"),both:B("both"),bottom:B("bottom"),border_box:B("border-box"),break_all:B("break-all"),break_word:B("break-word"),clip:B("clip"),crop:B("crop"),cross:B("cross"),column:B("column"),discard:B("discard"),exclusive:B("exclusive"),_false:B("false"),fixed:B("fixed"),flex:B("flex"),flow_root:B("flow-root"),footnote:B("footnote"),footer:B("footer"),grid:B("grid"),header:B("header"),hidden:B("hidden"),horizontal_tb:B("horizontal-tb"),inherit:B("inherit"),initial:B("initial"),inline:B("inline"),inline_block:B("inline-block"),inline_end:B("inline-end"),inline_start:B("inline-start"),inside:B("inside"),keep:B("keep"),landscape:B("landscape"),left:B("left"),line:B("line"),list_item:B("list-item"),ltr:B("ltr"),manual:B("manual"),max_content:B("max-content"),min_content:B("min-content"),none:B("none"),normal:B("normal"),oeb_page_foot:B("oeb-page-foot"),oeb_page_head:B("oeb-page-head"),outside:B("outside"),padding_box:B("padding-box"),page:B("page"),relative:B("relative"),revert:B("revert"),right:B("right"),same:B("same"),scale:B("scale"),snap_block:B("snap-block"),snap_inline:B("snap-inline"),solid:B("solid"),spread:B("spread"),_static:B("static"),rtl:B("rtl"),table:B("table"),table_caption:B("table-caption"),table_cell:B("table-cell"),table_footer_group:B("table-footer-group"),table_header_group:B("table-header-group"),table_row:B("table-row"),top:B("top"),transparent:B("transparent"),unset:B("unset"),vertical_lr:B("vertical-lr"),vertical_rl:B("vertical-rl"),visible:B("visible"),_true:B("true")},Bh=new O(100,"%"),Yo=new O(100,"pvw"),Zo=new O(100,"pvh"),Le=new O(0,"px"),sC=new Xc("U+0-10FFFF"),Mh={"font-size":1,"line-height":2,color:3};function Z(e){return e===y.inherit||e===y.initial||e===y.revert||e===y.unset}function _h(e,t){let i=Mh[e]||Number.MAX_VALUE,n=Mh[t]||Number.MAX_VALUE;return i-n}function Xe(e){return e?.length>2&&e.startsWith("--")}var gn,mn,yn,Yc=class li{constructor(t,i,n){ie(this,gn),ie(this,mn),ie(this,yn),de(this,gn,Math.round(Math.max(0,Math.min(t,li.MAX)))),de(this,mn,Math.round(Math.max(0,Math.min(i,li.MAX)))),de(this,yn,Math.round(Math.max(0,Math.min(n,li.MAX))))}static fromInt(t,i,n){return new li(t,i,n)}offset(t,i,n){return new li(H(this,gn)+t,H(this,mn)+i,H(this,yn)+n)}toKey(){return JSON.stringify([H(this,gn),H(this,mn),H(this,yn)])}toColorFunc(t){return new ai("color",[new J([B("srgb"),new At(H(this,gn)/li.MAX),new At(H(this,mn)/li.MAX),new At(H(this,yn)/li.MAX),...t!==null?[jn,new At(t)]:[]])])}};gn=new WeakMap,mn=new WeakMap,yn=new WeakMap,u(Yc,"MAX",1e4);var ui=Yc;function Pm(e){return Array.isArray(e)?e.every(t=>{if(!Array.isArray(t)||t.length!==2)return!1;let[i,n]=t;if(!i||typeof i!="object"||Array.isArray(i)||!n||typeof n!="object"||Array.isArray(n))return!1;let o=i,r=n;return Number.isFinite(o.r)&&Number.isFinite(o.g)&&Number.isFinite(o.b)&&Number.isFinite(r.c)&&Number.isFinite(r.m)&&Number.isFinite(r.y)&&Number.isFinite(r.k)}):!1}var Vi,Ui,$i,Qt,Zc=class yt{constructor(t,i,n,o){ie(this,Vi),ie(this,Ui),ie(this,$i),ie(this,Qt),de(this,Vi,Math.round(Math.max(0,Math.min(t,yt.MAX)))),de(this,Ui,Math.round(Math.max(0,Math.min(i,yt.MAX)))),de(this,$i,Math.round(Math.max(0,Math.min(n,yt.MAX)))),de(this,Qt,Math.round(Math.max(0,Math.min(o,yt.MAX))))}static fromInt(t,i,n,o){return new yt(t,i,n,o)}static fromNumber(t,i,n,o){return new yt(t*yt.MAX,i*yt.MAX,n*yt.MAX,o*yt.MAX)}toSRGB(){let t=yt.MAX-H(this,Qt);return ui.fromInt(ui.MAX-Math.min(ui.MAX,Math.round(H(this,Vi)*t/yt.MAX)+H(this,Qt)),ui.MAX-Math.min(ui.MAX,Math.round(H(this,Ui)*t/yt.MAX)+H(this,Qt)),ui.MAX-Math.min(ui.MAX,Math.round(H(this,$i)*t/yt.MAX)+H(this,Qt)))}equals(t){return H(this,Vi)===H(t,Vi)&&H(this,Ui)===H(t,Ui)&&H(this,$i)===H(t,$i)&&H(this,Qt)===H(t,Qt)}toJSON(){return{c:H(this,Vi),m:H(this,Ui),y:H(this,$i),k:H(this,Qt)}}};Vi=new WeakMap,Ui=new WeakMap,$i=new WeakMap,Qt=new WeakMap,u(Zc,"MAX",1e4);var Kc=Zc;function hn(e){return e instanceof At?Math.max(0,Math.min(1,e.num)):e instanceof O&&e.unit==="%"?Math.max(0,Math.min(1,e.num/100)):null}function Jc(e){if(e.name!=="device-cmyk"&&e.name!=="cmyk")return null;let t=e.values.length===1&&e.values[0]instanceof J?e.values[0].values:e.values;if(t.length<4||t.length>6)return null;let i=hn(t[0]),n=hn(t[1]),o=hn(t[2]),r=hn(t[3]);if(i===null||n===null||o===null||r===null)return null;let s=null;if(t.length>=5){if(t[4]===jn){if(t.length!==6)return null;s=hn(t[5])}else{if(t.length!==5)return null;s=hn(t[4])}if(s===null)return null}return{cmyk:Kc.fromNumber(i,n,o,r),alpha:s}}function*Nm(e){for(let t=-e;t<=e;t++)for(let i=-e;i<=e;i++)for(let n=-e;n<=e;n++)Math.abs(t)+Math.abs(i)+Math.abs(n)===e&&(yield[t,i,n])}var Ci,is,Qc,Dh,ed=class{constructor(){ie(this,is),ie(this,Ci,new Map)}registerDeviceCmyk(e){let t=Jc(e);return t?le(this,is,Qc).call(this,t.cmyk).toColorFunc(t.alpha):null}registerCmykReserveMap(e){for(let[t,i]of e){let n=ui.fromInt(t.r,t.g,t.b),o=Kc.fromInt(i.c,i.m,i.y,i.k);H(this,Ci).set(n.toKey(),o)}}toJSON(){let e={};return H(this,Ci).forEach((t,i)=>{e[i]=t.toJSON()}),e}};Ci=new WeakMap,is=new WeakSet,Qc=function(e){let t=e.toSRGB(),i=t.toKey(),n=H(this,Ci).get(i);return n?n.equals(e)?t:le(this,is,Dh).call(this,e,t):(H(this,Ci).set(i,e),t)},Dh=function(e,t){for(let i=1;i<=ui.MAX;i++)for(let[n,o,r]of Nm(i)){let s=t.offset(n,o,r),a=s.toKey();if(!H(this,Ci).has(a))return H(this,Ci).set(a,e),s}return Y.warn(`CmykStore: Exceeded trackable color limit for ${JSON.stringify(e.toJSON())}`),t};var Or,lo,ho,td=class extends nn{constructor(e){super(),ie(this,Or),ie(this,lo,new Map),ie(this,ho,!1),de(this,Or,e??new ed)}reset(){de(this,ho,!1)}hadDeviceCmyk(){return H(this,ho)}recordConversion(e,t){H(this,lo).set(e,t)}getConversions(){if(H(this,lo).size===0)return null;let e={};return H(this,lo).forEach((t,i)=>{e[i]=t}),e}visitFunc(e){let t=H(this,Or).registerDeviceCmyk(e);return t?(de(this,ho,!0),t):super.visitFunc(e)}};Or=new WeakMap,lo=new WeakMap,ho=new WeakMap;function id(e){if(e.nodeType==1){let t=e.getAttribute("id");if(t)return t}return null}function Tm(e){return`^${e}`}function zh(e){return e.replace(/[\[\]\(\),=;^]/g,Tm)}function Am(e){return e.substr(1)}function Ta(e){return e&&e.replace(/\^[\[\]\(\),=;^]/g,Am)}function Im(e){let t=[];do{let i=e.match(/^(\^,|[^,])*/),n=Ta(i[0]);if(e=e.substr(i[0].length+1),!e&&!t.length)return n;t.push(n)}while(e);return t}function Vh(e){let t={};for(;e;){let i=e.match(/^;([^;=]+)=(([^;]|\^;)*)/);if(!i)return t;t[i[1]]=Im(i[2]),e=e.substr(i[0].length)}return t}var Uh=class{appendTo(e){e.append("!")}applyTo(e){return!1}},$h=class{constructor(e,t,i){u(this,"index",e),u(this,"id",t),u(this,"sideBias",i)}appendTo(e){e.append("/"),e.append(this.index.toString()),(this.id||this.sideBias)&&(e.append("["),this.id&&e.append(this.id),this.sideBias&&(e.append(";s="),e.append(this.sideBias)),e.append("]"))}applyTo(e){if(e.node.nodeType!=1)throw new Error("E_CFI_NOT_ELEMENT");let t=e.node,i=t.children,n=i.length,o,r=Math.floor(this.index/2)-1;if(r<0||n==0)o=t.firstChild,e.node=o||t;else{if(o=i[Math.min(r,n-1)],this.index&1){let s=o.nextSibling;!s||s.nodeType==1?e.after=!0:o=s}e.node=o}if(this.id&&(e.after||this.id!=id(e.node))){let s=t.ownerDocument.getElementById(this.id);s?e.node=s:Y.warn("E_CFI_ID_MISMATCH:",this.id)}return e.sideBias=this.sideBias,!0}},Hh=class{constructor(e,t,i,n){u(this,"offset",e),u(this,"textBefore",t),u(this,"textAfter",i),u(this,"sideBias",n)}applyTo(e){if(this.offset>0&&!e.after){let t=this.offset,i=e.node;for(;;){let n=i.nodeType;if(n==1)break;let o=i.nextSibling;if(3<=n&&n<=5){let r=i.textContent.length;if(t<=r)break;if(!o){t=r;break}t-=r}if(!o){t=0;break}i=o}e.node=i,e.offset=t}return e.sideBias=this.sideBias,!0}appendTo(e){e.append(":"),e.append(this.offset.toString()),(this.textBefore||this.textAfter||this.sideBias)&&(e.append("["),(this.textBefore||this.textAfter)&&(this.textBefore&&e.append(zh(this.textBefore)),e.append(","),this.textAfter&&e.append(zh(this.textAfter))),this.sideBias&&(e.append(";s="),e.append(this.sideBias)),e.append("]"))}},Wh=class nd{constructor(){u(this,"steps",null)}fromString(t){let i=t.match(/^#?epubcfi\((.*)\)$/);if(!i)throw new Error("E_CFI_NOT_CFI");let n=decodeURIComponent(i[1]),o=0,r=[];for(;;){let s;switch(n.charAt(o)){case"/":{if(o++,i=n.substr(o).match(/^(0|[1-9][0-9]*)(\[(.*?)(;([^\]]|\^\])*)?\])?/),!i)throw new Error("E_CFI_NUMBER_EXPECTED");o+=i[0].length;let a=parseInt(i[1],10),h=i[3];s=Vh(i[4]),r.push(new $h(a,h,Th(s.s)));break}case":":{if(o++,i=n.substr(o).match(/^(0|[1-9][0-9]*)(\[((([^\];,]|\^[\];,])*)(,(([^\];,]|\^[\];,])*))?)(;([^]]|\^\])*)?\])?/),!i)throw new Error("E_CFI_NUMBER_EXPECTED");o+=i[0].length;let a=parseInt(i[1],10),h=i[4];h&&(h=Ta(h));let l=i[7];l&&(l=Ta(l)),s=Vh(i[10]),r.push(new Hh(a,h,l,Th(s.s)));break}case"!":o++,r.push(new Uh);break;case"~":case"@":case"":this.steps=r;return;default:throw new Error("E_CFI_PARSE_ERROR")}}}navigate(t){let i={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(i)){i.ref=new nd,i.ref.steps=this.steps.slice(n+1);break}return i}trim(t,i){return t.replace(/\s+/g," ").match(i?/^[ -\uD7FF\uE000-\uFFFF]{0,8}/:/[ -\uD7FF\uE000-\uFFFF]{0,8}$/)[0].replace(/^\s/,"").replace(/\s$/,"")}prependPathFromNode(t,i,n,o){let r=[],s=t.parentNode,a="",h="";for(;t;){switch(t.nodeType){case 3:case 4:case 5:{let l=t.textContent,c=l.length;n?(i+=c,a||(a=l)):(i>c&&(i=c),n=!0,a=l.substr(0,i),h=l.substr(i)),t=t.previousSibling;continue}case 8:t=t.previousSibling;continue}break}for((i>0||a||h)&&(a=this.trim(a,!1),h=this.trim(h,!0),r.push(new Hh(i,a,h,o)),o=null);s&&!(!s||s.nodeType==9);){let l=n?null:id(t),c=n?1:0;for(;t;)t.nodeType==1&&(c+=2),t=t.previousSibling;r.push(new $h(c,l,o)),o=null,t=s,s=s.parentNode,n=!1}r.reverse(),this.steps?(r.push(new Uh),this.steps=r.concat(this.steps)):this.steps=r}toString(){if(!this.steps)return"";let t=new gi;t.append("epubcfi(");for(let i=0;i<this.steps.length;i++)this.steps[i].appendTo(t);return t.append(")"),t.toString().replace(/%/g,"%25")}},Mt=class{constructor(e,t,i,n){u(this,"x1",e),u(this,"y1",t),u(this,"x2",i),u(this,"y2",n)}},Ei=class{constructor(e,t){u(this,"x",e),u(this,"y",t)}},ta=class{constructor(e,t,i,n){u(this,"left",e),u(this,"top",t),u(this,"right",i),u(this,"bottom",n)}},Gh=class{constructor(e,t,i,n){u(this,"low",e),u(this,"high",t),u(this,"winding",i),u(this,"shapeId",n)}},pi=class{constructor(e,t,i,n){u(this,"y1",e),u(this,"y2",t),u(this,"x1",i),u(this,"x2",n),u(this,"left",null),u(this,"right",null)}};function Fm(e,t){return e.low.y-t.low.y||e.low.x-t.low.x}var Fs=class od{constructor(t){u(this,"points",t)}addSegments(t,i){let n=this.points,o=n.length,r=n[o-1];for(let s=0;s<o;s++){let a=n[s],h;r.y<a.y?h=new Gh(r,a,1,i):h=new Gh(a,r,-1,i),t.push(h),r=a}}withOffset(t,i){let n=[];for(let o of this.points)n.push(new Ei(o.x+t,o.y+i));return new od(n)}};function jh(e,t,i,n){let o=[];for(let r=0;r<20;r++){let s=r*2*Math.PI/20;o.push(new Ei(e+i*Math.sin(s),t+n*Math.cos(s)))}return new Fs(o)}function Ol(e,t,i,n){return new Fs([new Ei(e,t),new Ei(i,t),new Ei(i,n),new Ei(e,n)])}var cr=class{constructor(e,t,i,n){u(this,"x",e),u(this,"winding",t),u(this,"shapeId",i),u(this,"lowOrHigh",n)}};function Xh(e,t){let i=e.low.x+(e.high.x-e.low.x)*(t-e.low.y)/(e.high.y-e.low.y);if(isNaN(i))throw new Error("Bad intersection");return i}function Rm(e,t,i,n){let o,r,s,a;t.high.y<i&&Y.warn("Error: inconsistent segment (1)"),t.low.y<=i?(o=Xh(t,i),r=t.winding):(o=t.low.x,r=0),t.high.y>=n?(s=Xh(t,n),a=t.winding):(s=t.high.x,a=0),o<s?(e.push(new cr(o,r,t.shapeId,-1)),e.push(new cr(s,a,t.shapeId,1))):(e.push(new cr(s,a,t.shapeId,-1)),e.push(new cr(o,r,t.shapeId,1)))}function Lm(e,t,i){let n=t+i,o=Array(n),r=Array(n),s;for(s=0;s<=n;s++)o[s]=0,r[s]=0;let a=[],h=!1,l=e.length;for(let c=0;c<l;c++){let d=e[c];o[d.shapeId]+=d.winding,r[d.shapeId]+=d.lowOrHigh;let p=!1;for(s=0;s<t;s++)if(o[s]&&!r[s]){p=!0;break}if(p){for(s=t;s<=n;s++)if(o[s]||r[s]){p=!1;break}}h!=p&&(a.push(d.x),h=p)}return a}function Om(e,t){return t?Math.ceil(e/t)*t:e}function qh(e,t){return t?Math.floor(e/t)*t:e}function Bm(e){return new Ei(e.y,-e.x)}function ns(e){return new Mt(e.y1,-e.x2,e.y2,-e.x1)}function rd(e){return new Mt(-e.y2,e.x1,-e.y1,e.x2)}function Yh(e){return new Fs(e.points.map(t=>Bm(t)))}function Mm(e,t,i,n,o,r){r&&(e=ns(e),t=t.map(m=>Yh(m)),i=i.map(m=>Yh(m)));let s=t.length,a=i?i.length:0,h=[],l=[],c,d,p;for(c=0;c<s;c++)t[c].addSegments(l,c);for(c=0;c<a;c++)i[c].addSegments(l,c+s);let f=l.length;l.sort(Fm);let g=0;for(;l[g].shapeId>=s;)g++;let v=l[g].low.y;v>e.y1&&h.push(new pi(e.y1,v,e.x2,e.x2));let w=0,x=[];for(;w<f&&(p=l[w]).low.y<v;)p.high.y>v&&x.push(p),w++;for(;w<f||x.length>0;){let m=e.y2,S=Math.min(Om(Math.ceil(v+n),o),e.y2);for(d=0;d<x.length&&m>S;d++)p=x[d],p.low.x==p.high.x?p.high.y<m&&(m=Math.max(qh(p.high.y,o),S)):p.low.x!=p.high.x&&(m=S);for(m>e.y2&&(m=e.y2);w<f&&(p=l[w]).low.y<m;){if(p.high.y<v){w++;continue}if(p.low.y<S)p.low.y==p.high.y&&p.low.y==v||(x.push(p),m=S),w++;else{let P=qh(p.low.y,o);P<m&&(m=P);break}}let b=[];for(d=0;d<x.length;d++)Rm(b,x[d],v,m);b.sort((P,L)=>P.x-L.x||P.lowOrHigh-L.lowOrHigh);let C=Lm(b,s,a);if(C.length==0)h.push(new pi(v,m,e.x2,e.x2));else{let P=0,L=e.x1;for(d=0;d<C.length;d+=2){let A=Math.max(e.x1,C[d]),z=Math.min(e.x2,C[d+1])-A;z>P&&(P=z,L=A)}P==0?h.push(new pi(v,m,e.x2,e.x2)):h.push(new pi(v,m,Math.max(L,e.x1),Math.min(L+P,e.x2)))}if(m==e.y2)break;for(v=m,d=x.length-1;d>=0;d--)x[d].high.y<=m&&x.splice(d,1)}return sd(e,h),h}function sd(e,t){let i=t.length-1,n=new pi(e.y2,e.y2,e.x1,e.x2);for(;i>=0;){let o=n;n=t[i],(n.y2-n.y1<1||n.x1==o.x1&&n.x2==o.x2)&&(o.y1=n.y1,t.splice(i,1),n=o),i--}}function ad(e,t){let i=0,n=e.length;for(;i<n;){let o=Math.floor((i+n)/2);t>=e[o].y2?i=o+1:n=o}return i}function _m(e,t){if(!e.length)return t;let i=t.y1,n,o;for(o=0;o<e.length&&(n=e[o],!(n.y2>t.y1&&n.x1-.1<=t.x1&&n.x2+.1>=t.x2));o++)i=Math.max(i,n.y2);let r=i;for(;o<e.length&&(n=e[o],!(n.y1>=t.y2||n.x1-.1>t.x1||n.x2+.1<t.x2));o++)r=n.y2;return o===e.length?r=t.y2:r=Math.min(r,t.y2),r<=i?null:new Mt(t.x1,i,t.x2,r)}function Dm(e,t){if(!e.length)return t;let i=t.y2,n,o;for(o=e.length-1;o>=0&&(n=e[o],!(o===e.length-1&&n.y2<t.y2))&&!(n.y1<t.y2&&n.x1-.1<=t.x1&&n.x2+.1>=t.x2);o--)i=Math.min(i,n.y1);let r=Math.min(i,n.y2);for(;o>=0&&(n=e[o],!(n.y2<=t.y1||n.x1-.1>t.x1||n.x2+.1<t.x2));o--)r=n.y1;return r=Math.max(r,t.y1),i<=r?null:new Mt(t.x1,r,t.x2,i)}function zm(e,t,i,n){let o=i.y1,r=i.x2-i.x1,s=i.y2-i.y1,a=ad(t,o);for(;;){let h=o+s;if(h>e.y2)return!1;let l=e.x1,c=e.x2;for(let d=a;d<t.length&&t[d].y1<h;d++){let p=t[d];p.x1>l&&(l=p.x1),p.x2<c&&(c=p.x2)}if(l+r<=c||a>=t.length)return n=="left"?(i.x1=l,i.x2=l+r):(i.x1=c-r,i.x2=c),i.y2+=o-i.y1,i.y1=o,!0;o=t[a].y2,a++}}function Vm(e,t,i,n,o){for(n||(n=[new pi(i.y1,i.y2,i.x1,i.x2)]);n.length>0&&n[0].y2<=e.y1;)n.shift();if(n.length==0)return;n[0].y1<e.y1&&(n[0].y1=e.y1);let r,s=t.length==0?e.y1:t[t.length-1].y2;s<e.y2&&t.push(new pi(s,e.y2,e.x1,e.x2));let a=ad(t,n[0].y1);for(let h of n){if(a==t.length)break;for(t[a].y1<h.y1&&(r=t[a],a++,t.splice(a,0,new pi(h.y1,r.y2,r.x1,r.x2)),r.y2=h.y1);a<t.length&&(r=t[a++],r.y2>h.y2&&(t.splice(a,0,new pi(h.y2,r.y2,r.x1,r.x2)),r.y2=h.y2),h.x1!=h.x2&&(o=="left"?r.x1=Math.min(h.x2,e.x2):r.x2=Math.max(h.x1,e.x1)),r.y2!=h.y2););}sd(e,t)}var Um=class extends Kt{constructor(){super(),u(this,"propSet",{})}visitIdent(e){return this.propSet[e.name]=!0,e}visitSpaceList(e){return this.visitValues(e.values),e}};function $m(e){if(e){let t=new Um;try{return e.visit(t),t.propSet}catch(i){Y.warn(i,"toSet:")}}return{}}var Hm=class extends Kt{constructor(e){super(),u(this,"value",e)}visitInt(e){return this.value=e.num,e}};function Zh(e,t){if(e){let i=new Hm(t);try{return e.visit(i),i.value}catch(n){Y.warn(n,"toInt: ")}}return t}var Wm=class extends Kt{constructor(){super(),u(this,"collect",!1),u(this,"coords",[]),u(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 O(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,t,i,n,o){if(this.coords.length>0){let r=[];switch(this.coords.forEach((s,a)=>{if(s.unit=="%"){let h=a%2==0?i:n;a==3&&this.name=="circle"&&(h=Math.sqrt((i*i+n*n)/2)),r.push(s.num*h/100)}else r.push(s.num*o.queryUnitSize(s.unit,!1))}),this.name){case"polygon":if(r.length%2==0){let s=[];for(let a=0;a<r.length;a+=2)s.push(new Ei(e+r[a],t+r[a+1]));return new Fs(s)}break;case"rectangle":if(r.length==4)return Ol(e+r[0],t+r[1],e+r[0]+r[2],t+r[1]+r[3]);break;case"ellipse":if(r.length==4)return jh(e+r[0],t+r[1],r[2],r[3]);break;case"circle":if(r.length==3)return jh(e+r[0],t+r[1],r[2],r[2]);break}}return null}};function ld(e,t,i,n,o,r){if(e){let s=new Wm;try{return e.visit(s),s.getShape(t,i,n,o,r)}catch(a){Y.warn(a,"toShape:")}}return Ol(t,i,t+n,i+o)}var Gm=class extends Kt{constructor(e,t){super(),u(this,"reset",e),u(this,"defaultValue",t),u(this,"counters",Object.create(null)),u(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)+this.defaultValue,e}visitInt(e){return this.name&&(this.counters[this.name]+=e.num-(this.reset?0:this.defaultValue)),e}visitSpaceList(e){return this.visitValues(e.values),e}};function qi(e,t){var i,n;let o=(i=t?.reset)!=null?i:!1,r=(n=t?.defaultValue)!=null?n:o?0:1,s=new Gm(o,r);try{e.visit(s)}catch(a){Y.warn(a,"toCounters:")}return s.counters}var jm=class extends nn{constructor(e,t){super(),u(this,"baseUrl",e),u(this,"transformer",t)}visitURL(e){return new Qe(Fo(this.transformer.transformURL(e.url,this.baseUrl)))}};function bi(e){let t=Object.create(null);return Object.keys(e).forEach(i=>{t[i]=Array.from(e[i])}),t}function Xm(e){return e.replace(/\\([0-9a-fA-F]{1,6})\s?|\\(.)/g,(t,i,n)=>i?String.fromCodePoint(parseInt(i,16)):n)}function kn(e,t){var i;if(t==="content"){let n=e.cloneNode(!0);return n.querySelectorAll("[data-adapt-pseudo]").forEach(o=>o.remove()),n.textContent||""}else if(t==="marker"){let n=e.querySelector('[data-adapt-pseudo="marker"], [data-adapt-pseudo="footnote-marker"]');if(n)return n.textContent||"";let o=(i=e.style)==null?void 0:i.getPropertyValue("--viv-marker-content");if(o){let r=o.match(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g);if(r&&r.length>0)return r.map(s=>Xm(s.substring(1,s.length-1))).join("")}return""}else{let n=e.querySelector(`[data-adapt-pseudo="${t}"]`);return n&&n.textContent||""}}var qm=class{constructor(e,t){u(this,"targetId",e),u(this,"resolved",t),u(this,"pageCounters",null),u(this,"spineIndex",-1),u(this,"pageIndex",-1)}equals(e){return this===e?!0:e?this.targetId===e.targetId&&this.resolved===e.resolved&&this.spineIndex===e.spineIndex&&this.pageIndex===e.pageIndex:!1}isResolved(){return this.resolved}resolve(){this.resolved=!0}unresolve(){this.resolved=!1}},Ym=class{constructor(e,t){u(this,"counterStore",e),u(this,"baseURL",t)}countersOfId(e,t){e=this.counterStore.documentURLTransformer.transformFragment(e,this.baseURL),this.counterStore.countersById[e]=t}getExprContentListener(){return this.counterStore.getExprContentListener()}},Zm=class{constructor(e,t,i,n){u(this,"counterStore",e),u(this,"baseURL",t),u(this,"rootScope",i),u(this,"pageScope",n),u(this,"styler",null),u(this,"namedStringValues",Object.create(null)),u(this,"runningElements",Object.create(null))}setStyler(e){this.styler=e}getFragment(e){let t=e.match(/^[^#]*#(.*)$/);return t?t[1]:null}getTransformedId(e){let t=this.counterStore.documentURLTransformer.transformURL(Ae(e,this.baseURL),this.baseURL);return t.charAt(0)==="#"&&(t=t.substring(1)),t}getPageCounterVal(e,t){let i=()=>{let r=this.counterStore.currentPageCounters[e];return r&&r.length?r[r.length-1]:null},n=new we(this.pageScope,()=>t(i()),`page-counter-${e}`),o=r=>t(r[r.length-1]);return this.counterStore.registerPageCounterExpr(e,o,n),n}getPageCountersVal(e,t){let i=()=>this.counterStore.currentPageCounters[e]||[],n=new we(this.pageScope,()=>t(i()),`page-counters-${e}`);return this.counterStore.registerPageCounterExpr(e,t,n),n}getTargetCounters(e,t,i){let n=this.counterStore.countersById[t];return!n&&i&&e&&(this.styler.styleUntilIdIsReached(e),n=this.counterStore.countersById[t]),n||null}getTargetPageCounters(e){return this.counterStore.currentPage.elementsById[e]?this.counterStore.currentPageCounters:this.counterStore.pageCountersById[e]||null}getTargetPageDocCounters(e){return this.counterStore.currentPage.elementsById[e]?this.counterStore.currentPageDocCounters:this.counterStore.pageDocCountersById[e]||null}adjustCountersForCrossScope(e,t,i,n){if(!this.counterStore.isPageControlledCounter(e)||!i)return t;let o=i[e]||[],r=o.length?o[o.length-1]:0,s=n?.[e]||[],a=s.length?s[0]:0;return t.length?[r+(t[0]-a),...t.slice(1)]:[r]}getTargetPageText(e,t){if(this.counterStore.currentPage.elementsById[e]){let i=this.counterStore.currentPage.elementsById[e];if(i&&i.length>0){let n=i[0];return t==="before"||t==="after"||t==="marker"?kn(n,t):kn(n,"content")}return""}else{if(e in this.counterStore.pageTextById){let i=this.counterStore.pageTextById[e];return i[t]!==void 0?i[t]:i.content||""}return null}}getTargetCounterVal(e,t,i){let n=this.getFragment(e),o=this.getTransformedId(e),r=new we(this.pageScope,()=>{let s=this.getTargetCounters(n,o,!0);if(s)if(s[t]){let a=s[t],h=this.getTargetPageCounters(o),l=this.getTargetPageDocCounters(o),c=this.adjustCountersForCrossScope(t,a,h,l);return h&&this.counterStore.resolveReference(o),i(c[c.length-1]||null)}else{let a=this.getTargetPageCounters(o);if(a)if(this.counterStore.resolveReference(o),a[t]){let h=a[t];return i(h[h.length-1]||null)}else return i(0);else return this.counterStore.saveReferenceOfCurrentPage(o,!1),"??"}else return this.counterStore.saveReferenceOfCurrentPage(o,!1),"??"},`target-counter-${t}-of-${e}`);return this.counterStore.registerTargetCounterExpr(t,i,r,o),r}getTargetCountersVal(e,t,i){let n=this.getFragment(e),o=this.getTransformedId(e);return new we(this.pageScope,()=>{let r=this.getTargetPageCounters(o);if(r){this.counterStore.resolveReference(o);let s=this.getTargetCounters(n,o,!0),a=s?.[t]||[],h=this.getTargetPageDocCounters(o),l=this.adjustCountersForCrossScope(t,a,r,h);if(l.length)return i(l);let c=r[t]||[];return i(c)}else return this.counterStore.saveReferenceOfCurrentPage(o,!1),"??"},`target-counters-${t}-of-${e}`)}getTargetTextVal(e,t){let i=this.getTransformedId(e),n=new we(this.pageScope,()=>{if(t==="first-letter"){let r=this.getTargetPageText(i,"before"),s=this.getTargetPageText(i,"content"),a=this.getTargetPageText(i,"after");if(r===null&&s===null&&a===null)return this.counterStore.saveReferenceOfCurrentPage(i,!1),"??";let h=(r??"")+(s??"")+(a??"");this.counterStore.resolveReference(i);let l=h.match(Jr);return l?l[0]:""}let o=this.getTargetPageText(i,t);return o!==null?(this.counterStore.resolveReference(i),o):(this.counterStore.saveReferenceOfCurrentPage(i,!1),"??")},`target-text-${t}-of-${e}`);return this.counterStore.registerTargetTextExpr(t,n,i),n}getNamedStringVal(e,t){let i=new we(this.pageScope,()=>this.getRunningValue(this.namedStringValues,e,t),`named-string-${t}-${e}`);return i.getContentList=()=>this.getRunningContentList(e,t),i}getRunningElementVal(e,t){return new we(this.pageScope,()=>this.getRunningValue(this.runningElements,e,t),`running-element-${t}-${e}`)}getRunningValue(e,t,i){let n=this.getRunningRawValue(e,t,i);return typeof n.value=="string"?n.value:this.contentListToString(this.resolveDeferredContentList(n.value,n.offset))}getRunningContentList(e,t){let i=this.getRunningRawValue(this.namedStringValues,e,t);return typeof i.value=="string"?null:this.resolveDeferredContentList(i.value,i.offset)}resolveDeferredContentList(e,t){return this.freezePageCounters(e,t)}freezePageCounters(e,t){if(e instanceof j){let i=e.expr;if(i instanceof we){let n=/^page-counters?-(.+)$/.exec(i.str);if(n){if(n[1]==="pages")return e;let o=this.counterStore,r=n[1],s=o.getPageCounterFormat(i)||(h=>h.length?String(h[h.length-1]):""),a=o.getOrCreateNamedStringPageCounterExpr(this.pageScope,t,r,s);return new j(a)}}return e}return e instanceof J?new J(e.values.map(i=>this.freezePageCounters(i,t))):e instanceof _e?new _e(e.values.map(i=>this.freezePageCounters(i,t))):e}contentListToString(e){if(e instanceof K)return e.stringValue();if(e instanceof j){let t=e.expr;if(t instanceof we){let i=t.fn.call(null);return i==null?"":String(i)}return""}return e instanceof J?e.values.map(t=>this.contentListToString(t)).join(""):e instanceof _e?e.values.map(t=>this.contentListToString(t)).join(""):""}getRunningRawValue(e,t,i){let n=e[t];if(!n)return{value:"",offset:-1};let o=Object.keys(n).map(p=>parseInt(p,10)).sort(kc),r=this.counterStore.currentPage;if(!r)return{value:"",offset:-1};let s=r.isBlankPage?r.offset-1:r.offset,a=r.isBlankPage?s:Math.max(s,...Array.from(r.container.querySelectorAll(`[${Ht}]`)).map(p=>parseInt(p.getAttribute(Ht),10))),h=-1,l=-1,c=-1,d=-1;for(let p=0;p<o.length;p++){let f=o[p],g=p>0?o[p-1]:-1,v=p<o.length-1?o[p+1]:-1;if(f>a)break;if(f>=s){if(h<0&&(h=f,d=-1),l<0)if(f===s)l=f;else{g<h&&(l=g);let w=r.container.querySelector(`[${Ht}="${f}"]`);if(!w)l<0&&(l=f);else{let x=r.container.querySelector(`[${Ht}="${s}"]`);if(x||(x=r.container.querySelector(`[${Ht}="0"]`)),x){for(let m=x;m;m=m.firstElementChild)if(m===w){l=f;break}}}}c=f}else(v>a||v<0)&&(h=l=c=d=f)}return{value:n[{first:h,start:l,last:c,"first-except":d}[i]]||"",offset:{first:h,start:l,last:c,"first-except":d}[i]}}setNamedString(e,t,i){let n=this.namedStringValues[e]||(this.namedStringValues[e]=Object.create(null));n[i]=t,typeof t!="string"&&(this.counterStore.hasDeferredNamedStrings=!0)}setRunningElement(e,t){let i=this.runningElements[e]||(this.runningElements[e]=Object.create(null));i[t]=String(t)}},Km=class{constructor(e){u(this,"documentURLTransformer",e),u(this,"countersById",Object.create(null)),u(this,"pageCountersById",Object.create(null)),u(this,"pageDocCountersById",Object.create(null)),u(this,"pageTextById",Object.create(null)),u(this,"currentPageDocCounters",null),u(this,"previousPageDocCounters",null),u(this,"currentPageDocCounterChanges",Object.create(null)),u(this,"currentPageDocCounterChangeTypes",Object.create(null)),u(this,"currentPageCounters",Object.create(null)),u(this,"previousPageCounters",Object.create(null)),u(this,"pageCountersBeforeOverride",Object.create(null)),u(this,"hasDeferredNamedStrings",!1),u(this,"namedStringPageSnapshots",Object.create(null)),u(this,"namedStringPageCounterExprMap",Object.create(null)),u(this,"currentPageCountersStack",[]),u(this,"pageIndicesById",Object.create(null)),u(this,"currentPage",null),u(this,"newReferencesOfCurrentPage",[]),u(this,"referencesToSolve",[]),u(this,"referencesToSolveStack",[]),u(this,"unresolvedReferences",Object.create(null)),u(this,"resolvedReferences",Object.create(null)),u(this,"pageControlledCounterNames",Object.assign(Object.create(null),{page:!0})),u(this,"pagesCounterExprs",[]),u(this,"pageCounterExprs",[]),u(this,"targetCounterExprs",[]),u(this,"targetTextExprs",[]),this.currentPageCounters.page=[0]}createCounterListener(e){return new Ym(this,e)}createCounterResolver(e,t,i){return new Zm(this,e,t,i)}setCurrentPage(e){this.currentPage=e}setCurrentPageDocCounters(e,t,i){this.previousPageDocCounters=this.currentPageDocCounters?bi(this.currentPageDocCounters):null,this.currentPageDocCounters=e?bi(e):null,this.currentPageDocCounterChanges=Object.create(null),this.currentPageDocCounterChangeTypes=i?{...i}:Object.create(null),t&&t.forEach(n=>{this.currentPageDocCounterChanges[n]=!0})}setPageControlledCounterNames(e){let t=Object.assign(Object.create(null),{page:!0});e.forEach(i=>{t[i]=!0}),this.pageControlledCounterNames=t}isPageControlledCounter(e){return!!this.pageControlledCounterNames[e]}definePageCounter(e,t){this.currentPageCounters[e]?this.currentPageCounters[e].push(t):this.currentPageCounters[e]=[t]}forceSetPageCounter(e){let t=this.currentPageCounters.page;!t||!t.length?this.currentPageCounters.page=[e]:t[t.length-1]=e}updatePageCounters(e,t){this.previousPageCounters=bi(this.currentPageCounters);let i=this.currentPageDocCounterChanges||{},n=this.currentPageDocCounterChangeTypes||{},o=Object.create(null);if(this.currentPageDocCounters){let x=this.previousPageDocCounters||{};for(let m in this.currentPageDocCounters){if(!i[m])continue;let S=this.currentPageDocCounters[m],b=S.length?S[S.length-1]:0,C=x[m]||[],P=C.length?C[C.length-1]:0,L=b-P,A=n[m],z=A==="reset"||A==="set";o[m]={delta:L,reset:z,value:b}}}let r=Object.create(null),s,a=!1,h=e["counter-reset"];if(h){let x=h.evaluate(t);x&&(a=x===y.none,a||(s=qi(x,{reset:!0})))}s&&"pages"in s&&delete s.pages;let l,c=e["counter-set"];if(c){let x=c.evaluate(t);x&&(l=qi(x,{defaultValue:0}))}l&&"pages"in l&&delete l.pages;let d=[];if(s)for(let x in s)d.push(x);if(l)for(let x in l)d.push(x);let p,f=e["counter-increment"];if(f){let x=f.evaluate(t);x&&(p=qi(x))}p&&"pages"in p&&delete p.pages,p?!("page"in p)&&!(o.page&&o.page.reset)&&(p.page=1):(p=Object.create(null),o.page&&o.page.reset||(p.page=1));for(let x in p)d.push(x);this.setPageControlledCounterNames(d);let g=bi(this.previousPageCounters);if(a)for(let x in this.pageCountersBeforeOverride)g[x]=Array.from(this.pageCountersBeforeOverride[x]);if(this.currentPageDocCounters)for(let x in this.currentPageDocCounters){if(this.isPageControlledCounter(x)){let m=o[x];if(m){if(m.reset)g[x]=[m.value],r[x]=!0;else if(m.delta!==0){g[x]||(g[x]=[0]);let S=g[x];S[S.length-1]+=m.delta}}else g[x]||(g[x]=Array.from(this.currentPageDocCounters[x]));continue}g[x]=Array.from(this.currentPageDocCounters[x])}this.currentPageCounters=g;let v=Object.create(null),w=x=>{if(!Object.prototype.hasOwnProperty.call(v,x)){let m=g[x];m&&(v[x]=Array.from(m))}};if(s)for(let x in s)w(x),this.definePageCounter(x,s[x]);for(let x in p){if(r[x])continue;this.currentPageCounters[x]||this.definePageCounter(x,0);let m=this.currentPageCounters[x];m[m.length-1]+=p[x]}if(l)for(let x in l)if(w(x),!this.currentPageCounters[x])this.definePageCounter(x,l[x]);else{let m=this.currentPageCounters[x];m[m.length-1]=l[x]}for(let x in v)this.pageCountersBeforeOverride[x]=Array.from(v[x])}pushPageCounters(e){this.currentPageCountersStack.push(this.currentPageCounters),this.currentPageCounters=bi(e)}popPageCounters(){this.currentPageCounters=this.currentPageCountersStack.pop()}resolveReference(e){let t=this.unresolvedReferences[e],i=this.resolvedReferences[e];i||(i=this.resolvedReferences[e]=[]);let n=!1;for(let o=0;o<this.referencesToSolve.length;){let r=this.referencesToSolve[o];if(r.targetId===e){if(r.resolve(),this.referencesToSolve.splice(o,1),t){let s=t.indexOf(r);s>=0&&t.splice(s,1)}i.push(r),n=!0}else o++}n||this.saveReferenceOfCurrentPage(e,!0)}saveReferenceOfCurrentPage(e,t){if(!this.newReferencesOfCurrentPage.some(i=>i.targetId===e)){let i=new qm(e,t);this.newReferencesOfCurrentPage.push(i)}}finishPage(e,t){let i=Object.keys(this.currentPage.elementsById);if(i.length>0){let r=bi(this.currentPageCounters),s=this.currentPageDocCounters?bi(this.currentPageDocCounters):null;i.forEach(a=>{this.pageCountersById[a]=r,s&&(this.pageDocCountersById[a]=s);let h=this.currentPage.elementsById[a];if(h&&h.length>0){let c=h[0];this.pageTextById[a]={content:kn(c,"content"),before:kn(c,"before"),after:kn(c,"after"),marker:kn(c,"marker")}}let l=this.pageIndicesById[a];if(l&&l.pageIndex<t){let c=this.resolvedReferences[a];if(c){let d=this.unresolvedReferences[a];d||(d=this.unresolvedReferences[a]=[]);let p;for(;p=c.shift();)p.unresolve(),d.push(p)}}this.pageIndicesById[a]={spineIndex:e,pageIndex:t}})}let n=this.previousPageCounters,o;for(;o=this.newReferencesOfCurrentPage.shift();){o.pageCounters=n,o.spineIndex=e,o.pageIndex=t;let r;o.isResolved()?(r=this.resolvedReferences[o.targetId],r||(r=this.resolvedReferences[o.targetId]=[])):(r=this.unresolvedReferences[o.targetId],r||(r=this.unresolvedReferences[o.targetId]=[])),r.every(s=>!o.equals(s))&&r.push(o)}this.hasDeferredNamedStrings&&this.currentPage&&this.recordNamedStringPageSnapshot(e),this.currentPage=null}recordNamedStringPageSnapshot(e){let t=this.currentPage,i=t.isBlankPage?t.offset-1:t.offset,n=t.isBlankPage?i:Math.max(i,...Array.from(t.container.querySelectorAll(`[${Ht}]`)).map(o=>parseInt(o.getAttribute(Ht),10)));for(let o of Object.keys(this.namedStringPageSnapshots)){let r=parseInt(o,10);if(r<=i)continue;let s=this.namedStringPageSnapshots[r];r<=n&&i<=s.lastOffset&&delete this.namedStringPageSnapshots[r]}this.namedStringPageSnapshots[i]={lastOffset:n,spineIndex:e,counters:bi(this.currentPageCounters)}}getPageCountersForOffset(e){for(let t of Object.keys(this.namedStringPageSnapshots)){let i=parseInt(t,10);if(i>e)break;let n=this.namedStringPageSnapshots[i];if(e<=n.lastOffset)return n.counters}return null}adjustPageCountersOfLaterSpines(e,t){if(t<=0)return;let i=new Set;for(let n of Object.keys(this.pageIndicesById))if(this.pageIndicesById[n].spineIndex>e){let o=this.pageCountersById[n];o&&o.page&&!i.has(o)&&(i.add(o),o.page=o.page.map(r=>r+t))}for(let n of Object.keys(this.namedStringPageSnapshots)){let o=this.namedStringPageSnapshots[parseInt(n,10)];o.spineIndex>e&&o.counters.page&&!i.has(o.counters)&&(i.add(o.counters),o.counters.page=o.counters.page.map(r=>r+t))}}updateTargetCounterNodesInPages(e){for(let t of e){if(!t||!t.container)continue;let i=t.container.querySelectorAll(`[${eo}]`);for(let n of i){let o=n.getAttribute(eo),r=this.targetCounterExprs.find(s=>s.expr.key===o);if(r&&r.transformedId){let s=this.pageCountersById[r.transformedId];if(s){let a=s[r.name];a&&(n.textContent=r.format(a[a.length-1]))}}}}}getPageCountersForPage(e,t){let i=Object.keys(e.elementsById);for(let n of i){let o=this.pageCountersById[n];if(o)return o}return t||null}updatePageCounterNodesInPages(e,t){var i;for(let n=0;n<e.length;n++){let o=e[n];if(!(o!=null&&o.container))continue;let r=o.container.querySelectorAll(`[${na}]`);for(let h of r){let l=h.getAttribute(na),c=this.namedStringPageCounterExprMap[l];if(!c)continue;let d=this.getPageCountersForOffset(c.offset),p=d?.[c.counterName];p&&(h.textContent=c.format(p))}let s=this.getPageCountersForPage(o,t?.[n]);if(!s)continue;let a=o.container.querySelectorAll(`[${Qn}]`);for(let h of a){let l=h.getAttribute(Qn),c=this.pageCounterExprs.find(g=>g.expr.key===l);if(!c)continue;let d=(i=c.expr)==null?void 0:i.str,p=d?.replace(/^page-counters?-/,""),f=s[p];f&&(h.textContent=c.format(f))}}}getUnresolvedRefsToPage(e){let t=[];Object.keys(e.elementsById).forEach(o=>{let r=this.unresolvedReferences[o];r&&(t=t.concat(r))}),t.sort((o,r)=>o.spineIndex-r.spineIndex||o.pageIndex-r.pageIndex);let i=[],n=null;return t.forEach(o=>{!n||n.spineIndex!==o.spineIndex||n.pageIndex!==o.pageIndex?(n={spineIndex:o.spineIndex,pageIndex:o.pageIndex,pageCounters:o.pageCounters,refs:[o]},i.push(n)):n.refs.push(o)}),i}pushReferencesToSolve(e){this.referencesToSolveStack.push(this.referencesToSolve),this.referencesToSolve=e}popReferencesToSolve(){this.referencesToSolve=this.referencesToSolveStack.pop()}registerPageCounterExpr(e,t,i){e==="pages"?this.pagesCounterExprs.push({expr:i,format:t}):this.pageCounterExprs.push({expr:i,format:t})}getPageCounterFormat(e){let t=this.pageCounterExprs.find(i=>i.expr===e);return t?t.format:null}getOrCreateNamedStringPageCounterExpr(e,t,i,n){for(let r in this.namedStringPageCounterExprMap){let s=this.namedStringPageCounterExprMap[r];if(s.offset===t&&s.counterName===i)return s.expr}let o=new we(e,()=>{let r=((t>=0?this.getPageCountersForOffset(t):null)||this.currentPageCounters)[i]||[];return n(r)},`named-string-page-counter-${i}`);return this.namedStringPageCounterExprMap[o.key]={expr:o,offset:t,counterName:i,format:n},o}registerTargetCounterExpr(e,t,i,n){this.targetCounterExprs.push({name:e,expr:i,format:t,transformedId:n})}registerTargetTextExpr(e,t,i){this.targetTextExprs.push({pseudoElement:e,expr:t,transformedId:i})}getExprContentListener(){return this.exprContentListener.bind(this)}exprContentListener(e,t,i){if(e instanceof we){if(e.str=="viv-leader"){let r=i.createElementNS("http://www.w3.org/1999/xhtml","span");return r.textContent=t,r.setAttribute("data-viv-leader",e.key),r.setAttribute("data-viv-leader-value",t),r}else if(e.str.startsWith("running-element-")){let r=t&&i.querySelectorAll(`[${Ht}="${t}"]`);if(!r||r.length===0)return null;let s=r[r.length-1].cloneNode(!0);return this.fixPageCounterInRunningElement(s),s.style.position="",s.style.visibility="",s}else if(e.str.startsWith("target-counter-")){let r=i.createElementNS("http://www.w3.org/1999/xhtml","span");return r.textContent=t,r.setAttribute(eo,e.key),r}else if(e.str.startsWith("target-text-")){let r=i.createElementNS("http://www.w3.org/1999/xhtml","span");return r.textContent=t,r.setAttribute(oa,e.key),r}else if(e.str.startsWith("named-string-page-counter-")){let r=i.createElementNS("http://www.w3.org/1999/xhtml","span");return r.textContent=t,r.setAttribute(na,e.key),r}}let n=this.pagesCounterExprs.findIndex(r=>r.expr===e)>=0,o=!n&&this.pageCounterExprs.findIndex(r=>r.expr===e)>=0;if(n||o){let r=i.createElementNS("http://www.w3.org/1999/xhtml","span");return r.textContent=t,r.setAttribute(n?ia:Qn,e.key),r}else return null}fixPageCounterInRunningElement(e){let t=e.querySelectorAll(`[${Qn}]`);for(let o of t){let r=o.getAttribute(Qn),s=this.pageCounterExprs.find(c=>c.expr.key===r),a=(s?.expr).str,h=a?.replace(/^page-counters?-/,""),l=this.currentPageCounters[h];l&&(o.textContent=s.format(l))}let i=e.querySelectorAll(`[${eo}]`);for(let o of i)o.setAttribute(Kh,!0);let n=e.querySelectorAll(`[${oa}]`);for(let o of n)o.setAttribute(Jh,!0)}finishLastPage(e){var t;let i=e.root.querySelectorAll(`[${ia}]`),n=e.contentContainer.childElementCount;for(let s of i){let a=s.getAttribute(ia),h=this.pagesCounterExprs.findIndex(l=>l.expr.key===a);h>=0,s.textContent=this.pagesCounterExprs[h].format([n])}let o=e.root.querySelectorAll(`[${Kh}]`);for(let s of o){let a=s.getAttribute(eo),h=this.targetCounterExprs.find(l=>l.expr.key===a);if(h&&h.transformedId){let l=this.pageCountersById[h.transformedId];if(l){let c=l[h.name];c&&(s.textContent=h.format(c[c.length-1]))}}}let r=e.root.querySelectorAll(`[${Jh}]`);for(let s of r){let a=s.getAttribute(oa),h=this.targetTextExprs.find(l=>l.expr.key===a);if(h&&h.transformedId){let l=this.pageTextById[h.transformedId];l&&(s.textContent=(t=l[h.pseudoElement])!=null?t:"")}}}createLayoutConstraint(e){return new Jm(this,e)}},ia="data-vivliostyle-pages-counter",Qn="data-vivliostyle-page-counter",na="data-vivliostyle-named-string-page-counter",eo="data-vivliostyle-target-counter",oa="data-vivliostyle-target-text",Kh="data-vivliostyle-target-counter-in-running",Jh="data-vivliostyle-target-text-in-running",Jm=class{constructor(e,t){u(this,"counterStore",e),u(this,"pageIndex",t)}allowLayout(e){if(!e||e.after)return!0;let t=e.viewNode;if(!t||t.nodeType!==1)return!0;let i=t.getAttribute("data-vivliostyle-id")||t.getAttribute("id")||t.getAttribute("name");if(!i||!this.counterStore.resolvedReferences[i]&&!this.counterStore.unresolvedReferences[i])return!0;let n=this.counterStore.pageIndicesById[i];return n?this.pageIndex>=n.pageIndex:!0}},Qm=new Set(["before","after","first-line","first-letter"]),Qh=new Set(["media","supports","-epubx-when"]),hd=new Set([";","}"]),ud=new Set(["{",";","}"]),ey=new Set([";","{","}"]),ty=":where(:scope)",iy=":where(:not(*))";function ny(e){let{statements:t,changed:i}=Aa(e,0,e.length,null);return i?t.join(`
5
- `):e}function Aa(e,t,i,n){let o=[],r=[],s=!1,a=t,h=()=>{r.length!==0&&(n?o.push(oy(n,r)):o.push(cd(r)),r.length=0)};for(;a<i&&(a=Qi(e,a,i),!(a>=i||e[a]==="}"));){if(e[a]==="@"){let d=vy(e,a,i);if(!d)break;if(n&&!Qh.has(d.name)){r.push(Gi(e.slice(a,d.end))),a=d.end;continue}if(h(),d.hasBlock&&Qh.has(d.name)){let p=Aa(e,d.blockStart,d.blockEnd,n);s||(s=p.changed||n!=null),o.push(`${d.header} {${ry(p.statements)}}`)}else o.push(Gi(e.slice(a,d.end)));a=d.end;continue}if(n&&uy(e,a,i)){let d=py(e,a,i);if(!d)break;r.push(Gi(d.text)),a=d.end;continue}h();let l=fy(e,a,i);if(!l){let d=wy(e,a,i);o.push(Gi(d.text)),a=d.end;continue}if(n&&gy(e,a,l)){let d=yy(e,a,l.end,i);r.push(Gi(d.text)),a=d.end;continue}let c=n?sy(n,l.prelude):dd(l.prelude);if(c){s||(s=n!=null);let d=Aa(e,l.blockStart,l.blockEnd,c);s||(s=d.changed),d.statements.length===0?o.push(`${c} {}`):o.push(...d.statements)}a=l.end}return h(),{statements:o,changed:s}}function oy(e,t){return`${e} { ${cd(t)} }`}function cd(e){return e.map(t=>t.endsWith(";")?t:`${t};`).join(" ")}function ry(e){return e.length===0?"":` ${e.join(" ")} `}function sy(e,t){let i=ay(e);if(!i)return null;let n=fd(t,",").map(o=>o.trim()).filter(Boolean).map(o=>{let r=pd(o,i);return r.found?r.text:`${i} ${o}`}).filter(Boolean);return n.length===0?null:n.join(", ")}function dd(e){return pd(e.trim(),ty).text}function ay(e){let t=fd(e,",").map(i=>i.trim()).filter(Boolean).filter(i=>!ly(i));return t.length===0?null:`:is(${t.join(", ")})`}function ly(e){let t=0;for(;t<e.length;){let i=Rs(e,t);if(i!=null){t=i;continue}let n=on(e,t,e.length);if(n!=null){t=n;continue}if(e[t]===":"){if(e[t+1]===":")return!0;let o=t+1,r=Ko(e,o,e.length),s=e.slice(o,r).toLowerCase();if(Qm.has(s))return!0;t=r;continue}t++}return!1}function pd(e,t){let i=0,n=!1,o="",r=[],s=hy(t);for(;i<e.length;){let a=Rs(e,i);if(a!=null){o+=e.slice(i,a),i=a;continue}let h=on(e,i,e.length);if(h!=null){o+=e.slice(i,h),i=h;continue}let l=e[i];if(l===":"&&e[i+1]!==":"){let c=i+1,d=Ko(e,c,e.length);if(d>c&&e[d]==="("){r.push(e.slice(c,d).toLowerCase()),o+=e.slice(i,d+1),i=d+1;continue}}if(l==="("){r.push(""),o+=l,i++;continue}if(l===")"){r.pop(),o+=l,i++;continue}if(l==="&"){o+=s&&r.includes("has")?iy:t,n=!0,i++;continue}o+=l,i++}return{text:o,found:n}}function hy(e){let t=0;for(;t<e.length;){let i=Rs(e,t);if(i!=null){t=i;continue}let n=on(e,t,e.length);if(n!=null){t=n;continue}if(e[t]===":"&&e[t+1]!==":"){let o=t+1,r=Ko(e,o,e.length);if(r>o&&e.slice(o,r).toLowerCase()==="has"&&e[r]==="(")return!0;t=r;continue}t++}return!1}function fd(e,t){let i=[],n=0,o=0,r=0,s=0;for(;o<e.length;){let a=Rs(e,o);if(a!=null){o=a;continue}let h=on(e,o,e.length);if(h!=null){o=h;continue}let l=e[o];switch(l){case"(":r++;break;case")":r=Math.max(0,r-1);break;case"[":s++;break;case"]":s=Math.max(0,s-1);break;default:r===0&&s===0&&l===t&&(i.push(e.slice(n,o)),n=o+1);break}o++}return i.push(e.slice(n)),i}function uy(e,t,i){let n=t,o=dy(e,n,i);if(o<=n)return!1;let r=Qi(e,o,i);if(r>=i||e[r]!==":")return!1;let s=Jo(e,r+1,i,ey);return s?.char==="{"?!cy(e,t,o,r,s.index):!0}function cy(e,t,i,n,o){if(Qi(e,i,o)!==n)return!1;let r=Qi(e,n+1,o);if(r!==n+1||r>=o)return!1;let s=e[r];return s===":"||s==="\\"||/[A-Za-z_-]/.test(s)}function dy(e,t,i){let n=t;return e[n]==="-"&&(n++,n<i&&e[n]==="-"&&n++),Ko(e,n,i)}function Ko(e,t,i){let n=t;for(;n<i;){let o=e[n];if(o==="\\"){n+=2;continue}if(!/[0-9A-Za-z_-]/.test(o))break;n++}return n}function py(e,t,i){let n=Jo(e,t,i,hd);if(!n){let r=e.slice(t,i).trim();return r?{text:r,end:i}:null}let o=n.char===";"?n.index+1:n.index;return{text:e.slice(t,o).trim(),end:o}}function fy(e,t,i){let n=Jo(e,t,i,ud);if(!n||n.char!=="{")return null;let o=gd(e,n.index,i);return o<0?null:{prelude:Gi(e.slice(t,n.index)),blockStart:n.index+1,blockEnd:o,end:o+1}}function gy(e,t,i){if(!my(e,t,i.blockStart-1))return!0;let n=Qi(e,i.blockStart,i.blockEnd);return n<i.blockEnd&&e[n]===";"}function my(e,t,i){let n=Qi(e,t,i);if(n>=i)return!1;let o=e[n];return o==="&"||o==="."||o==="#"||o===":"||o==="["||o==="|"||o==="*"||o===">"||o==="+"||o==="~"||o==="\\"||/[A-Za-z_-]/.test(o)}function yy(e,t,i,n){let o=Qi(e,i,n),r=o<n&&e[o]===";"?o+1:i;return{text:e.slice(t,r),end:r}}function vy(e,t,i){let n=Jo(e,t,i,ud);if(!n)return null;let o=Ko(e,t+1,i),r=e.slice(t+1,o).toLowerCase(),s=Gi(e.slice(t,n.index));if(n.char!=="{")return{name:r,header:s,hasBlock:!1,blockStart:-1,blockEnd:-1,end:n.index+(n.char===";"?1:0)};let a=gd(e,n.index,i);return a<0?null:{name:r,header:s,hasBlock:!0,blockStart:n.index+1,blockEnd:a,end:a+1}}function wy(e,t,i){let n=Jo(e,t,i,hd);if(!n)return{text:e.slice(t,i),end:i};let o=n.char===";"?n.index+1:n.index;return{text:e.slice(t,o),end:o}}function Jo(e,t,i,n){let o=t,r=0,s=0,a=0;for(;o<i;){let h=on(e,o,i);if(h!=null){o=h;continue}let l=e[o];switch(l){case"(":r++;break;case")":r=Math.max(0,r-1);break;case"[":s++;break;case"]":s=Math.max(0,s-1);break;case"{":if(r===0&&s===0&&a===0&&n.has(l))return{index:o,char:l};a++;break;case"}":if(r===0&&s===0&&a===0&&n.has(l))return{index:o,char:l};a=Math.max(0,a-1);break;default:if(r===0&&s===0&&a===0&&n.has(l))return{index:o,char:l};break}o++}return null}function gd(e,t,i){let n=t+1,o=1;for(;n<i;){let r=on(e,n,i);if(r!=null){n=r;continue}let s=e[n];if(s==="{")o++;else if(s==="}"&&(o--,o===0))return n;n++}return-1}function Qi(e,t,i){let n=t;for(;n<i;){let o=e[n];if(yd(o)){n++;continue}if(o==="/"&&e[n+1]==="*"){n=md(e,n,i);continue}break}return n}function md(e,t,i){let n=e.indexOf("*/",t+2);return n<0||n+2>i?i:n+2}function on(e,t,i){let n=e[t];return n==='"'||n==="'"?by(e,t):n==="/"&&e[t+1]==="*"?md(e,t,i):null}function Rs(e,t){return e[t]!=="\\"?null:t+1>=e.length?e.length:t+2}function by(e,t){let i=e[t],n=t+1;for(;n<e.length;){let o=e[n];if(o==="\\"){n+=2;continue}if(o===i)return n+1;n++}return e.length}function yd(e){return e===" "||e===`
6
- `||e==="\r"||e===" "||e==="\f"}function Gi(e){let t="",i=0,n=!1;for(;i<e.length;){let o=on(e,i,e.length);if(o!=null&&e[i]!=="/"){n&&t.length>0&&(t+=" ",n=!1),t+=e.slice(i,o),i=o;continue}if(o!=null){n=t.length>0,i=o;continue}let r=e[i];if(yd(r)){n=t.length>0,i++;continue}n&&t.length>0&&(t+=" ",n=!1),t+=r,i++}return t}function xy(e){if(e=e.substr(1),e.match(/^[^0-9a-fA-F\n\r]$/))return e;let t=parseInt(e,16);return isNaN(t)?"":t===0||t>=55296&&t<=57343||t>1114111?"\uFFFD":String.fromCodePoint(t)}function xi(e){return e.replace(/\\([0-9a-fA-F]{1,6}(\r\n|[ \n\r\t\f])?|[^0-9a-fA-F\n\r])/g,xy)}var Sy=class{constructor(){u(this,"type"),u(this,"precededBySpace",!1),u(this,"num",0),u(this,"text",""),u(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 et(e,t){let i=Array(128),n;for(n=0;n<128;n++)i[n]=e;for(i[NaN]=e==35?35:72,n=0;n<t.length;n+=2)i[t[n]]=t[n+1];return i}var ei=[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];ei[NaN]=80;var ti=[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];ti[NaN]=43;var Cy=[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];ti[NaN]=43;var vd=[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];vd[NaN]=35;var wd=[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];wd[NaN]=45;var Ia=[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];Ia[NaN]=37;var Fa=[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];Fa[NaN]=38;var Mi=et(35,[61,36]),ky=et(35,[58,77]),Ey=et(35,[61,36,124,50]),Py=et(35,[38,51]),Ny=et(35,[42,54]),Ty=et(39,[42,55]),Ay=et(54,[42,55,47,56]),Iy=et(62,[62,82]),Fy=et(35,[61,36,33,70]),Ry=et(62,[45,71]),Ly=et(63,[45,81]),ra=et(76,[10,72,13,72]),Oy=et(39,[39,46,10,72,13,72,92,48]),By=et(39,[34,46,10,72,13,72,92,49]),My=et(39,[39,47,10,74,13,74,92,48]),_y=et(39,[34,47,10,74,13,74,92,49]),eu=et(64,[9,39,32,39,34,66,39,65,41,72,10,39,13,39]),Dy=et(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]),zy=et(39,[39,68,10,74,13,74,92,75,NaN,67]),Vy=et(39,[34,68,10,74,13,74,92,75,NaN,67]),Uy=et(72,[9,39,10,39,13,39,32,39,41,69]),$y=15,xt=class{constructor(e,t){u(this,"input",e),u(this,"handler",t),u(this,"indexMask"),u(this,"buffer"),u(this,"tail",0),u(this,"curr",0),u(this,"position",0),this.indexMask=$y,this.buffer=Array(this.indexMask+1);for(let i=0;i<=this.indexMask;i++)this.buffer[i]=new Sy}token(){return this.tail==this.curr&&this.fillBuffer(),this.buffer[this.curr]}nthToken(e){return(this.tail-this.curr&this.indexMask)<=e&&this.fillBuffer(),this.buffer[this.curr+e&this.indexMask]}consume(){this.curr=this.curr+1&this.indexMask}fillBuffer(){let e=this.tail,t=this.curr,i=this.indexMask;if(e>=t?t+=i:t--,t==e)throw new Error("F_CSSTOK_INTERNAL");let n=ei,o=this.input,r=this.position,s=this.buffer,a=0,h=0,l="",c=0,d=!1,p=s[e],f=-9;for(;;){let g=o.charCodeAt(r);switch(n[g]||n[65]){case 72:isNaN(g)?(l=o.substring(h,r),a=0):n===ei&&a===0?(a=54,h=r,l=o.substring(r,r+1),r++):(l=o.substring(h,r),a=54),n=ei;break;case 1:r++,d=!0;continue;case 2:h=r++,n=Ia;continue;case 3:a=1,h=r++,n=ti;continue;case 4:h=r++,a=31,n=Mi;continue;case 33:a=2,h=++r,n=Oy;continue;case 34:a=2,h=++r,n=By;continue;case 6:h=++r,a=7,n=ti;continue;case 7:h=r++,a=32,n=Mi;continue;case 8:h=r++,a=21;break;case 9:h=r++,a=32,n=Py;continue;case 10:h=r++,a=10;break;case 11:h=r++,a=11;break;case 12:h=r++,a=36,n=Mi;continue;case 13:h=r++,a=23;break;case 14:h=r++,a=16;break;case 15:a=24,h=r++,n=vd;continue;case 16:h=r++,n=Cy;continue;case 78:h=r++,a=9,n=ti;continue;case 17:h=r++,a=19,n=Ny;continue;case 18:h=r++,a=18,n=ky;continue;case 77:r++,a=50;break;case 19:h=r++,a=17;break;case 20:h=r++,a=38,n=Fy;continue;case 21:h=r++,a=39,n=Mi;continue;case 22:h=r++,a=37,n=Mi;continue;case 23:h=r++,a=22;break;case 24:h=++r,a=20,n=ti;continue;case 25:h=r++,a=14;break;case 26:h=r++,a=15;break;case 27:h=r++,a=12;break;case 28:h=r++,a=13;break;case 29:h=r++,f=h,a=1,n=ra;continue;case 30:h=r++,a=33,n=Mi;continue;case 31:h=r++,a=34,n=Ey;continue;case 32:h=r++,a=35,n=Mi;continue;case 35:break;case 36:r++,a=a+41-31;break;case 37:a=5,c=parseInt(o.substring(h,r),10);break;case 38:a=4,c=parseFloat(o.substring(h,r));break;case 39:r++;continue;case 40:a=3,c=parseFloat(o.substring(h,r)),h=r++,n=ti;continue;case 41:a=3,c=parseFloat(o.substring(h,r)),l="%",h=r++;break;case 42:r++,n=Fa;continue;case 43:if(l=xi(o.substring(h,r)),a===27&&g===63||a===1&&l.toLowerCase()==="u"&&/^(\bu\+[?0-9a-f]+(-[?0-9a-f]+)?|,|\s+|\/\*([^*]|\*[^/])*\*\/)+[;}]/i.test(o.substring(r-1))){a=27,r++;continue}break;case 44:f=r++,n=ra;continue;case 45:l=xi(o.substring(h,r));break;case 46:l=o.substring(h,r),r++;break;case 47:l=xi(o.substring(h,r)),r++;break;case 48:f=r,r+=2,n=My;continue;case 49:f=r,r+=2,n=_y;continue;case 50:r++,a=25;break;case 51:r++,a=26;break;case 52:if(l=o.substring(h,r),a==1){if(r++,l.toLowerCase()=="url"){n=eu;continue}a=6}break;case 53:if(l=xi(o.substring(h,r)),a==1){if(r++,l.toLowerCase()=="url"){n=eu;continue}a=6}break;case 54:n=Ty,r++;continue;case 55:n=Ay,r++;continue;case 56:n=ei,r++;continue;case 57:n=Iy,r++,o[r]!==">"&&(a=1,n=ti);continue;case 81:a=51,l=o.substring(h,++r),n=ei;break;case 82:a=52,l=o.substring(h,++r),n=ei;break;case 58:a=5,n=Ia,r++;continue;case 59:a=4,n=Fa,r++;continue;case 60:a=1,n=ti,r++;continue;case 61:a=1,n=ra,f=r++;continue;case 62:r--;break;case 63:r-=2;break;case 64:h=r++,n=Dy;continue;case 65:h=++r,n=zy;continue;case 66:h=++r,n=Vy;continue;case 67:a=8,l=xi(o.substring(h,r)),r++;break;case 69:r++;break;case 70:n=Ry,r++;continue;case 71:n=Ly,r++;continue;case 79:if(r-f<8&&o.substring(f+1,r+1).match(/^[0-9a-fA-F]{0,6}(\r\n|[\n\r])|[ \t]$/)){r++;continue}case 68:a=8,l=xi(o.substring(h,r)),r++,n=Uy;continue;case 74:if(r++,r-f<9&&o.substring(f+1,r).match(/^[0-9a-fA-F]{0,6}(\r\n|[\n\r])$/))continue;a=54,l="E_CSS_UNEXPECTED_NEWLINE",n=ei;break;case 73:if(r-f<9&&o.substring(f+1,r+1).match(/^[0-9a-fA-F]{0,6}[ \t]$/)){r++,n=ti;continue}l=xi(o.substring(h,r));break;case 75:f=r++;continue;case 76:r++,n=wd;continue;default:if(n!==ei){a=54,l="E_CSS_UNEXPECTED_STATE";break}h=r,a=0}if(p.type=a,p.precededBySpace=d,p.num=c,p.text=l,p.position=h,e++,e>=t)break;n=ei,d=!1,a=0,h=r,l="",c=0,p=s[e&i]}this.position=r,this.tail=e&i}},Ye=null,Ra=null;function La(){return Ye}function M(e){if(!Ye)throw new Error("E_TASK_NO_CONTEXT");Ye.name||(Ye.name=e);let t=Ye,i=new Ls(t,t.top,e);return t.top=i,i.state=1,i}function Hy(e){return new jy(e||new Gy)}function T(e){return new Oa(e)}function _n(e,t,i){let n=M(e);n.handler=i;try{t(n)}catch(o){n.task.raise(o,n)}return n.result()}function Wy(e,t){return(Ye?Ye.getScheduler():Ra||Hy()).run(e,t)}var Gy=class{currentTime(){return new Date().valueOf()}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}},jy=class{constructor(e){u(this,"timer",e),u(this,"timeout",1),u(this,"slice",25),u(this,"sliceOverTime",0),u(this,"queue"),u(this,"wakeupTime",null),u(this,"timeoutToken",null),u(this,"inTimeSlice",!1),u(this,"order",0),this.queue=new Qg,Ra||(Ra=this)}setSlice(e){this.slice=e}setTimeout(e){this.timeout=e}isTimeSliceOver(){return this.timer.currentTime()>=this.sliceOverTime}arm(){if(this.inTimeSlice)return;let e=this.queue.peek().scheduledTime,t=this.timer.currentTime();if(this.timeoutToken!=null){if(t+this.timeout>this.wakeupTime)return;this.timer.clearTimeout(this.timeoutToken)}let i=e-t;i<=this.timeout&&(i=this.timeout),this.wakeupTime=t+i,this.timeoutToken=this.timer.setTimeout(()=>{this.timeoutToken=null,this.doTimeSlice()},i)}schedule(e,t){let i=e,n=this.timer.currentTime();i.order=this.order++,i.scheduledTime=n+(t||0),this.queue.add(i),this.arm()}doTimeSlice(){this.timeoutToken!=null&&(this.timer.clearTimeout(this.timeoutToken),this.timeoutToken=null),this.inTimeSlice=!0;try{let e=this.timer.currentTime();for(this.sliceOverTime=e+this.slice;this.queue.length();){let t=this.queue.peek();if(t.scheduledTime>e||(this.queue.remove(),t.canceled||t.resumeInternal(),e=this.timer.currentTime(),e>=this.sliceOverTime))break}}catch(e){Y.error(e)}this.inTimeSlice=!1,this.queue.length()&&this.arm()}run(e,t){let i=new Xy(this,t||"");i.top=new Ls(i,null,"bootstrap"),i.top.state=1,i.top.then(()=>{let o=()=>{i.running=!1;for(let r of i.callbacks)try{r()}catch(s){Y.error(s)}};try{e().then(r=>{i.result=r,o()})}catch(r){i.raise(r),o()}});let n=Ye;return Ye=i,this.schedule(i.top.suspend("bootstrap")),Ye=n,i}},bd=class{constructor(e){u(this,"task",e),u(this,"scheduledTime",0),u(this,"order",0),u(this,"result",null),u(this,"canceled",!1)}compare(e){let t=e;return t.scheduledTime-this.scheduledTime||t.order-this.order}getTask(){return this.task}schedule(e,t){this.result=e,this.task.scheduler.schedule(this,t)}resumeInternal(){let e=this.task;if(this.task=null,e&&e.continuation==this){e.continuation=null;let t=Ye;return Ye=e,e.top.finish(this.result),Ye=t,!0}return!1}cancel(){this.canceled=!0}},Xy=class{constructor(e,t){u(this,"scheduler",e),u(this,"name",t),u(this,"callbacks",[]),u(this,"exception",null),u(this,"running",!0),u(this,"result",null),u(this,"waitTarget",null),u(this,"top",null),u(this,"continuation",null)}getName(){return this.name}interrupt(e){if(this.raise(e||new Error("E_TASK_INTERRUPT")),this!==Ye&&this.continuation){this.continuation.cancel();let t=new bd(this);this.waitTarget="interrupt",this.continuation=t,this.scheduler.schedule(t)}}getScheduler(){return this.scheduler}isRunning(){return this.running}whenDone(e){this.callbacks.push(e)}join(){let e=M("Task.join");if(!this.running)e.finish(this.result);else{let t=e.suspend(this);this.whenDone(()=>{t.schedule(this.result)})}return e.result()}unwind(){for(;this.top&&!this.top.handler;)this.top=this.top.parent;if(this.top&&this.top.handler&&this.exception){let e=this.exception;this.exception=null,this.top.handler(this.top,e)}else this.exception&&Y.error(this.exception,"Unhandled exception in task",this.name)}raise(e,t){if(this.fillStack(e),t){let i=this.top;for(;i&&i!=t;)i=i.parent;i==t&&(this.top=i)}this.exception=e,this.unwind()}fillStack(e){let t=e.frameTrace;if(!t){t=e.stack?`${e.stack}
3
+ `]).concat(i))),n}var Y=new Gg,Ts=(e=>(e.SIMPLE_PROPERTY="SIMPLE_PROPERTY",e.PREPROCESS_SINGLE_DOCUMENT="PREPROCESS_SINGLE_DOCUMENT",e.PREPROCESS_TEXT_CONTENT="PREPROCESS_TEXT_CONTENT",e.PREPROCESS_ELEMENT_STYLE="PREPROCESS_ELEMENT_STYLE",e.POLYFILLED_INHERITED_PROPS="POLYFILLED_INHERITED_PROPS",e.CONFIGURATION="CONFIGURATION",e.RESOLVE_TEXT_NODE_BREAKER="RESOLVE_TEXT_NODE_BREAKER",e.RESOLVE_FORMATTING_CONTEXT="RESOLVE_FORMATTING_CONTEXT",e.RESOLVE_LAYOUT_PROCESSOR="RESOLVE_LAYOUT_PROCESSOR",e.POST_LAYOUT_BLOCK="POST_LAYOUT_BLOCK",e.PAGINATION_PROGRESS="PAGINATION_PROGRESS",e))(Ts||{}),Ko={};function Ft(e,t,i){if(!Ts[e])Y.warn(new Error(`Skipping unknown plugin hook '${e}'.`));else{let n=Ko[e];n||(n=Ko[e]=[]),i?n.unshift(t):n.push(t)}}function Cl(e,t){if(!Ts[e])Y.warn(new Error(`Ignoring unknown plugin hook '${e}'.`));else{let i=Ko[e];if(i){let n=i.indexOf(t);n>=0&&i.splice(n,1)}}}function _t(e){return Ko[e]||[]}var jg={registerHook:Ft,removeHook:Cl},wc=class{constructor(e){u(this,"performanceInstance",e),u(this,"timestamps",{}),u(this,"registerTiming"),u(this,"registerStartTiming"),u(this,"registerEndTiming"),this.registerTiming=ln,this.registerStartTiming=this.registerStartTiming=ln,this.registerEndTiming=this.registerEndTiming=ln}forceRegisterStartTiming(e,t){Qs.call(this,e,"start",t)}forceRegisterEndTiming(e,t){Qs.call(this,e,"end",t)}printTimings(){let e=this.timestamps,t="";Object.keys(e).forEach(i=>{let n=e[i],r=n.length;for(let o=0;o<r;o++){let s=n[o];t+=i,r>1&&(t+=`(${o})`),t+=` => start: ${s.start}, end: ${s.end}, duration: ${s.end-s.start}
4
+ `}}),Y.info(t)}disable(){this.registerTiming=ln,this.registerStartTiming=this.registerStartTiming=ln,this.registerEndTiming=this.registerEndTiming=ln}enable(){this.registerTiming=Qs,this.registerStartTiming=this.registerStartTiming=Eh,this.registerEndTiming=this.registerEndTiming=Xg}isEnabled(){return this.registerStartTiming===Eh}};function ln(){}function Qs(e,t,i){i||(i=this.performanceInstance.now());let n=this.timestamps[e];n||(n=this.timestamps[e]=[]);let r,o=n.length;for(let s=o-1;s>=0&&(r=n[s],!(r&&!r[t]));s--)r=null;r||(r={},n.push(r)),r[t]=i}function Eh(e,t){this.registerTiming(e,"start",t)}function Xg(e,t){this.registerTiming(e,"end",t)}var qg={now:Date.now},Yg=window&&window.performance,Nt=new wc(Yg||qg);Nt.forceRegisterStartTiming("load_vivliostyle");var Zg={profiler:{registerStartTiming:Nt.registerStartTiming,registerEndTiming:Nt.registerEndTiming,printTimings:Nt.printTimings,disable:Nt.disable,enable:Nt.enable}},Gr=navigator.userAgent.includes("Chrome")?"chromium":navigator.userAgent.includes("Firefox")?"firefox":navigator.userAgent.includes("AppleWebKit")?"webkit":"unknown",Jo=/^[\s\p{Zs}\p{P}\p{Mn}]*[\p{L}\p{N}]\p{Mn}*(?:[\s\p{Zs}]*\p{P}\p{Mn}*)*/u,Ht="data-adapt-eloff",Kg={};function kl(e){return JSON.parse(e)}function pt(e){let t=e.match(/^([^#]*)/);return t?t[1]:e}function bc(e){let t=e.match(/^([^#?]*)/);return t?t[1]:e}var El="?viv-toc-box";function As(e){return e.endsWith(El)}function dn(e){return As(e)?e.slice(0,-El.length):e}function xa(e){return As(e)?e:pt(e)+El}var Ji=window.location.href;function Ph(e){Ji=e}var Ni=window.location.href;function Nh(e){Ni=e}function Jg(e){let t=bc(e).match(/^(https?:\/\/raw\.githack\.com\/web-platform-tests\/wpt\/[^/]+)(?:\/|$)/);return t?t[1]:null}function Ir(e){return e.replace(/^(https?:)\/\/raw\.githack\.com\/web-platform-tests\/wpt\/[^/]+\//,"$1//wpt.live/")}function Ae(e,t){if(/^data:/i.test(t))return e||t;if(!t||e.match(/^\w{2,}:/))return e.toLowerCase().match("^javascript:")?"#":(e.match(/^\w{2,}:\/\/[^\/]+$/)&&(e=`${e}/`),e);t.match(/^\w{2,}:\/\/[^\/]+$/)&&(t=`${t}/`);let i;if(e.match(/^\/\//))return i=t.match(/^(\w{2,}:)\/\//),i?i[1]+e:e;if(e.match(/^\//)){let s=Jg(t);return s?s+e:(i=t.match(/^(\w{2,}:\/\/[^\/]+)\//),i?i[1]+e:e)}if(e.match(/^\.(\/|$)/)&&(e=e.substr(2)),t=bc(t),e.match(/^#/))return t+e;let n=t.lastIndexOf("/");if(n<0)return e;let r=t.substr(0,n+1)+e,o="";for(i=r.match(/^([^?#]*)([?#].*)$/),i&&(r=i[1],o=i[2]);n=r.indexOf("/../"),!(n<=0);){let s=r.lastIndexOf("/",n-1);if(s<=0)break;r=r.substr(0,s)+r.substr(n+3)}return r.replace(/\/(\.\/)+/g,"/")+o}function Qo(e,t){return e.match(/^#/)&&t?pt(t)+e:Ae(e,t)}function xc(e){return/^about:blank($|[?#])/i.test(e)?"data:text/html,":e}function Fn(e){let t;return(e=xc(e))!==e||((t=/^(https?:)\/\/github\.com\/web-platform-tests\/wpt\/(blob\/|tree\/|raw\/)?(.*)$/.exec(e))?e=`${t[1]}//raw.githack.com/web-platform-tests/wpt/${t[2]?"":"master/"}${t[3]}`:(t=/^(https?:)\/\/github\.com\/([^/]+\/[^/]+)\/(blob\/|tree\/|raw\/)?(.*)$/.exec(e))?e=`${t[1]}//raw.githubusercontent.com/${t[2]}/${t[3]?"":"master/"}${t[4]}`:(t=/^(https?:)\/\/wpt\.live\/(.*)$/.exec(e))?/\.sub\.[^/]+(?:[?#].*)?$/.test(t[2])||(e=`${t[1]}//raw.githack.com/web-platform-tests/wpt/master/${t[2]}`):(t=/^(https?:)\/\/www\.aozora\.gr\.jp\/(cards\/[^/]+\/files\/[^/.]+\.html)$/.exec(e))?e=`${t[1]}//raw.githubusercontent.com/aozorabunko/aozorabunko/master/${t[2]}`:(t=/^(https?:)\/\/gist\.github\.com\/([^/]+\/\w+)(\/|$)(raw(\/|$))?(.*)$/.exec(e))?e=`${t[1]}//gist.githubusercontent.com/${t[2]}/raw/${t[6]}`:(t=/^(https?:)\/\/gist\.github\.com\/([^/]+\/\w+)(?:#|%23)file-(.*)-(\w+)$/.exec(e))?e=`${t[1]}//gist.githubusercontent.com/${t[2]}/raw/${t[3]}.${t[4]}`:(t=/^(https?:)\/\/(?:[^/.]+\.)?jsbin\.com\/(?!(?:blog|help)\b)(\w+)((\/\d+)?).*$/.exec(e))&&(e=`${t[1]}//output.jsbin.com/${t[2]}${t[3]}/`)),e}function Th(e){return e==null?e:e.toString()}var Qg=class{constructor(){u(this,"queue",[null])}length(){return this.queue.length-1}add(e){let t=this.queue.length;for(;t>1;){let i=Math.floor(t/2),n=this.queue[i];if(n.compare(e)>0){this.queue[t]=e;return}this.queue[t]=n,t=i}this.queue[1]=e}peek(){return this.queue[1]}remove(){let e=this.queue[1],t=this.queue.pop(),i=this.queue.length;if(i>1){let n=1;for(;;){let r=n*2;if(r>=i)break;if(this.queue[r].compare(t)>0)r+1<i&&this.queue[r+1].compare(this.queue[r])>0&&r++;else if(r+1<i&&this.queue[r+1].compare(t)>0)r++;else break;this.queue[n]=this.queue[r],n=r}this.queue[n]=t}return e}},Sc=["","-webkit-","-moz-"],pn={};function Ro(e,t){return CSS.supports(e+t,"unset")}function em(e){let t=pn[e];if(t||t===null)return t;switch(e){case"behavior":case"template":case"ua-list-item-count":case"x-first-pseudo":return pn[e]=null,null;case"text-combine-upright":if(Ro("-webkit-","text-combine")&&!Ro("","text-combine-upright"))return pn[e]=["-webkit-text-combine"],["-webkit-text-combine"];break}for(let i of Sc)if(Ro(i,e))return t=[i+e],pn[e]=t,t;return Y.warn("Property not supported by the browser: ",e),pn[e]=null,null}function I(e,t,i){let n=e?.style;if(!n)return;if(t.startsWith("--")){n.setProperty(t,i||" ");return}let r=em(t);if(r)for(let o of r){switch(o){case"-webkit-text-combine":i==="all"&&(i="horizontal");break;case"text-combine-upright":i==="all"&&n.setProperty("text-indent","0");break}n.setProperty(o,i)}}function ki(e,t,i){try{let n=pn[t];return e.style.getPropertyValue(n?n[0]:t)}catch{}return i||""}function Sa(e){let t=e.getAttributeNS("http://www.w3.org/XML/1998/namespace","lang");return!t&&e.namespaceURI=="http://www.w3.org/1999/xhtml"&&(t=e.getAttribute("lang")),t}var gi=class{constructor(){u(this,"list",[])}append(e){return this.list.push(e),this}clear(){this.list=[]}toString(){let e=this.list.join("");return this.list=[e],e}};function Pl(e){return`\\${e.charCodeAt(0).toString(16)} `}function Ti(e){return e.replace(/[^-_a-zA-Z0-9\u0080-\uFFFF]/g,Pl)}function jr(e){return e.replace(/[\u0000-\u001F"\\]/g,Pl)}function Ah(e){return e.replace(/[\s+&?=#\u007F-\uFFFF]+/g,encodeURIComponent)}function Ih(e){return!!e.match(/^[a-zA-Z\u009E\u009F\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u024F\u037B-\u037D\u0386\u0388-\u0482\u048A-\u0527]$/)}function tm(e,t){return t=typeof t=="string"?t:"\\u",t+(65536|e.charCodeAt(0)).toString(16).substr(1)}function Cc(e,t){function i(n){return tm(n,t)}return e.replace(/[^-a-zA-Z0-9_]/g,i)}function es(e){return Cc(e)}function im(e,t){return t=typeof t=="string"?t:"\\u",e.indexOf(t)===0?String.fromCharCode(parseInt(e.substring(t.length),16)):e}function nm(e,t){t=typeof t=="string"?t:"\\u";function i(r){return im(r,t)}let n=new RegExp(`${es(t)}[0-9a-fA-F]{4}`,"g");return e.replace(n,i)}function mi(e,t){let i=0,n=e;for(;;){if(i<=n,i==0||t(i-1),n==e||t(n),i==n)return i;let r=i+n>>1;t(r)?n=r:i=r+1}}function kc(e,t){return e-t}function Fh(e,t){let i={};for(let n of e){let r=t(n);r&&!i[r]&&(i[r]=n)}return i}function rm(e){let t={};for(let i=0;i<e.length;i++)t[e[i]]=!0;return t}function ea(e,t){let i={};for(let n of e){let r=t(n);r&&(i[r]?i[r].push(n):i[r]=[n])}return i}function om(e,t){let i={};for(let n in e)i[n]=t(e[n],n);return i}var Nl=class{constructor(){u(this,"listeners",{})}dispatchEvent(e){let t=this.listeners[e.type];if(t){e.target=this,e.currentTarget=this;for(let i=0;i<t.length;i++)t[i](e)}}addEventListener(e,t,i){if(i)return;let n=this.listeners[e];n?n.includes(t)||n.push(t):this.listeners[e]=[t]}removeEventListener(e,t,i){if(i)return;let n=this.listeners[e];if(n){let r=n.indexOf(t);r>=0&&n.splice(r,1)}}},ji={audio:!0,canvas:!0,embed:!0,iframe:!0,img:!0,math:!0,object:!0,picture:!0,svg:!0,video:!0};function Ec(){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 Pc(e){return{fontFamily:e.fontFamily,lineHeight:e.lineHeight,margin:e.margin,hyphenate:e.hyphenate,columnWidth:e.columnWidth,horizontal:e.horizontal,nightMode:e.nightMode,spreadView:e.spreadView,pageBorder:e.pageBorder,enabledMediaTypes:Object.assign({},e.enabledMediaTypes),defaultPaperSize:e.defaultPaperSize?Object.assign({},e.defaultPaperSize):void 0}}var sm=Ec(),Rh={PENDING:{}};function Nc(e,t,i,n){let r=Math.min((e-0)/i,(t-0)/n);return`matrix(${r},0,0,${r},0,0)`}function am(e){return`"${jr(`${e}`)}"`}function lm(e){return Ti(`${e}`)}function Ca(e,t){return e?`${Ti(e)}.${Ti(t)}`:Ti(t)}var Tc=0,ts=class{constructor(e,t){if(u(this,"parent",e),u(this,"resolver",t),u(this,"scopeKey"),u(this,"children",[]),u(this,"zero"),u(this,"one"),u(this,"_true"),u(this,"_false"),u(this,"values",{}),u(this,"funcs",{}),u(this,"builtIns",{}),this.scopeKey=`S${Tc++}`,this.zero=new it(this,0),this.one=new it(this,1),this._true=new it(this,!0),this._false=new it(this,!1),e&&e.children.push(this),!e){let i=this.builtIns;i.floor=Math.floor,i.ceil=Math.ceil,i.round=Math.round,i.sqrt=Math.sqrt,i.min=Math.min,i.max=Math.max,i.letterbox=Nc,i["css-string"]=am,i["css-name"]=lm,i.typeof=n=>typeof n,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 this.pubTitle?this.pubTitle:""}),this.defineBuiltInName("doc-title",function(){return this.docTitle?this.docTitle:""})}}defineBuiltInName(e,t){this.values[e]=new we(this,t,e)}defineName(e,t){this.values[e]=t}defineFunc(e,t){this.funcs[e]=t}defineBuiltIn(e,t){this.builtIns[e]=t}};function hm(e){switch(e?.toLowerCase()){case"px":case"in":case"pt":case"pc":case"cm":case"mm":case"q":return!0;default:return!1}}function Ac(e){switch(e?.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 um(e){switch(e?.toLowerCase()){case"em":case"rem":case"lh":case"rlh":return!0;default:return!1}}function cm(e){switch(e?.toLowerCase()){case"rem":case"rlh":return!0;default:return!1}}var Zt={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,lh:20,rlh:20,dppx:1,dpi:1/96,dpcm:2.54/96};function Ic(e){switch(e){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 ka=class{constructor(e,t,i,n){u(this,"rootScope",e),u(this,"viewportWidth",t),u(this,"viewportHeight",i),u(this,"actualPageWidth",null),u(this,"pageWidth"),u(this,"actualPageHeight",null),u(this,"pageHeight"),u(this,"initialFontSize"),u(this,"rootFontSize",null),u(this,"isRelativeRootFontSize",null),u(this,"fontSize"),u(this,"rootLineHeight",null),u(this,"pref"),u(this,"scopes",{}),u(this,"pageAreaWidth",null),u(this,"pageAreaHeight",null),u(this,"pageVertical",null),u(this,"pubTitle",null),u(this,"docTitle",null),this.pageWidth=function(){return this.actualPageWidth?this.actualPageWidth:this.pref.spreadView?Math.floor(t/2)-this.pref.pageBorder:t},this.pageHeight=function(){return this.actualPageHeight?this.actualPageHeight:i},this.initialFontSize=n,this.fontSize=function(){return this.rootFontSize?this.rootFontSize:n},this.pref=sm}getScopeContext(e){let t=this.scopes[e.scopeKey];return t||(t={},this.scopes[e.scopeKey]=t),t}clearScope(e){this.scopes[e.scopeKey]={};for(let t=0;t<e.children.length;t++)this.clearScope(e.children[t])}queryUnitSize(e,t,i){if(Ac(e)){let n=this.pageWidth()/100,r=this.pageHeight()/100,o=this.pageAreaWidth!=null?this.pageAreaWidth/100:n,s=this.pageAreaHeight!=null?this.pageAreaHeight/100:r,a=i??this.pageVertical;switch(e){case"vw":return o;case"vh":return s;case"vi":return a?s:o;case"vb":return a?o:s;case"vmin":return o<s?o:s;case"vmax":return o>s?o:s;case"pvw":return n;case"pvh":return r;case"pvi":return a?r:n;case"pvb":return a?n:r;case"pvmin":return n<r?n:r;case"pvmax":return n>r?n:r}}return e=="em"||e=="rem"?t?this.initialFontSize:this.fontSize():e=="lh"||e=="rlh"?this.rootLineHeight:Zt[e]}evalName(e,t){do{let i=e.values[t];if(i||e.resolver&&(i=e.resolver.call(this,t,!1),i))return i;e=e.parent}while(e);throw new Error(`Name '${t}' is undefined`)}evalCall(e,t,i,n){do{let r=e.funcs[t];if(r||e.resolver&&(r=e.resolver.call(this,t,!0),r))return r;let o=e.builtIns[t];if(o){if(n)return e.zero;let s=Array(i.length);for(let a=0;a<i.length;a++)s[a]=i[a].evaluate(this);return new it(e,o.apply(this,s))}e=e.parent}while(e);throw new Error(`Function '${t}' is undefined`)}evalMediaName(e,t){let i=e==="all"||!!this.pref.enabledMediaTypes[e];return t?!i:i}evalMediaTest(e,t){let i="",n=e.match(/^(min|max)-(.*)$/);n&&(i=n[1],e=n[2]);let r=null,o=null;switch(e){case"width":case"height":case"device-width":case"device-height":case"color":t&&(r=t.evaluate(this));break}switch(e){case"width":o=this.pageWidth();break;case"height":o=this.pageHeight();break;case"device-width":o=window.screen.availWidth;break;case"device-height":o=window.screen.availHeight;break;case"color":o=window.screen.pixelDepth;break}if(o!=null&&r!=null)switch(i){case"min":return o>=Number(r);case"max":return o<=Number(r);default:return o==r}else if(o!=null&&t==null)return o!==0;return!1}evalSupportsTest(e,t,i){return!1}queryVal(e,t){let i=e&&this.scopes[e.scopeKey];return i?i[t]:void 0}storeVal(e,t,i){this.getScopeContext(e)[t]=i}},Xt=class{constructor(e){u(this,"scope",e),u(this,"key"),this.scope=e,this.key=`_${Tc++}`}toString(){let e=new gi;return this.appendTo(e,0),e.toString()}appendTo(e,t){throw new Error("F_ABSTRACT")}evaluateCore(e){throw new Error("F_ABSTRACT")}expand(e,t){return this}dependCore(e,t,i){return e===this}dependOuter(e,t,i){let n=i[this.key];if(n!=null)return n===Rh.PENDING?!1:n;{i[this.key]=Rh.PENDING;let r=this.dependCore(e,t,i);return i[this.key]=r,r}}depend(e,t){return this.dependOuter(e,t,{})}evaluate(e){let t=e.queryVal(this.scope,this.key);return typeof t<"u"||(t=this.evaluateCore(e),this.scope&&e.storeVal(this.scope,this.key,t)),t}isMediaName(){return!1}},Fc=class extends Xt{constructor(e,t){super(e),u(this,"val",t)}getOp(){throw new Error("F_ABSTRACT")}evalPrefix(e){throw new Error("F_ABSTRACT")}evaluateCore(e){let t=this.val.evaluate(e);return this.evalPrefix(t)}dependCore(e,t,i){return e===this||this.val.dependOuter(e,t,i)}appendTo(e,t){10<t&&e.append("("),e.append(this.getOp()),this.val.appendTo(e,10),10<t&&e.append(")")}expand(e,t){let i=this.val.expand(e,t);return i===this.val?this:new this.constructor(this.scope,i)}},Is=class extends Xt{constructor(e,t,i){super(e),u(this,"lhs",t),u(this,"rhs",i)}getPriority(){throw new Error("F_ABSTRACT")}getOp(){throw new Error("F_ABSTRACT")}evalInfix(e,t){throw new Error("F_ABSTRACT")}evaluateCore(e){let t=this.lhs.evaluate(e),i=this.rhs.evaluate(e);return this.evalInfix(t,i)}dependCore(e,t,i){return e===this||this.lhs.dependOuter(e,t,i)||this.rhs.dependOuter(e,t,i)}appendTo(e,t){let i=this.getPriority();i<=t&&e.append("("),this.lhs.appendTo(e,i),e.append(this.getOp()),this.rhs.appendTo(e,i),i<=t&&e.append(")")}expand(e,t){let i=this.lhs.expand(e,t),n=this.rhs.expand(e,t);return i===this.lhs&&n===this.rhs?this:new this.constructor(this.scope,i,n)}},Rc=class extends Is{constructor(e,t,i){super(e,t,i)}getPriority(){return 1}},Gn=class extends Is{constructor(e,t,i){super(e,t,i)}getPriority(){return 2}},Lc=class extends Is{constructor(e,t,i){super(e,t,i)}getPriority(){return 3}},Tl=class extends Is{constructor(e,t,i){super(e,t,i)}getPriority(){return 4}},Ai=class extends Fc{constructor(e,t){super(e,t)}getOp(){return"!"}evalPrefix(e){return!e}},dm=class extends Ai{constructor(e,t){super(e,t)}getOp(){return"not "}},Cn=class extends Fc{constructor(e,t){super(e,t)}getOp(){return"-"}evalPrefix(e){return-e}},Al=class extends Rc{constructor(e,t,i){super(e,t,i)}getOp(){return"&&"}evaluateCore(e){return this.lhs.evaluate(e)&&this.rhs.evaluate(e)}},pm=class extends Al{constructor(e,t,i){super(e,t,i)}getOp(){return" and "}},Il=class extends Rc{constructor(e,t,i){super(e,t,i)}getOp(){return"||"}evaluateCore(e){return this.lhs.evaluate(e)||this.rhs.evaluate(e)}},fm=class extends Il{constructor(e,t,i){super(e,t,i)}getOp(){return", "}},gm=class extends Il{constructor(e,t,i){super(e,t,i)}getOp(){return" or "}},mm=class extends Gn{constructor(e,t,i){super(e,t,i)}getOp(){return"<"}evalInfix(e,t){return e<t}},ym=class extends Gn{constructor(e,t,i){super(e,t,i)}getOp(){return"<="}evalInfix(e,t){return e<=t}},vm=class extends Gn{constructor(e,t,i){super(e,t,i)}getOp(){return">"}evalInfix(e,t){return e>t}},Ea=class extends Gn{constructor(e,t,i){super(e,t,i)}getOp(){return">="}evalInfix(e,t){return e>=t}},Fl=class extends Gn{constructor(e,t,i){super(e,t,i)}getOp(){return"=="}evalInfix(e,t){return e==t}},wm=class extends Gn{constructor(e,t,i){super(e,t,i)}getOp(){return"!="}evalInfix(e,t){return e!=t}},Oc=class extends Lc{constructor(e,t,i){super(e,t,i)}getOp(){return"+"}evalInfix(e,t){return e+t}},Bc=class extends Lc{constructor(e,t,i){super(e,t,i)}getOp(){return" - "}evalInfix(e,t){return e-t}},Rl=class extends Tl{constructor(e,t,i){super(e,t,i)}getOp(){return"*"}evalInfix(e,t){return e*t}},Mc=class extends Tl{constructor(e,t,i){super(e,t,i)}getOp(){return"/"}evalInfix(e,t){return e/t}},_c=class extends Tl{constructor(e,t,i){super(e,t,i)}getOp(){return"%"}evalInfix(e,t){return e%t}},Xr=class extends Xt{constructor(e,t,i){var n;super(e),u(this,"num",t),u(this,"unit"),this.unit=(n=i?.toLowerCase())!=null?n:""}appendTo(e,t){e.append(this.num.toString()),e.append(Ti(this.unit))}evaluateCore(e){return this.num*e.queryUnitSize(this.unit,!1)}},Je=class extends Xt{constructor(e,t){super(e),u(this,"qualifiedName",t)}appendTo(e,t){e.append(this.qualifiedName)}evaluateCore(e){return e.evalName(this.scope,this.qualifiedName).evaluate(e)}dependCore(e,t,i){return e===this||t.evalName(this.scope,this.qualifiedName).dependOuter(e,t,i)}},Lh=class extends Xt{constructor(e,t,i){super(e),u(this,"not",t),u(this,"name",i)}appendTo(e,t){this.not&&e.append("not "),e.append(Ti(this.name))}evaluateCore(e){return e.evalMediaName(this.name,this.not)}isMediaName(){return!0}},we=class extends Xt{constructor(e,t,i){super(e),u(this,"fn",t),u(this,"str",i)}appendTo(e,t){e.append(this.str)}evaluateCore(e){return this.fn.call(e)}};function bm(e,t){e.append("(");for(let i=0;i<t.length;i++)i&&e.append(","),t[i].appendTo(e,0);e.append(")")}function xm(e,t,i){let n=t;for(let r=0;r<t.length;r++){let o=t[r].expand(e,i);if(t!==n)n[r]=o;else if(o!==t[r]){n=Array(t.length);for(let s=0;s<r;s++)n[s]=t[s];n[r]=o}}return n}var yr=class Dc extends Xt{constructor(t,i,n){super(t),u(this,"qualifiedName",i),u(this,"params",n)}appendTo(t,i){t.append(this.qualifiedName),bm(t,this.params)}evaluateCore(t){return t.evalCall(this.scope,this.qualifiedName,this.params,!1).expand(t,this.params).evaluate(t)}dependCore(t,i,n){if(t===this)return!0;for(let r=0;r<this.params.length;r++)if(this.params[r].dependOuter(t,i,n))return!0;return i.evalCall(this.scope,this.qualifiedName,this.params,!0).dependOuter(t,i,n)}expand(t,i){let n=xm(t,this.params,i);return n===this.params?this:new Dc(this.scope,this.qualifiedName,n)}},Sm=class zc extends Xt{constructor(t,i,n,r){super(t),u(this,"cond",i),u(this,"ifTrue",n),u(this,"ifFalse",r)}appendTo(t,i){i>0&&t.append("("),this.cond.appendTo(t,0),t.append("?"),this.ifTrue.appendTo(t,0),t.append(":"),this.ifFalse.appendTo(t,0),i>0&&t.append(")")}evaluateCore(t){return this.cond.evaluate(t)?this.ifTrue.evaluate(t):this.ifFalse.evaluate(t)}dependCore(t,i,n){return t===this||this.cond.dependOuter(t,i,n)||this.ifTrue.dependOuter(t,i,n)||this.ifFalse.dependOuter(t,i,n)}expand(t,i){let n=this.cond.expand(t,i),r=this.ifTrue.expand(t,i),o=this.ifFalse.expand(t,i);return n===this.cond&&r===this.ifTrue&&o===this.ifFalse?this:new zc(this.scope,n,r,o)}},it=class extends Xt{constructor(e,t){super(e),u(this,"val",t)}appendTo(e,t){switch(typeof this.val){case"number":case"boolean":e.append(this.val.toString());break;case"string":e.append('"'),e.append(jr(this.val)),e.append('"');break;default:throw new Error("F_UNEXPECTED_STATE")}}evaluateCore(e){return this.val}},Oh=class Vc extends Xt{constructor(t,i,n){super(t),u(this,"name",i),u(this,"value",n)}appendTo(t,i){t.append("("),t.append(jr(this.name.name)),t.append(":"),this.value.appendTo(t,0),t.append(")")}evaluateCore(t){return t.evalMediaTest(this.name.name,this.value)}dependCore(t,i,n){return t===this||this.value.dependOuter(t,i,n)}expand(t,i){let n=this.value.expand(t,i);return n===this.value?this:new Vc(this.scope,this.name,n)}},Cm=class extends Xt{constructor(e,t,i,n){super(e),u(this,"name",t),u(this,"value",i),u(this,"isFunc",n)}appendTo(e,t){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)}},Uc=class extends Xt{constructor(e,t){super(e),u(this,"index",t)}appendTo(e,t){e.append("$"),e.append(this.index.toString())}expand(e,t){let i=t[this.index];if(!i)throw new Error(`Parameter missing: ${this.index}`);return i}};function Wt(e,t,i){return t===e._false||t===e.zero||i==e._false||i==e.zero?e._false:t===e._true||t===e.one?i:i===e._true||i===e.one?t:new Al(e,t,i)}function ne(e,t,i){return t===e.zero?i:i===e.zero?t:new Oc(e,t,i)}function ye(e,t,i){return t===e.zero?new Cn(e,i):i===e.zero?t:new Bc(e,t,i)}function Lo(e,t,i){return t===e.zero||i===e.zero?e.zero:t===e.one?i:i===e.one?t:new Rl(e,t,i)}function Pa(e,t,i){return t===e.zero?e.zero:i===e.one?t:new Mc(e,t,i)}var Kt=class{visitValues(e){for(let t=0;t<e.length;t++)e[t].visit(this);return null}visitEmpty(e){return null}visitSlash(e){return null}visitStr(e){return null}visitIdent(e){return null}visitNumeric(e){return null}visitNum(e){return null}visitInt(e){return this.visitNum(e)}visitHexColor(e){return null}visitURL(e){return null}visitURange(e){return null}visitSpaceList(e){return this.visitValues(e.values),null}visitCommaList(e){return this.visitValues(e.values),null}visitFunc(e){return this.visitValues(e.values),null}visitExpr(e){return null}},nn=class extends Kt{constructor(){super(),u(this,"error",!1)}visitValues(e){let t=null;for(let i=0;i<e.length;i++){let n=e[i],r=n.visit(this);if(this.error)return[];if(t)t[i]=r;else if(n!==r){t=new Array(e.length);for(let o=0;o<i;o++)t[o]=e[o];t[i]=r}}return t||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 t=this.visitValues(e.values);return this.error?Me:t===e.values?e:new J(t)}visitCommaList(e){let t=this.visitValues(e.values);return this.error?Me:t===e.values?e:new Oe(t)}visitFunc(e){let t=this.visitValues(e.values);return this.error?Me:t===e.values?e:new ai(e.name,t)}visitExpr(e){return e}},ot=class{toString(){let e=new gi;return this.appendTo(e,!0),e.toString()}stringValue(){let e=new gi;return this.appendTo(e,!1),e.toString()}toExpr(e,t){return null}appendTo(e,t){e.append("[error]")}isExpr(){return!1}isNumeric(){return!1}isNum(){return!1}isIdent(){return!1}isSpaceList(){return!1}visit(e){return this}},$c=class Hc extends ot{static get instance(){return this.empty||(this.empty=new Hc),this.empty}constructor(){super()}toExpr(t,i){return new it(t,"")}appendTo(t,i){}visit(t){return t.visitEmpty(this)}};u($c,"empty");var km=$c,Me=km.instance,Wc=class Gc extends ot{static get instance(){return this.slash||(this.slash=new Gc),this.slash}constructor(){super()}toExpr(t,i){return new it(t,"/")}appendTo(t,i){t.append("/")}visit(t){return t.visitSlash(this)}};u(Wc,"slash");var Em=Wc,jn=Em.instance,K=class extends ot{constructor(e){super(),u(this,"str",e)}toExpr(e,t){return new it(e,this.str)}appendTo(e,t){t?(e.append('"'),e.append(jr(this.str)),e.append('"')):e.append(this.str)}visit(e){return e.visitStr(this)}},Na=Object.create(null),he=class extends ot{constructor(e){if(super(),u(this,"name",e),Na[e])throw new Error("E_INVALID_CALL");Na[e]=this}toExpr(e,t){return new it(e,this.name)}appendTo(e,t){t?e.append(Ti(this.name)):e.append(this.name)}visit(e){return e.visitIdent(this)}isIdent(){return!0}};function B(e){let t=Na[e];return t||(t=new he(e)),t}var O=class extends ot{constructor(e,t){var i;super(),u(this,"num",e),u(this,"unit"),this.unit=(i=t?.toLowerCase())!=null?i:""}toExpr(e,t){return this.num==0?e.zero:t&&this.unit=="%"?this.num==100?t:new Rl(e,t,new it(e,this.num/100)):new Xr(e,this.num,this.unit)}appendTo(e,t){e.append(this.num.toString()),e.append(this.unit)}visit(e){return e.visitNumeric(this)}isNumeric(){return!0}},At=class extends ot{constructor(e){super(),u(this,"num",e)}toExpr(e,t){return this.num==0?e.zero:this.num==1?e.one:new it(e,this.num)}appendTo(e,t){e.append(this.num.toString())}visit(e){return e.visitNum(this)}isNum(){return!0}},lt=class extends At{constructor(e){super(e)}visit(e){return e.visitInt(this)}},jc=class extends ot{constructor(e){super(),u(this,"hex",e)}appendTo(e,t){e.append("#"),e.append(this.hex)}visit(e){return e.visitHexColor(this)}},Qe=class extends ot{constructor(e){super(),u(this,"url",e)}appendTo(e,t){e.append('url("'),e.append(jr(this.url)),e.append('")')}visit(e){return e.visitURL(this)}},Xc=class extends ot{constructor(e){super(),u(this,"urangeText",e)}appendTo(e,t){e.append(this.urangeText)}visit(e){return e.visitURange(this)}};function Ll(e,t,i,n){var r,o;let s=t.length;if(s>0){(r=t[0])==null||r.appendTo(e,n);for(let a=1;a<s;a++)e.append(i),(o=t[a])==null||o.appendTo(e,n)}}var J=class extends ot{constructor(e){super(),u(this,"values",e)}appendTo(e,t){Ll(e,this.values," ",t)}visit(e){return e.visitSpaceList(this)}isSpaceList(){return!0}},Oe=class extends ot{constructor(e){super(),u(this,"values",e)}appendTo(e,t){Ll(e,this.values,",",t)}visit(e){return e.visitCommaList(this)}},ai=class extends ot{constructor(e,t){super(),u(this,"name",e),u(this,"values",t)}appendTo(e,t){e.append(Ti(this.name)),e.append("("),Ll(e,this.values,",",t),e.append(")")}visit(e){return e.visitFunc(this)}},j=class extends ot{constructor(e){super(),u(this,"expr",e)}toExpr(){return this.expr}appendTo(e,t){this.expr instanceof it||this.expr instanceof Xr?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}},fn=class extends ot{constructor(e){super(),u(this,"text",e)}appendTo(e,t){e.append(this.text||" ")}};function ut(e,t){if(e){if(e.isNumeric()){let i=e;return t.queryUnitSize(i.unit,!1)*i.num}if(e.isNum())return e.num}return 0}function qc(e,t){return new O(ut(e,t),"px")}var y={absolute:B("absolute"),all:B("all"),always:B("always"),anywhere:B("anywhere"),auto:B("auto"),avoid:B("avoid"),balance:B("balance"),balance_all:B("balance-all"),block:B("block"),block_end:B("block-end"),block_start:B("block-start"),both:B("both"),bottom:B("bottom"),border_box:B("border-box"),break_all:B("break-all"),break_word:B("break-word"),clip:B("clip"),crop:B("crop"),cross:B("cross"),column:B("column"),discard:B("discard"),exclusive:B("exclusive"),_false:B("false"),fixed:B("fixed"),flex:B("flex"),flow_root:B("flow-root"),footnote:B("footnote"),footer:B("footer"),grid:B("grid"),header:B("header"),hidden:B("hidden"),horizontal_tb:B("horizontal-tb"),inherit:B("inherit"),initial:B("initial"),inline:B("inline"),inline_block:B("inline-block"),inline_end:B("inline-end"),inline_start:B("inline-start"),inside:B("inside"),keep:B("keep"),landscape:B("landscape"),left:B("left"),line:B("line"),list_item:B("list-item"),ltr:B("ltr"),manual:B("manual"),max_content:B("max-content"),min_content:B("min-content"),none:B("none"),normal:B("normal"),oeb_page_foot:B("oeb-page-foot"),oeb_page_head:B("oeb-page-head"),outside:B("outside"),padding_box:B("padding-box"),page:B("page"),relative:B("relative"),revert:B("revert"),right:B("right"),same:B("same"),scale:B("scale"),snap_block:B("snap-block"),snap_inline:B("snap-inline"),solid:B("solid"),spread:B("spread"),_static:B("static"),rtl:B("rtl"),table:B("table"),table_caption:B("table-caption"),table_cell:B("table-cell"),table_footer_group:B("table-footer-group"),table_header_group:B("table-header-group"),table_row:B("table-row"),top:B("top"),transparent:B("transparent"),unset:B("unset"),vertical_lr:B("vertical-lr"),vertical_rl:B("vertical-rl"),visible:B("visible"),_true:B("true")},Bh=new O(100,"%"),qr=new O(100,"pvw"),Yr=new O(100,"pvh"),Le=new O(0,"px"),sC=new Xc("U+0-10FFFF"),Mh={"font-size":1,"line-height":2,color:3};function Z(e){return e===y.inherit||e===y.initial||e===y.revert||e===y.unset}function _h(e,t){let i=Mh[e]||Number.MAX_VALUE,n=Mh[t]||Number.MAX_VALUE;return i-n}function Xe(e){return e?.length>2&&e.startsWith("--")}var gn,mn,yn,Yc=class li{constructor(t,i,n){ie(this,gn),ie(this,mn),ie(this,yn),de(this,gn,Math.round(Math.max(0,Math.min(t,li.MAX)))),de(this,mn,Math.round(Math.max(0,Math.min(i,li.MAX)))),de(this,yn,Math.round(Math.max(0,Math.min(n,li.MAX))))}static fromInt(t,i,n){return new li(t,i,n)}offset(t,i,n){return new li(H(this,gn)+t,H(this,mn)+i,H(this,yn)+n)}toKey(){return JSON.stringify([H(this,gn),H(this,mn),H(this,yn)])}toColorFunc(t){return new ai("color",[new J([B("srgb"),new At(H(this,gn)/li.MAX),new At(H(this,mn)/li.MAX),new At(H(this,yn)/li.MAX),...t!==null?[jn,new At(t)]:[]])])}};gn=new WeakMap,mn=new WeakMap,yn=new WeakMap,u(Yc,"MAX",1e4);var ui=Yc;function Pm(e){return Array.isArray(e)?e.every(t=>{if(!Array.isArray(t)||t.length!==2)return!1;let[i,n]=t;if(!i||typeof i!="object"||Array.isArray(i)||!n||typeof n!="object"||Array.isArray(n))return!1;let r=i,o=n;return Number.isFinite(r.r)&&Number.isFinite(r.g)&&Number.isFinite(r.b)&&Number.isFinite(o.c)&&Number.isFinite(o.m)&&Number.isFinite(o.y)&&Number.isFinite(o.k)}):!1}var Vi,Ui,$i,Qt,Zc=class yt{constructor(t,i,n,r){ie(this,Vi),ie(this,Ui),ie(this,$i),ie(this,Qt),de(this,Vi,Math.round(Math.max(0,Math.min(t,yt.MAX)))),de(this,Ui,Math.round(Math.max(0,Math.min(i,yt.MAX)))),de(this,$i,Math.round(Math.max(0,Math.min(n,yt.MAX)))),de(this,Qt,Math.round(Math.max(0,Math.min(r,yt.MAX))))}static fromInt(t,i,n,r){return new yt(t,i,n,r)}static fromNumber(t,i,n,r){return new yt(t*yt.MAX,i*yt.MAX,n*yt.MAX,r*yt.MAX)}toSRGB(){let t=yt.MAX-H(this,Qt);return ui.fromInt(ui.MAX-Math.min(ui.MAX,Math.round(H(this,Vi)*t/yt.MAX)+H(this,Qt)),ui.MAX-Math.min(ui.MAX,Math.round(H(this,Ui)*t/yt.MAX)+H(this,Qt)),ui.MAX-Math.min(ui.MAX,Math.round(H(this,$i)*t/yt.MAX)+H(this,Qt)))}equals(t){return H(this,Vi)===H(t,Vi)&&H(this,Ui)===H(t,Ui)&&H(this,$i)===H(t,$i)&&H(this,Qt)===H(t,Qt)}toJSON(){return{c:H(this,Vi),m:H(this,Ui),y:H(this,$i),k:H(this,Qt)}}};Vi=new WeakMap,Ui=new WeakMap,$i=new WeakMap,Qt=new WeakMap,u(Zc,"MAX",1e4);var Kc=Zc;function hn(e){return e instanceof At?Math.max(0,Math.min(1,e.num)):e instanceof O&&e.unit==="%"?Math.max(0,Math.min(1,e.num/100)):null}function Jc(e){if(e.name!=="device-cmyk"&&e.name!=="cmyk")return null;let t=e.values.length===1&&e.values[0]instanceof J?e.values[0].values:e.values;if(t.length<4||t.length>6)return null;let i=hn(t[0]),n=hn(t[1]),r=hn(t[2]),o=hn(t[3]);if(i===null||n===null||r===null||o===null)return null;let s=null;if(t.length>=5){if(t[4]===jn){if(t.length!==6)return null;s=hn(t[5])}else{if(t.length!==5)return null;s=hn(t[4])}if(s===null)return null}return{cmyk:Kc.fromNumber(i,n,r,o),alpha:s}}function*Nm(e){for(let t=-e;t<=e;t++)for(let i=-e;i<=e;i++)for(let n=-e;n<=e;n++)Math.abs(t)+Math.abs(i)+Math.abs(n)===e&&(yield[t,i,n])}var Ci,is,Qc,Dh,ed=class{constructor(){ie(this,is),ie(this,Ci,new Map)}registerDeviceCmyk(e){let t=Jc(e);return t?le(this,is,Qc).call(this,t.cmyk).toColorFunc(t.alpha):null}registerCmykReserveMap(e){for(let[t,i]of e){let n=ui.fromInt(t.r,t.g,t.b),r=Kc.fromInt(i.c,i.m,i.y,i.k);H(this,Ci).set(n.toKey(),r)}}toJSON(){let e={};return H(this,Ci).forEach((t,i)=>{e[i]=t.toJSON()}),e}};Ci=new WeakMap,is=new WeakSet,Qc=function(e){let t=e.toSRGB(),i=t.toKey(),n=H(this,Ci).get(i);return n?n.equals(e)?t:le(this,is,Dh).call(this,e,t):(H(this,Ci).set(i,e),t)},Dh=function(e,t){for(let i=1;i<=ui.MAX;i++)for(let[n,r,o]of Nm(i)){let s=t.offset(n,r,o),a=s.toKey();if(!H(this,Ci).has(a))return H(this,Ci).set(a,e),s}return Y.warn(`CmykStore: Exceeded trackable color limit for ${JSON.stringify(e.toJSON())}`),t};var Oo,lr,hr,td=class extends nn{constructor(e){super(),ie(this,Oo),ie(this,lr,new Map),ie(this,hr,!1),de(this,Oo,e??new ed)}reset(){de(this,hr,!1)}hadDeviceCmyk(){return H(this,hr)}recordConversion(e,t){H(this,lr).set(e,t)}getConversions(){if(H(this,lr).size===0)return null;let e={};return H(this,lr).forEach((t,i)=>{e[i]=t}),e}visitFunc(e){let t=H(this,Oo).registerDeviceCmyk(e);return t?(de(this,hr,!0),t):super.visitFunc(e)}};Oo=new WeakMap,lr=new WeakMap,hr=new WeakMap;function id(e){if(e.nodeType==1){let t=e.getAttribute("id");if(t)return t}return null}function Tm(e){return`^${e}`}function zh(e){return e.replace(/[\[\]\(\),=;^]/g,Tm)}function Am(e){return e.substr(1)}function Ta(e){return e&&e.replace(/\^[\[\]\(\),=;^]/g,Am)}function Im(e){let t=[];do{let i=e.match(/^(\^,|[^,])*/),n=Ta(i[0]);if(e=e.substr(i[0].length+1),!e&&!t.length)return n;t.push(n)}while(e);return t}function Vh(e){let t={};for(;e;){let i=e.match(/^;([^;=]+)=(([^;]|\^;)*)/);if(!i)return t;t[i[1]]=Im(i[2]),e=e.substr(i[0].length)}return t}var Uh=class{appendTo(e){e.append("!")}applyTo(e){return!1}},$h=class{constructor(e,t,i){u(this,"index",e),u(this,"id",t),u(this,"sideBias",i)}appendTo(e){e.append("/"),e.append(this.index.toString()),(this.id||this.sideBias)&&(e.append("["),this.id&&e.append(this.id),this.sideBias&&(e.append(";s="),e.append(this.sideBias)),e.append("]"))}applyTo(e){if(e.node.nodeType!=1)throw new Error("E_CFI_NOT_ELEMENT");let t=e.node,i=t.children,n=i.length,r,o=Math.floor(this.index/2)-1;if(o<0||n==0)r=t.firstChild,e.node=r||t;else{if(r=i[Math.min(o,n-1)],this.index&1){let s=r.nextSibling;!s||s.nodeType==1?e.after=!0:r=s}e.node=r}if(this.id&&(e.after||this.id!=id(e.node))){let s=t.ownerDocument.getElementById(this.id);s?e.node=s:Y.warn("E_CFI_ID_MISMATCH:",this.id)}return e.sideBias=this.sideBias,!0}},Hh=class{constructor(e,t,i,n){u(this,"offset",e),u(this,"textBefore",t),u(this,"textAfter",i),u(this,"sideBias",n)}applyTo(e){if(this.offset>0&&!e.after){let t=this.offset,i=e.node;for(;;){let n=i.nodeType;if(n==1)break;let r=i.nextSibling;if(3<=n&&n<=5){let o=i.textContent.length;if(t<=o)break;if(!r){t=o;break}t-=o}if(!r){t=0;break}i=r}e.node=i,e.offset=t}return e.sideBias=this.sideBias,!0}appendTo(e){e.append(":"),e.append(this.offset.toString()),(this.textBefore||this.textAfter||this.sideBias)&&(e.append("["),(this.textBefore||this.textAfter)&&(this.textBefore&&e.append(zh(this.textBefore)),e.append(","),this.textAfter&&e.append(zh(this.textAfter))),this.sideBias&&(e.append(";s="),e.append(this.sideBias)),e.append("]"))}},Wh=class nd{constructor(){u(this,"steps",null)}fromString(t){let i=t.match(/^#?epubcfi\((.*)\)$/);if(!i)throw new Error("E_CFI_NOT_CFI");let n=decodeURIComponent(i[1]),r=0,o=[];for(;;){let s;switch(n.charAt(r)){case"/":{if(r++,i=n.substr(r).match(/^(0|[1-9][0-9]*)(\[(.*?)(;([^\]]|\^\])*)?\])?/),!i)throw new Error("E_CFI_NUMBER_EXPECTED");r+=i[0].length;let a=parseInt(i[1],10),h=i[3];s=Vh(i[4]),o.push(new $h(a,h,Th(s.s)));break}case":":{if(r++,i=n.substr(r).match(/^(0|[1-9][0-9]*)(\[((([^\];,]|\^[\];,])*)(,(([^\];,]|\^[\];,])*))?)(;([^]]|\^\])*)?\])?/),!i)throw new Error("E_CFI_NUMBER_EXPECTED");r+=i[0].length;let a=parseInt(i[1],10),h=i[4];h&&(h=Ta(h));let l=i[7];l&&(l=Ta(l)),s=Vh(i[10]),o.push(new Hh(a,h,l,Th(s.s)));break}case"!":r++,o.push(new Uh);break;case"~":case"@":case"":this.steps=o;return;default:throw new Error("E_CFI_PARSE_ERROR")}}}navigate(t){let i={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(i)){i.ref=new nd,i.ref.steps=this.steps.slice(n+1);break}return i}trim(t,i){return t.replace(/\s+/g," ").match(i?/^[ -\uD7FF\uE000-\uFFFF]{0,8}/:/[ -\uD7FF\uE000-\uFFFF]{0,8}$/)[0].replace(/^\s/,"").replace(/\s$/,"")}prependPathFromNode(t,i,n,r){let o=[],s=t.parentNode,a="",h="";for(;t;){switch(t.nodeType){case 3:case 4:case 5:{let l=t.textContent,c=l.length;n?(i+=c,a||(a=l)):(i>c&&(i=c),n=!0,a=l.substr(0,i),h=l.substr(i)),t=t.previousSibling;continue}case 8:t=t.previousSibling;continue}break}for((i>0||a||h)&&(a=this.trim(a,!1),h=this.trim(h,!0),o.push(new Hh(i,a,h,r)),r=null);s&&!(!s||s.nodeType==9);){let l=n?null:id(t),c=n?1:0;for(;t;)t.nodeType==1&&(c+=2),t=t.previousSibling;o.push(new $h(c,l,r)),r=null,t=s,s=s.parentNode,n=!1}o.reverse(),this.steps?(o.push(new Uh),this.steps=o.concat(this.steps)):this.steps=o}toString(){if(!this.steps)return"";let t=new gi;t.append("epubcfi(");for(let i=0;i<this.steps.length;i++)this.steps[i].appendTo(t);return t.append(")"),t.toString().replace(/%/g,"%25")}},Mt=class{constructor(e,t,i,n){u(this,"x1",e),u(this,"y1",t),u(this,"x2",i),u(this,"y2",n)}},Ei=class{constructor(e,t){u(this,"x",e),u(this,"y",t)}},ta=class{constructor(e,t,i,n){u(this,"left",e),u(this,"top",t),u(this,"right",i),u(this,"bottom",n)}},Gh=class{constructor(e,t,i,n){u(this,"low",e),u(this,"high",t),u(this,"winding",i),u(this,"shapeId",n)}},pi=class{constructor(e,t,i,n){u(this,"y1",e),u(this,"y2",t),u(this,"x1",i),u(this,"x2",n),u(this,"left",null),u(this,"right",null)}};function Fm(e,t){return e.low.y-t.low.y||e.low.x-t.low.x}var Fs=class rd{constructor(t){u(this,"points",t)}addSegments(t,i){let n=this.points,r=n.length,o=n[r-1];for(let s=0;s<r;s++){let a=n[s],h;o.y<a.y?h=new Gh(o,a,1,i):h=new Gh(a,o,-1,i),t.push(h),o=a}}withOffset(t,i){let n=[];for(let r of this.points)n.push(new Ei(r.x+t,r.y+i));return new rd(n)}};function jh(e,t,i,n){let r=[];for(let o=0;o<20;o++){let s=o*2*Math.PI/20;r.push(new Ei(e+i*Math.sin(s),t+n*Math.cos(s)))}return new Fs(r)}function Ol(e,t,i,n){return new Fs([new Ei(e,t),new Ei(i,t),new Ei(i,n),new Ei(e,n)])}var uo=class{constructor(e,t,i,n){u(this,"x",e),u(this,"winding",t),u(this,"shapeId",i),u(this,"lowOrHigh",n)}};function Xh(e,t){let i=e.low.x+(e.high.x-e.low.x)*(t-e.low.y)/(e.high.y-e.low.y);if(isNaN(i))throw new Error("Bad intersection");return i}function Rm(e,t,i,n){let r,o,s,a;t.high.y<i&&Y.warn("Error: inconsistent segment (1)"),t.low.y<=i?(r=Xh(t,i),o=t.winding):(r=t.low.x,o=0),t.high.y>=n?(s=Xh(t,n),a=t.winding):(s=t.high.x,a=0),r<s?(e.push(new uo(r,o,t.shapeId,-1)),e.push(new uo(s,a,t.shapeId,1))):(e.push(new uo(s,a,t.shapeId,-1)),e.push(new uo(r,o,t.shapeId,1)))}function Lm(e,t,i){let n=t+i,r=Array(n),o=Array(n),s;for(s=0;s<=n;s++)r[s]=0,o[s]=0;let a=[],h=!1,l=e.length;for(let c=0;c<l;c++){let d=e[c];r[d.shapeId]+=d.winding,o[d.shapeId]+=d.lowOrHigh;let p=!1;for(s=0;s<t;s++)if(r[s]&&!o[s]){p=!0;break}if(p){for(s=t;s<=n;s++)if(r[s]||o[s]){p=!1;break}}h!=p&&(a.push(d.x),h=p)}return a}function Om(e,t){return t?Math.ceil(e/t)*t:e}function qh(e,t){return t?Math.floor(e/t)*t:e}function Bm(e){return new Ei(e.y,-e.x)}function ns(e){return new Mt(e.y1,-e.x2,e.y2,-e.x1)}function od(e){return new Mt(-e.y2,e.x1,-e.y1,e.x2)}function Yh(e){return new Fs(e.points.map(t=>Bm(t)))}function Mm(e,t,i,n,r,o){o&&(e=ns(e),t=t.map(m=>Yh(m)),i=i.map(m=>Yh(m)));let s=t.length,a=i?i.length:0,h=[],l=[],c,d,p;for(c=0;c<s;c++)t[c].addSegments(l,c);for(c=0;c<a;c++)i[c].addSegments(l,c+s);let f=l.length;l.sort(Fm);let g=0;for(;l[g].shapeId>=s;)g++;let v=l[g].low.y;v>e.y1&&h.push(new pi(e.y1,v,e.x2,e.x2));let w=0,x=[];for(;w<f&&(p=l[w]).low.y<v;)p.high.y>v&&x.push(p),w++;for(;w<f||x.length>0;){let m=e.y2,S=Math.min(Om(Math.ceil(v+n),r),e.y2);for(d=0;d<x.length&&m>S;d++)p=x[d],p.low.x==p.high.x?p.high.y<m&&(m=Math.max(qh(p.high.y,r),S)):p.low.x!=p.high.x&&(m=S);for(m>e.y2&&(m=e.y2);w<f&&(p=l[w]).low.y<m;){if(p.high.y<v){w++;continue}if(p.low.y<S)p.low.y==p.high.y&&p.low.y==v||(x.push(p),m=S),w++;else{let P=qh(p.low.y,r);P<m&&(m=P);break}}let b=[];for(d=0;d<x.length;d++)Rm(b,x[d],v,m);b.sort((P,L)=>P.x-L.x||P.lowOrHigh-L.lowOrHigh);let C=Lm(b,s,a);if(C.length==0)h.push(new pi(v,m,e.x2,e.x2));else{let P=0,L=e.x1;for(d=0;d<C.length;d+=2){let A=Math.max(e.x1,C[d]),z=Math.min(e.x2,C[d+1])-A;z>P&&(P=z,L=A)}P==0?h.push(new pi(v,m,e.x2,e.x2)):h.push(new pi(v,m,Math.max(L,e.x1),Math.min(L+P,e.x2)))}if(m==e.y2)break;for(v=m,d=x.length-1;d>=0;d--)x[d].high.y<=m&&x.splice(d,1)}return sd(e,h),h}function sd(e,t){let i=t.length-1,n=new pi(e.y2,e.y2,e.x1,e.x2);for(;i>=0;){let r=n;n=t[i],(n.y2-n.y1<1||n.x1==r.x1&&n.x2==r.x2)&&(r.y1=n.y1,t.splice(i,1),n=r),i--}}function ad(e,t){let i=0,n=e.length;for(;i<n;){let r=Math.floor((i+n)/2);t>=e[r].y2?i=r+1:n=r}return i}function _m(e,t){if(!e.length)return t;let i=t.y1,n,r;for(r=0;r<e.length&&(n=e[r],!(n.y2>t.y1&&n.x1-.1<=t.x1&&n.x2+.1>=t.x2));r++)i=Math.max(i,n.y2);let o=i;for(;r<e.length&&(n=e[r],!(n.y1>=t.y2||n.x1-.1>t.x1||n.x2+.1<t.x2));r++)o=n.y2;return r===e.length?o=t.y2:o=Math.min(o,t.y2),o<=i?null:new Mt(t.x1,i,t.x2,o)}function Dm(e,t){if(!e.length)return t;let i=t.y2,n,r;for(r=e.length-1;r>=0&&(n=e[r],!(r===e.length-1&&n.y2<t.y2))&&!(n.y1<t.y2&&n.x1-.1<=t.x1&&n.x2+.1>=t.x2);r--)i=Math.min(i,n.y1);let o=Math.min(i,n.y2);for(;r>=0&&(n=e[r],!(n.y2<=t.y1||n.x1-.1>t.x1||n.x2+.1<t.x2));r--)o=n.y1;return o=Math.max(o,t.y1),i<=o?null:new Mt(t.x1,o,t.x2,i)}function zm(e,t,i,n){let r=i.y1,o=i.x2-i.x1,s=i.y2-i.y1,a=ad(t,r);for(;;){let h=r+s;if(h>e.y2)return!1;let l=e.x1,c=e.x2;for(let d=a;d<t.length&&t[d].y1<h;d++){let p=t[d];p.x1>l&&(l=p.x1),p.x2<c&&(c=p.x2)}if(l+o<=c||a>=t.length)return n=="left"?(i.x1=l,i.x2=l+o):(i.x1=c-o,i.x2=c),i.y2+=r-i.y1,i.y1=r,!0;r=t[a].y2,a++}}function Vm(e,t,i,n,r){for(n||(n=[new pi(i.y1,i.y2,i.x1,i.x2)]);n.length>0&&n[0].y2<=e.y1;)n.shift();if(n.length==0)return;n[0].y1<e.y1&&(n[0].y1=e.y1);let o,s=t.length==0?e.y1:t[t.length-1].y2;s<e.y2&&t.push(new pi(s,e.y2,e.x1,e.x2));let a=ad(t,n[0].y1);for(let h of n){if(a==t.length)break;for(t[a].y1<h.y1&&(o=t[a],a++,t.splice(a,0,new pi(h.y1,o.y2,o.x1,o.x2)),o.y2=h.y1);a<t.length&&(o=t[a++],o.y2>h.y2&&(t.splice(a,0,new pi(h.y2,o.y2,o.x1,o.x2)),o.y2=h.y2),h.x1!=h.x2&&(r=="left"?o.x1=Math.min(h.x2,e.x2):o.x2=Math.max(h.x1,e.x1)),o.y2!=h.y2););}sd(e,t)}var Um=class extends Kt{constructor(){super(),u(this,"propSet",{})}visitIdent(e){return this.propSet[e.name]=!0,e}visitSpaceList(e){return this.visitValues(e.values),e}};function $m(e){if(e){let t=new Um;try{return e.visit(t),t.propSet}catch(i){Y.warn(i,"toSet:")}}return{}}var Hm=class extends Kt{constructor(e){super(),u(this,"value",e)}visitInt(e){return this.value=e.num,e}};function Zh(e,t){if(e){let i=new Hm(t);try{return e.visit(i),i.value}catch(n){Y.warn(n,"toInt: ")}}return t}var Wm=class extends Kt{constructor(){super(),u(this,"collect",!1),u(this,"coords",[]),u(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 O(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,t,i,n,r){if(this.coords.length>0){let o=[];switch(this.coords.forEach((s,a)=>{if(s.unit=="%"){let h=a%2==0?i:n;a==3&&this.name=="circle"&&(h=Math.sqrt((i*i+n*n)/2)),o.push(s.num*h/100)}else o.push(s.num*r.queryUnitSize(s.unit,!1))}),this.name){case"polygon":if(o.length%2==0){let s=[];for(let a=0;a<o.length;a+=2)s.push(new Ei(e+o[a],t+o[a+1]));return new Fs(s)}break;case"rectangle":if(o.length==4)return Ol(e+o[0],t+o[1],e+o[0]+o[2],t+o[1]+o[3]);break;case"ellipse":if(o.length==4)return jh(e+o[0],t+o[1],o[2],o[3]);break;case"circle":if(o.length==3)return jh(e+o[0],t+o[1],o[2],o[2]);break}}return null}};function ld(e,t,i,n,r,o){if(e){let s=new Wm;try{return e.visit(s),s.getShape(t,i,n,r,o)}catch(a){Y.warn(a,"toShape:")}}return Ol(t,i,t+n,i+r)}var Gm=class extends Kt{constructor(e,t){super(),u(this,"reset",e),u(this,"defaultValue",t),u(this,"counters",Object.create(null)),u(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)+this.defaultValue,e}visitInt(e){return this.name&&(this.counters[this.name]+=e.num-(this.reset?0:this.defaultValue)),e}visitSpaceList(e){return this.visitValues(e.values),e}};function qi(e,t){var i,n;let r=(i=t?.reset)!=null?i:!1,o=(n=t?.defaultValue)!=null?n:r?0:1,s=new Gm(r,o);try{e.visit(s)}catch(a){Y.warn(a,"toCounters:")}return s.counters}var jm=class extends nn{constructor(e,t){super(),u(this,"baseUrl",e),u(this,"transformer",t)}visitURL(e){return new Qe(Ir(this.transformer.transformURL(e.url,this.baseUrl)))}};function bi(e){let t=Object.create(null);return Object.keys(e).forEach(i=>{t[i]=Array.from(e[i])}),t}function Xm(e){return e.replace(/\\([0-9a-fA-F]{1,6})\s?|\\(.)/g,(t,i,n)=>i?String.fromCodePoint(parseInt(i,16)):n)}function kn(e,t){var i;if(t==="content"){let n=e.cloneNode(!0);return n.querySelectorAll("[data-adapt-pseudo]").forEach(r=>r.remove()),n.textContent||""}else if(t==="marker"){let n=e.querySelector('[data-adapt-pseudo="marker"], [data-adapt-pseudo="footnote-marker"]');if(n)return n.textContent||"";let r=(i=e.style)==null?void 0:i.getPropertyValue("--viv-marker-content");if(r){let o=r.match(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g);if(o&&o.length>0)return o.map(s=>Xm(s.substring(1,s.length-1))).join("")}return""}else{let n=e.querySelector(`[data-adapt-pseudo="${t}"]`);return n&&n.textContent||""}}var qm=class{constructor(e,t){u(this,"targetId",e),u(this,"resolved",t),u(this,"pageCounters",null),u(this,"spineIndex",-1),u(this,"pageIndex",-1)}equals(e){return this===e?!0:e?this.targetId===e.targetId&&this.resolved===e.resolved&&this.spineIndex===e.spineIndex&&this.pageIndex===e.pageIndex:!1}isResolved(){return this.resolved}resolve(){this.resolved=!0}unresolve(){this.resolved=!1}},Ym=class{constructor(e,t){u(this,"counterStore",e),u(this,"baseURL",t)}countersOfId(e,t){e=this.counterStore.documentURLTransformer.transformFragment(e,this.baseURL),this.counterStore.countersById[e]=t}getExprContentListener(){return this.counterStore.getExprContentListener()}},Zm=class{constructor(e,t,i,n){u(this,"counterStore",e),u(this,"baseURL",t),u(this,"rootScope",i),u(this,"pageScope",n),u(this,"styler",null),u(this,"namedStringValues",Object.create(null)),u(this,"runningElements",Object.create(null))}setStyler(e){this.styler=e}getFragment(e){let t=e.match(/^[^#]*#(.*)$/);return t?t[1]:null}getTransformedId(e){let t=this.counterStore.documentURLTransformer.transformURL(Ae(e,this.baseURL),this.baseURL);return t.charAt(0)==="#"&&(t=t.substring(1)),t}getPageCounterVal(e,t){let i=()=>{let o=this.counterStore.currentPageCounters[e];return o&&o.length?o[o.length-1]:null},n=new we(this.pageScope,()=>t(i()),`page-counter-${e}`),r=o=>t(o[o.length-1]);return this.counterStore.registerPageCounterExpr(e,r,n),n}getPageCountersVal(e,t){let i=()=>this.counterStore.currentPageCounters[e]||[],n=new we(this.pageScope,()=>t(i()),`page-counters-${e}`);return this.counterStore.registerPageCounterExpr(e,t,n),n}getTargetCounters(e,t,i){let n=this.counterStore.countersById[t];return!n&&i&&e&&(this.styler.styleUntilIdIsReached(e),n=this.counterStore.countersById[t]),n||null}getTargetPageCounters(e){return this.counterStore.currentPage.elementsById[e]?this.counterStore.currentPageCounters:this.counterStore.pageCountersById[e]||null}getTargetPageDocCounters(e){return this.counterStore.currentPage.elementsById[e]?this.counterStore.currentPageDocCounters:this.counterStore.pageDocCountersById[e]||null}adjustCountersForCrossScope(e,t,i,n){if(!this.counterStore.isPageControlledCounter(e)||!i)return t;let r=i[e]||[],o=r.length?r[r.length-1]:0,s=n?.[e]||[],a=s.length?s[0]:0;return t.length?[o+(t[0]-a),...t.slice(1)]:[o]}getTargetPageText(e,t){if(this.counterStore.currentPage.elementsById[e]){let i=this.counterStore.currentPage.elementsById[e];if(i&&i.length>0){let n=i[0];return t==="before"||t==="after"||t==="marker"?kn(n,t):kn(n,"content")}return""}else{if(e in this.counterStore.pageTextById){let i=this.counterStore.pageTextById[e];return i[t]!==void 0?i[t]:i.content||""}return null}}getTargetCounterVal(e,t,i){let n=this.getFragment(e),r=this.getTransformedId(e),o=new we(this.pageScope,()=>{let s=this.getTargetCounters(n,r,!0);if(s)if(s[t]){let a=s[t],h=this.getTargetPageCounters(r),l=this.getTargetPageDocCounters(r),c=this.adjustCountersForCrossScope(t,a,h,l);return h&&this.counterStore.resolveReference(r),i(c[c.length-1]||null)}else{let a=this.getTargetPageCounters(r);if(a)if(this.counterStore.resolveReference(r),a[t]){let h=a[t];return i(h[h.length-1]||null)}else return i(0);else return this.counterStore.saveReferenceOfCurrentPage(r,!1),"??"}else return this.counterStore.saveReferenceOfCurrentPage(r,!1),"??"},`target-counter-${t}-of-${e}`);return this.counterStore.registerTargetCounterExpr(t,i,o,r),o}getTargetCountersVal(e,t,i){let n=this.getFragment(e),r=this.getTransformedId(e);return new we(this.pageScope,()=>{let o=this.getTargetPageCounters(r);if(o){this.counterStore.resolveReference(r);let s=this.getTargetCounters(n,r,!0),a=s?.[t]||[],h=this.getTargetPageDocCounters(r),l=this.adjustCountersForCrossScope(t,a,o,h);if(l.length)return i(l);let c=o[t]||[];return i(c)}else return this.counterStore.saveReferenceOfCurrentPage(r,!1),"??"},`target-counters-${t}-of-${e}`)}getTargetTextVal(e,t){let i=this.getTransformedId(e),n=new we(this.pageScope,()=>{if(t==="first-letter"){let o=this.getTargetPageText(i,"before"),s=this.getTargetPageText(i,"content"),a=this.getTargetPageText(i,"after");if(o===null&&s===null&&a===null)return this.counterStore.saveReferenceOfCurrentPage(i,!1),"??";let h=(o??"")+(s??"")+(a??"");this.counterStore.resolveReference(i);let l=h.match(Jo);return l?l[0]:""}let r=this.getTargetPageText(i,t);return r!==null?(this.counterStore.resolveReference(i),r):(this.counterStore.saveReferenceOfCurrentPage(i,!1),"??")},`target-text-${t}-of-${e}`);return this.counterStore.registerTargetTextExpr(t,n,i),n}getNamedStringVal(e,t){let i=new we(this.pageScope,()=>this.getRunningValue(this.namedStringValues,e,t),`named-string-${t}-${e}`);return i.getContentList=()=>this.getRunningContentList(e,t),i}getRunningElementVal(e,t){return new we(this.pageScope,()=>this.getRunningValue(this.runningElements,e,t),`running-element-${t}-${e}`)}getRunningValue(e,t,i){let n=this.getRunningRawValue(e,t,i);return typeof n.value=="string"?n.value:this.contentListToString(this.resolveDeferredContentList(n.value,n.offset))}getRunningContentList(e,t){let i=this.getRunningRawValue(this.namedStringValues,e,t);return typeof i.value=="string"?null:this.resolveDeferredContentList(i.value,i.offset)}resolveDeferredContentList(e,t){return this.freezePageCounters(e,t)}freezePageCounters(e,t){if(e instanceof j){let i=e.expr;if(i instanceof we){let n=/^page-counters?-(.+)$/.exec(i.str);if(n){if(n[1]==="pages")return e;let r=this.counterStore,o=n[1],s=r.getPageCounterFormat(i)||(h=>h.length?String(h[h.length-1]):""),a=r.getOrCreateNamedStringPageCounterExpr(this.pageScope,t,o,s);return new j(a)}}return e}return e instanceof J?new J(e.values.map(i=>this.freezePageCounters(i,t))):e instanceof Oe?new Oe(e.values.map(i=>this.freezePageCounters(i,t))):e}contentListToString(e){if(e instanceof K)return e.stringValue();if(e instanceof j){let t=e.expr;if(t instanceof we){let i=t.fn.call(null);return i==null?"":String(i)}return""}return e instanceof J?e.values.map(t=>this.contentListToString(t)).join(""):e instanceof Oe?e.values.map(t=>this.contentListToString(t)).join(""):""}getRunningRawValue(e,t,i){let n=e[t];if(!n)return{value:"",offset:-1};let r=Object.keys(n).map(p=>parseInt(p,10)).sort(kc),o=this.counterStore.currentPage;if(!o)return{value:"",offset:-1};let s=o.isBlankPage?o.offset-1:o.offset,a=o.isBlankPage?s:Math.max(s,...Array.from(o.container.querySelectorAll(`[${Ht}]`)).map(p=>parseInt(p.getAttribute(Ht),10))),h=-1,l=-1,c=-1,d=-1;for(let p=0;p<r.length;p++){let f=r[p],g=p>0?r[p-1]:-1,v=p<r.length-1?r[p+1]:-1;if(f>a)break;if(f>=s){if(h<0&&(h=f,d=-1),l<0)if(f===s)l=f;else{g<h&&(l=g);let w=o.container.querySelector(`[${Ht}="${f}"]`);if(!w)l<0&&(l=f);else{let x=o.container.querySelector(`[${Ht}="${s}"]`);if(x||(x=o.container.querySelector(`[${Ht}="0"]`)),x){for(let m=x;m;m=m.firstElementChild)if(m===w){l=f;break}}}}c=f}else(v>a||v<0)&&(h=l=c=d=f)}return{value:n[{first:h,start:l,last:c,"first-except":d}[i]]||"",offset:{first:h,start:l,last:c,"first-except":d}[i]}}setNamedString(e,t,i){let n=this.namedStringValues[e]||(this.namedStringValues[e]=Object.create(null));n[i]=t,typeof t!="string"&&(this.counterStore.hasDeferredNamedStrings=!0)}setRunningElement(e,t){let i=this.runningElements[e]||(this.runningElements[e]=Object.create(null));i[t]=String(t)}},Km=class{constructor(e){u(this,"documentURLTransformer",e),u(this,"countersById",Object.create(null)),u(this,"pageCountersById",Object.create(null)),u(this,"pageDocCountersById",Object.create(null)),u(this,"pageTextById",Object.create(null)),u(this,"currentPageDocCounters",null),u(this,"previousPageDocCounters",null),u(this,"currentPageDocCounterChanges",Object.create(null)),u(this,"currentPageDocCounterChangeTypes",Object.create(null)),u(this,"currentPageCounters",Object.create(null)),u(this,"previousPageCounters",Object.create(null)),u(this,"pageCountersBeforeOverride",Object.create(null)),u(this,"hasDeferredNamedStrings",!1),u(this,"namedStringPageSnapshots",Object.create(null)),u(this,"namedStringPageCounterExprMap",Object.create(null)),u(this,"currentPageCountersStack",[]),u(this,"pageIndicesById",Object.create(null)),u(this,"currentPage",null),u(this,"newReferencesOfCurrentPage",[]),u(this,"referencesToSolve",[]),u(this,"referencesToSolveStack",[]),u(this,"unresolvedReferences",Object.create(null)),u(this,"resolvedReferences",Object.create(null)),u(this,"pageControlledCounterNames",Object.assign(Object.create(null),{page:!0})),u(this,"pagesCounterExprs",[]),u(this,"pageCounterExprs",[]),u(this,"targetCounterExprs",[]),u(this,"targetTextExprs",[]),this.currentPageCounters.page=[0]}createCounterListener(e){return new Ym(this,e)}createCounterResolver(e,t,i){return new Zm(this,e,t,i)}setCurrentPage(e){this.currentPage=e}setCurrentPageDocCounters(e,t,i){this.previousPageDocCounters=this.currentPageDocCounters?bi(this.currentPageDocCounters):null,this.currentPageDocCounters=e?bi(e):null,this.currentPageDocCounterChanges=Object.create(null),this.currentPageDocCounterChangeTypes=i?{...i}:Object.create(null),t&&t.forEach(n=>{this.currentPageDocCounterChanges[n]=!0})}setPageControlledCounterNames(e){let t=Object.assign(Object.create(null),{page:!0});e.forEach(i=>{t[i]=!0}),this.pageControlledCounterNames=t}isPageControlledCounter(e){return!!this.pageControlledCounterNames[e]}definePageCounter(e,t){this.currentPageCounters[e]?this.currentPageCounters[e].push(t):this.currentPageCounters[e]=[t]}forceSetPageCounter(e){let t=this.currentPageCounters.page;!t||!t.length?this.currentPageCounters.page=[e]:t[t.length-1]=e}updatePageCounters(e,t){this.previousPageCounters=bi(this.currentPageCounters);let i=this.currentPageDocCounterChanges||{},n=this.currentPageDocCounterChangeTypes||{},r=Object.create(null);if(this.currentPageDocCounters){let x=this.previousPageDocCounters||{};for(let m in this.currentPageDocCounters){if(!i[m])continue;let S=this.currentPageDocCounters[m],b=S.length?S[S.length-1]:0,C=x[m]||[],P=C.length?C[C.length-1]:0,L=b-P,A=n[m],z=A==="reset"||A==="set";r[m]={delta:L,reset:z,value:b}}}let o=Object.create(null),s,a=!1,h=e["counter-reset"];if(h){let x=h.evaluate(t);x&&(a=x===y.none,a||(s=qi(x,{reset:!0})))}s&&"pages"in s&&delete s.pages;let l,c=e["counter-set"];if(c){let x=c.evaluate(t);x&&(l=qi(x,{defaultValue:0}))}l&&"pages"in l&&delete l.pages;let d=[];if(s)for(let x in s)d.push(x);if(l)for(let x in l)d.push(x);let p,f=e["counter-increment"];if(f){let x=f.evaluate(t);x&&(p=qi(x))}p&&"pages"in p&&delete p.pages,p?!("page"in p)&&!(r.page&&r.page.reset)&&(p.page=1):(p=Object.create(null),r.page&&r.page.reset||(p.page=1));for(let x in p)d.push(x);this.setPageControlledCounterNames(d);let g=bi(this.previousPageCounters);if(a)for(let x in this.pageCountersBeforeOverride)g[x]=Array.from(this.pageCountersBeforeOverride[x]);if(this.currentPageDocCounters)for(let x in this.currentPageDocCounters){if(this.isPageControlledCounter(x)){let m=r[x];if(m){if(m.reset)g[x]=[m.value],o[x]=!0;else if(m.delta!==0){g[x]||(g[x]=[0]);let S=g[x];S[S.length-1]+=m.delta}}else g[x]||(g[x]=Array.from(this.currentPageDocCounters[x]));continue}g[x]=Array.from(this.currentPageDocCounters[x])}this.currentPageCounters=g;let v=Object.create(null),w=x=>{if(!Object.prototype.hasOwnProperty.call(v,x)){let m=g[x];m&&(v[x]=Array.from(m))}};if(s)for(let x in s)w(x),this.definePageCounter(x,s[x]);for(let x in p){if(o[x])continue;this.currentPageCounters[x]||this.definePageCounter(x,0);let m=this.currentPageCounters[x];m[m.length-1]+=p[x]}if(l)for(let x in l)if(w(x),!this.currentPageCounters[x])this.definePageCounter(x,l[x]);else{let m=this.currentPageCounters[x];m[m.length-1]=l[x]}for(let x in v)this.pageCountersBeforeOverride[x]=Array.from(v[x])}pushPageCounters(e){this.currentPageCountersStack.push(this.currentPageCounters),this.currentPageCounters=bi(e)}popPageCounters(){this.currentPageCounters=this.currentPageCountersStack.pop()}resolveReference(e){let t=this.unresolvedReferences[e],i=this.resolvedReferences[e];i||(i=this.resolvedReferences[e]=[]);let n=!1;for(let r=0;r<this.referencesToSolve.length;){let o=this.referencesToSolve[r];if(o.targetId===e){if(o.resolve(),this.referencesToSolve.splice(r,1),t){let s=t.indexOf(o);s>=0&&t.splice(s,1)}i.push(o),n=!0}else r++}n||this.saveReferenceOfCurrentPage(e,!0)}saveReferenceOfCurrentPage(e,t){if(!this.newReferencesOfCurrentPage.some(i=>i.targetId===e)){let i=new qm(e,t);this.newReferencesOfCurrentPage.push(i)}}finishPage(e,t){let i=Object.keys(this.currentPage.elementsById);if(i.length>0){let o=bi(this.currentPageCounters),s=this.currentPageDocCounters?bi(this.currentPageDocCounters):null;i.forEach(a=>{this.pageCountersById[a]=o,s&&(this.pageDocCountersById[a]=s);let h=this.currentPage.elementsById[a];if(h&&h.length>0){let c=h[0];this.pageTextById[a]={content:kn(c,"content"),before:kn(c,"before"),after:kn(c,"after"),marker:kn(c,"marker")}}let l=this.pageIndicesById[a];if(l&&l.pageIndex<t){let c=this.resolvedReferences[a];if(c){let d=this.unresolvedReferences[a];d||(d=this.unresolvedReferences[a]=[]);let p;for(;p=c.shift();)p.unresolve(),d.push(p)}}this.pageIndicesById[a]={spineIndex:e,pageIndex:t}})}let n=this.previousPageCounters,r;for(;r=this.newReferencesOfCurrentPage.shift();){r.pageCounters=n,r.spineIndex=e,r.pageIndex=t;let o;r.isResolved()?(o=this.resolvedReferences[r.targetId],o||(o=this.resolvedReferences[r.targetId]=[])):(o=this.unresolvedReferences[r.targetId],o||(o=this.unresolvedReferences[r.targetId]=[])),o.every(s=>!r.equals(s))&&o.push(r)}this.hasDeferredNamedStrings&&this.currentPage&&this.recordNamedStringPageSnapshot(e),this.currentPage=null}recordNamedStringPageSnapshot(e){let t=this.currentPage,i=t.isBlankPage?t.offset-1:t.offset,n=t.isBlankPage?i:Math.max(i,...Array.from(t.container.querySelectorAll(`[${Ht}]`)).map(r=>parseInt(r.getAttribute(Ht),10)));for(let r of Object.keys(this.namedStringPageSnapshots)){let o=parseInt(r,10);if(o<=i)continue;let s=this.namedStringPageSnapshots[o];o<=n&&i<=s.lastOffset&&delete this.namedStringPageSnapshots[o]}this.namedStringPageSnapshots[i]={lastOffset:n,spineIndex:e,counters:bi(this.currentPageCounters)}}getPageCountersForOffset(e){for(let t of Object.keys(this.namedStringPageSnapshots)){let i=parseInt(t,10);if(i>e)break;let n=this.namedStringPageSnapshots[i];if(e<=n.lastOffset)return n.counters}return null}adjustPageCountersOfLaterSpines(e,t){if(t<=0)return;let i=new Set;for(let n of Object.keys(this.pageIndicesById))if(this.pageIndicesById[n].spineIndex>e){let r=this.pageCountersById[n];r&&r.page&&!i.has(r)&&(i.add(r),r.page=r.page.map(o=>o+t))}for(let n of Object.keys(this.namedStringPageSnapshots)){let r=this.namedStringPageSnapshots[parseInt(n,10)];r.spineIndex>e&&r.counters.page&&!i.has(r.counters)&&(i.add(r.counters),r.counters.page=r.counters.page.map(o=>o+t))}}updateTargetCounterNodesInPages(e){for(let t of e){if(!t||!t.container)continue;let i=t.container.querySelectorAll(`[${er}]`);for(let n of i){let r=n.getAttribute(er),o=this.targetCounterExprs.find(s=>s.expr.key===r);if(o&&o.transformedId){let s=this.pageCountersById[o.transformedId];if(s){let a=s[o.name];a&&(n.textContent=o.format(a[a.length-1]))}}}}}getPageCountersForPage(e,t){let i=Object.keys(e.elementsById);for(let n of i){let r=this.pageCountersById[n];if(r)return r}return t||null}updatePageCounterNodesInPages(e,t){var i;for(let n=0;n<e.length;n++){let r=e[n];if(!(r!=null&&r.container))continue;let o=r.container.querySelectorAll(`[${na}]`);for(let h of o){let l=h.getAttribute(na),c=this.namedStringPageCounterExprMap[l];if(!c)continue;let d=this.getPageCountersForOffset(c.offset),p=d?.[c.counterName];p&&(h.textContent=c.format(p))}let s=this.getPageCountersForPage(r,t?.[n]);if(!s)continue;let a=r.container.querySelectorAll(`[${Qn}]`);for(let h of a){let l=h.getAttribute(Qn),c=this.pageCounterExprs.find(g=>g.expr.key===l);if(!c)continue;let d=(i=c.expr)==null?void 0:i.str,p=d?.replace(/^page-counters?-/,""),f=s[p];f&&(h.textContent=c.format(f))}}}getUnresolvedRefsToPage(e){let t=[];Object.keys(e.elementsById).forEach(r=>{let o=this.unresolvedReferences[r];o&&(t=t.concat(o))}),t.sort((r,o)=>r.spineIndex-o.spineIndex||r.pageIndex-o.pageIndex);let i=[],n=null;return t.forEach(r=>{!n||n.spineIndex!==r.spineIndex||n.pageIndex!==r.pageIndex?(n={spineIndex:r.spineIndex,pageIndex:r.pageIndex,pageCounters:r.pageCounters,refs:[r]},i.push(n)):n.refs.push(r)}),i}pushReferencesToSolve(e){this.referencesToSolveStack.push(this.referencesToSolve),this.referencesToSolve=e}popReferencesToSolve(){this.referencesToSolve=this.referencesToSolveStack.pop()}registerPageCounterExpr(e,t,i){e==="pages"?this.pagesCounterExprs.push({expr:i,format:t}):this.pageCounterExprs.push({expr:i,format:t})}getPageCounterFormat(e){let t=this.pageCounterExprs.find(i=>i.expr===e);return t?t.format:null}getOrCreateNamedStringPageCounterExpr(e,t,i,n){for(let o in this.namedStringPageCounterExprMap){let s=this.namedStringPageCounterExprMap[o];if(s.offset===t&&s.counterName===i)return s.expr}let r=new we(e,()=>{let o=((t>=0?this.getPageCountersForOffset(t):null)||this.currentPageCounters)[i]||[];return n(o)},`named-string-page-counter-${i}`);return this.namedStringPageCounterExprMap[r.key]={expr:r,offset:t,counterName:i,format:n},r}registerTargetCounterExpr(e,t,i,n){this.targetCounterExprs.push({name:e,expr:i,format:t,transformedId:n})}registerTargetTextExpr(e,t,i){this.targetTextExprs.push({pseudoElement:e,expr:t,transformedId:i})}getExprContentListener(){return this.exprContentListener.bind(this)}exprContentListener(e,t,i){if(e instanceof we){if(e.str=="viv-leader"){let o=i.createElementNS("http://www.w3.org/1999/xhtml","span");return o.textContent=t,o.setAttribute("data-viv-leader",e.key),o.setAttribute("data-viv-leader-value",t),o}else if(e.str.startsWith("running-element-")){let o=t&&i.querySelectorAll(`[${Ht}="${t}"]`);if(!o||o.length===0)return null;let s=o[o.length-1].cloneNode(!0);return this.fixPageCounterInRunningElement(s),s.style.position="",s.style.visibility="",s}else if(e.str.startsWith("target-counter-")){let o=i.createElementNS("http://www.w3.org/1999/xhtml","span");return o.textContent=t,o.setAttribute(er,e.key),o}else if(e.str.startsWith("target-text-")){let o=i.createElementNS("http://www.w3.org/1999/xhtml","span");return o.textContent=t,o.setAttribute(ra,e.key),o}else if(e.str.startsWith("named-string-page-counter-")){let o=i.createElementNS("http://www.w3.org/1999/xhtml","span");return o.textContent=t,o.setAttribute(na,e.key),o}}let n=this.pagesCounterExprs.findIndex(o=>o.expr===e)>=0,r=!n&&this.pageCounterExprs.findIndex(o=>o.expr===e)>=0;if(n||r){let o=i.createElementNS("http://www.w3.org/1999/xhtml","span");return o.textContent=t,o.setAttribute(n?ia:Qn,e.key),o}else return null}fixPageCounterInRunningElement(e){let t=e.querySelectorAll(`[${Qn}]`);for(let r of t){let o=r.getAttribute(Qn),s=this.pageCounterExprs.find(c=>c.expr.key===o),a=(s?.expr).str,h=a?.replace(/^page-counters?-/,""),l=this.currentPageCounters[h];l&&(r.textContent=s.format(l))}let i=e.querySelectorAll(`[${er}]`);for(let r of i)r.setAttribute(Kh,!0);let n=e.querySelectorAll(`[${ra}]`);for(let r of n)r.setAttribute(Jh,!0)}finishLastPage(e){var t;let i=e.root.querySelectorAll(`[${ia}]`),n=e.contentContainer.childElementCount;for(let s of i){let a=s.getAttribute(ia),h=this.pagesCounterExprs.findIndex(l=>l.expr.key===a);h>=0,s.textContent=this.pagesCounterExprs[h].format([n])}let r=e.root.querySelectorAll(`[${Kh}]`);for(let s of r){let a=s.getAttribute(er),h=this.targetCounterExprs.find(l=>l.expr.key===a);if(h&&h.transformedId){let l=this.pageCountersById[h.transformedId];if(l){let c=l[h.name];c&&(s.textContent=h.format(c[c.length-1]))}}}let o=e.root.querySelectorAll(`[${Jh}]`);for(let s of o){let a=s.getAttribute(ra),h=this.targetTextExprs.find(l=>l.expr.key===a);if(h&&h.transformedId){let l=this.pageTextById[h.transformedId];l&&(s.textContent=(t=l[h.pseudoElement])!=null?t:"")}}}createLayoutConstraint(e){return new Jm(this,e)}},ia="data-vivliostyle-pages-counter",Qn="data-vivliostyle-page-counter",na="data-vivliostyle-named-string-page-counter",er="data-vivliostyle-target-counter",ra="data-vivliostyle-target-text",Kh="data-vivliostyle-target-counter-in-running",Jh="data-vivliostyle-target-text-in-running",Jm=class{constructor(e,t){u(this,"counterStore",e),u(this,"pageIndex",t)}allowLayout(e){if(!e||e.after)return!0;let t=e.viewNode;if(!t||t.nodeType!==1)return!0;let i=t.getAttribute("data-vivliostyle-id")||t.getAttribute("id")||t.getAttribute("name");if(!i||!this.counterStore.resolvedReferences[i]&&!this.counterStore.unresolvedReferences[i])return!0;let n=this.counterStore.pageIndicesById[i];return n?this.pageIndex>=n.pageIndex:!0}},Qm=new Set(["before","after","first-line","first-letter"]),Qh=new Set(["media","supports","-epubx-when"]),hd=new Set([";","}"]),ud=new Set(["{",";","}"]),ey=new Set([";","{","}"]),ty=":where(:scope)",iy=":where(:not(*))";function ny(e){let{statements:t,changed:i}=Aa(e,0,e.length,null);return i?t.join(`
5
+ `):e}function Aa(e,t,i,n){let r=[],o=[],s=!1,a=t,h=()=>{o.length!==0&&(n?r.push(ry(n,o)):r.push(cd(o)),o.length=0)};for(;a<i&&(a=Qi(e,a,i),!(a>=i||e[a]==="}"));){if(e[a]==="@"){let d=vy(e,a,i);if(!d)break;if(n&&!Qh.has(d.name)){o.push(Gi(e.slice(a,d.end))),a=d.end;continue}if(h(),d.hasBlock&&Qh.has(d.name)){let p=Aa(e,d.blockStart,d.blockEnd,n);s||(s=p.changed||n!=null),r.push(`${d.header} {${oy(p.statements)}}`)}else r.push(Gi(e.slice(a,d.end)));a=d.end;continue}if(n&&uy(e,a,i)){let d=py(e,a,i);if(!d)break;o.push(Gi(d.text)),a=d.end;continue}h();let l=fy(e,a,i);if(!l){let d=wy(e,a,i);r.push(Gi(d.text)),a=d.end;continue}if(n&&gy(e,a,l)){let d=yy(e,a,l.end,i);o.push(Gi(d.text)),a=d.end;continue}let c=n?sy(n,l.prelude):dd(l.prelude);if(c){s||(s=n!=null);let d=Aa(e,l.blockStart,l.blockEnd,c);s||(s=d.changed),d.statements.length===0?r.push(`${c} {}`):r.push(...d.statements)}a=l.end}return h(),{statements:r,changed:s}}function ry(e,t){return`${e} { ${cd(t)} }`}function cd(e){return e.map(t=>t.endsWith(";")?t:`${t};`).join(" ")}function oy(e){return e.length===0?"":` ${e.join(" ")} `}function sy(e,t){let i=ay(e);if(!i)return null;let n=fd(t,",").map(r=>r.trim()).filter(Boolean).map(r=>{let o=pd(r,i);return o.found?o.text:`${i} ${r}`}).filter(Boolean);return n.length===0?null:n.join(", ")}function dd(e){return pd(e.trim(),ty).text}function ay(e){let t=fd(e,",").map(i=>i.trim()).filter(Boolean).filter(i=>!ly(i));return t.length===0?null:`:is(${t.join(", ")})`}function ly(e){let t=0;for(;t<e.length;){let i=Rs(e,t);if(i!=null){t=i;continue}let n=rn(e,t,e.length);if(n!=null){t=n;continue}if(e[t]===":"){if(e[t+1]===":")return!0;let r=t+1,o=Zr(e,r,e.length),s=e.slice(r,o).toLowerCase();if(Qm.has(s))return!0;t=o;continue}t++}return!1}function pd(e,t){let i=0,n=!1,r="",o=[],s=hy(t);for(;i<e.length;){let a=Rs(e,i);if(a!=null){r+=e.slice(i,a),i=a;continue}let h=rn(e,i,e.length);if(h!=null){r+=e.slice(i,h),i=h;continue}let l=e[i];if(l===":"&&e[i+1]!==":"){let c=i+1,d=Zr(e,c,e.length);if(d>c&&e[d]==="("){o.push(e.slice(c,d).toLowerCase()),r+=e.slice(i,d+1),i=d+1;continue}}if(l==="("){o.push(""),r+=l,i++;continue}if(l===")"){o.pop(),r+=l,i++;continue}if(l==="&"){r+=s&&o.includes("has")?iy:t,n=!0,i++;continue}r+=l,i++}return{text:r,found:n}}function hy(e){let t=0;for(;t<e.length;){let i=Rs(e,t);if(i!=null){t=i;continue}let n=rn(e,t,e.length);if(n!=null){t=n;continue}if(e[t]===":"&&e[t+1]!==":"){let r=t+1,o=Zr(e,r,e.length);if(o>r&&e.slice(r,o).toLowerCase()==="has"&&e[o]==="(")return!0;t=o;continue}t++}return!1}function fd(e,t){let i=[],n=0,r=0,o=0,s=0;for(;r<e.length;){let a=Rs(e,r);if(a!=null){r=a;continue}let h=rn(e,r,e.length);if(h!=null){r=h;continue}let l=e[r];switch(l){case"(":o++;break;case")":o=Math.max(0,o-1);break;case"[":s++;break;case"]":s=Math.max(0,s-1);break;default:o===0&&s===0&&l===t&&(i.push(e.slice(n,r)),n=r+1);break}r++}return i.push(e.slice(n)),i}function uy(e,t,i){let n=t,r=dy(e,n,i);if(r<=n)return!1;let o=Qi(e,r,i);if(o>=i||e[o]!==":")return!1;let s=Kr(e,o+1,i,ey);return s?.char==="{"?!cy(e,t,r,o,s.index):!0}function cy(e,t,i,n,r){if(Qi(e,i,r)!==n)return!1;let o=Qi(e,n+1,r);if(o!==n+1||o>=r)return!1;let s=e[o];return s===":"||s==="\\"||/[A-Za-z_-]/.test(s)}function dy(e,t,i){let n=t;return e[n]==="-"&&(n++,n<i&&e[n]==="-"&&n++),Zr(e,n,i)}function Zr(e,t,i){let n=t;for(;n<i;){let r=e[n];if(r==="\\"){n+=2;continue}if(!/[0-9A-Za-z_-]/.test(r))break;n++}return n}function py(e,t,i){let n=Kr(e,t,i,hd);if(!n){let o=e.slice(t,i).trim();return o?{text:o,end:i}:null}let r=n.char===";"?n.index+1:n.index;return{text:e.slice(t,r).trim(),end:r}}function fy(e,t,i){let n=Kr(e,t,i,ud);if(!n||n.char!=="{")return null;let r=gd(e,n.index,i);return r<0?null:{prelude:Gi(e.slice(t,n.index)),blockStart:n.index+1,blockEnd:r,end:r+1}}function gy(e,t,i){if(!my(e,t,i.blockStart-1))return!0;let n=Qi(e,i.blockStart,i.blockEnd);return n<i.blockEnd&&e[n]===";"}function my(e,t,i){let n=Qi(e,t,i);if(n>=i)return!1;let r=e[n];return r==="&"||r==="."||r==="#"||r===":"||r==="["||r==="|"||r==="*"||r===">"||r==="+"||r==="~"||r==="\\"||/[A-Za-z_-]/.test(r)}function yy(e,t,i,n){let r=Qi(e,i,n),o=r<n&&e[r]===";"?r+1:i;return{text:e.slice(t,o),end:o}}function vy(e,t,i){let n=Kr(e,t,i,ud);if(!n)return null;let r=Zr(e,t+1,i),o=e.slice(t+1,r).toLowerCase(),s=Gi(e.slice(t,n.index));if(n.char!=="{")return{name:o,header:s,hasBlock:!1,blockStart:-1,blockEnd:-1,end:n.index+(n.char===";"?1:0)};let a=gd(e,n.index,i);return a<0?null:{name:o,header:s,hasBlock:!0,blockStart:n.index+1,blockEnd:a,end:a+1}}function wy(e,t,i){let n=Kr(e,t,i,hd);if(!n)return{text:e.slice(t,i),end:i};let r=n.char===";"?n.index+1:n.index;return{text:e.slice(t,r),end:r}}function Kr(e,t,i,n){let r=t,o=0,s=0,a=0;for(;r<i;){let h=rn(e,r,i);if(h!=null){r=h;continue}let l=e[r];switch(l){case"(":o++;break;case")":o=Math.max(0,o-1);break;case"[":s++;break;case"]":s=Math.max(0,s-1);break;case"{":if(o===0&&s===0&&a===0&&n.has(l))return{index:r,char:l};a++;break;case"}":if(o===0&&s===0&&a===0&&n.has(l))return{index:r,char:l};a=Math.max(0,a-1);break;default:if(o===0&&s===0&&a===0&&n.has(l))return{index:r,char:l};break}r++}return null}function gd(e,t,i){let n=t+1,r=1;for(;n<i;){let o=rn(e,n,i);if(o!=null){n=o;continue}let s=e[n];if(s==="{")r++;else if(s==="}"&&(r--,r===0))return n;n++}return-1}function Qi(e,t,i){let n=t;for(;n<i;){let r=e[n];if(yd(r)){n++;continue}if(r==="/"&&e[n+1]==="*"){n=md(e,n,i);continue}break}return n}function md(e,t,i){let n=e.indexOf("*/",t+2);return n<0||n+2>i?i:n+2}function rn(e,t,i){let n=e[t];return n==='"'||n==="'"?by(e,t):n==="/"&&e[t+1]==="*"?md(e,t,i):null}function Rs(e,t){return e[t]!=="\\"?null:t+1>=e.length?e.length:t+2}function by(e,t){let i=e[t],n=t+1;for(;n<e.length;){let r=e[n];if(r==="\\"){n+=2;continue}if(r===i)return n+1;n++}return e.length}function yd(e){return e===" "||e===`
6
+ `||e==="\r"||e===" "||e==="\f"}function Gi(e){let t="",i=0,n=!1;for(;i<e.length;){let r=rn(e,i,e.length);if(r!=null&&e[i]!=="/"){n&&t.length>0&&(t+=" ",n=!1),t+=e.slice(i,r),i=r;continue}if(r!=null){n=t.length>0,i=r;continue}let o=e[i];if(yd(o)){n=t.length>0,i++;continue}n&&t.length>0&&(t+=" ",n=!1),t+=o,i++}return t}function xy(e){if(e=e.substr(1),e.match(/^[^0-9a-fA-F\n\r]$/))return e;let t=parseInt(e,16);return isNaN(t)?"":t===0||t>=55296&&t<=57343||t>1114111?"\uFFFD":String.fromCodePoint(t)}function xi(e){return e.replace(/\\([0-9a-fA-F]{1,6}(\r\n|[ \n\r\t\f])?|[^0-9a-fA-F\n\r])/g,xy)}var Sy=class{constructor(){u(this,"type"),u(this,"precededBySpace",!1),u(this,"num",0),u(this,"text",""),u(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 et(e,t){let i=Array(128),n;for(n=0;n<128;n++)i[n]=e;for(i[NaN]=e==35?35:72,n=0;n<t.length;n+=2)i[t[n]]=t[n+1];return i}var ei=[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];ei[NaN]=80;var ti=[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];ti[NaN]=43;var Cy=[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];ti[NaN]=43;var vd=[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];vd[NaN]=35;var wd=[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];wd[NaN]=45;var Ia=[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];Ia[NaN]=37;var Fa=[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];Fa[NaN]=38;var Mi=et(35,[61,36]),ky=et(35,[58,77]),Ey=et(35,[61,36,124,50]),Py=et(35,[38,51]),Ny=et(35,[42,54]),Ty=et(39,[42,55]),Ay=et(54,[42,55,47,56]),Iy=et(62,[62,82]),Fy=et(35,[61,36,33,70]),Ry=et(62,[45,71]),Ly=et(63,[45,81]),oa=et(76,[10,72,13,72]),Oy=et(39,[39,46,10,72,13,72,92,48]),By=et(39,[34,46,10,72,13,72,92,49]),My=et(39,[39,47,10,74,13,74,92,48]),_y=et(39,[34,47,10,74,13,74,92,49]),eu=et(64,[9,39,32,39,34,66,39,65,41,72,10,39,13,39]),Dy=et(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]),zy=et(39,[39,68,10,74,13,74,92,75,NaN,67]),Vy=et(39,[34,68,10,74,13,74,92,75,NaN,67]),Uy=et(72,[9,39,10,39,13,39,32,39,41,69]),$y=15,xt=class{constructor(e,t){u(this,"input",e),u(this,"handler",t),u(this,"indexMask"),u(this,"buffer"),u(this,"tail",0),u(this,"curr",0),u(this,"position",0),this.indexMask=$y,this.buffer=Array(this.indexMask+1);for(let i=0;i<=this.indexMask;i++)this.buffer[i]=new Sy}token(){return this.tail==this.curr&&this.fillBuffer(),this.buffer[this.curr]}nthToken(e){return(this.tail-this.curr&this.indexMask)<=e&&this.fillBuffer(),this.buffer[this.curr+e&this.indexMask]}consume(){this.curr=this.curr+1&this.indexMask}fillBuffer(){let e=this.tail,t=this.curr,i=this.indexMask;if(e>=t?t+=i:t--,t==e)throw new Error("F_CSSTOK_INTERNAL");let n=ei,r=this.input,o=this.position,s=this.buffer,a=0,h=0,l="",c=0,d=!1,p=s[e],f=-9;for(;;){let g=r.charCodeAt(o);switch(n[g]||n[65]){case 72:isNaN(g)?(l=r.substring(h,o),a=0):n===ei&&a===0?(a=54,h=o,l=r.substring(o,o+1),o++):(l=r.substring(h,o),a=54),n=ei;break;case 1:o++,d=!0;continue;case 2:h=o++,n=Ia;continue;case 3:a=1,h=o++,n=ti;continue;case 4:h=o++,a=31,n=Mi;continue;case 33:a=2,h=++o,n=Oy;continue;case 34:a=2,h=++o,n=By;continue;case 6:h=++o,a=7,n=ti;continue;case 7:h=o++,a=32,n=Mi;continue;case 8:h=o++,a=21;break;case 9:h=o++,a=32,n=Py;continue;case 10:h=o++,a=10;break;case 11:h=o++,a=11;break;case 12:h=o++,a=36,n=Mi;continue;case 13:h=o++,a=23;break;case 14:h=o++,a=16;break;case 15:a=24,h=o++,n=vd;continue;case 16:h=o++,n=Cy;continue;case 78:h=o++,a=9,n=ti;continue;case 17:h=o++,a=19,n=Ny;continue;case 18:h=o++,a=18,n=ky;continue;case 77:o++,a=50;break;case 19:h=o++,a=17;break;case 20:h=o++,a=38,n=Fy;continue;case 21:h=o++,a=39,n=Mi;continue;case 22:h=o++,a=37,n=Mi;continue;case 23:h=o++,a=22;break;case 24:h=++o,a=20,n=ti;continue;case 25:h=o++,a=14;break;case 26:h=o++,a=15;break;case 27:h=o++,a=12;break;case 28:h=o++,a=13;break;case 29:h=o++,f=h,a=1,n=oa;continue;case 30:h=o++,a=33,n=Mi;continue;case 31:h=o++,a=34,n=Ey;continue;case 32:h=o++,a=35,n=Mi;continue;case 35:break;case 36:o++,a=a+41-31;break;case 37:a=5,c=parseInt(r.substring(h,o),10);break;case 38:a=4,c=parseFloat(r.substring(h,o));break;case 39:o++;continue;case 40:a=3,c=parseFloat(r.substring(h,o)),h=o++,n=ti;continue;case 41:a=3,c=parseFloat(r.substring(h,o)),l="%",h=o++;break;case 42:o++,n=Fa;continue;case 43:if(l=xi(r.substring(h,o)),a===27&&g===63||a===1&&l.toLowerCase()==="u"&&/^(\bu\+[?0-9a-f]+(-[?0-9a-f]+)?|,|\s+|\/\*([^*]|\*[^/])*\*\/)+[;}]/i.test(r.substring(o-1))){a=27,o++;continue}break;case 44:f=o++,n=oa;continue;case 45:l=xi(r.substring(h,o));break;case 46:l=r.substring(h,o),o++;break;case 47:l=xi(r.substring(h,o)),o++;break;case 48:f=o,o+=2,n=My;continue;case 49:f=o,o+=2,n=_y;continue;case 50:o++,a=25;break;case 51:o++,a=26;break;case 52:if(l=r.substring(h,o),a==1){if(o++,l.toLowerCase()=="url"){n=eu;continue}a=6}break;case 53:if(l=xi(r.substring(h,o)),a==1){if(o++,l.toLowerCase()=="url"){n=eu;continue}a=6}break;case 54:n=Ty,o++;continue;case 55:n=Ay,o++;continue;case 56:n=ei,o++;continue;case 57:n=Iy,o++,r[o]!==">"&&(a=1,n=ti);continue;case 81:a=51,l=r.substring(h,++o),n=ei;break;case 82:a=52,l=r.substring(h,++o),n=ei;break;case 58:a=5,n=Ia,o++;continue;case 59:a=4,n=Fa,o++;continue;case 60:a=1,n=ti,o++;continue;case 61:a=1,n=oa,f=o++;continue;case 62:o--;break;case 63:o-=2;break;case 64:h=o++,n=Dy;continue;case 65:h=++o,n=zy;continue;case 66:h=++o,n=Vy;continue;case 67:a=8,l=xi(r.substring(h,o)),o++;break;case 69:o++;break;case 70:n=Ry,o++;continue;case 71:n=Ly,o++;continue;case 79:if(o-f<8&&r.substring(f+1,o+1).match(/^[0-9a-fA-F]{0,6}(\r\n|[\n\r])|[ \t]$/)){o++;continue}case 68:a=8,l=xi(r.substring(h,o)),o++,n=Uy;continue;case 74:if(o++,o-f<9&&r.substring(f+1,o).match(/^[0-9a-fA-F]{0,6}(\r\n|[\n\r])$/))continue;a=54,l="E_CSS_UNEXPECTED_NEWLINE",n=ei;break;case 73:if(o-f<9&&r.substring(f+1,o+1).match(/^[0-9a-fA-F]{0,6}[ \t]$/)){o++,n=ti;continue}l=xi(r.substring(h,o));break;case 75:f=o++;continue;case 76:o++,n=wd;continue;default:if(n!==ei){a=54,l="E_CSS_UNEXPECTED_STATE";break}h=o,a=0}if(p.type=a,p.precededBySpace=d,p.num=c,p.text=l,p.position=h,e++,e>=t)break;n=ei,d=!1,a=0,h=o,l="",c=0,p=s[e&i]}this.position=o,this.tail=e&i}},Ye=null,Ra=null;function La(){return Ye}function M(e){if(!Ye)throw new Error("E_TASK_NO_CONTEXT");Ye.name||(Ye.name=e);let t=Ye,i=new Ls(t,t.top,e);return t.top=i,i.state=1,i}function Hy(e){return new jy(e||new Gy)}function T(e){return new Oa(e)}function _n(e,t,i){let n=M(e);n.handler=i;try{t(n)}catch(r){n.task.raise(r,n)}return n.result()}function Wy(e,t){return(Ye?Ye.getScheduler():Ra||Hy()).run(e,t)}var Gy=class{currentTime(){return new Date().valueOf()}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}},jy=class{constructor(e){u(this,"timer",e),u(this,"timeout",1),u(this,"slice",25),u(this,"sliceOverTime",0),u(this,"queue"),u(this,"wakeupTime",null),u(this,"timeoutToken",null),u(this,"inTimeSlice",!1),u(this,"order",0),this.queue=new Qg,Ra||(Ra=this)}setSlice(e){this.slice=e}setTimeout(e){this.timeout=e}isTimeSliceOver(){return this.timer.currentTime()>=this.sliceOverTime}arm(){if(this.inTimeSlice)return;let e=this.queue.peek().scheduledTime,t=this.timer.currentTime();if(this.timeoutToken!=null){if(t+this.timeout>this.wakeupTime)return;this.timer.clearTimeout(this.timeoutToken)}let i=e-t;i<=this.timeout&&(i=this.timeout),this.wakeupTime=t+i,this.timeoutToken=this.timer.setTimeout(()=>{this.timeoutToken=null,this.doTimeSlice()},i)}schedule(e,t){let i=e,n=this.timer.currentTime();i.order=this.order++,i.scheduledTime=n+(t||0),this.queue.add(i),this.arm()}doTimeSlice(){this.timeoutToken!=null&&(this.timer.clearTimeout(this.timeoutToken),this.timeoutToken=null),this.inTimeSlice=!0;try{let e=this.timer.currentTime();for(this.sliceOverTime=e+this.slice;this.queue.length();){let t=this.queue.peek();if(t.scheduledTime>e||(this.queue.remove(),t.canceled||t.resumeInternal(),e=this.timer.currentTime(),e>=this.sliceOverTime))break}}catch(e){Y.error(e)}this.inTimeSlice=!1,this.queue.length()&&this.arm()}run(e,t){let i=new Xy(this,t||"");i.top=new Ls(i,null,"bootstrap"),i.top.state=1,i.top.then(()=>{let r=()=>{i.running=!1;for(let o of i.callbacks)try{o()}catch(s){Y.error(s)}};try{e().then(o=>{i.result=o,r()})}catch(o){i.raise(o),r()}});let n=Ye;return Ye=i,this.schedule(i.top.suspend("bootstrap")),Ye=n,i}},bd=class{constructor(e){u(this,"task",e),u(this,"scheduledTime",0),u(this,"order",0),u(this,"result",null),u(this,"canceled",!1)}compare(e){let t=e;return t.scheduledTime-this.scheduledTime||t.order-this.order}getTask(){return this.task}schedule(e,t){this.result=e,this.task.scheduler.schedule(this,t)}resumeInternal(){let e=this.task;if(this.task=null,e&&e.continuation==this){e.continuation=null;let t=Ye;return Ye=e,e.top.finish(this.result),Ye=t,!0}return!1}cancel(){this.canceled=!0}},Xy=class{constructor(e,t){u(this,"scheduler",e),u(this,"name",t),u(this,"callbacks",[]),u(this,"exception",null),u(this,"running",!0),u(this,"result",null),u(this,"waitTarget",null),u(this,"top",null),u(this,"continuation",null)}getName(){return this.name}interrupt(e){if(this.raise(e||new Error("E_TASK_INTERRUPT")),this!==Ye&&this.continuation){this.continuation.cancel();let t=new bd(this);this.waitTarget="interrupt",this.continuation=t,this.scheduler.schedule(t)}}getScheduler(){return this.scheduler}isRunning(){return this.running}whenDone(e){this.callbacks.push(e)}join(){let e=M("Task.join");if(!this.running)e.finish(this.result);else{let t=e.suspend(this);this.whenDone(()=>{t.schedule(this.result)})}return e.result()}unwind(){for(;this.top&&!this.top.handler;)this.top=this.top.parent;if(this.top&&this.top.handler&&this.exception){let e=this.exception;this.exception=null,this.top.handler(this.top,e)}else this.exception&&Y.error(this.exception,"Unhandled exception in task",this.name)}raise(e,t){if(this.fillStack(e),t){let i=this.top;for(;i&&i!=t;)i=i.parent;i==t&&(this.top=i)}this.exception=e,this.unwind()}fillStack(e){let t=e.frameTrace;if(!t){t=e.stack?`${e.stack}
7
7
  ---- async ---
8
8
  `:"";for(let i=this.top;i;i=i.parent)t+=" ",t+=i.getName(),t+=`
9
- `;e.frameTrace=t}}},Oa=class xd{constructor(t){u(this,"value",t)}then(t){t(this.value)}thenAsync(t){return t(this.value)}thenReturn(t){return new xd(t)}thenFinish(t){t.finish(this.value)}isPending(){return!1}get(){return this.value}},qy=class{constructor(e){u(this,"frame",e)}then(e){this.frame.then(e)}thenAsync(e){if(this.isPending()){let t=new Ls(this.frame.task,this.frame.parent,"AsyncResult.thenAsync");return t.state=1,this.frame.parent=t,this.frame.then(i=>{e(i).then(n=>{t.finish(n)})}),t.result()}else return e(this.frame.res)}thenReturn(e){return this.isPending()?this.thenAsync(()=>new Oa(e)):new Oa(e)}thenFinish(e){this.isPending()?this.then(t=>{e.finish(t)}):e.finish(this.frame.res)}isPending(){return this.frame.state==1}get(){if(this.isPending())throw new Error("Result is pending");return this.frame.res}},Ls=class{constructor(e,t,i){u(this,"task",e),u(this,"parent",t),u(this,"name",i),u(this,"res",null),u(this,"state"),u(this,"callback",null),u(this,"handler",null),this.state=0}checkEnvironment(){if(!Ye)throw new Error("F_TASK_NO_CONTEXT");if(this!==Ye.top)throw new Error("F_TASK_NOT_TOP_FRAME")}result(){return new qy(this)}finish(e){this.checkEnvironment(),Ye&&!Ye.exception&&(this.res=e),this.state=2;let t=this.parent;if(Ye&&(Ye.top=t),this.callback){try{this.callback(e)}catch(i){this.task.raise(i,t)}this.state=3}}getTask(){return this.task}getName(){return this.name}getScheduler(){return this.task.scheduler}then(e){switch(this.state){case 1:if(this.callback)throw new Error("F_TASK_FRAME_ALREADY_HAS_CALLBACK");this.callback=e;break;case 2:{let t=this.task,i=this.parent;try{e(this.res),this.state=3}catch(n){this.state=3,t.raise(n,i)}break}case 3:throw new Error("F_TASK_DEAD_FRAME");default:throw new Error(`F_TASK_UNEXPECTED_FRAME_STATE ${this.state}`)}}timeSlice(){let e=M("Frame.timeSlice");return e.getScheduler().isTimeSliceOver()?(Y.debug("-- time slice --"),e.suspend().schedule(!0)):e.finish(!0),e.result()}sleep(e){let t=M("Frame.sleep");return t.suspend().schedule(!0,e),t.result()}loop(e){let t=M("Frame.loop"),i=n=>{try{for(;n;){let o=e();if(o.isPending()){o.then(i);return}else o.then(r=>{n=r})}t.finish(!0)}catch(o){t.task.raise(o,t)}};return i(!0),t.result()}loopWithFrame(e){let t=Ye;if(!t)throw new Error("E_TASK_NO_CONTEXT");return this.loop(()=>{let i;do{let n=new Yy(t,t.top);t.top=n,n.state=1,e(n),i=n.result()}while(!i.isPending()&&i.get());return i})}suspend(e){if(this.checkEnvironment(),this.task.continuation)throw new Error("E_TASK_ALREADY_SUSPENDED");let t=new bd(this.task);return this.task.continuation=t,Ye=null,this.task.waitTarget=e||null,t}},Yy=class extends Ls{constructor(e,t){super(e,t,"loop")}continueLoop(){this.finish(!0)}breakLoop(){this.finish(!1)}},Qo=class{constructor(e,t){u(this,"fetch",e),u(this,"name"),u(this,"arrived",!1),u(this,"resource",null),u(this,"task",null),u(this,"piggybacks",[]),this.name=t}start(){this.task||(this.task=La().getScheduler().run(()=>{let e=M("Fetcher.run");return this.fetch().then(t=>{let i=this.piggybacks;if(this.arrived=!0,this.resource=t,this.task=null,this.piggybacks=[],i)for(let n=0;n<i.length;n++)try{i[n](t)}catch(o){Y.error(o,"Error:")}e.finish(t)}),e.result()},this.name))}piggyback(e){this.arrived?e(this.resource):this.piggybacks.push(e)}get(){return this.arrived?T(this.resource):(this.start(),this.task.join())}hasArrived(){return this.arrived}},Dn=e=>{if(e.length==0)return T(!0);if(e.length==1)return e[0].get().thenReturn(!0);let t=M("waitForFetches"),i=0;return t.loop(()=>{for(;i<e.length;){let n=e[i++];if(!n.hasArrived())return n.get().thenReturn(!0)}return T(!1)}).then(()=>{t.finish(!0)}),t.result()},Sd=`
9
+ `;e.frameTrace=t}}},Oa=class xd{constructor(t){u(this,"value",t)}then(t){t(this.value)}thenAsync(t){return t(this.value)}thenReturn(t){return new xd(t)}thenFinish(t){t.finish(this.value)}isPending(){return!1}get(){return this.value}},qy=class{constructor(e){u(this,"frame",e)}then(e){this.frame.then(e)}thenAsync(e){if(this.isPending()){let t=new Ls(this.frame.task,this.frame.parent,"AsyncResult.thenAsync");return t.state=1,this.frame.parent=t,this.frame.then(i=>{e(i).then(n=>{t.finish(n)})}),t.result()}else return e(this.frame.res)}thenReturn(e){return this.isPending()?this.thenAsync(()=>new Oa(e)):new Oa(e)}thenFinish(e){this.isPending()?this.then(t=>{e.finish(t)}):e.finish(this.frame.res)}isPending(){return this.frame.state==1}get(){if(this.isPending())throw new Error("Result is pending");return this.frame.res}},Ls=class{constructor(e,t,i){u(this,"task",e),u(this,"parent",t),u(this,"name",i),u(this,"res",null),u(this,"state"),u(this,"callback",null),u(this,"handler",null),this.state=0}checkEnvironment(){if(!Ye)throw new Error("F_TASK_NO_CONTEXT");if(this!==Ye.top)throw new Error("F_TASK_NOT_TOP_FRAME")}result(){return new qy(this)}finish(e){this.checkEnvironment(),Ye&&!Ye.exception&&(this.res=e),this.state=2;let t=this.parent;if(Ye&&(Ye.top=t),this.callback){try{this.callback(e)}catch(i){this.task.raise(i,t)}this.state=3}}getTask(){return this.task}getName(){return this.name}getScheduler(){return this.task.scheduler}then(e){switch(this.state){case 1:if(this.callback)throw new Error("F_TASK_FRAME_ALREADY_HAS_CALLBACK");this.callback=e;break;case 2:{let t=this.task,i=this.parent;try{e(this.res),this.state=3}catch(n){this.state=3,t.raise(n,i)}break}case 3:throw new Error("F_TASK_DEAD_FRAME");default:throw new Error(`F_TASK_UNEXPECTED_FRAME_STATE ${this.state}`)}}timeSlice(){let e=M("Frame.timeSlice");return e.getScheduler().isTimeSliceOver()?(Y.debug("-- time slice --"),e.suspend().schedule(!0)):e.finish(!0),e.result()}sleep(e){let t=M("Frame.sleep");return t.suspend().schedule(!0,e),t.result()}loop(e){let t=M("Frame.loop"),i=n=>{try{for(;n;){let r=e();if(r.isPending()){r.then(i);return}else r.then(o=>{n=o})}t.finish(!0)}catch(r){t.task.raise(r,t)}};return i(!0),t.result()}loopWithFrame(e){let t=Ye;if(!t)throw new Error("E_TASK_NO_CONTEXT");return this.loop(()=>{let i;do{let n=new Yy(t,t.top);t.top=n,n.state=1,e(n),i=n.result()}while(!i.isPending()&&i.get());return i})}suspend(e){if(this.checkEnvironment(),this.task.continuation)throw new Error("E_TASK_ALREADY_SUSPENDED");let t=new bd(this.task);return this.task.continuation=t,Ye=null,this.task.waitTarget=e||null,t}},Yy=class extends Ls{constructor(e,t){super(e,t,"loop")}continueLoop(){this.finish(!0)}breakLoop(){this.finish(!1)}},Jr=class{constructor(e,t){u(this,"fetch",e),u(this,"name"),u(this,"arrived",!1),u(this,"resource",null),u(this,"task",null),u(this,"piggybacks",[]),this.name=t}start(){this.task||(this.task=La().getScheduler().run(()=>{let e=M("Fetcher.run");return this.fetch().then(t=>{let i=this.piggybacks;if(this.arrived=!0,this.resource=t,this.task=null,this.piggybacks=[],i)for(let n=0;n<i.length;n++)try{i[n](t)}catch(r){Y.error(r,"Error:")}e.finish(t)}),e.result()},this.name))}piggyback(e){this.arrived?e(this.resource):this.piggybacks.push(e)}get(){return this.arrived?T(this.resource):(this.start(),this.task.join())}hasArrived(){return this.arrived}},Dn=e=>{if(e.length==0)return T(!0);if(e.length==1)return e[0].get().thenReturn(!0);let t=M("waitForFetches"),i=0;return t.loop(()=>{for(;i<e.length;){let n=e[i++];if(!n.hasArrived())return n.get().thenReturn(!0)}return T(!1)}).then(()=>{t.finish(!0)}),t.result()},Sd=`
10
10
  @media screen {
11
11
  [data-vivliostyle-viewer-viewport] {
12
12
  background: #aaaaaa;
@@ -1870,12 +1870,12 @@ span[data-viv-leader] {
1870
1870
  @counter-style upper-russian {
1871
1871
  system: alphabetic;
1872
1872
  symbols: \u0410 \u0411 \u0412 \u0413 \u0414 \u0415 \u0416 \u0417 \u0418 \u041A \u041B \u041C \u041D \u041E \u041F \u0420 \u0421 \u0422 \u0423 \u0424 \u0425 \u0426 \u0427 \u0428 \u0429 \u042D \u042E \u042F;
1873
- }`;function Os(e,t,i){let n=M("fetchFromURL"),o={method:i||"GET",mode:"cors"},r=n.suspend(),s={status:0,statusText:"",url:e,contentType:null,responseText:null,responseXML:null,responseBlob:null};return fetch(e,o).then(a=>{var h;if(s.status=a.status,s.url=a.url,s.statusText=a.statusText,s.contentType=(h=a.headers.get("Content-Type"))==null?void 0:h.replace(/;.*$/,"").toLowerCase(),!a.ok)throw new Error(`HTTP ${a.status}${a.statusText?` ${a.statusText}`:""}`);return t==="blob"?a.blob():t==="arraybuffer"?a.arrayBuffer():t==="json"?a.json():/\/aozorabunko\/[^/]+\/cards\/[^/]+\/files\/[^/.]+\.html$/.test(e)?(s.contentType="text/html",a.arrayBuffer().then(l=>new TextDecoder("Shift_JIS").decode(l))):(/^data:,(<|%3c)/i.test(e)&&(s.contentType="text/html"),a.text())}).then(a=>{t==="blob"&&a instanceof Blob?s.responseBlob=a:t==="arraybuffer"&&a instanceof ArrayBuffer?s.responseBlob=Fd([a]):t==="json"?s.responseText=JSON.stringify(a):typeof a=="string"&&(s.responseText=a),r.schedule(s)}).catch(a=>{s.status>=400?Y.warn(`Error fetching ${e} (${s.status}${s.statusText?" "+s.statusText:""})`):Y.warn(a,`Error fetching ${e}`),r.schedule(s)}),n.result()}function Fd(e,t){let i=t||"application/octet-stream";return new Blob(e,{type:i})}function Zy(e){let t=M("readBlob"),i=new FileReader,n=t.suspend(i);return i.addEventListener("load",()=>{n.schedule(i.result)},!1),i.readAsArrayBuffer(e),t.result()}function Ky(e){return URL.createObjectURL(e)}var Bl=class{constructor(e,t){u(this,"parser",e),u(this,"type",t),u(this,"resources",{}),u(this,"fetchers",{})}load(e,t,i){e=pt(e);let n=this.resources[e];return typeof n<"u"?T(n):this.fetch(e,t,i).get()}fetchInner(e,t,i){let n=M("fetch"),o=As(e);o&&(e=dn(e));let r=Ae("user-agent.xml",Ni),s=!o&&e===r;return s&&(e=`data:application/xml,${encodeURIComponent(Ed)}`),Os(e,this.type).then(a=>{if(a.status>=400&&t)throw new Error((i||`Failed to fetch required resource: ${e}`)+` (${a.status}${a.statusText?" "+a.statusText:""})`);o?(e=xa(e),a.url=xa(a.url)):s&&(a.url=e=r),this.parser(a,this).then(h=>{delete this.fetchers[e],this.resources[e]=h,n.finish(h)})}),n.result()}fetch(e,t,i){if(e=pt(e),this.resources[e])return null;let n=this.fetchers[e];return n||(n=new Qo(()=>this.fetchInner(e,t,i),`Fetch ${e}`),this.fetchers[e]=n,n.start()),n}get(e){return this.resources[pt(e)]}delete(e){delete this.resources[pt(e)]}};function Jy(e,t){let i=e.responseText;return T(i?kl(i):null)}function Qy(){return new Bl(Jy,"text")}function Et(e,t,i){let n=new Qo(()=>{let o=M("loadElement"),r=o.suspend(e),s=!1,a=null,h=l=>{s||(s=!0,a!==null&&(clearTimeout(a),a=null),r.schedule(l?l.type:"timeout"))};if(e.addEventListener("load",h,!1),e.addEventListener("error",h,!1),e.addEventListener("abort",h,!1),e.namespaceURI=="http://www.w3.org/2000/svg")t&&e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",t),a=setTimeout(h,300);else if(e.localName==="script")a=setTimeout(h,3e3);else if(t)if(e.localName==="img"){let l=e;l.loading==="lazy"&&(l.loading="eager"),l.src=t,i&&(l.alt=i),l.complete?setTimeout(()=>h(new Event("load")),0):a=setTimeout(h,3e4)}else e.src=t,i&&(e.alt=i);else(e.localName==="img"||e.localName==="embed"||e.localName==="object"||e.localName==="iframe")&&(e.complete?setTimeout(()=>h(new Event("load")),0):a=setTimeout(h,3e4));return o.result()},`loadElement ${t||e.localName}`);return n.start(),n}var tu=0,ev=16777216,Rd=33554432,Ld=50331648,Od=67108864,tv=83886080,iv=100663296,Bs=class{constructor(e){u(this,"scope",e),u(this,"flavor"),this.flavor="Author"}getCurrentToken(){return null}getScope(){return this.scope}error(e,t){}startStylesheet(e){this.flavor=e}tagSelector(e,t){}classSelector(e){}pseudoclassSelector(e,t){}pseudoelementSelector(e,t){}idSelector(e){}attributeSelector(e,t,i,n,o){}descendantSelector(){}childSelector(){}adjacentSiblingSelector(){}followingSiblingSelector(){}nextSelector(){}startSelectorRule(){}startFontFaceRule(){}startCounterStyleRule(e){}startFootnoteRule(e){}startViewportRule(){}startDefineRule(){}startRegionRule(){}startPageRule(){}startPageMarginBoxRule(e){}startWhenRule(e){}startMediaRule(e){this.startWhenRule(e)}startFlowRule(e){}startPageTemplateRule(){}startPageMasterRule(e,t,i){}startPartitionRule(e,t,i){}startPartitionGroupRule(e,t,i){}startRuleBody(){}property(e,t,i){}endRule(){}startFuncWithSelector(e,t){}endFuncWithSelector(){}pushSelectorText(e){}getImportantSpecificity(){switch(this.flavor){case"UA":return tu;case"User":return iv;default:return tv}}getBaseSpecificity(){switch(this.flavor){case"UA":return tu;case"User":return ev;default:return Rd}}},Ba=class extends Bs{constructor(){super(null),u(this,"stack",[]),u(this,"tokenizer",null),u(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,t){this.slave.error(e,t)}errorMsg(e,t){var i;Y.warn(e,(i=t?.toString())!=null?i:"")}startStylesheet(e){super.startStylesheet(e),this.stack.length>0&&(this.slave=this.stack[0],this.stack=[]),this.slave.startStylesheet(e)}tagSelector(e,t){this.slave.tagSelector(e,t)}classSelector(e){this.slave.classSelector(e)}pseudoclassSelector(e,t){this.slave.pseudoclassSelector(e,t)}pseudoelementSelector(e,t){this.slave.pseudoelementSelector(e,t)}idSelector(e){this.slave.idSelector(e)}attributeSelector(e,t,i,n,o){this.slave.attributeSelector(e,t,i,n,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()}startCounterStyleRule(e){this.slave.startCounterStyleRule(e)}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,t,i){this.slave.startPageMasterRule(e,t,i)}startPartitionRule(e,t,i){this.slave.startPartitionRule(e,t,i)}startPartitionGroupRule(e,t,i){this.slave.startPartitionGroupRule(e,t,i)}startRuleBody(){this.slave.startRuleBody()}property(e,t,i){this.slave.property(e,t,i)}endRule(){this.slave.endRule()}startFuncWithSelector(e,t){this.slave.startFuncWithSelector(e,t)}endFuncWithSelector(){this.slave.endFuncWithSelector()}pushSelectorText(e){this.slave.pushSelectorText(e)}},iu=class extends Bs{constructor(e,t,i){super(e),u(this,"owner",t),u(this,"topLevel",i),u(this,"depth",0),t&&(this.flavor=t.flavor)}getCurrentToken(){var e;return(e=this.owner)==null?void 0:e.getCurrentToken()}error(e,t){var i;(i=this.owner)==null||i.errorMsg(e,t)}startRuleBody(){this.depth++}endRule(){--this.depth==0&&!this.topLevel&&this.owner.popHandler()}},rn=class extends iu{constructor(e,t,i){super(e,t,i)}report(e){this.error(e,this.getCurrentToken())}reportAndSkip(e){this.report(e),this.owner.pushHandler(new iu(this.scope,this.owner,!1))}startSelectorRule(){this.reportAndSkip("E_CSS_UNEXPECTED_SELECTOR")}startFontFaceRule(){this.reportAndSkip("E_CSS_UNEXPECTED_FONT_FACE")}startCounterStyleRule(e){this.reportAndSkip("E_CSS_UNEXPECTED_COUNTER_STYLE")}startFootnoteRule(e){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(e){this.reportAndSkip("E_CSS_UNEXPECTED_WHEN")}startFlowRule(e){this.reportAndSkip("E_CSS_UNEXPECTED_FLOW")}startPageTemplateRule(){this.reportAndSkip("E_CSS_UNEXPECTED_PAGE_TEMPLATE")}startPageMasterRule(e,t,i){this.reportAndSkip("E_CSS_UNEXPECTED_PAGE_MASTER")}startPartitionRule(e,t,i){this.reportAndSkip("E_CSS_UNEXPECTED_PARTITION")}startPartitionGroupRule(e,t,i){this.reportAndSkip("E_CSS_UNEXPECTED_PARTITION_GROUP")}startFuncWithSelector(e,t){this.reportAndSkip("E_CSS_UNEXPECTED_SELECTOR_FUNC")}endFuncWithSelector(){this.reportAndSkip("E_CSS_UNEXPECTED_END_SELECTOR_FUNC")}property(e,t,i){this.error("E_CSS_UNEXPECTED_PROPERTY",this.getCurrentToken())}},$e=[],os=[],Se=[],Me=[],Vt=[],at=[],Ue=[],Ke=[],xe=[],tt=[],ct=[],je=[],Ve=[],vn=55,wn=56,dr=57;$e[1]=28,$e[36]=29,$e[7]=29,$e[9]=29,$e[14]=29,$e[18]=29,$e[50]=29,$e[20]=30,$e[13]=27,$e[0]=200,os[1]=46,os[0]=200,at[1]=2,at[36]=4,at[7]=6,at[9]=8,at[14]=10,at[18]=14,at[50]=42,Se[37]=11,Se[23]=12,Se[35]=56,Se[1]=1,Se[36]=3,Se[7]=5,Se[9]=7,Se[14]=9,Se[12]=13,Se[18]=55,Se[50]=58,Se[16]=41,Me[37]=11,Me[23]=12,Me[35]=56,Me[1]=1,Me[36]=3,Me[7]=5,Me[9]=7,Me[14]=9,Me[18]=55,Vt[1]=2,Vt[36]=4,Vt[7]=6,Vt[9]=8,Vt[18]=14,Vt[50]=42,Vt[14]=10,Vt[12]=13,Ue[1]=15,Ue[7]=16,Ue[4]=17,Ue[5]=18,Ue[3]=19,Ue[2]=20,Ue[8]=21,Ue[27]=57,Ue[16]=22,Ue[19]=23,Ue[6]=24,Ue[11]=25,Ue[17]=26,Ue[13]=48,Ue[31]=47,Ue[23]=54,Ue[0]=44,Ke[1]=31,Ke[4]=32,Ke[5]=32,Ke[3]=33,Ke[2]=34,Ke[10]=40,Ke[6]=38,Ke[31]=36,Ke[24]=36,Ke[32]=35,xe[1]=45,xe[16]=37,xe[37]=37,xe[38]=37,xe[47]=37,xe[48]=37,xe[39]=37,xe[49]=37,xe[41]=37,xe[26]=37,xe[25]=37,xe[23]=37,xe[24]=37,xe[19]=37,xe[21]=37,xe[36]=37,xe[18]=37,xe[22]=37,xe[11]=39,xe[12]=43,xe[17]=49,tt[0]=200,tt[12]=50,tt[13]=51,tt[14]=50,tt[15]=51,tt[10]=50,tt[11]=51,tt[17]=53,ct[0]=200,ct[12]=50,ct[13]=52,ct[14]=50,ct[15]=51,ct[10]=50,ct[11]=51,ct[17]=53,je[0]=200,je[12]=50,je[13]=51,je[14]=50,je[15]=51,je[10]=50,je[11]=51,Ve[11]=0,Ve[16]=0,Ve[22]=1,Ve[18]=1,Ve[26]=2,Ve[25]=2,Ve[38]=3,Ve[37]=3,Ve[48]=3,Ve[47]=3,Ve[39]=3,Ve[49]=3,Ve[41]=3,Ve[23]=4,Ve[24]=4,Ve[36]=5,Ve[19]=5,Ve[21]=5,Ve[0]=6,Ve[vn]=2,Ve[wn]=2;var er=class{constructor(e,t,i,n){u(this,"actions",e),u(this,"tokenizer",t),u(this,"handler",i),u(this,"baseURL",n),u(this,"valStack",[]),u(this,"namespacePrefixToURI",{}),u(this,"defaultNamespaceURI",null),u(this,"propName",null),u(this,"propImportant",!1),u(this,"exprContext"),u(this,"result",null),u(this,"importReady",!1),u(this,"importURL",null),u(this,"importCondition",null),u(this,"errorBrackets",[]),u(this,"ruleStack",[]),u(this,"regionRule",!1),u(this,"pageRule",!1),u(this,"inStyleDeclaration",!1),this.exprContext=2}extractVals(e,t){let i=[],n=this.valStack;for(;t<n.length&&(i.push(n[t++]),t!==n.length);){if(n[t++]!==e)throw new Error("Unexpected state");t===n.length&&i.push(Be)}return i}valStackReduce(e,t){let i=this.valStack,n=i.length,o=0,r;do if(r=i[--n],e===")"&&r instanceof fn){if(r.text===")")o++;else if(r.text==="("){if(o===0)return null;o--}}while(typeof r<"u"&&typeof r!="string");let s=i.length-(n+1);if(s>1&&i.splice(n+1,s,new J(i.slice(n+1,i.length))),e==",")return null;n++;do r=i[--n];while(typeof r<"u"&&(typeof r!="string"||r==","));if(s=i.length-(n+1),r=="("){if(e!=")"&&t.type!==0)return this.handler.error("E_CSS_MISMATCHED_C_PAR",t),this.actions=ct,null;let h=new ai(i[n-1],this.extractVals(",",n+1));if(i.splice(n-1,s+2,h),h.name==="var"){let l=h.values[0]instanceof he&&h.values[0].name;Xe(l)||(this.handler.error(`E_CSS_INVALID_VAR ${h.toString()}`,t),this.actions=ct)}return h}if(e!=";"||n>=0)return this.handler.error("E_CSS_UNEXPECTED_VAL_END",t),this.actions=ct,null;if(s>1)return new _e(this.extractVals(",",n+1));let a=i[0];return a instanceof rt?a:a?new fn(a.toString()):Be}exprError(e,t){this.actions=this.propName?ct:tt,Y.warn(e,t.toString())}exprStackReduce(e,t){let i=this.valStack,n=this.handler,o=i.pop(),r;for(;;){let s=i.pop();if(e==11){let a=[o];for(;s==16;)a.unshift(i.pop()),s=i.pop();if(typeof s=="string"){if(s=="{"){for(;a.length>=2;){let h=a.shift(),l=a.shift(),c=new fm(n.getScope(),h,l);a.unshift(c)}return i.push(new j(a[0])),!0}else if(s=="("){let h=i.pop(),l=i.pop();o=new vo(n.getScope(),Ca(l,h),a),e=0;continue}}if(s==10){o.isMediaName()&&(o=new Oh(n.getScope(),o,null)),e=0;continue}}else if(typeof s=="string"){i.push(s);break}if(s<0)if(s==-31)o=new Ai(n.getScope(),o);else if(s==-24)o=new Cn(n.getScope(),o);else if(s==-dr)o=new dm(n.getScope(),o);else return this.exprError("F_UNEXPECTED_STATE",t),!1;else{if(Ve[e]>Ve[s]){i.push(s);break}switch(r=i.pop(),s){case 26:o=new Al(n.getScope(),r,o);break;case vn:o=new pm(n.getScope(),r,o);break;case wn:o=new gm(n.getScope(),r,o);break;case 25:o=new Il(n.getScope(),r,o);break;case 38:o=new mm(n.getScope(),r,o);break;case 37:o=new vm(n.getScope(),r,o);break;case 48:o=new ym(n.getScope(),r,o);break;case 47:o=new Ea(n.getScope(),r,o);break;case 39:case 49:o=new Fl(n.getScope(),r,o);break;case 41:o=new wm(n.getScope(),r,o);break;case 23:o=new Oc(n.getScope(),r,o);break;case 24:o=new Bc(n.getScope(),r,o);break;case 36:o=new Rl(n.getScope(),r,o);break;case 19:o=new Mc(n.getScope(),r,o);break;case 21:o=new _c(n.getScope(),r,o);break;case 18:if(i.length>1)switch(i[i.length-1]){case 22:i.pop(),o=new Sm(n.getScope(),i.pop(),r,o);break;case 10:if(r.isMediaName())o=new Oh(n.getScope(),r,o);else return this.exprError("E_CSS_MEDIA_TEST",t),!1;break}else return this.exprError("E_CSS_EXPR_COND",t),!1;break;case 22:if(e!=18)return this.exprError("E_CSS_EXPR_COND",t),!1;case 10:return i.push(r),i.push(s),i.push(o),!1;default:return this.exprError("F_UNEXPECTED_STATE",t),!1}}}return i.push(o),!1}readSupportsTest(e){let t=e.type===6,i=this.tokenizer,n,o;if(t)o=e.text,n=e.position+o.length+1;else if(e.type===10){let d=i.nthToken(1),p=i.nthToken(2);if(d.type===1&&p.type===18)i.consume(),i.consume(),o=d.text,n=p.position+1;else{if(d.type===10||d.type===6||d.type===1&&d.text.toLowerCase()==="not"&&(p.type===10||p.type===6))return null;n=e.position+1}}else return null;let r=0,s,a=0;for(;r>=0;)switch(i.consume(),s=i.token(),s.type){case 11:r--;break;case 10:case 6:r++;break;case 16:r===0&&a++;break;case 0:return this.exprError("E_CSS_UNEXPECTED_EOF",s),null}i.consume();let h=s.position,l=i.input.substring(n,h),c=t&&o==="selector"&&a>0?"":Xe(o)?l:l.trim();return new Cm(this.handler.getScope(),o,c,t)}readPseudoParams(){let e=[];for(;;){let t=this.tokenizer.token();switch(t.type){case 1:e.push(t.text);break;case 23:e.push("+");break;case 4:case 5:e.push(t.num);break;default:return e}this.tokenizer.consume()}}skipPseudoFunctionContents(){let e=0;for(;;){switch(this.tokenizer.token().type){case 0:return!1;case 11:if(e===0)return!0;e--;break;case 10:case 6:e++;break}this.tokenizer.consume()}}readNthPseudoParams(){let e=!1,t=this.tokenizer.token();if(t.type===23)e=!0,this.tokenizer.consume(),t=this.tokenizer.token();else if(t.type===1&&(t.text==="even"||t.text==="odd"))return this.tokenizer.consume(),[2,t.text==="odd"?1:0];switch(t.type){case 3:if(e&&t.num<0)return null;case 1:if(e&&t.text.charAt(0)==="-")return null;if(t.text==="n"||t.text==="-n"){if(e&&t.precededBySpace)return null;let i=t.text==="-n"?-1:1;t.type===3&&(i=t.num);let n=0;this.tokenizer.consume(),t=this.tokenizer.token();let o=t.type===24,r=t.type===23||o;if(r&&(this.tokenizer.consume(),t=this.tokenizer.token()),t.type===5){if(n=t.num,1/n===-1/0){if(n=0,r)return null}else if(n<0){if(r)return null}else if(n>=0&&!r)return null;this.tokenizer.consume()}else if(r)return null;return[i,o&&n>0?-n:n]}else if(t.text==="n-"||t.text==="-n-"){if(e&&t.precededBySpace)return null;let i=t.text==="-n-"?-1:1;if(t.type===3&&(i=t.num),this.tokenizer.consume(),t=this.tokenizer.token(),t.type===5)return t.num<0||1/t.num===-1/0?null:(this.tokenizer.consume(),[i,t.num])}else{let i=t.text.match(/^n(-[0-9]+)$/);if(i)return e&&t.precededBySpace?null:(this.tokenizer.consume(),[t.type===3?t.num:1,parseInt(i[1],10)]);if(i=t.text.match(/^-n(-[0-9]+)$/),i)return this.tokenizer.consume(),[-1,parseInt(i[1],10)]}return null;case 5:return e&&(t.precededBySpace||t.num<0)?null:(this.tokenizer.consume(),[0,t.num])}return null}makeCondition(e,t){let i=this.handler.getScope();if(!i)return null;if(t=t||i._true,e){let n=e.split(/\s+/);for(let o of n)switch(o){case"vertical":t=Wt(i,t,new Ai(i,new Je(i,"pref-horizontal")));break;case"horizontal":t=Wt(i,t,new Je(i,"pref-horizontal"));break;case"day":t=Wt(i,t,new Ai(i,new Je(i,"pref-night-mode")));break;case"night":t=Wt(i,t,new Je(i,"pref-night-mode"));break;default:t=i._false}}return t===i._true?null:new j(t)}isInsidePropertyOnlyRule(){switch(this.ruleStack[this.ruleStack.length-1]){case"[selector]":case"font-face":case"counter-style":case"-epubx-flow":case"-epubx-viewport":case"-epubx-define":case"-adapt-footnote-area":case"footnote":return!0}return!1}runParser(e,t,i,n,o,r){let s=this.handler,a=this.tokenizer,h=this.valStack,l,c,d,p,f,g,v,w=null;for(i&&(this.inStyleDeclaration=!0),n&&(this.exprContext=2,this.valStack.push("{"));e>0;--e){if(l=a.token(),o&&w===null&&(w=l.position-1,a.input[w]==="("&&w++),this.actions===Ue&&this.errorBrackets.length>0&&(l.type===this.errorBrackets[this.errorBrackets.length-1]||l.type===17||l.type===31)){if(l.type===this.errorBrackets[this.errorBrackets.length-1]&&(this.errorBrackets.pop(),l.type===11&&this.valStackReduce(")",l))){a.consume();continue}h.push(new fn(l.toString())),a.consume();continue}switch(this.actions[l.type]){case 28:if(!this.inStyleDeclaration||a.nthToken(1).type!=18){this.isInsidePropertyOnlyRule()?(s.error("E_CSS_COLON_EXPECTED",a.nthToken(1)),this.actions=ct):(this.actions=at,s.startSelectorRule());continue}this.propName=l.text,this.propImportant=!1,a.consume(),a.consume(),this.actions=Ue,h.splice(0,h.length);continue;case 46:if(a.nthToken(1).type!=18){this.actions=ct,s.error("E_CSS_COLON_EXPECTED",a.nthToken(1));continue}this.propName=l.text,this.propImportant=!1,a.consume(),a.consume(),this.actions=Ue,h.splice(0,h.length);continue;case 29:this.actions=at,s.startSelectorRule();continue;case 1:if(!l.precededBySpace){this.actions=je,s.error("E_CSS_SPACE_EXPECTED",l);continue}s.descendantSelector();case 2:if(a.nthToken(1).type==34)if(a.consume(),a.consume(),d=this.namespacePrefixToURI[l.text],d!=null)switch(l=a.token(),l.type){case 1:s.tagSelector(d,l.text),o?this.actions=Me:this.actions=Se,a.consume();break;case 36:s.tagSelector(d,null),o?this.actions=Me:this.actions=Se,a.consume();break;default:this.actions=tt,s.error("E_CSS_NAMESPACE",l)}else this.actions=tt,s.error("E_CSS_UNDECLARED_PREFIX",l);else s.tagSelector(this.defaultNamespaceURI,l.text),o?this.actions=Me:this.actions=Se,a.consume();continue;case 3:if(!l.precededBySpace){this.actions=je,s.error("E_CSS_SPACE_EXPECTED",l);continue}s.descendantSelector();case 4:if(a.nthToken(1).type==34)switch(a.consume(),a.consume(),l=a.token(),l.type){case 1:s.tagSelector(null,l.text),o?this.actions=Me:this.actions=Se,a.consume();break;case 36:s.tagSelector(null,null),o?this.actions=Me:this.actions=Se,a.consume();break;default:this.actions=tt,s.error("E_CSS_NAMESPACE",l)}else s.tagSelector(this.defaultNamespaceURI,null),o?this.actions=Me:this.actions=Se,a.consume();continue;case 5:l.precededBySpace&&s.descendantSelector();case 6:if(!l.text){s.error("E_CSS_SYNTAX",l),a.consume();continue}s.idSelector(l.text),o?this.actions=Me:this.actions=Se,a.consume();continue;case 7:l.precededBySpace&&s.descendantSelector();case 8:s.classSelector(l.text),o?this.actions=Me:this.actions=Se,a.consume();continue;case 55:l.precededBySpace&&s.descendantSelector();case 14:a.consume(),l=a.token();e:switch(l.type){case 1:s.pseudoclassSelector(l.text,null),a.consume(),o?this.actions=Me:this.actions=Se;continue;case 6:switch(p=l.text,a.consume(),p){case"is":case"not":case"where":case"has":this.actions=at,s.startFuncWithSelector(p),this.runParser(Number.POSITIVE_INFINITY,!1,!1,!1,!0,p==="has")?this.actions=Se:this.actions=je;continue;case"lang":case"href-epub-type":case"href-role-type":if(l=a.token(),l.type===1){v=[l.text],a.consume(),(p==="href-epub-type"||p==="href-role-type")&&a.token().type===16&&(a.consume(),l=a.token(),l.type===1&&(v.push(l.text),a.consume()));break}else break e;case"nth-child":case"nth-of-type":case"nth-last-child":case"nth-last-of-type":case"nth":if(v=this.readNthPseudoParams(),v)if(p==="nth-child"||p==="nth-last-child"){if(c=a.nthToken(0),c.type===1&&c.text==="of"){a.consume(),this.actions=at,s.startFuncWithSelector(p,v),this.runParser(Number.POSITIVE_INFINITY,!1,!1,!1,!0,!1)?o?this.actions=Me:this.actions=Se:this.actions=je;continue}break}else if(p==="nth"){if(c=a.nthToken(0),c.type===1&&c.text==="of")if(a.consume(),c=a.token(),c.type===1)v.push(c.text),a.consume();else break e;break}else break;else break e;default:if(v=[],!this.skipPseudoFunctionContents())break e}if(l=a.token(),l.type==11){s.pseudoclassSelector(p,v),a.consume(),o?this.actions=Me:this.actions=Se;continue}break}s.error("E_CSS_PSEUDOCLASS_SYNTAX",l),this.actions=tt;continue;case 58:l.precededBySpace&&s.descendantSelector();case 42:switch(a.consume(),l=a.token(),l.type){case 1:s.pseudoelementSelector(l.text,null),o?this.actions=Me:this.actions=Se,a.consume();continue;case 6:if(p=l.text,a.consume(),p=="nth-fragment"){if(v=this.readNthPseudoParams(),v===null)break}else v=this.readPseudoParams();if(l=a.token(),l.type==11){s.pseudoelementSelector(p,v),o?this.actions=Me:this.actions=Se,a.consume();continue}break}s.error("E_CSS_PSEUDOELEM_SYNTAX",l),this.actions=tt;continue;case 9:l.precededBySpace&&s.descendantSelector();case 10:{if(a.consume(),l=a.token(),l.type==1)p=l.text,a.consume();else if(l.type==36)p=null,a.consume();else if(l.type==34)p="";else{this.actions=je,s.error("E_CSS_ATTR",l),a.consume();continue}if(l=a.token(),l.type==34){if(d=p&&this.namespacePrefixToURI[p],d===void 0){this.actions=je,s.error("E_CSS_UNDECLARED_PREFIX",l),a.consume();continue}if(a.consume(),l=a.token(),l.type!=1){this.actions=je,s.error("E_CSS_ATTR_NAME_EXPECTED",l);continue}p=l.text,a.consume(),l=a.token()}else d="";switch(l.type){case 39:case 45:case 44:case 43:case 42:case 46:case 50:f=l.type,a.consume(),l=a.token();break;case 15:s.attributeSelector(d,p,0,null,null),o?this.actions=Me:this.actions=Se,a.consume();continue;default:this.actions=je,s.error("E_CSS_ATTR_OP_EXPECTED",l);continue}let x=p,m=null;switch(l.type){case 1:case 2:{let S=l.text;if(a.consume(),l=a.token(),l.type==1){let b=l.text.toLowerCase();(b=="i"||b=="s")&&(m=b,a.consume(),l=a.token())}s.attributeSelector(d,x,f,S,m);break}default:this.actions=je,s.error("E_CSS_ATTR_VAL_EXPECTED",l);continue}if(l.type!=15){this.actions=je,s.error("E_CSS_ATTR",l);continue}o?this.actions=Me:this.actions=Se,a.consume();continue}case 11:s.childSelector(),this.actions=Vt,a.consume();continue;case 12:s.adjacentSiblingSelector(),this.actions=Vt,a.consume();continue;case 56:s.followingSiblingSelector(),this.actions=Vt,a.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),s.startRuleBody(),this.actions=$e,a.consume();continue;case 41:s.nextSelector(),this.actions=at,a.consume();continue;case 15:h.push(B(l.text)),a.consume();continue;case 16:f=parseInt(l.text,16),h.push(new jc(l.text)),a.consume();continue;case 17:h.push(new At(l.num)),a.consume();continue;case 18:h.push(new lt(l.num)),a.consume();continue;case 19:h.push(new O(l.num,l.text)),a.consume();continue;case 20:h.push(new K(l.text)),a.consume();continue;case 21:h.push(new Qe(Ae(l.text,this.baseURL))),a.consume();continue;case 57:h.push(new Xc(l.text)),a.consume();continue;case 22:this.valStackReduce(",",l),h.push(","),a.consume();continue;case 23:h.push(jn),a.consume();continue;case 24:p=l.text.toLowerCase(),p=="-epubx-expr"||p=="env"?(this.actions=Ke,this.exprContext=0,h.push("{")):(h.push(p),h.push("("),this.errorBrackets.length>0&&this.errorBrackets.push(11)),a.consume();continue;case 25:this.valStackReduce(")",l),a.consume();continue;case 47:if(a.consume(),l=a.token(),c=a.nthToken(1),l.type==1&&l.text.toLowerCase()=="important"&&(c.type==17||c.type==0||c.type==13)){a.consume(),this.propImportant=!0;continue}this.exprError("E_CSS_SYNTAX",l);continue;case 54:switch(c=a.nthToken(1),c.type){case 4:case 3:case 5:if(!c.precededBySpace){a.consume();continue}}h.push(new fn("+")),a.consume();continue;case 26:a.consume();case 48:g=this.valStackReduce(";",l),g&&this.propName&&s.property(this.propName,g,this.propImportant),this.actions=i?os:$e;continue;case 44:for(a.consume();h.length>0;){let x=h.length;if(g=this.valStackReduce(";",l),!g||h.length===x)break}return t?(this.result=g,!0):(this.propName&&g&&s.property(this.propName,g,this.propImportant),!0);case 31:if(c=a.nthToken(1),c.type==9)a.nthToken(2).type==10&&!a.nthToken(2).precededBySpace?(h.push(l.text,c.text,"("),a.consume()):(h.push(new Je(s.getScope(),Ca(l.text,c.text))),this.actions=xe),a.consume();else{if(this.exprContext==2||this.exprContext==3)l.text.toLowerCase()=="not"?(a.consume(),h.push(new Lh(s.getScope(),!0,c.text))):(l.text.toLowerCase()=="only"&&(a.consume(),l=c),h.push(new Lh(s.getScope(),!1,l.text)));else if(this.exprContext===4&&l.text.toLowerCase()==="not"&&h[h.length-1]!==vn&&h[h.length-1]!==wn&&(c.type===10||c.type===6)){h.push(-dr),a.consume();continue}else h.push(new Je(s.getScope(),l.text));this.actions=xe}a.consume();continue;case 38:if(this.exprContext===4){h.push(this.readSupportsTest(l)),this.actions=xe;continue}h.push(null,l.text,"("),a.consume();continue;case 32:h.push(new it(s.getScope(),l.num)),a.consume(),this.actions=xe;continue;case 33:p=l.text,p=="%"&&(this.propName&&this.propName.match(/height|^(top|bottom)$/)?p="vh":p="vw"),h.push(new qo(s.getScope(),l.num,p)),a.consume(),this.actions=xe;continue;case 34:h.push(new it(s.getScope(),l.text)),a.consume(),this.actions=xe;continue;case 35:a.consume(),l=a.token(),l.type!=5||l.precededBySpace?this.exprError("E_CSS_SYNTAX",l):(h.push(new Uc(s.getScope(),l.num)),a.consume(),this.actions=xe);continue;case 36:h.push(-l.type),a.consume();continue;case 37:this.actions=Ke,this.exprStackReduce(l.type,l),h.push(l.type),a.consume();continue;case 45:l.text.toLowerCase()==="and"&&h[h.length-2]!==wn&&h[h.length-2]!==-dr?(this.actions=Ke,this.exprStackReduce(vn,l),h.push(vn),a.consume()):l.text.toLowerCase()==="or"&&h[h.length-2]!==vn&&h[h.length-2]!==-dr?(this.actions=Ke,this.exprStackReduce(wn,l),h.push(wn),a.consume()):this.exprError("E_CSS_SYNTAX",l);continue;case 39:this.exprStackReduce(l.type,l)&&(this.actions=Ue),a.consume();continue;case 43:this.exprStackReduce(11,l)&&(this.propName||this.exprContext==3?this.exprError("E_CSS_UNEXPECTED_BRC",l):(this.exprContext==1?s.startWhenRule(h.pop()):s.startMediaRule(h.pop()),this.ruleStack.push("media"),s.startRuleBody(),this.actions=$e)),a.consume();continue;case 49:if(this.exprStackReduce(11,l))return this.propName||this.exprContext!=3?(this.exprError("E_CSS_UNEXPECTED_SEMICOL",l),this.actions=$e,a.consume(),!1):(this.importCondition=h.pop(),this.importReady=!0,this.actions=$e,a.consume(),!1);a.consume();continue;case 40:if(this.exprContext===4){let x=this.readSupportsTest(l);if(x){h.push(x),this.actions=xe;continue}}h.push(l.type),a.consume();continue;case 27:if(this.actions=$e,a.consume(),s.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(p=l.text.toLowerCase(),p){case"import":if(a.consume(),l=a.token(),l.type==2||l.type==8){if(this.importURL=l.text,a.consume(),l=a.token(),l.type==17||l.type==0)return this.importReady=!0,a.consume(),!1;this.propName=null,this.exprContext=3,this.actions=Ke,h.push("{");continue}s.error("E_CSS_IMPORT_SYNTAX",l),this.actions=tt;continue;case"namespace":switch(a.consume(),l=a.token(),l.type){case 1:if(p=l.text,a.consume(),l=a.token(),(l.type==2||l.type==8)&&a.nthToken(1).type==17){this.namespacePrefixToURI[p]=l.text,a.consume(),a.consume();continue}break;case 2:case 8:if(a.nthToken(1).type==17){this.defaultNamespaceURI=l.text,a.consume(),a.consume();continue}break}s.error("E_CSS_NAMESPACE_SYNTAX",l),this.actions=tt;continue;case"charset":if(a.consume(),l=a.token(),l.type==2&&a.nthToken(1).type==17){p=l.text.toLowerCase(),p!="utf-8"&&p!="utf-16"&&s.error(`E_CSS_UNEXPECTED_CHARSET ${p}`,l),a.consume(),a.consume();continue}s.error("E_CSS_CHARSET_SYNTAX",l),this.actions=tt;continue;case"font-face":case"-epubx-page-template":case"-epubx-define":case"-epubx-viewport":if(a.nthToken(1).type==12){switch(a.consume(),a.consume(),p){case"font-face":s.startFontFaceRule(),this.inStyleDeclaration=!0;break;case"-epubx-page-template":s.startPageTemplateRule();break;case"-epubx-define":s.startDefineRule(),this.inStyleDeclaration=!0;break;case"-epubx-viewport":s.startViewportRule(),this.inStyleDeclaration=!0;break}this.ruleStack.push(p),s.startRuleBody();continue}break;case"-epubx-region":a.consume(),s.startRegionRule(),this.regionRule=!0,this.actions=at;continue;case"page":a.consume(),s.startPageRule(),this.pageRule=!0,this.actions=Vt;continue;case"-adapt-footnote-area":case"footnote":switch(a.consume(),l=a.token(),l.type){case 12:a.consume(),s.startFootnoteRule(null),this.ruleStack.push(p),s.startRuleBody(),this.inStyleDeclaration=!0;continue;case 50:if(a.consume(),l=a.token(),l.type==1&&a.nthToken(1).type==12){let x=l.text;a.consume(),a.consume(),s.startFootnoteRule(x),this.ruleStack.push(p==="footnote"?"footnote":"-adapt-footnote-area"),s.startRuleBody(),this.inStyleDeclaration=!0;continue}break}break;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(a.consume(),l=a.token(),l.type==12){a.consume(),s.startPageMarginBoxRule(p),this.ruleStack.push(p),s.startRuleBody(),this.inStyleDeclaration=!0;continue}break;case"-epubx-when":a.consume(),this.propName=null,this.exprContext=1,this.actions=Ke,h.push("{");continue;case"media":a.consume(),this.propName=null,this.exprContext=2,this.actions=Ke,h.push("{");continue;case"supports":a.consume(),this.propName=null,this.exprContext=4,this.actions=Ke,h.push("{");continue;case"-epubx-flow":if(a.nthToken(1).type==1&&a.nthToken(2).type==12){s.startFlowRule(a.nthToken(1).text),a.consume(),a.consume(),a.consume(),this.ruleStack.push(p),s.startRuleBody(),this.inStyleDeclaration=!0;continue}break;case"counter-style":if(a.nthToken(1).type==1&&a.nthToken(2).type==12){s.startCounterStyleRule(a.nthToken(1).text),a.consume(),a.consume(),a.consume(),this.ruleStack.push(p),s.startRuleBody(),this.inStyleDeclaration=!0;continue}break;case"-epubx-page-master":case"-epubx-partition":case"-epubx-partition-group":{a.consume(),l=a.token();let x=null,m=null,S=[];for(l.type==1&&(x=l.text,a.consume(),l=a.token()),l.type==18&&a.nthToken(1).type==1&&(m=a.nthToken(1).text,a.consume(),a.consume(),l=a.token());l.type==6&&l.text.toLowerCase()=="class"&&a.nthToken(1).type==1&&a.nthToken(2).type==11;)S.push(a.nthToken(1).text),a.consume(),a.consume(),a.consume(),l=a.token();if(l.type==12){switch(a.consume(),p){case"-epubx-page-master":s.startPageMasterRule(x,m,S);break;case"-epubx-partition":s.startPartitionRule(x,m,S);break;case"-epubx-partition-group":s.startPartitionGroupRule(x,m,S);break}this.ruleStack.push(p),s.startRuleBody(),this.inStyleDeclaration=!0;continue}break}case"":s.error(`E_CSS_UNEXPECTED_AT${p}`,l),this.actions=je;continue;default:s.error(`E_CSS_AT_UNKNOWN ${p}`,l),this.actions=tt;continue}s.error(`E_CSS_AT_SYNTAX ${p}`,l),this.actions=tt;continue;case 50:this.errorBrackets.push(l.type+1),a.consume();continue;case 52:if(this.errorBrackets.length==0){this.actions=$e;continue}case 51:if(o&&this.errorBrackets.length==0&&l.type==11)return a.consume(),s.endFuncWithSelector(),!0;this.errorBrackets.length>0&&this.errorBrackets[this.errorBrackets.length-1]==l.type&&this.errorBrackets.pop(),this.errorBrackets.length==0&&l.type==13&&(this.actions=$e),a.consume();continue;case 53:if(o&&this.errorBrackets.length==0&&l.type==16){s.nextSelector(),this.actions=at,w=l.position+1,a.consume();continue}this.errorBrackets.length==0&&(this.actions=$e),a.consume();continue;case 200:return!0;default:if(n)return this.exprStackReduce(11,l)?(this.result=h.pop(),!0):!1;if(o){if(this.actions===je)switch(l.type){case 16:this.errorBrackets.length==0&&(s.nextSelector(),w=l.position+1,this.actions=at),a.consume();continue;case 11:if(this.errorBrackets.length==0)return s.endFuncWithSelector(),a.consume(),!0;this.errorBrackets.length>0&&this.errorBrackets[this.errorBrackets.length-1]==l.type&&this.errorBrackets.pop(),a.consume();continue;case 12:case 14:case 10:this.errorBrackets.push(l.type+1),a.consume();continue;case 6:this.errorBrackets.push(11),a.consume();continue;case 13:case 15:this.errorBrackets.length>0&&this.errorBrackets[this.errorBrackets.length-1]==l.type&&this.errorBrackets.pop(),a.consume();continue;default:a.consume();continue}switch(l.type){case 16:case 11:if(this.actions===at)s.error("E_CSS_SYNTAX",l);else{let x=a.input.substring(w,l.position);s.pushSelectorText(x),w=l.position+1}if(l.type===16){s.nextSelector(),this.actions=at,a.consume();continue}else return s.endFuncWithSelector(),a.consume(),!0;case 37:case 23:case 35:if(r){this.actions=Se;continue}break;case 12:case 14:case 10:this.errorBrackets.push(l.type+1);break}s.error("E_CSS_SYNTAX",l),a.consume(),this.actions=je;continue}if(this.actions!==tt&&this.actions!==je&&this.actions!==ct){if(l.type==54)s.error("E_CSS_SYNTAX",l);else if(this.actions===Ue){switch(l.type){case 10:case 12:case 14:this.errorBrackets.push(l.type+1);break}h.push(new fn(l.toString())),a.consume();continue}else if(l.type===12&&this.actions==Ke&&h.length>0){s.startMediaRule(h.pop()),this.ruleStack.push("media"),s.startRuleBody(),this.actions=$e,a.consume();continue}else{if(l.type===17&&this.actions==Ke)return this.actions=$e,a.consume(),!1;s.error("E_CSS_SYNTAX",l)}this.isInsidePropertyOnlyRule()?this.actions=ct:this.actions=je;continue}a.consume();continue}}return!1}},Bd=class extends Bs{constructor(e){super(null),u(this,"scope",e)}error(e,t){Y.warn(e,t.toString())}getScope(){return this.scope}};function nv(e,t,i,n,o){let r=Md(t),s=ny(e.input);return s!==e.input?nu(new xt(s,r),r,i,n,o):nu(e,r,i,n,o)}function nu(e,t,i,n,o){let r=M("parseStylesheet"),s=new er($e,e,t,i),a=null;return o&&(a=Dd(new xt(o,t),t,i)),a=s.makeCondition(n,a&&a.toExpr()),a&&(t.startMediaRule(a),t.startRuleBody()),r.loop(()=>{for(;!s.runParser(100,!1,!1,!1,!1);){if(s.importReady){let l=Ae(s.importURL,i);s.importCondition&&(t.startMediaRule(s.importCondition),t.startRuleBody());let c=M("parseStylesheet.import");return _d(l,t,null,null).then(()=>{s.importCondition&&t.endRule(),s.importReady=!1,s.importURL=null,s.importCondition=null,c.finish(!0)}),c.result()}let h=r.timeSlice();if(h.isPending)return h}return T(!1)}).then(()=>{a&&t.endRule(),r.finish(!0)}),r.result()}function Ml(e,t,i,n,o){let r=Md(t);return _n("parseStylesheetFromText",s=>{let a=new xt(e,r);nv(a,r,i,n,o).thenFinish(s)},(s,a)=>{Y.warn(a,`Failed to parse stylesheet text: ${e}`),s.finish(!1)})}function Md(e){if(e instanceof Ba)return e;if(e instanceof rn){if(e.owner)return e.owner;let t=new Ba;return t.flavor=e.flavor,t.slave=e,e.owner=t,t}return e}function _d(e,t,i,n){return _n("parseStylesheetFromURL",o=>{Os(e).then(r=>{r.responseText?Ml(r.responseText,t,e,i,n).then(s=>{s||Y.warn(`Failed to parse stylesheet from ${e}`),o.finish(!0)}):o.finish(!0)})},(o,r)=>{Y.warn(r,"Exception while fetching and parsing:",e),o.finish(!0)})}function Ri(e,t,i){let n=new er(Ue,t,new Bd(e),i);return n.runParser(Number.POSITIVE_INFINITY,!0,!1,!1,!1),n.result}function ov(e,t,i){new er(os,e,t,i).runParser(Number.POSITIVE_INFINITY,!1,!0,!1,!1)}function Dd(e,t,i){let n=new er(Ke,e,t,i);return n.runParser(Number.POSITIVE_INFINITY,!1,!1,!0,!1),n.result}var rv={"z-index":!0,"column-count":!0,"flow-linger":!0,opacity:!0,page:!0,"flow-priority":!0,utilization:!0};function sv(e){return!!rv[e]}function av(e,t,i){if(t instanceof we&&t.str==="viv-leader")return new j(t);if(i==="content"&&t instanceof we)return new j(t);let n=t.evaluate(e);switch(typeof n){case"number":return sv(i)?n==Math.round(n)?new lt(n):new At(n):new O(n,"px");case"string":return n?i==="content"?new K(n):Ri(t.scope,new xt(n,null),""):Be;case"boolean":return n?y._true:y._false;case"undefined":return Be}throw new Error("E_UNEXPECTED")}var lv="data-vivliostyle-flow-root";function hv(e){return e.getAttribute(lv)==="true"}function ou(e){let t=e?.toString()||"block",i;switch(t){case"inline-flex":i="flex";break;case"inline-grid":i="grid";break;case"inline-table":i="table";break;case"initial":case"unset":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":i="block";break;default:i=t}return B(i)}function Ro(e){return e===y.absolute||e===y.fixed}function wo(e){return e instanceof ai&&e.name==="running"}function zd(e,t,i,n){return e===y.none||(Ro(t)?(i=y.none,e=ou(e)):(i&&i!==y.none&&!Z(i)||n)&&(e=ou(e))),{display:e,position:t,float:i}}function Vd(e,t,i,n){return zd(e,t,i,n).display===y.block}function Ms(e){return e instanceof he||e instanceof J||typeof e=="string"}function Ut(e){if(!Ms(e))return!1;let t=e.toString();switch(t){case"inline":case"inline-block":case"inline-flex":case"inline-grid":case"ruby":case"inline-table":return!0;default:return t.includes("inline")}}function uo(e){return Ms(e)?e.toString().includes("list-item"):!1}function uv(e){if(!Ms(e))return!1;switch(e.toString()){case"block":case"flex":case"grid":case"table":case"list-item":case"flow-root":return!0;default:return!1}}function Ud(e){if(!Ms(e))return!1;switch(e.toString()){case"ruby-base":case"ruby-text":case"ruby-base-container":case"ruby-text-container":return!0;default:return!1}}function cv(e,t,i,n,o,r,s){return o=o||r||y.horizontal_tb,!!s||!!i&&i!==y.none&&!Z(i)||Ro(t)||e===y.inline_block||e===y.table_cell||e===y.table_caption||e==y.flex||e==y.grid||e==y.flow_root||(e===y.block||e===y.list_item)&&!!n&&n!==y.visible&&n!==y.clip&&!Z(n)||!!r&&o!==r}function dv(e){return e===y.relative||e===y.absolute||e===y.fixed}var ii=1e5;function _l(e){let t=e.element.style;t.columnGap=`${ii-(e.vertical?e.height:e.width)}px`,t.columnFill="auto",t.columnCount="1",t.columnWidth="0"}function _s(e){let t=("element"in e?e.element:e).style;t.columnWidth="",t.columnCount="",t.columnGap="",t.columnFill=""}function rs(e){return e.element.style.columnCount==="1"}function pv(e){e.element.setAttribute("data-vivliostyle-column","true")}function Lo(e,t){let i=t?e.bottom:Math.max(Math.abs(e.left),Math.abs(e.right));return Math.round(i/ii)}function Dl(e,t){let i=Lo(e,t);if(i===0)return 0;let n=t?e.top:Math.min(Math.abs(e.left),Math.abs(e.right)),o=Math.round(n/ii),r=o*ii,s=i*ii;return t?(e.top-=r,e.bottom-=s,e.bottom<e.top&&(e.bottom+=ii),e.right-=r,e.left-=s):e.left<-ii/2?(e.right+=r,e.left+=s,e.left>e.right&&(e.left-=ii),e.top+=r,e.bottom+=s):(e.left-=r,e.right-=s,e.right<e.left&&(e.right+=ii),e.top+=r,e.bottom+=s),e.width=e.right-e.left,e.height=e.bottom-e.top,o}function ss(e,t){for(let i=0;i<e.length;i++)Dl(e[i],t)}function Bt(e,t,i){let n=e.getElementClientRect(t);if(Dl(n,i)>0&&e.getElementComputedStyle(t).display.startsWith("table")&&!tr(t)){let o=t.closest("[data-vivliostyle-column]");if(o)return _s(o),e.getElementClientRect(t)}return n}function fv(e,t){var i,n;if(e.nodeType===1){let o=e;((i=o.style)==null?void 0:i.breakAfter)==="column"&&(o.style.breakAfter="")}if(t.nodeType===1){let o=t;((n=o.style)==null?void 0:n.breakBefore)==="column"&&(o.style.breakBefore="")}}function Ma(e){let t=e.style;return t?!isNaN(parseFloat(t.columnCount))||!isNaN(parseFloat(t.columnWidth)):!1}function gv(e){if(!e.hasAttribute("data-vivliostyle-column")&&Ma(e))return!0;for(let t of e.querySelectorAll("*"))if(!t.hasAttribute("data-vivliostyle-column")&&Ma(t))return!0;return!1}function tr(e){for(let t=e.nodeType===1?e:e.parentElement;t;t=t.parentElement){let i=t.style;if(!i||t.hasAttribute("data-vivliostyle-column"))break;if(Ma(t))return t;if(i.position==="absolute")break}return null}function mv(e){var t;if(e.nodeType!==1)return;let i=e,n=i.style,o=n?.breakBefore==="column",r=i.previousElementSibling,s=r&&((t=r.style)==null?void 0:t.breakAfter)==="column";if(!o&&!s)return;let a=tr(i);if(!a)return;let h=a.ownerDocument.defaultView.getComputedStyle(a),{writingMode:l,direction:c,columnGap:d,fontSize:p}=h,f=l==="vertical-rl"||l==="vertical-lr",g=c==="rtl",v=(parseFloat(d)||parseFloat(p)||16)/2,w=a.getBoundingClientRect(),x=i.getBoundingClientRect();(f?x.top>w.bottom+v:g?x.right<w.left-v:x.left>w.right+v)&&(o&&(n.breakBefore=""),s&&r&&(r.style.breakAfter=""),n.marginBlockStart=`${ii}px`)}function pr(e){let t=e.element.lastElementChild,i=t&&e.clientLayout.getElementClientRect(t);return i?Lo(i,e.vertical):0}function $d(e,t){if(e.getAttribute("data-viv-saved-column-fill")!=="auto"||pr(t))return;let i=t.clientLayout.getElementComputedStyle(e),n=parseFloat(i.blockSize);e.style.columnFill="auto";let o=parseFloat(i.blockSize);if(o<=0||e.parentElement&&tr(e.parentElement)){e.removeAttribute("data-viv-saved-column-fill");return}let r=NaN;if(e.style.blockSize=`${o}px`,pr(t)){if(e.style.blockSize=`${n}px`,!pr(t)){let s=1/(t.clientLayout.pixelRatio||1),a=n,h=o;for(;h-a>s;){let l=(a+h)/2;e.style.blockSize=`${l}px`,pr(t)?h=l:a=l}r=a,e.style.blockSize=`${r}px`}}else if(r=parseFloat(i.blockSize),r<o){let s=1/t.clientLayout.layoutUnitPerPixel;r=o+s,e.style.blockSize=`${r}px`}if(isNaN(r)){e.style.blockSize="",e.style.columnFill="balance";return}e.removeAttribute("data-viv-saved-column-fill")}function yv(e){let t=e.element.querySelectorAll('[data-viv-saved-column-fill="auto"]');for(let i of t)$d(i,e)}function bn(e,t,i,n){let o=e.viewNode;if(!o)return NaN;let r=o.nodeType===1?o:o.parentElement;if(r&&r.namespaceURI==="http://www.w3.org/1999/xhtml"){let s=r.style;if(r.localName==="wbr"||s&&Ut(s.display)&&/^([\d\.]|super|(text-)?top)/.test(s.verticalAlign))return NaN}if(o===r){if(r.localName==="br"){let s=r.ownerDocument.createElement("span");r.parentNode.insertBefore(s,r);let a=t.getElementClientRect(s);if(s.remove(),a){let h=[a];ss(h,n);let l=h[0],c=n?l.left:l.bottom;if(!isNaN(c)&&c!==0)return c}return NaN}if(e.after||!e.inline){if(e.after&&!e.inline&&r.querySelector("ruby")){let a=r.parentNode,h=r.nextSibling;a.removeChild(r),a.insertBefore(r,h)}let s=Bt(t,r,n);if(s.left===0&&s.top===0&&s.right===0&&s.bottom===0)return NaN;if(s.right>=s.left&&s.bottom>=s.top)return e.after?n?s.left:s.bottom:n?s.right:s.top}return NaN}else{let s=NaN,a=o.ownerDocument.createRange(),h=o.textContent.length;if(!h)return NaN;e.after&&(i+=h),i>=h&&(i=h-1),a.setStart(o,i),a.setEnd(o,i+1);let l=t.getRangeClientRects(a);ss(l,n);let c=l.filter(d=>d.right>d.left&&d.bottom>d.top);if(c.length>0)l=c;else{let d=r?t.getElementComputedStyle(r).whiteSpace:"";l=d==="pre"||d==="pre-wrap"||d==="pre-line"||d==="break-spaces"?l.filter(p=>n?p.right>p.left:p.bottom>p.top):[]}return l.length?(n?s=Math.min.apply(null,l.map(d=>d.left)):s=Math.max.apply(null,l.map(d=>d.bottom)),s):NaN}}function _a(e,t,i){let n=rs(t);n&&_s(t);let o=t.clientLayout.getElementClientRect(e);n&&_l(t);let r=t.getComputedMargin(e);return i?o.width+r.left+r.right:o.height+r.top+r.bottom}function En(e){for(;e;){if(e.parentNode===e.ownerDocument)return!1;e=e.parentNode}return!0}function Hd(e,t){var i;if(e)for(let n=e.lastChild,o=n;n!==t;n=o)o=n.previousSibling,!(n.nodeType===1&&n.hasAttribute("data-vivliostyle-float-box-moved")&&((i=t.style)==null?void 0:i.display)==="inline")&&e.removeChild(n)}var zn="data-adapt-spec";function zl(e){return!!e.getAttribute(zn)}function Ot(e){return e?.nodeType!==1?!1:zl(e)?!0:Wd(e)}function Wd(e){var t,i;if(e?.nodeType!==1)return!1;let n=e,o=(t=n.style)==null?void 0:t.position;if(o==="absolute"||o==="fixed")return!0;let r=(i=n.style)==null?void 0:i.float;return r==="left"||r==="right"||r==="inline-start"||r==="inline-end"}function ru(e){var t;return e?.nodeType!==1?!1:((t=e.style)==null?void 0:t.position)==="fixed"}function Pn(e){let t=e?.viewNode;return t?.nodeType===1&&zl(t)}function vv(e){return e!=="inline"&&(Ut(e)||Ud(e))}function su(e){var t;for(let i=e.parent;i;i=i.parent)if((i.display!=="inline"||i.vertical!==((t=i.parent)==null?void 0:t.vertical))&&Ut(i.display))return i;return null}function wv(e){let t=e;for(;t;){if(t.nodeType===Node.TEXT_NODE&&t.textContent.length>0)return t;if(t.lastChild)t=t.lastChild;else{for(;t&&!t.previousSibling;)if(t=t.parentNode,t===e||!t)return null;t=t?.previousSibling||null}}return null}function Gd(e,t){let i={};return Object.keys(e).forEach(n=>{let o=i[n]={},r=e[n];Object.keys(r).forEach(s=>{o[s]=r[s].map(a=>{let h=t?a.logical:a.physical,l=t?a.physical:a.logical;return{regexp:new RegExp(`(-?)${h}(-?)`),to:`$1${l}$2`}})})}),i}function jd(e,t,i,n){let o=n[t];if(!o)throw new Error(`unknown writing-mode: ${t}`);let r=o[i||"ltr"];if(!r)throw new Error(`unknown direction: ${i}`);for(let s of r){let a=e.replace(s.regexp,s.to);if(a!==e)return a}return e}var Xd={"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"}]}},bv=Gd(Xd,!0);function qd(e,t,i){return jd(e,t,i||null,bv)}var xv=Gd(Xd,!1);function Yd(e,t,i){return jd(e,t,i||null,xv)}var Sv={"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 Cv(e,t){let i=Sv[t];if(!i)throw new Error(`unknown writing-mode: ${t}`);for(let n=0;n<i.length;n++)if(i[n].physical===e)return i[n].logical;return e}function Vl(e,t,i){var n;let o=t,r={width:o.style.width,height:o.style.height};function s(p){return e.getElementComputedStyle(t).getPropertyValue(p)}let a=s("writing-mode")!=="horizontal-tb",h=a?"height":"width",l=a?"width":"height";function c(p,f){o.style[p]=f;let g=s(p);return o.style[p]=r[p],g}let d={};for(let p of i){let f;switch(p){case"max-content inline size":f=c(h,"max-content");break;case"min-content inline size":f=c(h,"min-content");break;case"fit-content inline size":f=c(h,"fit-content");break;case"max-content block size":f=c(l,"max-content");break;case"min-content block size":f=c(l,"min-content");break;case"fit-content block size":f=c(l,"fit-content");break;case"max-content width":f=c("width","max-content");break;case"max-content height":f=c("height","max-content");break;case"min-content width":f=c("width","min-content");break;case"min-content height":f=c("height","min-content");break;case"fit-content width":f=c("width","fit-content");break;case"fit-content height":f=c("height","fit-content");break}f==="0px"&&t.childNodes.length===1&&((n=t.firstElementChild)==null?void 0:n.localName)==="img"&&!t.firstElementChild.complete&&(f="1px"),d[p]=parseFloat(f)}return d}function Nn(e){var t,i;return((t=e?.style)==null?void 0:t["box-decoration-break"])==="clone"||((i=e?.style)==null?void 0:i["-webkit-box-decoration-break"])==="clone"}function Zd(e){let t=e.getAttribute("data-viv-box-break");return t?t.split(" "):[]}function Kd(e,t){e.setAttribute("data-viv-box-break",t.join(" "))}function Ct(e,t){let i=Zd(e);i.includes(t)||(i.push(t),Kd(e,i))}function kv(e){let t=e.getAttribute("data-viv-margin-discard");return t?t.split(" "):[]}function Ev(e,t){e.setAttribute("data-viv-margin-discard",t.join(" "))}function sa(e,t){let i=kv(e);i.includes(t)||(i.push(t),Ev(e,i))}function Pv(e){let t=e.name,i=e.value;switch(t){case"page-break-before":case"page-break-after":case"page-break-inside":return{name:t.replace(/^page-/,""),value:i===y.always?y.page:i,important:e.important};default:return e}}var Da={page:!0,left:!0,right:!0,recto:!0,verso:!0,column:!0,region:!0};function Ze(e){return!!Da[e]}var Nv={left:!0,right:!0,recto:!0,verso:!0};function en(e){return!!Nv[e]}function au(e){return Ze(e)&&e!=="column"&&e!=="region"}var Tv={avoid:!0,"avoid-page":!0,"avoid-column":!0,"avoid-region":!0};function as(e){return!!Tv[e]}function nt(e,t){if(e)if(t){if(en(t))return t;if(en(e))return e;{let i=Ze(e),n=Ze(t);if(i&&n)switch(t){case"column":return e;case"region":return e==="column"?t:e;default:return t}else return n?t:i?e:as(t)?t:as(e)?e:t}}else return e;else return t}function lu(e){return Ze(e)?e:"auto"}Ft("SIMPLE_PROPERTY",Pv);var bo=$g(Wg());function Av(e,t){return(0,bo.default)(e,t,0)}function hu(e){return e.reduce((t,i)=>i[0]===bo.default.DELETE?t:t+i[1],"")}function Iv(e,t){return Jd(e,t,1)}function Fv(e,t){return Jd(e,t,-1)}function Jd(e,t,i){let n=0,o=0;return e.some(r=>{for(let s=0;s<r[1].length;s++){switch(r[0]*i){case bo.default.INSERT:n++;break;case bo.default.DELETE:n--,o++;break;case bo.default.EQUAL:o++;break}if(o>t)return!0}return!1}),Math.max(Math.min(t,o-1)+n,0)}var za;(e=>{function t(i){return i&&i.formattingContextType==="Block"}e.isInstanceOfBlockFormattingContext=t})(za||(za={}));var Rn;(e=>{let t;(i=>(i.INLINE="inline",i.COLUMN="column",i.REGION="region",i.PAGE="page"))(t=e.FloatReference||(e.FloatReference={}))})(Rn||(Rn={}));var ls;(e=>{function t(i){return i&&i.flagmentLayoutConstraintType=="AfterIfContinue"}e.isInstanceOfAfterIfContinuesLayoutConstraint=t})(ls||(ls={}));var Yi;(e=>{function t(n){return n?n.formattingContextType==="RepetitiveElementsOwner"||Li.isInstanceOfTableFormattingContext(n):!1}e.isInstanceOfRepetitiveElementsOwnerFormattingContext=t;function i(n){return n?n.flagmentLayoutConstraintType==="RepetitiveElementsOwner"||Li.isInstanceOfTableRowLayoutConstraint(n):!1}e.isInstanceOfRepetitiveElementsOwnerLayoutConstraint=i})(Yi||(Yi={}));var Li;(e=>{function t(n){return n&&n.formattingContextType==="Table"}e.isInstanceOfTableFormattingContext=t;function i(n){return n&&n.flagmentLayoutConstraintType==="TableRow"}e.isInstanceOfTableRowLayoutConstraint=i})(Li||(Li={}));var yi;(e=>{let t;(n=>(n[n.IGNORE=0]="IGNORE",n[n.NEWLINE=1]="NEWLINE",n[n.PRESERVE=2]="PRESERVE"))(t=e.Whitespace||(e.Whitespace={}));let i;(n=>(n[n.NONE=0]="NONE",n[n.CONTENT=1]="CONTENT",n[n.ROOTLESS=2]="ROOTLESS",n[n.ROOTED=3]="ROOTED"))(i=e.ShadowType||(e.ShadowType={}))})(yi||(yi={}));var Rv={transform:!0,"transform-origin":!0},Lv={top:!0,bottom:!0,left:!0,right:!0},Ul=class{constructor(e,t,i){u(this,"target",e),u(this,"name",t),u(this,"value",i)}},Ov={show:function(e){e.style.visibility="visible"},hide:function(e){e.style.visibility="hidden"},play:function(e){e.currentTime=0,e.play()},pause:function(e){e.pause()},resume:function(e){e.play()},mute:function(e){e.muted=!0},unmute:function(e){e.muted=!1}};function Bv(e,t){let i=Ov[t];return i?()=>{for(let n=0;n<e.length;n++)try{i(e[n])}catch{}}:null}var Va=class co extends Nl{constructor(t,i){super(),u(this,"container",t),u(this,"bleedBox",i),u(this,"pageAreaElement",null),u(this,"delayedItems",[]),u(this,"hrefHandler"),u(this,"elementsById",{}),u(this,"dimensions",{width:0,height:0}),u(this,"isFirstPage",!1),u(this,"isLastPage",!1),u(this,"isBlankPage",!1),u(this,"isAutoPageWidth",!0),u(this,"isAutoPageHeight",!0),u(this,"spineIndex",0),u(this,"position",null),u(this,"offset",-1),u(this,"side",null),u(this,"fetchers",[]),u(this,"marginBoxes",{top:{},bottom:{},left:{},right:{}}),u(this,"pageFloatLayoutContext",null),u(this,"pageType",null),this.hrefHandler=n=>{let o=n.currentTarget,r=o.getAttribute("href")||o.getAttributeNS("http://www.w3.org/1999/xlink","href");if(r){let s={type:"hyperlink",target:null,currentTarget:null,anchorElement:o,href:r,preventDefault(){n.preventDefault()}};this.dispatchEvent(s)}}}setAutoPageWidth(t){this.isAutoPageWidth=t,t?this.container.setAttribute(co.AUTO_PAGE_WIDTH_ATTRIBUTE,"true"):this.container.removeAttribute(co.AUTO_PAGE_WIDTH_ATTRIBUTE)}setAutoPageHeight(t){this.isAutoPageHeight=t,t?this.container.setAttribute(co.AUTO_PAGE_HEIGHT_ATTRIBUTE,"true"):this.container.removeAttribute(co.AUTO_PAGE_HEIGHT_ATTRIBUTE)}registerElementWithId(t,i){let n=this.elementsById[i];n?n.push(t):this.elementsById[i]=[t]}finish(t,i){Object.keys(this.elementsById).forEach(r=>{let s=this.elementsById[r];for(let a=0;a<s.length;)this.container.contains(s[a])?a++:s.splice(a,1);s.length===0&&delete this.elementsById[r]});let n=this.delayedItems;for(let r=0;r<n.length;r++){let s=n[r];s.target===this.container&&s.name==="transform"&&!this.isAutoPageWidth&&!this.isAutoPageHeight||I(s.target,s.name,s.value.toString())}let o=i.getElementClientRect(this.container);this.dimensions.width=o.width,this.dimensions.height=o.height;for(let r=0;r<t.length;r++){let s=t[r],a=this.elementsById[s.ref],h=this.elementsById[s.observer];if(a&&h){let l=Bv(a,s.action);if(l)for(let c=0;c<h.length;c++)h[c].addEventListener(s.event,l,!1)}}}};u(Va,"AUTO_PAGE_WIDTH_ATTRIBUTE","data-vivliostyle-auto-page-width"),u(Va,"AUTO_PAGE_HEIGHT_ATTRIBUTE","data-vivliostyle-auto-page-height");var Qd=Va,bt=yi.Whitespace;function ep(e){switch(e){case"normal":case"nowrap":return bt.IGNORE;case"pre-line":return bt.NEWLINE;case"pre":case"pre-wrap":case"break-spaces":return bt.PRESERVE;default:return null}}function Ee(e,t){return e?e.nodeType==1?!1:tp(e.textContent,t):!0}function tp(e,t){switch(t){case bt.PRESERVE:return e.length==0;case bt.NEWLINE:return!!e.match(/^[ \t]*$/);case bt.IGNORE:default:return!!e.match(/^[ \t\r\n\f]*$/)}}var Mv=class{constructor(e,t){u(this,"flowName",e),u(this,"parentFlowName",t),u(this,"forcedBreakOffsets",[]),u(this,"formattingContext",null)}},_v=class{constructor(e,t,i,n,o,r,s,a,h){u(this,"flowName",e),u(this,"element",t),u(this,"startOffset",i),u(this,"priority",n),u(this,"linger",o),u(this,"exclusive",r),u(this,"repeated",s),u(this,"last",a),u(this,"breakBefore",h),u(this,"startPage",-1)}isBetter(e){return this.exclusive?!e.exclusive||this.priority>e.priority?!0:this.last:!1}};function Dv(e,t){return e.top-t.top}function zv(e,t){return t.right-e.right}function ip(e,t){var i,n;return e===t?!0:!e||!t?!1:(e.node===t.node||!!e.shadowContext&&!!t.shadowContext&&e.shadowType===yi.ShadowType.ROOTLESS&&t.shadowType===yi.ShadowType.ROOTLESS&&((i=e.node)==null?void 0:i.outerHTML)===((n=t.node)==null?void 0:n.outerHTML))&&e.shadowType===t.shadowType&&Ua(e.shadowContext,t.shadowContext)&&Ua(e.nodeShadow,t.nodeShadow)&&ip(e.shadowSibling,t.shadowSibling)}function Oi(e,t){if(e===t)return!0;if(!e||!t||e.offsetInNode!==t.offsetInNode||e.after!==t.after||e.steps.length!==t.steps.length)return!1;for(let i=0;i<e.steps.length;i++)if(!ip(e.steps[i],t.steps[i]))return!1;return!0}function Vv(e){return{steps:[{node:e,shadowType:st.NONE,shadowContext:null,nodeShadow:null,shadowSibling:null,formattingContext:null,fragmentIndex:0}],offsetInNode:0,after:!1,preprocessedTextContent:null}}function hs(e,t){return{steps:[{node:e.sourceNode,shadowType:st.NONE,shadowContext:e.shadowContext,nodeShadow:null,shadowSibling:null,formattingContext:e.formattingContext,fragmentIndex:t??e.fragmentIndex}],offsetInNode:0,after:!1,preprocessedTextContent:e.preprocessedTextContent}}function us(e,t){let i=new xn(e.node,t,0);return i.shadowType=e.shadowType,i.shadowContext=e.shadowContext,i.nodeShadow=e.nodeShadow,i.shadowSibling=e.shadowSibling?us(e.shadowSibling,t.copy()):null,i.formattingContext=e.formattingContext,i.fragmentIndex=e.fragmentIndex+1,i}var st=yi.ShadowType,Br=class{constructor(e,t,i,n,o,r,s){u(this,"owner",e),u(this,"root",t),u(this,"xmldoc",i),u(this,"parentShadow",n),u(this,"type",r),u(this,"styler",s),u(this,"subShadow",null),o&&(o.subShadow=this)}equals(e){return e?this.owner===e.owner&&this.xmldoc===e.xmldoc&&this.type===e.type&&Ua(this.parentShadow,e.parentShadow):!1}};function Ua(e,t){return e===t||!!e&&!!t&&e.equals(t)}var Uv=class{constructor(e,t){u(this,"outer",e),u(this,"count",t)}},xn=class np{constructor(t,i,n){u(this,"sourceNode",t),u(this,"parent",i),u(this,"boxOffset",n),u(this,"offsetInNode",0),u(this,"after",!1),u(this,"shadowType"),u(this,"shadowContext"),u(this,"nodeShadow",null),u(this,"shadowSibling",null),u(this,"shared",!1),u(this,"inline",!0),u(this,"overflow",!1),u(this,"breakPenalty"),u(this,"display",null),u(this,"floatReference"),u(this,"floatSide",null),u(this,"clearSide",null),u(this,"floatMinWrapBlock",null),u(this,"columnSpan",null),u(this,"captionSide","top"),u(this,"inlineBorderSpacing",0),u(this,"blockBorderSpacing",0),u(this,"flexContainer",!1),u(this,"whitespace"),u(this,"hyphenateCharacter"),u(this,"breakWord"),u(this,"establishesBFC",!1),u(this,"containingBlockForAbsolute",!1),u(this,"breakBefore",null),u(this,"breakAfter",null),u(this,"viewNode",null),u(this,"clearSpacer",null),u(this,"inheritedProps"),u(this,"vertical"),u(this,"direction"),u(this,"firstPseudo"),u(this,"lang",null),u(this,"preprocessedTextContent",null),u(this,"formattingContext"),u(this,"repeatOnBreak",null),u(this,"pluginProps",{}),u(this,"fragmentIndex",1),u(this,"afterIfContinues",null),u(this,"footnotePolicy",null),u(this,"pageType"),this.shadowType=st.NONE,this.shadowContext=i?i.shadowContext:null,this.breakPenalty=i?i.breakPenalty:0,this.floatReference=Rn.FloatReference.INLINE,this.whitespace=i?i.whitespace:bt.IGNORE,this.hyphenateCharacter=i?i.hyphenateCharacter:null,this.breakWord=i?i.breakWord:!1,this.inheritedProps=i?i.inheritedProps:{},this.vertical=i?i.vertical:!1,this.direction=i?i.direction:"ltr",this.firstPseudo=i?i.firstPseudo:null,this.formattingContext=i?i.formattingContext:null,this.pageType=i?i.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=Rn.FloatReference.INLINE,this.floatSide=null,this.clearSide=null,this.floatMinWrapBlock=null,this.columnSpan=null,this.flexContainer=!1,this.whitespace=this.parent?this.parent.whitespace:bt.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,this.pageType=this.parent?this.parent.pageType:null}cloneItem(){let t=new np(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.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.pageType=this.pageType,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(),i=t,n;for(;(n=i.parent)!=null;)n=n.cloneItem(),i.parent=n,i=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 t,i,n;let o=this,r=[];o.shadowType===yi.ShadowType.ROOTLESS&&(o.floatReference!==Rn.FloatReference.INLINE||o.floatSide==="footnote")&&(n=(i=(t=o.shadowContext)==null?void 0:t.styler)==null?void 0:i.style)!=null&&n._pseudos&&(o=o.parent);do(!o.firstPseudo||!o.parent||o.parent.firstPseudo===o.firstPseudo)&&r.push(o.toNodePositionStep()),o=o.parent;while(o);let s=this.preprocessedTextContent?Fv(this.preprocessedTextContent,this.offsetInNode):this.offsetInNode;return{steps:r,offsetInNode:s,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}},Bi=class op{constructor(t){u(this,"primary",t),u(this,"floats",null)}clone(){let t=new op(this.primary);if(this.floats){t.floats=[];for(let i=0;i<this.floats.length;++i)t.floats[i]=this.floats[i]}return t}isSamePosition(t){if(!t)return!1;if(this===t)return!0;if(!Oi(this.primary,t.primary))return!1;if(this.floats){if(!t.floats||this.floats.length!==t.floats.length)return!1;for(let i=0;i<this.floats.length;i++)if(!Oi(this.floats[i],t.floats[i]))return!1}else if(t.floats)return!1;return!0}},$v=class rp{constructor(t,i){u(this,"chunkPosition",t),u(this,"flowChunk",i)}clone(){return new rp(this.chunkPosition.clone(),this.flowChunk)}isSamePosition(t){return!!t&&(this===t||this.chunkPosition.isSamePosition(t.chunkPosition))}},Hv=class sp{constructor(){u(this,"positions",[]),u(this,"startBreakType",null),u(this,"breakAfter",null)}clone(){let t=new sp,i=this.positions,n=t.positions;for(let o=0;o<i.length;o++)n[o]=i[o].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 i=0;i<this.positions.length;i++)if(!this.positions[i].isSamePosition(t.positions[i]))return!1;return!0}hasContent(t){return this.positions.length>0&&this.positions[0].flowChunk.startOffset<=t}},Wv=class ap{constructor(){u(this,"page",0),u(this,"flows",{}),u(this,"flowPositions",{}),u(this,"isBlankPage",!1),u(this,"highestSeenOffset",0),u(this,"highestSeenNode"),u(this,"lookupPositionOffset")}clone(){let t=new ap;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 i in this.flowPositions)t.flowPositions[i]=this.flowPositions[i].clone();return t}isSamePosition(t){if(this===t)return!0;if(!t||this.page!==t.page)return!1;let i=Object.keys(this.flowPositions),n=Object.keys(t.flowPositions);if(i.length!==n.length)return!1;for(let o of i)if(!this.flowPositions[o].isSamePosition(t.flowPositions[o]))return!1;return!0}hasContent(t,i){let n=this.flowPositions[t];return n?n.hasContent(i):!1}startSideOfFlow(t){var i;let n=(i=this.flowPositions[t])==null?void 0:i.startBreakType;return n&&en(n)?n:"any"}firstFlowChunkOfFlow(t){let i=this.flowPositions[t];if(!i)return null;let n=i.positions[0];return n?n.flowChunk:null}},lp=class{constructor(e){u(this,"element",e),u(this,"left",0),u(this,"top",0),u(this,"marginLeft",0),u(this,"marginRight",0),u(this,"marginTop",0),u(this,"marginBottom",0),u(this,"borderLeft",0),u(this,"borderRight",0),u(this,"borderTop",0),u(this,"borderBottom",0),u(this,"paddingLeft",0),u(this,"paddingRight",0),u(this,"paddingTop",0),u(this,"paddingBottom",0),u(this,"width",0),u(this,"height",0),u(this,"originX",0),u(this,"originY",0),u(this,"exclusions",null),u(this,"innerShape",null),u(this,"computedBlockSize",0),u(this,"snapWidth",0),u(this,"snapHeight",0),u(this,"snapOffsetX",0),u(this,"snapOffsetY",0),u(this,"vertical",!1),u(this,"rtl",!1),u(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(e){return this.vertical?e.right:e.top}getAfterEdge(e){return this.vertical?e.left:e.bottom}getStartEdge(e){return this.vertical?this.rtl?e.bottom:e.top:this.rtl?e.right:e.left}getEndEdge(e){return this.vertical?this.rtl?e.top:e.bottom:this.rtl?e.left:e.right}getInlineSize(e){return this.vertical?e.bottom-e.top:e.right-e.left}getBoxSize(e){return this.vertical?e.right-e.left:e.bottom-e.top}getBoxDir(){return this.vertical?-1:1}getInlineDir(){return this.rtl?-1:1}copyFrom(e){this.element=e.element,this.left=e.left,this.top=e.top,this.marginLeft=e.marginLeft,this.marginRight=e.marginRight,this.marginTop=e.marginTop,this.marginBottom=e.marginBottom,this.borderLeft=e.borderLeft,this.borderRight=e.borderRight,this.borderTop=e.borderTop,this.borderBottom=e.borderBottom,this.paddingLeft=e.paddingLeft,this.paddingRight=e.paddingRight,this.paddingTop=e.paddingTop,this.paddingBottom=e.paddingBottom,this.width=e.width,this.height=e.height,this.originX=e.originX,this.originY=e.originY,this.innerShape=e.innerShape,this.exclusions=e.exclusions,this.computedBlockSize=e.computedBlockSize,this.snapWidth=e.snapWidth,this.snapHeight=e.snapHeight,this.vertical=e.vertical,this.rtl=e.rtl,this.borderBoxSizing=e.borderBoxSizing}setVerticalPosition(e,t){this.top=e,this.height=t,I(this.element,"top",`${e}px`),I(this.element,"height",`${t}px`)}setHorizontalPosition(e,t){this.left=e,this.width=t,I(this.element,"left",`${e}px`),I(this.element,"width",`${t}px`)}setBlockPosition(e,t){if(this.vertical){let i=t+this.marginLeft+this.marginRight+(this.borderBoxSizing?0:this.paddingLeft+this.paddingRight+this.borderLeft+this.borderRight);this.setHorizontalPosition(e+i*this.getBoxDir(),t)}else this.setVerticalPosition(e,t)}setInlinePosition(e,t){if(this.vertical)if(this.rtl){let i=t+this.marginTop+this.marginBottom+(this.borderBoxSizing?0:this.paddingTop+this.paddingBottom+this.borderTop+this.borderBottom);this.setVerticalPosition(e+i*this.getInlineDir(),t)}else this.setVerticalPosition(e,t);else if(this.rtl){let i=t+this.marginLeft+this.marginRight+(this.borderBoxSizing?0:this.paddingLeft+this.paddingRight+this.borderLeft+this.borderRight);this.setHorizontalPosition(e+i*this.getInlineDir(),t)}else this.setHorizontalPosition(e,t)}clear(){let e=this.element,t;for(;t=e.lastChild;)e.removeChild(t)}getInnerShape(){let e=this.getInnerRect();return this.innerShape?this.innerShape.withOffset(e.x1,e.y1):Ol(e.x1,e.y1,e.x2,e.y2)}getInnerRect(){let e=this.originX+this.left+this.getInsetLeft(),t=this.originY+this.top+this.getInsetTop();return new Mt(e,t,e+this.width,t+this.height)}getPaddingRect(){let e=this.originX+this.left+this.marginLeft+this.borderLeft,t=this.originY+this.top+this.marginTop+this.borderTop,i=this.paddingLeft+this.width+this.paddingRight,n=this.paddingTop+this.height+this.paddingBottom;return new Mt(e,t,e+i,t+n)}getOuterShape(e,t){let i=this.getOuterRect();return ld(e,i.x1,i.y1,i.x2-i.x1,i.y2-i.y1,t)}getOuterRect(){let e=this.originX+this.left,t=this.originY+this.top,i=this.getInsetLeft()+this.width+this.getInsetRight(),n=this.getInsetTop()+this.height+this.getInsetBottom();return new Mt(e,t,e+i,t+n)}},Oo=class extends Kt{constructor(e,t,i,n){super(),u(this,"elem",e),u(this,"context",t),u(this,"rootContentValue",i),u(this,"exprContentListener",n)}visitStrInner(e,t){var i;if(!t){if(((i=this.elem.lastChild)==null?void 0:i.nodeType)===3){this.elem.lastChild.textContent+=e;return}t=this.elem.ownerDocument.createTextNode(e)}this.elem.appendChild(t)}visitStr(e){return this.visitStrInner(e.str),null}visitURL(e){if(this.rootContentValue instanceof Qe)this.elem.setAttribute("src",e.url);else{let t=this.elem.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml","img");t.setAttribute("src",e.url),this.elem.appendChild(t)}return null}visitSpaceList(e){return this.visitValues(e.values),null}visitExpr(e){let t=e.toExpr();if(t instanceof we){let n=t;if(typeof n.getContentList=="function"){let o=n.getContentList();if(o)return o.visit(this),null}}let i=t.evaluate(this.context);if(typeof i=="string"){this.elem.ownerDocument;let n=this.exprContentListener(t,i,this.elem.ownerDocument);!n&&i&&t instanceof we&&t.str.startsWith("running-element-")&&(i=""),this.visitStrInner(i,n)}return null}};function It(e){return e!=null&&e!==Be&&e!==y.normal&&e!==y.none&&!Z(e)}var Pe=Rn.FloatReference,Gv=20;function jv(e){switch(e){case"inline":return Pe.INLINE;case"column":return Pe.COLUMN;case"region":return Pe.REGION;case"page":return Pe.PAGE;default:throw new Error(`Unknown float-reference: ${e}`)}}function Ii(e){switch(e){case Pe.INLINE:return!1;case Pe.COLUMN:case Pe.REGION:case Pe.PAGE:return!0;default:throw new Error(`Unknown float-reference: ${e}`)}}function aa(e,t,i,n){let o=t?"vertical-rl":"horizontal-tb";if((e==="top"||e==="bottom")&&(e=Yd(e,o,i)),e==="block-start"&&(e="inline-start"),e==="block-end"&&(e="inline-end"),e==="inline-start"||e==="inline-end"){let r=qd(e,o,i),s=Cv(r,o);s==="line-left"?e="left":s==="line-right"&&(e="right")}else e==="inside"?e=n==="left"?"right":"left":e==="outside"&&(e=n==="left"?"left":"right");return e!=="left"&&e!=="right"&&(Y.warn(`Invalid float value: ${e}. Fallback to left.`),e="left"),e}var hp=class{constructor(e,t,i,n,o,r){u(this,"nodePosition",e),u(this,"floatReference",t),u(this,"floatSide",i),u(this,"clearSide",n),u(this,"flowName",o),u(this,"floatMinWrapBlock",r),u(this,"order",null),u(this,"id",null),u(this,"insidePageFloatArea",!1),u(this,"parentPageFloat",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(e){return e.isAnchorAlreadyAppeared(this.getId())?!0:this.insidePageFloatArea&&this.parentPageFloat?!!e.findPageFloatFragment(this.parentPageFloat):!1}isAllowedToPrecede(e){return!1}},Xv=class{constructor(){u(this,"floats",[]),u(this,"nextPageFloatIndex",0)}nextOrder(){return this.nextPageFloatIndex++}createPageFloatId(e){return`pf${e}`}addPageFloat(e){if(this.floats.findIndex(t=>Oi(t.nodePosition,e.nodePosition))>=0)throw new Error("A page float with the same source node is already registered");{let t=e.order=this.nextOrder();e.id=this.createPageFloatId(t),this.floats.push(e)}}findPageFloatByNodePosition(e){let t=this.floats.findIndex(n=>Oi(n.nodePosition,e));if(t>=0)return this.floats[t];let i=e?.steps;if(i!=null&&i.length){let n=this.floats.findIndex(o=>{let r=o.nodePosition.steps;if(!(r!=null&&r.length)||r.length===i.length||o.nodePosition.offsetInNode!==e.offsetInNode||o.nodePosition.after!==e.after)return!1;let s=Math.min(r.length,i.length);for(let a=0;a<s;a++)if(r[a].node!==i[a].node)return!1;return!0});if(n>=0)return this.floats[n]}return null}findPageFloatById(e){let t=this.floats.findIndex(i=>i.id===e);return t>=0?this.floats[t]:null}},up=class{constructor(e,t,i,n,o,r){u(this,"floatReference",e),u(this,"floatSide",t),u(this,"clearSide",i),u(this,"continuations",n),u(this,"area",o),u(this,"continues",r)}hasFloat(e){return this.continuations.some(t=>t.float===e)}findNotAllowedFloat(e){for(let t=this.continuations.length-1;t>=0;t--){let i=this.continuations[t].float;if(!i.isAllowedOnContext(e))return i}return null}getOuterShape(){return this.area.getOuterShape(null,null)}getOuterRect(){return this.area.getOuterRect()}getOrder(){let e=this.continuations.map(t=>t.float);return Math.min.apply(null,e.map(t=>t.getOrder()))}shouldBeStashedBefore(e){return this.getOrder()<e.getOrder()}addContinuations(e){e.forEach(t=>{this.continuations.push(t)})}getFlowName(){let e=this.continuations[0].float.flowName;return this.continuations.every(t=>t.float.flowName===e),e}},uu=class{constructor(e,t){u(this,"float",e),u(this,"nodePosition",t)}equals(e){return e?this===e?!0:this.float===e.float&&Oi(this.nodePosition,e.nodePosition):!1}},Sn=class{constructor(e,t,i,n,o,r,s){u(this,"parent",e),u(this,"floatReference",t),u(this,"container",i),u(this,"flowName",n),u(this,"generatingNodePosition",o),u(this,"children",[]),u(this,"writingMode"),u(this,"direction"),u(this,"invalidated",!1),u(this,"floatStore"),u(this,"forbiddenFloats",[]),u(this,"floatFragments",[]),u(this,"stashedFloatFragments",[]),u(this,"floatAnchors",{}),u(this,"floatsDeferredToNext",[]),u(this,"floatsDeferredFromPrevious"),u(this,"layoutConstraints",[]),u(this,"locked",!1),u(this,"footnoteMaxBlockSize",null),u(this,"ignoreFootnoteAreaMaxHeight",!1),u(this,"footnoteAnchorsSeen",new Set),u(this,"lineFootnoteInvalidationMaxBlockSize",new Map),u(this,"lineFootnoteFinishInvalidatedOnce",new Set),u(this,"outerContext",null),e&&e.children.push(this),this.writingMode=!Z(r)&&r||e&&e.writingMode||y.horizontal_tb,this.direction=!Z(s)&&s||e&&e.direction||y.ltr,this.floatStore=e?e.floatStore:new Xv;let a=this.getPreviousSibling();this.floatsDeferredFromPrevious=a?[].concat(a.floatsDeferredToNext):[]}get effectiveParent(){var e;return(e=this.parent)!=null?e:this.outerContext}getParent(e){if(this.parent)return this.parent;if(this.outerContext)return this.outerContext;throw new Error(`No PageFloatLayoutContext for ${e}`)}setOuterContext(e){this.outerContext=e,this.floatStore=e.floatStore}addPageFloatLayoutContextAsPreviousSibling(e){this.children.push(e)}getPreviousSiblingOf(e,t,i,n){let o=this.children.indexOf(e);o<0&&(o=this.children.length);for(let r=o-1;r>=0;r--){let s=this.children[r];if(s.floatReference===t&&s.flowName===i&&Oi(s.generatingNodePosition,n)||(s=s.getPreviousSiblingOf(null,t,i,n),s))return s}return null}getPreviousSibling(){let e=this,t=this.parent,i;for(;t;){if(i=t.getPreviousSiblingOf(e,this.floatReference,this.flowName,this.generatingNodePosition),i)return i;e=t,t=t.parent}return null}getContainer(e){return!e||e===this.floatReference?this.container:this.getParent(e).getContainer(e)}setContainer(e){this.container=e,this.reattachFloatFragments()}addPageFloat(e){this.floatStore.addPageFloat(e)}getPageFloatLayoutContext(e){return e===this.floatReference?this:this.getParent(e).getPageFloatLayoutContext(e)}findPageFloatByNodePosition(e){return this.floatStore.findPageFloatByNodePosition(e)}forbid(e){let t=e.getId(),i=e.floatReference;i===this.floatReference?this.forbiddenFloats.includes(t)||(this.forbiddenFloats.push(t),new Vn().findByFloat(e).forbid(e,this)):this.getParent(i).forbid(e)}isForbidden(e){let t=e.getId(),i=e.floatReference;return i===this.floatReference?this.forbiddenFloats.includes(t):this.getParent(i).isForbidden(e)}addPageFloatFragment(e,t){let i=e.floatReference;i!==this.floatReference?this.getParent(i).addPageFloatFragment(e,t):this.floatFragments.includes(e)||(this.floatFragments.push(e),this.floatFragments.sort((n,o)=>n.getOrder()-o.getOrder())),t||this.invalidate()}removePageFloatFragment(e,t){let i=e.floatReference;if(i!==this.floatReference)this.getParent(i).removePageFloatFragment(e,t);else{let n=this.floatFragments.indexOf(e);if(n>=0){let o=this.floatFragments.splice(n,1)[0],r=o.area&&o.area.element;r&&r.parentNode&&r.parentNode.removeChild(r),t||this.invalidate()}}}findPageFloatFragment(e){if(e.floatReference!==this.floatReference)return this.getParent(e.floatReference).findPageFloatFragment(e);let t=this.floatFragments.findIndex(i=>i.hasFloat(e));return t>=0?this.floatFragments[t]:null}hasFloatFragments(e){return this.floatFragments.length>0&&(!e||this.floatFragments.some(e))?!0:this.parent?this.parent.hasFloatFragments(e):!1}hasContinuingFloatFragmentsInFlow(e){return this.hasFloatFragments(t=>t.continues&&t.getFlowName()===e&&t.floatSide!=="block-end")}markPageFloatAnchorSeen(e){var t;if(!("footnotePolicy"in e))return;let i=this;for(;i;)i.footnoteAnchorsSeen.add(e.getId()),i=(t=i.parent)!=null?t:i.outerContext}registerPageFloatAnchor(e,t){this.floatAnchors[e.getId()]=t,this.markPageFloatAnchorSeen(e)}collectPageFloatAnchors(){let e=Object.assign({},this.floatAnchors);return this.children.reduce((t,i)=>Object.assign(t,i.collectPageFloatAnchors()),e)}findPageFloatAnchor(e){var t;for(let i=this.children.length-1;i>=0;i--){let n=this.children[i].findPageFloatAnchor(e);if(n)return n}return(t=this.floatAnchors[e])!=null?t:null}hasCurrentAnchor(e){var t,i;let n=this.findPageFloatAnchor(e);return n?!!((i=(t=this.container)==null?void 0:t.element)!=null&&i.contains(n)):!1}hasInvalidatedForLineFootnote(e){return e.floatReference===this.floatReference?this.lineFootnoteInvalidationMaxBlockSize.get(e.getId())===this.footnoteMaxBlockSize:this.getParent(e.floatReference).hasInvalidatedForLineFootnote(e)}markInvalidatedForLineFootnote(e){e.floatReference===this.floatReference?this.lineFootnoteInvalidationMaxBlockSize.set(e.getId(),this.footnoteMaxBlockSize):this.getParent(e.floatReference).markInvalidatedForLineFootnote(e)}isAnchorAlreadyAppeared(e){if(this.getDeferredPageFloatContinuations().some(i=>i.float.getId()===e))return!0;let t=this.findPageFloatAnchor(e);return t&&this.container&&this.container.element?this.container.element.contains(t):!1}deferPageFloat(e){let t=e.float;if(t.floatReference===this.floatReference){let i=this.floatsDeferredToNext.findIndex(n=>n.float===t);i>=0?this.floatsDeferredToNext.splice(i,1,e):this.floatsDeferredToNext.push(e)}else this.getParent(t.floatReference).deferPageFloat(e)}removeFloatDeferredToNext(e){let t=this.floatsDeferredToNext.findIndex(i=>i.float===e);t>=0&&this.floatsDeferredToNext.splice(t,1)}hasPrecedingFloatsDeferredToNext(e,t){if(!t&&e.floatReference!==this.floatReference)return this.getParent(e.floatReference).hasPrecedingFloatsDeferredToNext(e,!1);let i=e.getOrder();return this.floatsDeferredToNext.some(n=>n.float.getOrder()<i&&!e.isAllowedToPrecede(n.float))?!0:this.parent?this.parent.hasPrecedingFloatsDeferredToNext(e,!0):!1}getLastFollowingFloatInFragments(e){let t=e.getOrder(),i=null;if(this.floatFragments.forEach(n=>{n.continuations.forEach(o=>{let r=o.float,s=r.getOrder();s>t&&(!i||s>i.getOrder())&&(i=r)})}),this.parent){let n=this.parent.getLastFollowingFloatInFragments(e);n&&(!i||n.getOrder()>i.getOrder())&&(i=n)}return i}getDeferredPageFloatContinuations(e){e=e||this.flowName;let t=this.floatsDeferredFromPrevious.filter(i=>!e||i.float.flowName===e);return this.parent&&(t=this.parent.getDeferredPageFloatContinuations(e).concat(t)),t.sort((i,n)=>i.float.getOrder()-n.float.getOrder())}getPageFloatContinuationsDeferredToNext(e){e=e||this.flowName;let t=this.floatsDeferredToNext.filter(i=>!e||i.float.flowName===e);return this.parent?this.parent.getPageFloatContinuationsDeferredToNext(e).concat(t):t}getFloatsDeferredToNextInChildContexts(){let e=[],t=[];for(let i=this.children.length-1;i>=0;i--){let n=this.children[i];t.includes(n.flowName)||(t.push(n.flowName),e=e.concat(n.floatsDeferredToNext.map(o=>o.float)),e=e.concat(n.getFloatsDeferredToNextInChildContexts()))}return e}hasRootMultiColumnFootnoteContext(){return this.children.some(e=>{let t=0;for(let i of e.children)if(!i.generatingNodePosition&&(t+=1,t>1))return!0;return!1})}hasNonRootMultiColumnFootnoteContext(){return this.children.some(e=>e.children.some(t=>{var i;let n=(i=t.getContainer())==null?void 0:i.element;return n!=null&&gv(n)}))}hasMultiColumnFootnoteContext(){return this.hasRootMultiColumnFootnoteContext()||this.hasNonRootMultiColumnFootnoteContext()}trySetFootnoteRetryMaxBlockSize(e){let t=this.footnoteMaxBlockSize!=null?this.footnoteMaxBlockSize/2:e/2;return t<Gv?!1:(this.footnoteMaxBlockSize=t,!0)}initFootnoteRetryFromEmptyFragment(e,t){if(!("footnotePolicy"in e&&this.footnoteMaxBlockSize==null&&this.footnoteAnchorsSeen.has(e.getId())&&this.hasMultiColumnFootnoteContext()))return!1;let i=(t.vertical?t.width:t.height)+t.getInsetBefore()+t.getInsetAfter();return this.trySetFootnoteRetryMaxBlockSize(i)}checkAndForbidNotAllowedFloat(){if(this.checkAndForbidFloatFollowingDeferredFloat())return!0;for(let e=this.floatFragments.length-1;e>=0;e--){let t=this.floatFragments[e],i=t.findNotAllowedFloat(this);if(i){let n=t.area&&"isFootnote"in t.area&&t.area.isFootnote;if(this.locked)this.invalidate();else{let o=n&&"footnotePolicy"in i&&i.footnotePolicy===y.line;if(n&&this.footnoteAnchorsSeen.has(i.getId())&&(o||this.hasMultiColumnFootnoteContext())){let r=t.area.computedBlockSize+t.area.getInsetBefore()+t.area.getInsetAfter();if(this.trySetFootnoteRetryMaxBlockSize(r))return this.removePageFloatFragment(t),this.removeEndFloatFragments(t.floatSide),!0}this.removePageFloatFragment(t),this.forbid(i),this.removeEndFloatFragments(t.floatSide)}return!0}}return this.floatReference===Pe.REGION&&this.parent.locked?this.parent.checkAndForbidNotAllowedFloat():!1}checkAndForbidFloatFollowingDeferredFloat(){let e=this.getFloatsDeferredToNextInChildContexts(),t=this.floatFragments.reduce((i,n)=>i.concat(n.continuations.map(o=>o.float)),[]);t.sort((i,n)=>n.getOrder()-i.getOrder());for(let i of t){let n=i.getOrder();if(e.some(o=>!i.isAllowedToPrecede(o)&&n>o.getOrder())){if(this.locked)this.invalidate();else{this.forbid(i);let o=this.findPageFloatFragment(i);this.removePageFloatFragment(o)}return!0}}return!1}finish(){for(let e=this.floatFragments.length-1;e>=0;e--){let t=this.floatFragments[e];if(t.continuations.some(i=>{let n=i.float;return"footnotePolicy"in n&&n.footnotePolicy===y.line&&!this.hasCurrentAnchor(n.getId())&&!this.floatsDeferredFromPrevious.some(o=>o.float===n)})){if(this.locked){this.invalidate();return}this.removePageFloatFragment(t);return}}if(!this.checkAndForbidNotAllowedFloat()){for(let e=this.floatsDeferredToNext.length-1;e>=0;e--){let t=this.floatsDeferredToNext[e].float,i=this.findPageFloatFragment(t);if("footnotePolicy"in t&&t.footnotePolicy===y.line&&this.hasCurrentAnchor(t.getId())&&!i&&!this.lineFootnoteFinishInvalidatedOnce.has(t.getId())){if(this.locked){this.invalidate();return}this.lineFootnoteFinishInvalidatedOnce.add(t.getId()),this.removeFloatDeferredToNext(t),this.forbid(t),this.invalidate();return}}for(let e=this.floatsDeferredToNext.length-1;e>=0;e--)if(!this.floatsDeferredToNext[e].float.isAllowedOnContext(this)){if(this.locked){this.invalidate();return}this.floatsDeferredToNext.splice(e,1)}this.floatsDeferredFromPrevious.forEach(e=>{this.floatsDeferredToNext.findIndex(t=>e.equals(t))>=0||this.floatFragments.some(t=>t.hasFloat(e.float))||this.floatsDeferredToNext.push(e)})}}hasSameContainerAs(e){return!!this.container&&!!e.container&&this.container.element===e.container.element}invalidate(){this.invalidated=!0,!this.locked&&(this.container&&(this.children.forEach(e=>{this.hasSameContainerAs(e)&&e.floatFragments.forEach(t=>{let i=t.area.element;i&&i.parentNode&&i.parentNode.removeChild(i)})}),this.container.clear()),this.children.forEach(e=>{e.layoutConstraints.splice(0)}),this.children.splice(0),Object.keys(this.floatAnchors).forEach(e=>{delete this.floatAnchors[e]}))}detachChildren(){let e=this.children.splice(0);return e.forEach(t=>{t.floatFragments.forEach(i=>{let n=i.area.element;n&&n.parentNode&&n.parentNode.removeChild(n)})}),e}attachChildren(e){e.forEach(t=>{this.children.push(t),t.reattachFloatFragments()})}isInvalidated(){return this.invalidated||!!this.parent&&this.parent.isInvalidated()}validate(){this.invalidated=!1}toLogical(e){let t=this.writingMode.toString(),i=this.direction.toString();if(e==="inside"||e==="outside"){let n=!!this.container.element.closest("[data-vivliostyle-page-side='left']");e=e==="inside"?n?"right":"left":n?"left":"right"}return Yd(e,t,i)}toPhysical(e){let t=this.writingMode.toString(),i=this.direction.toString();return qd(e,t,i)}toLogicalFloatSides(e){let t=e.split(" "),i=[];for(let s of t){let a=this.toLogical(s);i.includes(a)||i.push(a)}let n=[],o=!1,r=!1;for(let s=0;s<i.length;s++){let a=i[s];a.includes("block")?o||(i.slice(s+1).some(h=>h.includes("block"))?(n.push("snap-block"),o=!0):n.push(a)):a.includes("inline")&&(r||(i.slice(s+1).some(h=>h.includes("inline"))?(n.push("snap-inline"),r=!0):n.push(a)))}return n}removeEndFloatFragments(e){let t=this.toLogicalFloatSides(e)[0];if(t==="block-end"||t==="inline-end"){let i=0;for(;i<this.floatFragments.length;){let n=this.floatFragments[i];this.toLogicalFloatSides(n.floatSide)[0]===t?this.removePageFloatFragment(n):i++}}}isFragmentInCurrentContainer(e){var t;if(this.floatReference!==Pe.REGION)return!0;let i=e.area;return!i.parentElement||!((t=this.container)!=null&&t.element)||i.parentElement===this.container.element}stashEndFloatFragments(e){let t=e.floatReference;if(t!==this.floatReference){this.getParent(t).stashEndFloatFragments(e);return}let i=this.toLogicalFloatSides(e.floatSide)[0];if(i==="block-end"||i==="snap-block"||i==="inline-end"||i==="snap-inline"){let n=0;for(;n<this.floatFragments.length;){let o=this.floatFragments[n],r=this.toLogicalFloatSides(o.floatSide)[0];this.isFragmentInCurrentContainer(o)&&(r===i||i==="snap-block"&&r==="block-end"||i==="snap-inline"&&r==="inline-end")&&o.shouldBeStashedBefore(e)?(this.stashedFloatFragments.push(o),this.floatFragments.splice(n,1)):n++}}}restoreStashedFragments(e){if(e!==this.floatReference){this.getParent(e).restoreStashedFragments(e);return}this.stashedFloatFragments.forEach(t=>{this.addPageFloatFragment(t,!0)}),this.stashedFloatFragments.splice(0)}discardStashedFragments(e){if(e!==this.floatReference){this.getParent(e).discardStashedFragments(e);return}this.stashedFloatFragments.splice(0)}getStashedFloatFragments(e){return e===this.floatReference?this.stashedFloatFragments.concat().sort((t,i)=>i.getOrder()-t.getOrder()):this.getParent(e).getStashedFloatFragments(e)}getLimitValue(e,t,i,n,o,r=!0,s){this.container;let a=this.toLogical(e),h=this.toPhysical(e),l=t&&this.toLogical(t),c=t&&this.toPhysical(t),d=this.getLimitValueInner(a,l,i,n,o,s);if(r&&this.parent&&this.parent.container){let p=this.parent.getLimitValue(h,c,i,n,o,r,s);switch(h){case"top":return Math.max(d,p);case"left":return Math.max(d,p);case"bottom":return Math.min(d,p);case"right":return Math.min(d,p);default:}}return d}getLimitValueInner(e,t,i,n,o,r){this.container;let s=this.getLimitValuesInner(i,n,o,e,t,r);switch(e){case"block-start":return this.container.vertical?s.right:s.top;case"block-end":return this.container.vertical?s.left:s.bottom;case"inline-start":return this.container.vertical?this.container.rtl?s.bottom:s.top:this.container.rtl?s.right:s.left;case"inline-end":return this.container.vertical?this.container.rtl?s.top:s.bottom:this.container.rtl?s.left:s.right;default:throw new Error(`Unknown logical side: ${e}`)}}getLimitValuesInner(e,t,i,n,o,r){var s,a,h,l;this.container;let c=this.container.originX,d=this.container.originY,p=this.container.getPaddingRect(),f={top:p.y1-d,left:p.x1-c,bottom:p.y2-d,right:p.x2-c,floatMinWrapBlockStart:0,floatMinWrapBlockEnd:0};if(this.container.vertical){let w=parseFloat((a=(s=this.container.element)==null?void 0:s.style)==null?void 0:a.width);isFinite(w)&&w>this.container.width&&(f.right+=w-this.container.width)}else{let w=parseFloat((l=(h=this.container.element)==null?void 0:h.style)==null?void 0:l.height);isFinite(w)&&w>this.container.height&&(f.bottom+=w-this.container.height)}function g(w,x,m){return w.unit==="%"?m*w.num/100:e.convertLengthToPx(w,x,t)}let v=this.floatFragments;return v.length>0&&(f=v.reduce((w,x)=>{if(x.area===r||!this.isFragmentInCurrentContainer(x)||i&&!i(x,this))return w;let[m,S]=this.toLogicalFloatSides(x.floatSide);if(S&&(n&&S.includes("block")===n.includes("block")&&S!==n||o&&S.includes("block")===o.includes("block")&&S!==o))return w;let b=x.area,C=x.continuations[0].float.floatMinWrapBlock,P=b.vertical?b.left+b.getInsetLeft()+b.width+b.getInsetRight():b.top+b.getInsetTop()+b.height+b.getInsetBottom(),L=b.vertical?b.top+b.getInsetTop()+b.height+b.getInsetBottom():b.left+b.getInsetLeft()+b.width+b.getInsetRight(),A=w.top,z=w.left,U=w.bottom,X=w.right,oe=w.floatMinWrapBlockStart,k=w.floatMinWrapBlockEnd;switch(m){case"inline-start":b.vertical?A=Math.max(A,L):z=Math.max(z,L);break;case"block-start":b.vertical?(C&&b.left<X&&(oe=g(C,b.rootViewNodes[0],p.x2-p.x1)),X=Math.min(X,b.left)):(C&&P>A&&(oe=g(C,b.rootViewNodes[0],p.y2-p.y1)),A=Math.max(A,P));break;case"inline-end":b.vertical?U=Math.min(U,b.top):X=Math.min(X,b.left);break;case"block-end":b.vertical?(C&&P>z&&(k=g(C,b.rootViewNodes[0],p.x2-p.x1)),z=Math.max(z,P)):(C&&b.top<U&&(k=g(C,b.rootViewNodes[0],p.y2-p.y1)),U=Math.min(U,b.top));break;default:throw new Error(`Unknown logical float side: ${m}`)}return{top:A,left:z,bottom:U,right:X,floatMinWrapBlockStart:oe,floatMinWrapBlockEnd:k}},f)),f.left+=c,f.right+=c,f.top+=d,f.bottom+=d,f}setFloatAreaDimensions(e,t,i,n,o,r,s){if(t!==this.floatReference)return this.getParent(t).setFloatAreaDimensions(e,t,i,n,o,r,s);let a=this.toLogicalFloatSides(i);if(a[0]==="snap-block"){if(!s["block-start"]&&!s["block-end"])return null}else if(a[0].includes("block")&&!s[a[0]])return null;e.clientLayout;let h=a.find(P=>P.includes("inline")&&s[P==="inline-start"?"inline-end":"inline-start"]),l=a.find(P=>P.includes("block")),c=!0,d=this.getLimitValue("block-start",h,e.layoutContext,e.clientLayout,void 0,c,e),p=this.getLimitValue("block-end",h,e.layoutContext,e.clientLayout,void 0,c,e),f=this.getLimitValue("inline-start",l,e.layoutContext,e.clientLayout,void 0,c,e),g=this.getLimitValue("inline-end",l,e.layoutContext,e.clientLayout,void 0,c,e),v=e.vertical?e.originX:e.originY,w=e.vertical?e.originY:e.originX;e.isFootnote||(d=e.vertical?Math.min(d,e.left+e.getInsetLeft()+e.width+e.getInsetRight()+v):Math.max(d,e.top+v),p=e.vertical?Math.max(p,e.left+v):Math.min(p,e.top+e.getInsetTop()+e.height+e.getInsetBottom()+v));function x(P,L){let A=P(e.bands,L);return A?(e.vertical&&(A=rd(A)),d=e.vertical?Math.min(d,A.x2):Math.max(d,A.y1),p=e.vertical?Math.max(p,A.x1):Math.min(p,A.y2),!0):r}let m,S,b,C;if(o){let P=e.vertical?ns(new Mt(p,f,d,g)):new Mt(f,d,g,p);if((a[0]==="block-start"||a[0]==="snap-block"||a[0]==="inline-start"||a[0]==="snap-inline")&&!x(_m,P)||(a[0]==="block-end"||a[0]==="snap-block"||a[0]==="inline-end"||a[0]==="snap-inline")&&!x(Dm,P)||(e.isFootnote&&n!==null&&isFinite(n)&&a[0]==="block-end"&&(e.vertical?d=Math.min(d,n):d=Math.max(d,n)),b=(p-d)*e.getBoxDir(),e.isFootnote&&this.footnoteMaxBlockSize!=null&&(b=Math.min(b,this.footnoteMaxBlockSize),e.vertical?d=p+b:d=p-b),m=Math.max(0,b-e.getInsetBefore()-e.getInsetAfter()),C=(g-f)*e.getInlineDir(),S=C-e.getInsetStart()-e.getInsetEnd(),!r&&(m<=0||S<=0)))return null}else{let P=e.getContentBlockMarginAfter();m=Math.max(0,e.computedBlockSize+Math.min(0,P)),b=m+e.getInsetBefore()+e.getInsetAfter();let L=(p-d)*e.getBoxDir();if(a[0]==="snap-block"){if(n===null)a[0]="block-start";else{let z=this.container.getPaddingRect(),U=this.container.getBoxDir()*(n-(this.container.vertical?z.x2:z.y1)),X=this.container.getBoxDir()*((this.container.vertical?z.x1:z.y2)-n-b);U<=X?a[0]="block-start":a[0]="block-end"}if(!s[a[0]])if(s["block-end"])a[0]="block-end";else return null}else if(a[0]==="snap-inline")if(n===null)a[0]="inline-start";else if(s["inline-start"])a[0]="inline-start";else if(s["inline-end"])a[0]="inline-end";else return null;if(!r&&L<b)return null;a[0]==="inline-start"||a[0]==="inline-end"||a[1]?S=Vl(e.clientLayout,e.element,["fit-content inline size"])["fit-content inline size"]:e.adjustContentRelativeSize?S=e.getContentInlineSize():S=e.vertical?e.height:e.width,C=S+e.getInsetStart()+e.getInsetEnd();let A=(g-f)*e.getInlineDir();if(!r&&A<C)return null}if(d-=v,p-=v,f-=w,g-=w,a.some(P=>P==="inline-start"||P==="snap-inline")||a.length===1&&(a[0]==="block-start"||a[0]==="snap-block")?e.setInlinePosition(f,S):(a.some(P=>P==="inline-end")||a.length===1&&a[0]==="block-end")&&e.setInlinePosition(g-C*e.getInlineDir(),S),a.some(P=>P==="block-start"||P==="snap-block")||a.length===1&&(a[0]==="inline-start"||a[0]==="snap-inline"))e.setBlockPosition(d,m);else if(a.some(P=>P==="block-end")||a.length===1&&a[0]==="inline-end"){let P=p-b*e.getBoxDir();e.setBlockPosition(P,m)}return a.join(" ")}getFloatFragmentExclusions(){let e=this.floatFragments.map(t=>t.getOuterShape());return this.parent?this.parent.getFloatFragmentExclusions().concat(e):e}reattachFloatFragments(){let e=this.container.element&&this.container.element.parentNode;e&&this.floatFragments.forEach(t=>{e.appendChild(t.area.element)})}getMaxReachedAfterEdge(){let e=this.getContainer().vertical;return this.floatFragments.reduce((t,i)=>{let n=i.getOuterRect();return e?Math.min(t,n.x1):Math.max(t,n.y2)},e?1/0:0)}getBlockEndEdgeOfBlockStartFloats(e){let t=this,i=null;for(;t&&!i;)i=t.container,t=t.parent;let n=!!(i!=null&&i.vertical),o=NaN;if(this.floatFragments.filter(r=>r.floatSide.includes("block-start")).filter(r=>{if(!isFinite(e))return!0;let s=r.getOuterRect();return n?s.y1<=e&&e<=s.y2:s.x1<=e&&e<=s.x2}).forEach(r=>{let s=r.getOuterRect(),a=n?s.x1:s.y2;o=isFinite(o)?n?Math.min(o,a):Math.max(o,a):a}),this.parent){let r=this.parent.getBlockEndEdgeOfBlockStartFloats(e);isFinite(r)&&(o=isFinite(o)?n?Math.min(o,r):Math.max(o,r):r)}return o}getBlockStartEdgeOfBlockEndFloats(e){let t=this,i=null;for(;t&&!i;)i=t.container,t=t.parent;let n=!!(i!=null&&i.vertical),o=NaN;if(this.floatFragments.filter(r=>r.floatSide.includes("block-end")).filter(r=>{if(!isFinite(e))return!0;let s=r.getOuterRect();return n?s.y1<=e&&e<=s.y2:s.x1<=e&&e<=s.x2}).forEach(r=>{let s=r.getOuterRect(),a=n?s.x2:s.y1;o=isFinite(o)?n?Math.max(o,a):Math.min(o,a):a}),this.parent){let r=this.parent.getBlockStartEdgeOfBlockEndFloats(e);isFinite(r)&&(o=isFinite(o)?n?Math.max(o,r):Math.min(o,r):r)}return o}getPageFloatClearEdge(e,t){let i=c=>{let d=this.toLogicalFloatSides(c),p=d[0];return e==="both"?p==="block-end":e==="inline-start"?d.includes("inline-end")||p==="block-end":e==="inline-end"?d.includes("inline-start")||p==="block-start"||p==="block-end":!1};function n(c){return d=>!i(d.float.floatSide)&&c.isAnchorAlreadyAppeared(d.float.getId())}function o(c,d){return i(c.floatSide)?!1:c.continuations.some(n(d))}let r=t.getPaddingRect(),s=t.vertical?r.x1:r.y2,a=this;for(;a;){if(a.floatsDeferredToNext.some(n(a)))return s;a=a.parent}function h(c){return c.floatFragments.some(d=>o(d,c))||c.children.some(d=>h(d))}if(e==="column"||e==="region"||e==="page"){for(a=this;a;a=a.parent)if(a.floatReference===e){if(h(a))return s;break}}t.clientLayout;let l=this.getLimitValue("block-start",null,t.layoutContext,t.clientLayout,o);return this.getLimitValue("block-end",null,t.layoutContext,t.clientLayout,o)*t.getBoxDir()<s*t.getBoxDir()?s:l}getPageFloatPlacementCondition(e,t,i){if(e.floatReference!==this.floatReference)return this.getParent(e.floatReference).getPageFloatPlacementCondition(e,t,i);let n={"block-start":!0,"block-end":!0,"inline-start":!0,"inline-end":!0};if(!i)return n;let o=this.toLogicalFloatSides(t)[0],r=this.toLogical(i),s;r==="all"?s=["block-start","block-end","inline-start","inline-end"]:r==="both"?s=["inline-start","inline-end"]:r==="same"?o==="snap-block"?s=["block-start","block-end"]:s=[o]:s=[r];let a=e.getOrder();function h(d){return p=>(!d||p.floatSide.includes(d))&&p.getOrder()<a}function l(d,p){return d.children.some(f=>f.floatFragments.some(h(p))||l(f,p))}function c(d,p){let f=d.parent;return!!f&&(f.floatFragments.some(h(p))||c(f,p))}if(i==="column"||i==="region"||i==="page"){for(let d=this;d;d=d.parent)if(d.floatReference===i){(d.floatFragments.some(h(null))||l(d,null))&&(n["block-start"]=!1,n["block-end"]=!1,n["inline-start"]=!1,n["inline-end"]=!1);break}return n}return s.forEach(d=>{switch(d){case"block-start":n[d]=!l(this,d);break;case"block-end":n[d]=!c(this,d);break;case"inline-start":case"inline-end":n[d]=!this.floatFragments.some(h(d));break;default:throw new Error(`Unexpected side: ${d}`)}}),n}getLayoutConstraints(){return(this.parent?this.parent.getLayoutConstraints():[]).concat(this.layoutConstraints)}addLayoutConstraint(e,t){t===this.floatReference?this.layoutConstraints.push(e):this.getParent(t).addLayoutConstraint(e,t)}isColumnFullWithPageFloats(e){let t=e.layoutContext,i=e.clientLayout,n=this,o=null;for(;n&&n.container;){let s=n.getLimitValuesInner(t,i);o?e.vertical?(s.right<o.right&&(o.right=s.right,o.floatMinWrapBlockStart=s.floatMinWrapBlockStart),s.left>o.left&&(o.left=s.left,o.floatMinWrapBlockEnd=s.floatMinWrapBlockEnd)):(s.top>o.top&&(o.top=s.top,o.floatMinWrapBlockStart=s.floatMinWrapBlockStart),s.bottom<o.bottom&&(o.bottom=s.bottom,o.floatMinWrapBlockEnd=s.floatMinWrapBlockEnd)):o=s,n=n.parent}let r=Math.max(o.floatMinWrapBlockStart,o.floatMinWrapBlockEnd);return(e.vertical?o.right-o.left:o.bottom-o.top)<=r}getMaxBlockSizeOfPageFloats(){let e=this.getContainer().vertical;return this.floatFragments.length?Math.max.apply(null,this.floatFragments.map(t=>{let i=t.area;return e?i.width:i.height})):0}lock(){this.locked=!0}unlock(){this.locked=!1}isLocked(){return this.locked}},to=[],Vn=class{static register(e){to.push(e)}findByNodeContext(e){for(let t=to.length-1;t>=0;t--){let i=to[t];if(i.appliesToNodeContext(e))return i}throw new Error(`No PageFloatLayoutStrategy found for ${e}`)}findByFloat(e){for(let t=to.length-1;t>=0;t--){let i=to[t];if(i.appliesToFloat(e))return i}throw new Error(`No PageFloatLayoutStrategy found for ${e}`)}},qv=class{appliesToNodeContext(e){return Ii(e.floatReference)}appliesToFloat(e){return!0}createPageFloat(e,t,i){let n=e.floatReference;e.floatSide;let o=e.floatSide,r=e.toNodePosition(),s=!!t.generatingNodePosition;return i.resolveFloatReferenceFromColumnSpan(n,e.columnSpan,e).thenAsync(a=>{n=a,t.flowName;let h=new hp(r,n,o,e.clearSide,t.flowName,e.floatMinWrapBlock);if(h.insidePageFloatArea=s,s){let l=t.generatingNodePosition;l&&(h.parentPageFloat=t.findPageFloatByNodePosition(l))}return t.addPageFloat(h),T(h)})}createPageFloatFragment(e,t,i,n,o){let r=e[0].float;return new up(r.floatReference,t,i,e,n,o)}findPageFloatFragment(e,t){return t.findPageFloatFragment(e)}adjustPageFloatArea(e,t,i){return T(void 0)}forbid(e,t){}};Vn.register(new qv);var cp="data-vivliostyle-footnote-first-ref",dp="data-vivliostyle-footnote-referenced";function cs(e,t){return!!(e&&e.match(new RegExp(`(^|\\s)${t}($|\\s)`)))}function Pt(e){if(e.localName!=="aside")return!1;if(cs(e.getAttribute("role"),"doc-footnote"))return!0;let t=e.getAttributeNS("http://www.idpf.org/2007/ops","type")||e.getAttribute("epub:type");return cs(t,"footnote")}function Gt(e){if(e.localName!=="a")return!1;if(cs(e.getAttribute("role"),"doc-noteref"))return!0;let t=e.getAttributeNS("http://www.idpf.org/2007/ops","type")||e.getAttribute("epub:type");return cs(t,"noteref")}function $l(e,t){if(!Gt(e))return null;let i=e.getAttribute("href")||e.getAttributeNS("http://www.w3.org/1999/xlink","href");if(!i)return null;let n=Qr(i,t);return n==="#"?null:n}function pp(e,t,i){let n=$l(e,t);if(!n)return null;let o=i(n);return o&&Pt(o)?o:null}function Yv(e,t,i,n,o){if(o.value)return;let r=e.getElementsByTagName("a");for(let s=0;s<r.length;s++){let a=r.item(s),h=$l(a,t);!h||n.has(h)||n.set(h,i(a))}o.value=!0}function cu(e,t,i,n,o){if(e.localName!=="a"||!Gt(e))return!0;let r=$l(e,t);if(!r)return!0;Yv(e.ownerDocument,t,i,n,o);let s=n.get(r);return s==null||i(e)===s}function Hl(e,t){let i=t.getProp(e,"footnote-display");if(i)return i;let n=t.getProp(e,"display");return n?.value===y.inline?t.createCascadeValue(y.inline,n.priority):null}function Zv(e,t,i,n,o,r,s){if(e.namespaceURI!=="http://www.pyroxy.com/ns/shadow"||e.localName!=="include"||!e.classList.contains("-vivliostyle-footnote-content"))return t;let a=i?.owner;if(!(a instanceof Element)||!Gt(a))return t;let h=pp(a,n,o);if(!h)return t;let l=a.getAttribute(r);l?(e.setAttribute(r,l),h.setAttribute(r,l)):(e.removeAttribute(r),h.removeAttribute(r));let c=s.getStyle(h);if(!c)return t;let d={...t},p=Hl(c,s),f=s.getProp(c,"footnote-policy"),g=s.getStyleMap(c,"_pseudos"),v=g?.after;if(p&&(d["footnote-display"]=p),f&&(d["footnote-policy"]=f),v){let w=s.getMutableStyleMap(d,"_pseudos");w.after={...v}}return d}function Kv(e,t,i,n,o){var r;if(!(i?.type===st.ROOTED&&Pt(e)))return t;let s=o.getStyle(e);if(!s)return t;let a={...t},h=Hl(s,o),l=o.getProp(s,"footnote-policy"),c=o.getStyleMap(s,"_pseudos"),d=c?.["footnote-marker"],p=o.getProp(d,"content"),f=o.getProp(d,"list-style-position");if(h&&(a["footnote-display"]=h),l&&(a["footnote-policy"]=l),p&&((r=f?.evaluate)==null?void 0:r.call(f,n,"list-style-position"))===y.outside){let g=o.filterFootnoteMarkerContent(p,e);a["--viv-marker-content"]=o.createCascadeValue(g,0),a.display=o.createCascadeValue(B("list-item"),0),a["list-style-position"]=o.createCascadeValue(y.outside,0),a["list-style-type"]=o.createCascadeValue(y.none,0),a["list-style-image"]=o.createCascadeValue(y.none,0)}return a}function Jv(e,t,i){var n,o;let r=t?.type===st.ROOTED&&Pt(e)?i.getStyle(e):null;return{sourceStyle:r,footnoteDisplay:((n=Hl(r,i))==null?void 0:n.value)||null,footnotePolicy:((o=i.getProp(r,"footnote-policy"))==null?void 0:o.value)||null}}function fp(e,t){if(e instanceof j){let i=e.expr.evaluate(t);return typeof i=="string"?new K(i):typeof i=="number"?new K(String(i)):e}return e instanceof J?new J(e.values.map(i=>fp(i,t))):e}function Qv(e,t,i){let n=e?.["_footnote-marker-content"];n&&(t["--viv-marker-content"]=fp(n.value,i))}function ew(e){let t=e.getElementsByTagName("a"),i=new Set;for(let n=0;n<t.length;n++){let o=t.item(n);if(!Gt(o)||!(o instanceof HTMLAnchorElement)||!o.hash||o.href!==o.baseURI.replace(/#.*$/,"")+o.hash)continue;let r=o.hash.substring(1),s=e.getElementById(r);if(s&&Pt(s)){let a=o.baseURI.replace(/#.*$/,"")+o.hash;i.has(a)||(i.add(a),o.setAttribute(cp,"true")),s.setAttribute(dp,"true")}}}Ft("PREPROCESS_SINGLE_DOCUMENT",ew);var tw=up,iw=.1,Bo=class gp extends hp{constructor(t,i,n,o,r,s){super(t,i,"block-end",null,n,r),u(this,"footnotePolicy",o),u(this,"policyAnchorNode",s)}isAllowedToPrecede(t){return!(t instanceof gp)}};function nw(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;for(;t;){if(/^(p|li|dd|dt|td|th|blockquote)$/i.test(t.localName)&&!t.querySelector("br"))return t;t=t.parentElement}return e}function mp(e){return e?-1:1}function $a(e,t){return t?e.right:e.top}function Wl(e,t){return t?e.left:e.bottom}function yp(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom,width:e.width,height:e.height}}function vp(e,t){let i=yp(e.getBoundingClientRect());return Dl(i,t),i.right<i.left||i.bottom<i.top?null:i}function Ha(e,t){let i=Array.from(e,yp);return ss(i,t),i.filter(n=>n.right>n.left&&n.bottom>n.top)}function wp(e,t){return e.length?t?Math.min(...e.map(i=>i.left)):Math.max(...e.map(i=>i.bottom)):NaN}function ow(e,t){if(!e.length)return NaN;let i=mp(t),n=e.reduce((o,r)=>$a(r,t)*i<$a(o,t)*i?r:o);return Wl(n,t)}function rw(e,t){if(!e)return NaN;if(e.nodeType===Node.ELEMENT_NODE){let r=vp(e,t);return r?Wl(r,t):NaN}let i=e.textContent||"";if(!i.length)return NaN;let n=e.ownerDocument.createRange();n.setStart(e,0),n.setEnd(e,i.length);let o=Ha(n.getClientRects(),t);return wp(o,t)}function sw(e,t){let i=e.viewNode;if(!i)return NaN;if(i.nodeType===Node.ELEMENT_NODE){let a=i;if(e.after||!e.inline){let l=vp(a,t);if(l)return e.after?Wl(l,t):$a(l,t)}let h=Ha(a.getClientRects(),t);return ow(h,t)}let n=i.textContent||"";if(!n.length)return NaN;let o=e.offsetInNode;e.after&&(o+=n.length),o=Math.max(0,Math.min(o,n.length-1));let r=i.ownerDocument.createRange();r.setStart(i,o),r.setEnd(i,o+1);let s=Ha(r.getClientRects(),t);return wp(s,t)}var du=class extends tw{constructor(e,t,i,n){super(e,"block-end",null,t,i,n)}getOrder(){return 1/0}shouldBeStashedBefore(e){return e instanceof Bo?!0:this.getOrder()<e.getOrder()}},aw=class{constructor(e,t,i){u(this,"footnote",e),u(this,"vertical",i),u(this,"anchorEdge"),this.anchorEdge=rw(t,i)}allowLayout(e){if(!isNaN(this.anchorEdge)){let i=sw(e,this.vertical);if(!isNaN(i)){let n=mp(this.vertical);return i*n<this.anchorEdge*n-iw}}let t=e.toNodePosition();return!Oi(t,this.footnote.nodePosition)}},lw=class{appliesToNodeContext(e){return e.floatSide==="footnote"}appliesToFloat(e){return e instanceof Bo}createPageFloat(e,t,i){var n;let o=Pe.REGION,r=t.getPageFloatLayoutContext(o);t.getPageFloatLayoutContext(Pe.PAGE).hasSameContainerAs(r)&&(o=Pe.PAGE);let s=!!t.generatingNodePosition;s&&o!==Pe.PAGE&&(o=Pe.PAGE);let a=e.toNodePosition();t.flowName;let h=e.sourceNode,l=(n=e.shadowContext)==null?void 0:n.owner;l instanceof Element&&Gt(l)&&(h=l),h=nw(h);let c=new Bo(a,o,t.flowName,e.footnotePolicy,e.floatMinWrapBlock,h);if(c.insidePageFloatArea=s,s){let d=t.generatingNodePosition;d&&(c.parentPageFloat=t.findPageFloatByNodePosition(d))}return t.addPageFloat(c),T(c)}createPageFloatFragment(e,t,i,n,o){let r=e[0].float;return new du(r.floatReference,e,n,o)}findPageFloatFragment(e,t){let i=t.getPageFloatLayoutContext(e.floatReference),n=i.getContainer(e.floatReference).element,o=i.floatFragments.filter(r=>r instanceof du&&(e.floatReference!==Pe.REGION||!r.area.parentElement||r.area.parentElement===n));return o.find(r=>r.hasFloat(e))||o[0]||null}adjustPageFloatArea(e,t,i){e.isFootnote=!0,e.adjustContentRelativeSize=!1;let n=e.element;return i.layoutContext.applyFootnoteStyle(t.vertical,i.layoutContext.nodeContext&&i.layoutContext.nodeContext.direction==="rtl",n).thenAsync(o=>{var r,s;if(e.vertical=o,e.convertPercentageSizesToPx(n),i.setComputedInsets(n,e),i.setComputedWidthAndHeight(n,e),((r=i.clientLayout.getElementComputedStyle(n))==null?void 0:r.boxSizing)==="border-box"){let h=e.vertical?e.paddingLeft+e.paddingRight+e.borderLeft+e.borderRight:e.paddingTop+e.paddingBottom+e.borderTop+e.borderBottom,l=e.vertical?["max-width","min-width","width"]:["max-height","min-height","height"],c=getComputedStyle(n);for(let d of l){let p=c.getPropertyValue(d);if(p&&p!=="none"){let f=parseFloat(p);isNaN(f)||I(n,d,`${Math.max(0,f-h)}px`)}}I(n,"box-sizing","content-box")}let a=i.pageFloatLayoutContext;for(;a;){if(a.ignoreFootnoteAreaMaxHeight){I(n,"max-block-size",""),I(n,e.vertical?"max-width":"max-height","");break}a=(s=a.parent)!=null?s:null}return T(void 0)})}forbid(e,t){let i=e;if(i.footnotePolicy===y.line){let n=t.collectPageFloatAnchors()[i.getId()]||null,o=new aw(i,n,t.getContainer(i.floatReference).vertical);t.addLayoutConstraint(o,i.floatReference)}}};Vn.register(new lw);var Gl=class{calculateOffset(e){return Ln(this.getNodeContext(),e.collectElementsOffset())}breakPositionChosen(e){}getNodeContext(){return null}};function Ln(e,t){return{current:t.reduce((i,n)=>i+n.calculateOffset(e),0),minimum:t.reduce((i,n)=>i+n.calculateMinimumOffset(e),0)}}var ir=class extends Gl{constructor(e,t,i,n){super(),u(this,"position",e),u(this,"breakOnEdge",t),u(this,"overflows",i),u(this,"computedBlockSize",n),u(this,"overflowIfRepetitiveElementsDropped"),u(this,"isEdgeUpdated",!1),u(this,"edge",0),this.overflowIfRepetitiveElementsDropped=i}findAcceptableBreak(e,t){return this.updateOverflows(e),t<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(as(this.breakOnEdge)?1:0)+(this.overflows&&!e?3:0)+(this.position.parent?this.position.parent.breakPenalty:0)}updateEdge(e){var t;let i=e.calculateClonedPaddingBorder(this.position);if(this.edge=bn(this.position,e.clientLayout,0,e.vertical)+i,!this.position.after&&!this.position.inline){let n=e.parseComputedLength(e.clientLayout.getElementComputedStyle(this.position.viewNode).marginBlockStart);this.edge-=(e.vertical?-1:1)*n}else if(this.position.after&&((t=this.position.shadowContext)==null?void 0:t.root.id)==="table-cell"){let n=e.element.parentElement,o=n?.closest("table, [style*='display: table;']");if(o){let r=o.style.borderCollapse==="collapse",s=0,a=0;for(let h=n;h;h=h.parentElement){let l=e.clientLayout.getElementComputedStyle(h);if((h===n||h===o&&!r)&&(s+=e.parseComputedLength(l.paddingBlockEnd)),h===o&&!r&&(s+=e.parseComputedLength(l.borderSpacing.replace(/^\S+ (\S+)$/,"$1"))),r?a=Math.max(a,e.parseComputedLength(l.borderBlockEndWidth)):(h===n||h===o)&&(a+=e.parseComputedLength(l.borderBlockEndWidth)),h===o)break}this.edge+=(e.vertical?-1:1)*(s+a)}}this.isEdgeUpdated=!0}updateOverflows(e){this.isEdgeUpdated||this.updateEdge(e);let t=this.edge,i=this.calculateOffset(e);this.overflowIfRepetitiveElementsDropped=e.isOverflown(t+(e.vertical?-1:1)*i.minimum),this.overflows=this.position.overflow=e.isOverflown(t+(e.vertical?-1:1)*i.current)}getNodeContext(){return this.position}isFirstContentOfRepetitiveElementsOwner(){let e=this.getNodeContext();if(!e||!e.parent)return!1;let{formattingContext:t}=e.parent;if(!Yi.isInstanceOfRepetitiveElementsOwnerFormattingContext(t))return!1;let i=t.getRepetitiveElements();return i?i.isFirstContentNode(e):!1}},io=class{find(e){let t=_t("RESOLVE_LAYOUT_PROCESSOR");for(let i=0;i<t.length;i++){let n=t[i](e);if(n)return n}throw new Error(`No processor found for a formatting context: ${e.getName()}`)}},Tn=class{layout(e,t,i){return t.isFloatNodeContext(e)?t.layoutFloatOrFootnote(e):t.isBreakable(e)?t.layoutBreakableBlock(e):t.layoutUnbreakable(e)}createEdgeBreakPosition(e,t,i,n){return new ir(e.copy(),t,i,n)}startNonInlineElementNode(e){return!1}afterNonInlineElementNode(e,t){return!1}clearOverflownViewNodes(e,t,i,n){var o;if(!i.viewNode||!i.viewNode.parentNode||i.shadowType===yi.ShadowType.ROOTLESS&&Pn(i))return;let r=i.viewNode;((o=r.parentElement)==null?void 0:o.localName)==="viv-ts-inner"&&(r=r.parentElement.parentElement);let s=r.parentNode;Hd(s,r),n&&s.removeChild(r)}finishBreak(e,t,i,n){let o=i||t.viewNode!=null&&t.viewNode.nodeType==1&&!t.after;return e.clearOverflownViewNodes(t,o),n&&e.layoutContext.processFragmentedBlockEdge(t),T(!0)}},jl=class{constructor(e){u(this,"parent",e),u(this,"formattingContextType","Block")}getName(){return"Block formatting context (BlockFormattingContext)"}isFirstTime(e,t){return t}getParent(){return this.parent}saveState(){}restoreState(e){}},Xl=new Tn,hw=za.isInstanceOfBlockFormattingContext;Ft("RESOLVE_FORMATTING_CONTEXT",(e,t,i,n,o,r)=>{let s=e.parent;return!s&&e.formattingContext||s&&e.formattingContext!==s.formattingContext?null:e.establishesBFC||!e.formattingContext&&Vd(i,n,o,r)?new jl(s?s.formattingContext:null):null});Ft("RESOLVE_LAYOUT_PROCESSOR",e=>e instanceof jl?Xl:null);var ql=class{constructor(){u(this,"initialBreakPositions",null),u(this,"initialStateOfFormattingContext",null),u(this,"initialPosition"),u(this,"initialFragmentLayoutConstraints")}layout(e,t){return this.prepareLayout(e,t),this.tryLayout(e,t)}tryLayout(e,t){let i=M("AbstractLayoutRetryer.tryLayout");this.saveState(e,t);let n=this.resolveLayoutMode(e);return n.doLayout(e,t).then(o=>{let r=n.accept(o,t);r=n.postLayout(o,this.initialPosition,t,r),r?i.finish(o):(this.initialPosition,this.clearNodes(this.initialPosition),this.restoreState(e,t),this.tryLayout(this.initialPosition,t).thenFinish(i))}),i.result()}prepareLayout(e,t){}clearNodes(e){let t=e.viewNode||e.parent.viewNode,i;for(;i=t.lastChild;)t.removeChild(i);let n;for(;n=t.nextSibling;)n.parentNode.removeChild(n)}saveState(e,t){this.initialPosition=e.copy(),this.initialBreakPositions=[].concat(t.breakPositions),this.initialFragmentLayoutConstraints=[].concat(t.fragmentLayoutConstraints),e.formattingContext&&(this.initialStateOfFormattingContext=e.formattingContext.saveState())}restoreState(e,t){t.breakPositions=this.initialBreakPositions,t.fragmentLayoutConstraints=this.initialFragmentLayoutConstraints,e.formattingContext&&e.formattingContext.restoreState(this.initialStateOfFormattingContext)}},uw=class{initialState(e){return{nodeContext:e,atUnforcedBreak:!1,break:!1}}startNonDisplayableNode(e){}afterNonDisplayableNode(e){}startIgnoredTextNode(e){}afterIgnoredTextNode(e){}startNonElementNode(e){}afterNonElementNode(e){}startInlineElementNode(e){}afterInlineElementNode(e){}startNonInlineElementNode(e){}afterNonInlineElementNode(e){}finish(e){}},Wa=class{constructor(e,t){u(this,"strategy",e),u(this,"layoutContext",t)}iterate(e){let t=this.strategy,i=t.initialState(e),n=M("LayoutIterator");return n.loopWithFrame(o=>{let r;for(;i.nodeContext;){i.nodeContext.viewNode?i.nodeContext.viewNode.nodeType!==1?Ee(i.nodeContext.viewNode,i.nodeContext.whitespace)?i.nodeContext.after?r=t.afterIgnoredTextNode(i):r=t.startIgnoredTextNode(i):i.nodeContext.after?r=t.afterNonElementNode(i):r=t.startNonElementNode(i):i.nodeContext.inline?i.nodeContext.after?r=t.afterInlineElementNode(i):r=t.startInlineElementNode(i):i.nodeContext.after?r=t.afterNonInlineElementNode(i):r=t.startNonInlineElementNode(i):i.nodeContext.after?r=t.afterNonDisplayableNode(i):r=t.startNonDisplayableNode(i);let s=(r&&r.isPending()?r:T(!0)).thenAsync(()=>i.break?T(null):this.layoutContext.nextInTree(i.nodeContext,i.atUnforcedBreak));if(s.isPending()){s.then(a=>{i.break?o.breakLoop():(i.nodeContext=a,o.continueLoop())});return}else if(i.break){o.breakLoop();return}else i.nodeContext=s.get()}t.finish(i),o.breakLoop()}).then(()=>{n.finish(i.nodeContext)}),n.result()}},xo=class extends uw{constructor(e){super(),u(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,t){let i=!e.leadingEdge&&Ze(e.breakAtTheEdge);if(i){let n=e.nodeContext=e.leadingEdgeContexts[0]||e.nodeContext;n.viewNode.parentNode.removeChild(n.viewNode),t.pageBreakType=e.breakAtTheEdge}return i}saveEdgeAndProcessOverflow(e,t){let i=t.checkOverflowAndSaveEdgeAndBreakPosition(e.lastAfterNodeContext,null,!0,e.breakAtTheEdge);return i&&(e.nodeContext=(e.lastAfterNodeContext||e.nodeContext).modify(),e.nodeContext.overflow=!0),i}processLayoutConstraint(e,t,i){let n=e.nodeContext,o=!t.allowLayout(n);return o&&(i.checkOverflowAndSaveEdgeAndBreakPosition(e.lastAfterNodeContext,null,!1,e.breakAtTheEdge),n=e.nodeContext=n.modify(),n.overflow=!0),o}startNonElementNode(e){e.onStartEdges=!1}startNonInlineElementNode(e){return e.leadingEdgeContexts.push(e.nodeContext.copy()),e.breakAtTheEdge=nt(e.breakAtTheEdge,e.nodeContext.breakBefore),e.onStartEdges=!0,this.startNonInlineBox(e)}afterNonInlineElementNode(e){let t,i;return e.onStartEdges?(t=this.endEmptyNonInlineBox(e),i=t&&t.isPending()?t:T(!0),i=i.thenAsync(()=>(e.break||(e.leadingEdgeContexts=[],e.leadingEdge=!1,e.atUnforcedBreak=!1,e.breakAtTheEdge=null),T(!0)))):(t=this.endNonInlineBox(e),i=t&&t.isPending()?t:T(!0)),i.thenAsync(()=>(e.break||(e.onStartEdges=!1,e.lastAfterNodeContext=e.nodeContext.copy(),e.breakAtTheEdge=nt(e.breakAtTheEdge,e.nodeContext.breakAfter)),T(!0)))}},Ga=[];function cw(){Ga=[]}var fr;function gr(e){if(e==="")return 0;if(fr===void 0){let i=Intl.Segmenter;fr=typeof i=="function"?new i(void 0,{granularity:"grapheme"}):null}if(fr===null)return[...e].length;let t=0;for(let i of fr.segment(e))t++;return t}var dw=["decimal","disc","square","circle","disclosure-open","disclosure-closed"],pw=new Set(dw);function fw(e){return!(e.toLowerCase()==="none"||pw.has(e))}var gw=["cyclic","numeric","alphabetic","symbolic","additive","fixed"],mw=new Set(gw),yw=["fixed","extends"],vw=new Set(yw);function nr(e){return e instanceof he&&e.name.toLowerCase()!=="none"}function bp(e){return e.name}function ww(e){if(e instanceof he)return mw.has(e.name);if(e instanceof J&&e.values.length===2){let t=e.values[0],i=e.values[1];if(t instanceof he){let n=t.name;return vw.has(n)&&(n==="fixed"&&i instanceof lt||n==="extends"&&nr(i))}}return!1}function bw(e){let t=dt(e,"system");return t instanceof he&&t.name==="cyclic"}function xw(e){let t=dt(e,"system");if(t instanceof he&&t.name==="fixed")return!0;if(t instanceof J&&t.values.length===2){let[i,n]=t.values;return i instanceof he&&i.name==="fixed"&&n instanceof lt}return!1}function Sw(e){let t=dt(e,"system");return t instanceof he?1:t.values[1].num}function Cw(e){let t=dt(e,"system");return t instanceof he&&t.name==="alphabetic"}function kw(e){let t=dt(e,"system");return t instanceof he&&t.name==="numeric"}function Ew(e){let t=dt(e,"system");return t instanceof he&&t.name==="additive"}function Pw(e){let t=dt(e,"system");if(t instanceof J&&t.values.length===2){let[i,n]=t.values;return i instanceof he&&i.name==="extends"&&nr(n)}return!1}function Nw(e){let t=dt(e,"system");return bp(t.values[1])}function jt(e){return e instanceof K||e instanceof he}function fi(e){return e instanceof K?e.str:e.name}function xp(e){if(jt(e))return!0;if(e instanceof J&&e.values.length===2){let t=e.values[0],i=e.values[1];return jt(t)&&jt(i)}return!1}function Tw(e){if(jt(e))return{prefix:fi(e),suffix:null};{let t=e.values[0],i=e.values[1];return{prefix:fi(t),suffix:fi(i)}}}function pu(e){return e instanceof lt||e instanceof he&&e.name==="infinite"}function ds(e,t){return e instanceof lt?e.num:t?-1/0:1/0}function ja(e){if(!(e instanceof J&&e.values.length===2))return!1;let t=e.values[0],i=e.values[1];if(!(pu(t)&&pu(i)))return!1;let n=ds(t,!0),o=ds(i,!1);return!(n>o)}function Aw(e){return{lower:ds(e.values[0],!0),upper:ds(e.values[1],!1)}}function Sp(e){return e instanceof he&&e.name==="auto"||ja(e)||e instanceof _e&&e.values.length>=1&&e.values.every(t=>ja(t))}function Iw(e){return e instanceof he?null:(ja(e)?[e]:e.values).map(t=>Aw(t))}function ps(e){if(!(e instanceof J&&e.values.length===2))return!1;let t=e.values[0],i=e.values[1];return t instanceof lt&&t.num>=0&&jt(i)||jt(t)&&i instanceof lt&&i.num>=0}function fs(e){let[t,i]=e.values;return t instanceof lt?[t.num,fi(i)]:[i.num,fi(t)]}function Cp(e){return ps(e)}function Fw(e){let[t,i]=fs(e);return{minLength:t,symbol:i}}function kp(e){return jt(e)||e instanceof J&&e.values.length>=1&&e.values.every(t=>jt(t))}function Rw(e){return jt(e)?[fi(e)]:e.values.map(t=>fi(t))}function Ep(e){if(ps(e))return!0;if(e instanceof _e&&e.values.length>=1){let t=1/0;for(let i of e.values){if(!ps(i))return!1;let[n]=fs(i);if(n>=t)return!1;t=n}return!0}return!1}function Lw(e){if(ps(e)){let[t,i]=fs(e);return[{weight:t,symbol:i}]}else return e.values.map(t=>{let[i,n]=fs(t);return{weight:i,symbol:n}})}var Ow=["auto","bullets","numbers","words","spell-out"],Bw=new Set(Ow);function Mw(e){return e instanceof he&&Bw.has(e.name)||nr(e)}function _w(e,t){switch(e){case"system":return ww(t);case"negative":return xp(t);case"prefix":case"suffix":return jt(t);case"range":return Sp(t);case"pad":return Cp(t);case"fallback":return nr(t);case"symbols":return kp(t);case"additive-symbols":return Ep(t);case"speak-as":return Mw(t);default:return!0}}function dt(e,t){var i;let n=(i=e[t])==null?void 0:i.value;return n??null}function Dw(e,t){return t.some(({lower:i,upper:n})=>e>=i&&e<=n)}function Un(e){let t=e.get("decimal");return t||(t=ce.createDecimal(e),e.set("decimal",t)),t}var Mr,_r,Dr,zr,Vr,Ur,$r,Hr,mr,ci,Pp,yr,Np,vr,Tp,wr,Ap,br,Ip,xr,Fp,Sr,Rp,wt,la,Lp,Op,fu,gu,ha,mu,po,ze=class Hi{constructor(t,i){ie(this,wt),u(this,"_store"),ie(this,Mr),ie(this,_r),ie(this,Dr),ie(this,zr),ie(this,Vr),ie(this,Ur),ie(this,$r),ie(this,Hr),this._store=t;let n=dt(i,"negative");de(this,Mr,n&&xp(n)?Tw(n):null);let o=dt(i,"prefix");de(this,_r,o&&jt(o)?fi(o):null);let r=dt(i,"suffix");de(this,Dr,r&&jt(r)?fi(r):null);let s=dt(i,"range");de(this,zr,s&&Sp(s)?Iw(s):null);let a=dt(i,"pad");de(this,Vr,a&&Cp(a)?Fw(a):null);let h=dt(i,"fallback");de(this,Ur,h&&nr(h)?bp(h):null);let l=dt(i,"symbols");de(this,$r,l&&kp(l)?Rw(l):null);let c=dt(i,"additive-symbols");de(this,Hr,c&&Ep(c)?Lw(c):null)}static create(t,i){return bw(i)?new _i(t,i):xw(i)?new zw(t,i):Cw(i)?new Uw(t,i):kw(i)?new yu(t,i):Ew(i)?new $w(t,i):Pw(i)?new Hw(t,i):new Vw(t,i)}static createDecimal(t){var i;return new yu(t,le(i=Hi,ci,Pp).call(i))}static createDisc(t){var i;return new _i(t,le(i=Hi,ci,Np).call(i))}static createSquare(t){var i;return new _i(t,le(i=Hi,ci,Tp).call(i))}static createCircle(t){var i;return new _i(t,le(i=Hi,ci,Ap).call(i))}static createDisclosureOpen(t){var i;return new _i(t,le(i=Hi,ci,Ip).call(i))}static createDisclosureClosed(t){return new _i(t,le(this,ci,Fp).call(this))}static createNone(t){var i;return new _i(t,le(i=Hi,ci,Rp).call(i))}static get CHINESE_LONGHAND_NAMES(){return vu.NAMES}static createChineseLonghand(t,i){return new vu(t,i)}static createEthiopicNumeric(t){return new Gw(t)}_getNegative(){return H(this,Mr)}static _getNegativeFrom(t){return t._getNegative()}_getPrefix(){return H(this,_r)}static _getPrefixFrom(t){return t._getPrefix()}_getSuffix(){return H(this,Dr)}static _getSuffixFrom(t){return t._getSuffix()}static _getAutoRangeFrom(t){return t._getAutoRange()}_getRange(){return H(this,zr)}static _getRangeFrom(t){return t._getRange()}_getPad(){return H(this,Vr)}static _getPadFrom(t){return t._getPad()}_getFallback(){var t;return(t=this._store.get(H(this,Ur)))!=null?t:null}static _getFallbackFrom(t){return t._getFallback()}_getSymbols(){return H(this,$r)}static _getSymbolsFrom(t){return t._getSymbols()}_getAdditiveSymbols(){return H(this,Hr)}static _getAdditiveSymbolsFrom(t){return t._getAdditiveSymbols()}static _useNegativeSignFrom(t,i){return t._usesNegativeSign(i)}static _generateInitialRepresentationFrom(t,i){return t._generateInitialRepresentation(i)}format(t){return le(this,wt,po).call(this,t,new Set)}formatMarker(t){return le(this,wt,Lp).call(this)+this.format(t)+le(this,wt,Op).call(this)}};Mr=new WeakMap,_r=new WeakMap,Dr=new WeakMap,zr=new WeakMap,Vr=new WeakMap,Ur=new WeakMap,$r=new WeakMap,Hr=new WeakMap,mr=new WeakMap,ci=new WeakSet,Pp=function(){var e;return(e=H(ze,mr))!=null?e:de(ze,mr,{system:new W(B("numeric"),0),symbols:new W(new J([new K("0"),new K("1"),new K("2"),new K("3"),new K("4"),new K("5"),new K("6"),new K("7"),new K("8"),new K("9")]),0)})},yr=new WeakMap,Np=function(){var e;return(e=H(ze,yr))!=null?e:de(ze,yr,{system:new W(B("cyclic"),0),symbols:new W(new K("\u2022"),0),suffix:new W(new K(" "),0)})},vr=new WeakMap,Tp=function(){var e;return(e=H(ze,vr))!=null?e:de(ze,vr,{system:new W(B("cyclic"),0),symbols:new W(new K("\u25AA"),0),suffix:new W(new K(" "),0)})},wr=new WeakMap,Ap=function(){var e;return(e=H(ze,wr))!=null?e:de(ze,wr,{system:new W(B("cyclic"),0),symbols:new W(new K("\u25E6"),0),suffix:new W(new K(" "),0)})},br=new WeakMap,Ip=function(){var e;return(e=H(ze,br))!=null?e:de(ze,br,{system:new W(B("cyclic"),0),symbols:new W(new K("\u25BE"),0),suffix:new W(new K(" "),0)})},xr=new WeakMap,Fp=function(){var e;return(e=H(ze,xr))!=null?e:de(ze,xr,{system:new W(B("cyclic"),0),symbols:new W(new K("\u25B8"),0),suffix:new W(new K(" "),0)})},Sr=new WeakMap,Rp=function(){var e;return(e=H(ze,Sr))!=null?e:de(ze,Sr,{system:new W(B("cyclic"),0),symbols:new W(new K(""),0),suffix:new W(new K(""),0)})},wt=new WeakSet,la=function(){var e;return(e=this._getNegative())!=null?e:{prefix:"-",suffix:null}},Lp=function(){var e;return(e=this._getPrefix())!=null?e:""},Op=function(){var e;return(e=this._getSuffix())!=null?e:". "},fu=function(){var e;return(e=this._getRange())!=null?e:this._getAutoRange()},gu=function(){var e;return(e=this._getPad())!=null?e:{minLength:0,symbol:""}},ha=function(){var e;return(e=this._getFallback())!=null?e:Un(this._store)},mu=function(e,t){let{minLength:i,symbol:n}=le(this,wt,gu).call(this);if(i===0||n==="")return e;let{prefix:o,suffix:r}=le(this,wt,la).call(this),s=t?gr(o)+(r?gr(r):0):0,a=i-gr(e)-s;if(a<=0)return e;let h=gr(n),l=Math.ceil(a/h);return n.repeat(l)+e},po=function(e,t){var i,n,o;if(t.has(this))return le(i=Un(this._store),wt,po).call(i,e,new Set);if(t.add(this),!Dw(e,le(this,wt,fu).call(this))){let l=le(this,wt,ha).call(this);return le(n=l,wt,po).call(n,e,t)}let r=this._usesNegativeSign(e),s=r?Math.abs(e):e,a=this._generateInitialRepresentation(s);if(a===null){let l=le(this,wt,ha).call(this);return le(o=l,wt,po).call(o,e,t)}let h=le(this,wt,mu).call(this,a,r);if(r){let{prefix:l,suffix:c}=le(this,wt,la).call(this);h=l+h+(c??"")}return h},ie(ze,ci),ie(ze,mr,null),ie(ze,yr,null),ie(ze,vr,null),ie(ze,wr,null),ie(ze,br,null),ie(ze,xr,null),ie(ze,Sr,null);var ce=ze,_i=class extends ce{constructor(e,t){super(e,t)}_getAutoRange(){return[{lower:-1/0,upper:1/0}]}_usesNegativeSign(e){return!1}_generateInitialRepresentation(e){let t=this._getSymbols();if(!t||t.length===0)return null;let i=t.length,n=((e-1)%i+i)%i;return t[n]}},Wr,zw=class extends ce{constructor(e,t){super(e,t),ie(this,Wr),de(this,Wr,Sw(t))}_getAutoRange(){return[{lower:-1/0,upper:1/0}]}_usesNegativeSign(e){return!1}_generateInitialRepresentation(e){var t;let i=this._getSymbols();if(!i||i.length===0)return null;let n=e-H(this,Wr);return(t=i[n])!=null?t:null}};Wr=new WeakMap;var Vw=class extends ce{constructor(e,t){super(e,t)}_getAutoRange(){return[{lower:1,upper:1/0}]}_usesNegativeSign(e){return e<0}_generateInitialRepresentation(e){let t=this._getSymbols();if(!t||t.length===0||e<1)return null;let i=t.length,n=t[(e-1)%i],o=Math.ceil(e/i);return n.repeat(o)}},Uw=class extends ce{constructor(e,t){super(e,t)}_getAutoRange(){return[{lower:1,upper:1/0}]}_usesNegativeSign(e){return e<0}_generateInitialRepresentation(e){let t=this._getSymbols();if(!t||t.length<2||e<1)return null;let i=t.length,n="",o=e;for(;o!==0;)o=o-1,n=t[o%i]+n,o=Math.floor(o/i);return n}},yu=class extends ce{constructor(e,t){super(e,t)}_getAutoRange(){return[{lower:-1/0,upper:1/0}]}_usesNegativeSign(e){return e<0}_generateInitialRepresentation(e){let t=this._getSymbols();if(!t||t.length<2)return null;let i=t.length;if(e===0)return t[0];let n="",o=e;for(;o!==0;)n=t[o%i]+n,o=Math.floor(o/i);return n}},$w=class extends ce{constructor(e,t){super(e,t)}_getAutoRange(){return[{lower:0,upper:1/0}]}_usesNegativeSign(e){return e<0}_generateInitialRepresentation(e){let t=this._getAdditiveSymbols();if(!t||t.length===0)return null;let i="";if(e===0){let o=t.find(r=>r.weight===0);return o?o.symbol:null}let n=e;for(let o of t){let{weight:r,symbol:s}=o;if(r===0||r>n)continue;let a=Math.floor(n/r);if(i+=s.repeat(a),n-=r*a,n===0)return i}return null}},So,kt,Lt,Bp=class extends ce{constructor(t,i){super(t,i),ie(this,kt),ie(this,So);let n=Nw(i),o=n.toLowerCase();o==="disc"||o==="circle"||o==="square"||o==="disclosure-open"||o==="disclosure-closed"?de(this,So,o):de(this,So,n)}_getNegative(){var t;return(t=super._getNegative())!=null?t:ce._getNegativeFrom(le(this,kt,Lt).call(this))}_getPrefix(){var t;return(t=super._getPrefix())!=null?t:ce._getPrefixFrom(le(this,kt,Lt).call(this))}_getSuffix(){var t;return(t=super._getSuffix())!=null?t:ce._getSuffixFrom(le(this,kt,Lt).call(this))}_getAutoRange(){return ce._getAutoRangeFrom(le(this,kt,Lt).call(this))}_getRange(){var t;return(t=super._getRange())!=null?t:ce._getRangeFrom(le(this,kt,Lt).call(this))}_getPad(){var t;return(t=super._getPad())!=null?t:ce._getPadFrom(le(this,kt,Lt).call(this))}_getFallback(){var t;return(t=super._getFallback())!=null?t:ce._getFallbackFrom(le(this,kt,Lt).call(this))}_getSymbols(){var t;return(t=super._getSymbols())!=null?t:ce._getSymbolsFrom(le(this,kt,Lt).call(this))}_getAdditiveSymbols(){var t;return(t=super._getAdditiveSymbols())!=null?t:ce._getAdditiveSymbolsFrom(le(this,kt,Lt).call(this))}_usesNegativeSign(t){return ce._useNegativeSignFrom(le(this,kt,Lt).call(this),t)}_generateInitialRepresentation(t){return super._getSymbols()||super._getAdditiveSymbols()?null:ce._generateInitialRepresentationFrom(le(this,kt,Lt).call(this),t)}};So=new WeakMap,kt=new WeakSet,Lt=function(e=new Set){var t;if(e.has(this))return Un(this._store);e.add(this);let i=this._store.get(H(this,So));return i?i instanceof Bp?le(t=i,kt,Lt).call(t,e):i:Un(this._store)};var Hw=Bp,Ww=["simp-chinese-informal","simp-chinese-formal","trad-chinese-informal","trad-chinese-formal","cjk-ideographic"];function no(e){return{suffix:new W(new K("\u3001"),0),fallback:new W(B("cjk-decimal"),0),range:new W(new J([new lt(-9999),new lt(9999)]),0),negative:new W(new K(e),0)}}var ua,ca,Cr,da,kr,Xa,Mp,Gr,vt=class _p extends ce{constructor(t,i){var n;let{chars:o,descriptors:r}=le(n=_p,Xa,Mp).call(n).get(i);super(t,r),ie(this,Gr),de(this,Gr,o)}_getAutoRange(){return[{lower:-9999,upper:9999}]}_usesNegativeSign(t){return t<0}_generateInitialRepresentation(t){let i=H(this,Gr);if(t===0)return i.digits[0];let n=[],o=0,r=t;for(;r>0;)n.unshift({digit:r%10,position:o}),r=Math.floor(r/10),o++;let s=i.informal&&t>=10&&t<=19,a="",h=!1;for(let l=0;l<n.length;l++){let{digit:c,position:d}=n[l],p=l===n.length-1;c===0?!p&&!h&&(h=!0):(h&&(a+=i.digits[0],h=!1),s&&d===1?a+=i.markers[d]:(a+=i.digits[c],d>0&&(a+=i.markers[d])))}return a}};ua=new WeakMap,ca=new WeakMap,Cr=new WeakMap,da=new WeakMap,kr=new WeakMap,Xa=new WeakSet,Mp=function(){var e;return(e=H(vt,kr))!=null?e:de(vt,kr,new Map([["simp-chinese-informal",{chars:H(vt,ua),descriptors:no("\u8D1F")}],["simp-chinese-formal",{chars:H(vt,ca),descriptors:no("\u8D1F")}],["trad-chinese-informal",{chars:H(vt,Cr),descriptors:no("\u8CA0")}],["trad-chinese-formal",{chars:H(vt,da),descriptors:no("\u8CA0")}],["cjk-ideographic",{chars:H(vt,Cr),descriptors:no("\u8CA0")}]]))},Gr=new WeakMap,ie(vt,Xa),ie(vt,ua,{digits:["\u96F6","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D","\u4E03","\u516B","\u4E5D"],markers:["","\u5341","\u767E","\u5343"],informal:!0}),ie(vt,ca,{digits:["\u96F6","\u58F9","\u8D30","\u53C1","\u8086","\u4F0D","\u9646","\u67D2","\u634C","\u7396"],markers:["","\u62FE","\u4F70","\u4EDF"],informal:!1}),ie(vt,Cr,{digits:["\u96F6","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D","\u4E03","\u516B","\u4E5D"],markers:["","\u5341","\u767E","\u5343"],informal:!0}),ie(vt,da,{digits:["\u96F6","\u58F9","\u8CB3","\u53C3","\u8086","\u4F0D","\u9678","\u67D2","\u634C","\u7396"],markers:["","\u62FE","\u4F70","\u4EDF"],informal:!1}),u(vt,"NAMES",new Set(Ww)),ie(vt,kr,null);var vu=vt,Er,qa,Dp,Ya,gs,Za,Ka,hi=class Wi extends ce{constructor(t){var i;super(t,le(i=Wi,qa,Dp).call(i))}_getAutoRange(){return[{lower:1,upper:1/0}]}_usesNegativeSign(t){return!1}_generateInitialRepresentation(t){if(t<1)return null;if(t===1)return H(Wi,gs)[1];let i=[],n=t;for(;n>0;)i.push(n%100),n=Math.floor(n/100);let o=i.length,r="";for(let s=o-1;s>=0;s--){let a=i[s],h=s%2===1,l=s===o-1;if(!(a===0||l&&a===1||h&&a===1)){let c=Math.floor(a/10),d=a%10;r+=H(Wi,Ya)[c]+H(Wi,gs)[d]}h?a!==0&&(r+=H(Wi,Za)):s!==0&&(r+=H(Wi,Ka))}return r}};Er=new WeakMap,qa=new WeakSet,Dp=function(){var e;return(e=H(hi,Er))!=null?e:de(hi,Er,{range:new W(new J([new lt(1),B("infinite")]),0),suffix:new W(new K("/ "),0)})},Ya=new WeakMap,gs=new WeakMap,Za=new WeakMap,Ka=new WeakMap,ie(hi,qa),ie(hi,Er,null),ie(hi,Ya,["","\u1372","\u1373","\u1374","\u1375","\u1376","\u1377","\u1378","\u1379","\u137A"]),ie(hi,gs,["","\u1369","\u136A","\u136B","\u136C","\u136D","\u136E","\u136F","\u1370","\u1371"]),ie(hi,Za,"\u137B"),ie(hi,Ka,"\u137C");var Gw=hi,Re,jw=class{constructor(){ie(this,Re),de(this,Re,new Map),H(this,Re).set("none",ce.createNone(H(this,Re))),H(this,Re).set("decimal",ce.createDecimal(H(this,Re))),H(this,Re).set("disc",ce.createDisc(H(this,Re))),H(this,Re).set("square",ce.createSquare(H(this,Re))),H(this,Re).set("circle",ce.createCircle(H(this,Re))),H(this,Re).set("disclosure-open",ce.createDisclosureOpen(H(this,Re))),H(this,Re).set("disclosure-closed",ce.createDisclosureClosed(H(this,Re)));for(let e of ce.CHINESE_LONGHAND_NAMES)H(this,Re).set(e,ce.createChineseLonghand(H(this,Re),e));H(this,Re).set("ethiopic-numeric",ce.createEthiopicNumeric(H(this,Re)))}define(e,t){if(!fw(e))return null;let i=ce.create(H(this,Re),t);return H(this,Re).set(e,i),i}getStyle(e){var t;return(t=H(this,Re).get(e))!=null?t:null}format(e,t){var i;return((i=this.getStyle(e))!=null?i:Un(H(this,Re))).format(t)}formatMarker(e,t){var i;return((i=this.getStyle(e))!=null?i:Un(H(this,Re))).formatMarker(t)}};Re=new WeakMap;var An=class{constructor(e){u(this,"validator",e),u(this,"success",null),u(this,"failure",null),u(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(e){this.code=2*e+1}isStartAlternate(){return this.code>0&&this.code%2!=0}markAsEndAlternate(e){this.code=2*e+2}isEndAlternate(){return this.code>0&&this.code%2==0}getAlternate(){return Math.floor((this.code-1)/2)}},Di=class{constructor(e,t){u(this,"where",e),u(this,"success",t),u(this,"what",-1)}},oo=class zp{constructor(){u(this,"nodes",[]),u(this,"connections",[]),u(this,"match",[]),u(this,"nomatch",[]),u(this,"error",[]),u(this,"emptyHead",!0)}connect(t,i){for(let n=0;n<t.length;n++)this.connections[t[n]].what=i;t.splice(0,t.length)}clone(){let t=new zp;for(let i=0;i<this.nodes.length;i++){let n=this.nodes[i],o=new An(n.validator);o.code=n.code,t.nodes.push(o)}for(let i=0;i<this.connections.length;i++){let n=this.connections[i],o=new Di(n.where,n.success);o.what=n.what,t.connections.push(o)}return t.match.push(...this.match),t.nomatch.push(...this.nomatch),t.error.push(...this.error),t}addSpecialToArr(t,i,n){let o=this.nodes.length,r=new An(wu);n>=0?i?r.markAsStartAlternate(n):r.markAsEndAlternate(n):i?r.markAsStartGroup():r.markAsEndGroup(),this.nodes.push(r),this.connect(t,o);let s=new Di(o,!0),a=new Di(o,!1);t.push(this.connections.length),this.connections.push(a),t.push(this.connections.length),this.connections.push(s)}endSpecialGroup(){let t=[this.match,this.nomatch,this.error];for(let i=0;i<t.length;i++)this.addSpecialToArr(t[i],!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 i=new An(wu);i.markAsStartAlternate(t),this.nodes.push(i);let n=new Di(0,!0),o=new Di(0,!1);this.nomatch.push(this.connections.length),this.connections.push(o),this.match.push(this.connections.length),this.connections.push(n)}addPrimitive(t){let i=this.nodes.length;this.nodes.push(new An(t));let n=new Di(i,!0),o=new Di(i,!1);this.connect(this.match,i),this.emptyHead?(this.nomatch.push(this.connections.length),this.emptyHead=!1):this.error.push(this.connections.length),this.connections.push(o),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 ue}addGroup(t,i){if(t.nodes.length==0)return;let n=this.nodes.length;if(i==4&&n==1&&t.isPrimitive()&&this.isPrimitive()){this.nodes[0].validator=this.nodes[0].validator.combine(t.nodes[0].validator);return}for(let r=0;r<t.nodes.length;r++)this.nodes.push(t.nodes[r]);i==4?(this.emptyHead=!0,this.connect(this.nomatch,n)):this.connect(this.match,n);let o=this.connections.length;for(let r=0;r<t.connections.length;r++){let s=t.connections[r];s.where+=n,s.what>=0&&(s.what+=n),this.connections.push(s)}for(let r=0;r<t.match.length;r++)this.match.push(t.match[r]+o);if(i==3&&this.connect(this.match,n),i==2||i==3)for(let r=0;r<t.nomatch.length;r++)this.match.push(t.nomatch[r]+o);else if(this.emptyHead){for(let r=0;r<t.nomatch.length;r++)this.nomatch.push(t.nomatch[r]+o);this.emptyHead=t.emptyHead}else for(let r=0;r<t.nomatch.length;r++)this.error.push(t.nomatch[r]+o);for(let r=0;r<t.error.length;r++)this.error.push(t.error[r]+o);t.nodes=null,t.connections=null}finish(t,i){let n=this.nodes.length;this.nodes.push(t),this.nodes.push(i),this.connect(this.match,n),this.connect(this.nomatch,n+1),this.connect(this.error,n+1);for(let o of this.connections)o.success?this.nodes[o.where].success=this.nodes[o.what]:this.nodes[o.where].failure=this.nodes[o.what];for(let o=0;o<n;o++)if(this.nodes[o].failure==null||this.nodes[o].success==null)throw new Error("Invalid validator state");return this.nodes[0]}},Xw=1,ms=2,Vp=4,Si=8,Zi=16,$n=32,On=64,ys=128,ni=256,oi=512,vs=1024,Up=2048,$p=4096,ws=8192,Yl=class extends Kt{constructor(){super()}validateForShorthand(e,t){let i=e[t].visit(this);return i?[i]:null}},ue=class Hp extends Yl{constructor(t,i,n){super(),u(this,"allowed",t),u(this,"idents",i),u(this,"units",n)}visitEmpty(t){return this.allowed&Xw?t:null}visitSlash(t){return this.allowed&Up?t:null}visitStr(t){return this.allowed&ms?t:null}visitIdent(t){return this.idents[t.name.toLowerCase()]||(this.allowed&Vp||this.allowed&On&&CSS.supports("color",t.name)?t:null)}visitNumeric(t){return t.num==0&&!(this.allowed&oi)?t.unit=="%"&&this.allowed&vs?t:null:t.num<0&&!(this.allowed&ni)?null:this.units[t.unit]?t:null}visitNum(t){return t.num==0?this.allowed&oi?t:null:t.num<=0&&!(this.allowed&ni)?null:this.allowed&Zi?t:null}visitInt(t){return t.num==0?this.allowed&oi?t:null:t.num<=0&&!(this.allowed&ni)?null:this.allowed&($n|Zi)?t:this.idents[`${t.num}`]||null}visitHexColor(t){return this.allowed&On&&/^([0-9A-F]{3,4}|([0-9A-F]{2}){3,4})$/i.test(t.hex)?t:null}visitURL(t){return this.allowed&ys?t:null}visitURange(t){return this.allowed&$p?t:null}visitSpaceList(t){return null}visitCommaList(t){return null}visitFunc(t){if(t.name.toLowerCase()==="attr"){let i=Ql(t);if(i&&Jw(i.type,this.allowed,this.units))return t}if(this.allowed&On){if(t.name==="device-cmyk"||t.name==="cmyk")return CSS.supports("color","color(srgb 0 0 0)")&&Jc(t)!==null?t:null;if(CSS.supports("color",t.toString()))return t}if(this.allowed&ws){let i=t.visit(new td);if(CSS.supports("background-image",i.toString()))return t}return t.name==="calc"&&this.allowed&(Si|Zi|$n|ni|oi|vs)?t:null}visitExpr(t){return this.allowed&2046?t:null}combine(t){let i={},n={};for(let o in this.idents)i[o]=this.idents[o];for(let o in t.idents)i[o]=t.idents[o];for(let o in this.units)n[o]=this.units[o];for(let o in t.units)n[o]=t.units[o];return new Hp(this.allowed|t.allowed,i,n)}},te=Object.create(null),qw=Zi|ni|oi,Yw=$n|ni|oi,zi=Si|ni|oi|vs;function or(e){let t=Object.create(null);for(let i of e)t[i]=Be;return t}var Ds=or(["%"]),zs=or(["em","ex","ch","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","pvw","pvh","pvi","pvb","pvmin","pvmax","cm","mm","in","px","pt","pc","q"]),Wp={...zs,...Ds},Zl=or(["deg","grad","rad","turn"]),Kl=or(["s","ms"]),Jl=or(["hz","khz"]);function Zw(e){return e.replace(/\s+/g,"").toLowerCase()}function Vs(e){return e.toLowerCase()}function Kw(e){if(e instanceof he)switch(e.name.toLowerCase()){case"string":case"raw-string":return{kind:"string"};case"url":return{kind:"url"};case"color":case"integer":case"number":case"length":case"angle":case"time":case"frequency":return{kind:"syntax",syntax:`<${e.name.toLowerCase()}>`};default:return{kind:"unit",unit:Vs(e.name)}}if(e instanceof ai&&e.name.toLowerCase()==="type"){if(e.values.length!==1)return null;let t=Zw(e.values[0].stringValue());return t?{kind:"syntax",syntax:t}:null}return null}function Ql(e){var t;if(e.name.toLowerCase()!=="attr"||e.values.length<1||e.values.length>2)return null;let i,n={kind:"string"},o=e.values[0];if(o instanceof he)i=o.name;else if(o instanceof J){let r=o.values;if(r.length<1||r.length>2||!(r[0]instanceof he)||(i=r[0].name,r.length===2&&(n=Kw(r[1]),!n)))return null}else return null;return{attributeName:i,type:n,fallback:(t=e.values[1])!=null?t:null}}function Gp(e,t){return!!e[Vs(t)]}function un(e,t){return Object.keys(t).some(i=>Gp(e,i))}function Jw(e,t,i){switch(e.kind){case"string":return!!(t&ms);case"url":return!!(t&(ys|ws));case"unit":return Gp(i,e.unit);case"syntax":switch(e.syntax){case"<string>":return!!(t&ms);case"<url>":return!!(t&(ys|ws));case"<color>":return!!(t&On);case"<integer>":return!!(t&($n|Zi|ni|oi));case"<number>":return!!(t&(Zi|$n|ni|oi));case"<length>":return un(i,zs);case"<length-percentage>":return un(i,Wp);case"<percentage>":return un(i,Ds);case"<angle>":return un(i,Zl);case"<time>":return un(i,Kl);case"<frequency>":return un(i,Jl);default:return!1}}return!1}function Ja(e){switch(e.kind){case"string":return null;case"url":return null;case"unit":return new ue(zi,te,{[Vs(e.unit)]:Be});case"syntax":switch(e.syntax){case"<color>":return new ue(On,te,te);case"<integer>":return new ue(Yw,te,te);case"<number>":return new ue(qw,te,te);case"<length>":return new ue(zi,te,zs);case"<length-percentage>":return new ue(zi,te,Wp);case"<percentage>":return new ue(zi,te,Ds);case"<angle>":return new ue(zi,te,Zl);case"<time>":return new ue(zi,te,Kl);case"<frequency>":return new ue(zi,te,Jl);default:return null}}return null}function Qw(e){switch(e.kind){case"string":case"url":case"unit":return!0;case"syntax":return e.syntax==="<string>"||e.syntax==="<url>"||!!Ja(e)}return!1}function eb(e){switch(e.kind){case"url":return new Qe("about:invalid");case"string":return new K("");default:return y.unset}}function tb(e,t,i){if(t==null)return null;switch(i.kind){case"string":return new K(t);case"url":return t?new Qe(t):new Qe("about:invalid");case"unit":{let n=Ri(e,new xt(`${t.trim()}${Vs(i.unit)}`,null),""),o=Ja(i);return n&&o?n.visit(o):null}case"syntax":{if(i.syntax==="<string>")return new K(t);if(i.syntax==="<url>")return t?new Qe(t):new Qe("about:invalid");let n=Ri(e,new xt(t,null),""),o=Ja(i);return n&&o?n.visit(o):null}}return null}var wu=new ue(0,te,te),eh=class extends Yl{constructor(e){super(),u(this,"successTerminal"),u(this,"failureTerminal"),u(this,"first"),this.successTerminal=new An(null),this.failureTerminal=new An(null),this.first=e.finish(this.successTerminal,this.failureTerminal)}validateList(e,t,i){let n=t?[]:e,o=this.first,r=i,s=null,a=null;for(;o!==this.successTerminal&&o!==this.failureTerminal;){if(r>=e.length){o=o.failure;continue}let h=e[r],l=h;if(o.isSpecial()){let c=!0;o.isStartGroup()?(s?s.push(a):s=[a],a=[]):o.isEndGroup()?s.length>0?a=s.pop():a=null:o.isEndAlternate()?a[o.getAlternate()]="taken":c=a[o.getAlternate()]==null,o=c?o.success:o.failure}else{if(r==0&&!t&&o.validator instanceof Co&&this instanceof Co){if(l=new J(e).visit(o.validator),l){r=e.length,o=o.success;continue}}else if(r==0&&!t&&o.validator instanceof th&&this instanceof Co){if(l=new _e(e).visit(o.validator),l){r=e.length,o=o.success;continue}}else l=h.visit(o.validator);if(!l){o=o.failure;continue}if(l!==h&&e===n){n=[];for(let c=0;c<r;c++)n[c]=e[c]}e!==n&&(n[r-i]=l),r++,o=o.success}}return o===this.successTerminal&&(t?n.length>0:r==e.length)?n:null}validateSingle(e){let t=this.validateList([e],!1,0);return t?t[0]: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}},Co=class extends eh{constructor(e){super(e)}visitSpaceList(e){let t=this.validateList(e.values,!1,0);return t===e.values?e:t?new J(t):null}visitCommaList(e){let t=this.first,i=!1;for(;t;){if(t.validator instanceof th){i=!0;break}t=t.failure}if(i){let n=this.validateList(e.values,!1,0);return n===e.values?e:n?new _e(n):null}return null}validateForShorthand(e,t){return this.validateList(e,!0,t)}},th=class extends eh{constructor(e){super(e)}visitSpaceList(e){return this.validateSingle(e)}visitCommaList(e){let t=this.validateList(e.values,!1,0);return t===e.values?e:t?new _e(t):null}validateForShorthand(e,t){let i=this.first,n;for(;i!==this.failureTerminal;){if(n=i.validator.validateForShorthand(e,t),n)return n;i=i.failure}return null}},ib=class extends eh{constructor(e,t){super(t),u(this,"name",e)}validateSingle(e){return null}visitFunc(e){if(e.name.toLowerCase()!=this.name)return null;let t=this.validateList(e.values,!1,0);return t===e.values?e:t?new ai(e.name,t):null}},bu=class extends Yl{validateSingle(e){return null}visitFunc(e){let t=Ql(e);return t&&Qw(t.type)?e:null}},jp=class{tryParse(e,t,i){return t}success(e,t){}},Xp=class extends jp{constructor(e,t){super(),u(this,"name",t),u(this,"validator"),this.validator=e.validators[this.name]}tryParse(e,t,i){if(i.values[this.name])return t;let n=this.validator.validateForShorthand(e,t);if(n){let o=n.length,r=o>1?new J(n):n[0];return this.success(r,i),t+o}return t}success(e,t){t.values[this.name]=e}},nb=class extends Xp{constructor(e,t){super(e,t[0]),u(this,"names",t)}success(e,t){for(let i=0;i<this.names.length;i++)t.values[this.names[i]]=e}},ob=class extends jp{constructor(e,t){super(),u(this,"nodes",e),u(this,"slash",t)}tryParse(e,t,i){let n=t;if(this.slash)if(e[t]==jn){if(++t==e.length)return n}else return n;let o=this.nodes[0].tryParse(e,t,i);if(o==t)return n;t=o;for(let r=1;r<this.nodes.length&&t<e.length&&(o=this.nodes[r].tryParse(e,t,i),o!=t);r++)t=o;return t}},Us=class extends Kt{constructor(){super(...arguments),u(this,"syntax",null),u(this,"propList",null),u(this,"error",!1),u(this,"values",{}),u(this,"validatorSet",null)}setOwner(e){this.validatorSet=e}syntaxNodeForProperty(e){return new Xp(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,t){this.syntax=e,this.propList=t}finish(e,t){var i,n;if(!this.error){for(let o of this.propList)t.simpleProperty(o,(n=(i=this.values[o])!=null?i:this.validatorSet.defaultValues[o])!=null?n:y.initial,e);return!0}return!1}propagateDefaultingValue(e,t,i){for(let n of this.propList)i.simpleProperty(n,e,t)}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)}},Xn=class extends Us{constructor(){super()}validateList(e){let t=0,i=0;for(;t<e.length;){let n=this.syntax[i].tryParse(e,t,this);if(n>t){t=n,i=0;continue}if(++i==this.syntax.length){this.error=!0;break}}return t}},qp=class extends Us{constructor(){super()}validateList(e){if(e.length>this.syntax.length||e.length==0)return this.error=!0,0;for(let t=0;t<this.syntax.length;t++){let i=t;for(;i>=e.length;)i=i==1?0:i-2;if(this.syntax[t].tryParse(e,i,this)!=i+1)return this.error=!0,0}return e.length}createSyntaxNode(){return new nb(this.validatorSet,this.propList)}},rb=class extends Us{constructor(){super()}validateList(e){let t=e.length;for(let i=0;i<e.length;i++)if(e[i]===jn){t=i;break}if(t>this.syntax.length||e.length==0)return this.error=!0,0;for(let i=0;i<this.syntax.length;i++){let n=i;for(;n>=t;)n=n==1?0:n-2;let o;if(t+1<e.length)for(o=t+i+1;o>=e.length;)o=o-(o==t+2?1:2);else o=n;let r=[e[n],e[o]];if(this.syntax[i].tryParse(r,0,this)!=2)return this.error=!0,0}return e.length}},sb=class extends Xn{constructor(){super()}mergeIn(e,t){var i,n;for(let o of this.propList){let r=(n=(i=t[o])!=null?i:this.validatorSet.defaultValues[o])!=null?n:y.initial,s=e[o];s||(s=[],e[o]=s),s.push(r)}}visitCommaList(e){let t={};for(let i=0;i<e.values.length;i++)if(this.values={},e.values[i]instanceof _e?this.error=!0:(e.values[i].visit(this),this.mergeIn(t,this.values),this.values["background-color"]&&i!=e.values.length-1&&(this.error=!0)),this.error)return null;this.values={};for(let i in t)i=="background-color"?this.values[i]=t[i].pop():this.values[i]=new _e(t[i]);return null}},ab=class extends Xn{constructor(){super()}init(e,t){super.init(e,t),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(e){let t=super.validateList(e),i=this.values["font-variant_css2"];i&&(delete this.values["font-variant_css2"],this.values["font-variant-caps"]=i);let n=this.values["font-stretch_css3"];if(n&&(delete this.values["font-stretch_css3"],this.values["font-stretch"]=n),t+2>e.length)return this.error=!0,t;this.error=!1;let o=this.validatorSet.validators;if(!e[t].visit(o["font-size"])){let s=this.values["font-weight"],a=s instanceof ai&&s.name==="calc"?e.indexOf(s):-1;if(a>=0&&e[a].visit(o["font-size"]))delete this.values["font-weight"],t=a;else return this.error=!0,t}if(this.values["font-size"]=e[t++],e[t]===jn){if(t++,t+2>e.length)return this.error=!0,t;if(!e[t].visit(o["line-height"]))return this.error=!0,t;this.values["line-height"]=e[t++]}let r=t==e.length-1?e[t]:new J(e.slice(t,e.length));return r.visit(o["font-family"])?(this.values["font-family"]=r,e.length):(this.error=!0,t)}visitCommaList(e){if(e.values[0].visit(this),this.error)return null;let t=[this.values["font-family"]];for(let n=1;n<e.values.length;n++)t.push(e.values[n]);let i=new _e(t);return i.visit(this.validatorSet.validators["font-family"])?this.values["font-family"]=i:this.error=!0,null}visitIdent(e){let t=this.validatorSet.systemFonts[e.name];if(t)for(let i in t)this.values[i]=t[i];else this.error=!0;return null}},lb=class extends Xn{validateList(e){if(e.length===1&&e[0]instanceof he)switch(e[0].name.toLowerCase()){case"normal":e=[this.validatorSet.defaultValues["text-autospace"],this.validatorSet.defaultValues["text-spacing-trim"]];break;case"auto":e=[y.auto,y.auto];break;case"none":e=[B("no-autospace"),B("space-all")];break}return super.validateList(e)}},hb=class extends Us{constructor(e,t=[]){super(),u(this,"name",e),this.propList=t}clone(){let e=new this.constructor(this.name,[...this.propList]);return e.validatorSet=this.validatorSet,e}validateValueText(e){let t=this.validatorSet.expandBrowserShorthand(this.name,e);if(!t)return this.error=!0,!1;this.propList=t.propList,this.values={};for(let i of t.propList){let n=t.values[i];if(!n)continue;let o=Ri(this.validatorSet.scope,new xt(n,null),"");if(!o)return this.error=!0,!1;this.values[i]=o}return this.error=!1,!0}validateList(e){let t=e.length===1?e[0].toString():new J(e).toString();return this.validateValueText(t)?e.length:0}visitCommaList(e){return this.validateValueText(e.toString()),null}},xu=["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","inset-block-start","inset-block-end","inset-inline-start","inset-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","src","template","text-decoration-skip","text-justify","text-zoom","unicode-range","utilization","wrap-flow"],Yp=class extends Xn{constructor(){super()}refreshPropList(){this.propList=this.validatorSet.getPropertiesForAll()}init(e,t){super.init(e,t)}validateList(e){return this.error=!0,0}},Su={SIMPLE:Xn,INSETS:qp,INSETS_SLASH:rb,COMMA:sb,FONT:ab,TEXT_SPACING:lb,ALL:Yp},ub=["initial-letter"],cb=class{constructor(){u(this,"validators",{}),u(this,"prefixes",{}),u(this,"defaultValues",{}),u(this,"namedValidators",{}),u(this,"systemFonts",{}),u(this,"shorthands",{}),u(this,"layoutProps",{}),u(this,"backgroundProps",{}),u(this,"scope",new ts(null)),u(this,"browserShorthandStyle",null),u(this,"browserShorthandMisses",{}),u(this,"browserPropertyNamesForAll",null),u(this,"allPropertyNames",null)}invalidateAllPropertyNames(){this.allPropertyNames=null}getBrowserPropertyNamesForAll(){if(this.browserPropertyNamesForAll)return this.browserPropertyNamesForAll;if(typeof document>"u"||typeof getComputedStyle!="function")return null;let e=document.documentElement;if(!e)return null;let t=getComputedStyle(e),i=[];for(let n=0;n<t.length;n++){let o=t.item(n);!o||Xe(o)||xu.includes(o)||i.push(o)}return this.browserPropertyNamesForAll=i,this.browserPropertyNamesForAll}getPropertiesForAll(){if(this.allPropertyNames)return this.allPropertyNames;let e=new Set;for(let n in this.validators)xu.includes(n)||e.add(n);let t=this.getBrowserPropertyNamesForAll();if(t)for(let n of t)this.shorthands[n]||e.add(n);let i=Array.from(e);return t&&(this.allPropertyNames=i),i}getBrowserShorthandStyle(){return this.browserShorthandStyle!==null?this.browserShorthandStyle:typeof document>"u"?null:(this.browserShorthandStyle=document.createElement("div").style,this.browserShorthandStyle)}expandBrowserShorthand(e,t){let i=this.getBrowserShorthandStyle();if(!i)return null;i.cssText="",i.setProperty(e,t);let n=Array.from({length:i.length},(r,s)=>i.item(s)).filter(r=>!!r);if(!n.length||n.length===1&&n[0]===e.toLowerCase())return null;let o={};for(let r of n)o[r]=i.getPropertyValue(r);return{propList:n,values:o}}getShorthand(e,t){if(Xe(e))return null;let i=this.shorthands[e];if(i)return i instanceof Yp&&!this.allPropertyNames&&i.refreshPropList(),i;if(this.browserShorthandMisses[e]||t==null)return null;let n=this.expandBrowserShorthand(e,typeof t=="string"?t:t.toString());if(!n)return(typeof t=="string"?!/\bvar\(/i.test(t):!Cu(t))&&(this.browserShorthandMisses[e]=!0),null;let o=new hb(e,n.propList);return o.setOwner(this),this.shorthands[e]=o,this.invalidateAllPropertyNames(),o}addReplacement(e,t){let i;if(t.type==3)i=new O(t.num,t.text);else if(t.type==7)i=new jc(t.text);else if(t.type==1)i=B(t.text);else throw new Error("unexpected replacement");if(e.isPrimitive()){let n=e.nodes[0].validator.idents;for(let o in n)n[o]=i;return e}throw new Error("unexpected replacement")}newGroup(e,t){let i=new oo;if(e=="||"){for(let o=0;o<t.length;o++){let r=new oo;r.startClause(o),r.addGroup(t[o],1),r.endClause(o),i.addGroup(r,o==0?1:4)}let n=new oo;return n.startSpecialGroup(),n.addGroup(i,3),n.endSpecialGroup(),n}else{let n;switch(e){case" ":n=1;break;case"|":case"||":n=4;break;default:throw new Error("unexpected op")}for(let o=0;o<t.length;o++)i.addGroup(t[o],o==0?1:n);return i}}addCounts(e,t,i){let n=new oo;for(let o=0;o<t;o++)n.addGroup(e.clone(),1);if(i==Number.POSITIVE_INFINITY)n.addGroup(e,3);else for(let o=t;o<i;o++)n.addGroup(e.clone(),2);return n}primitive(e){let t=new oo;return t.addPrimitive(e),t}newFunc(e,t){let i;switch(e){case"COMMA":i=new th(t);break;case"SPACE":i=new Co(t);break;case"attr":i=new bu;break;default:i=new ib(e.toLowerCase(),t);break}return this.primitive(i)}initBuiltInValidators(){this.namedValidators.COLOR=this.primitive(new ue(On,te,te)),this.namedValidators.ATTR=this.primitive(new bu),this.namedValidators.IMAGE_FUNCTION=this.primitive(new ue(ws,te,te)),this.namedValidators.POS_INT=this.primitive(new ue($n,te,te)),this.namedValidators.POS_NUM=this.primitive(new ue(Zi,te,te)),this.namedValidators.POS_PERCENTAGE=this.primitive(new ue(Si,te,Ds)),this.namedValidators.NEGATIVE=this.primitive(new ue(ni,te,te)),this.namedValidators.ZERO=this.primitive(new ue(oi,te,te)),this.namedValidators.ZERO_PERCENTAGE=this.primitive(new ue(vs,te,te)),this.namedValidators.POS_LENGTH=this.primitive(new ue(Si,te,zs)),this.namedValidators.POS_ANGLE=this.primitive(new ue(Si,te,Zl)),this.namedValidators.POS_TIME=this.primitive(new ue(Si,te,Kl)),this.namedValidators.FREQUENCY=this.primitive(new ue(Si,te,Jl)),this.namedValidators.RESOLUTION=this.primitive(new ue(Si,te,{dpi:Be,dpcm:Be,dppx:Be})),this.namedValidators.URI=this.primitive(new ue(ys,te,te)),this.namedValidators.URANGE=this.primitive(new ue($p,te,te)),this.namedValidators.IDENT=this.primitive(new ue(Vp,te,te)),this.namedValidators.STRING=this.primitive(new ue(ms,te,te)),this.namedValidators.SLASH=this.primitive(new ue(Up,te,te));let e={"font-family":B("sans-serif")};this.systemFonts.caption=e,this.systemFonts.icon=e,this.systemFonts.menu=e,this.systemFonts["message-box"]=e,this.systemFonts["small-caption"]=e,this.systemFonts["status-bar"]=e}isBuiltIn(e){return!!e.match(/^[A-Z_0-9]+$/)}readNameAndPrefixes(e,t){let i=e.token();if(i.type==0)return null;let n={"":!0};if(i.type==14){do{if(e.consume(),i=e.token(),i.type!=1)throw new Error("Prefix name expected");n[i.text]=!0,e.consume(),i=e.token()}while(i.type==16);if(i.type!=15)throw new Error("']' expected");e.consume(),i=e.token()}if(i.type!=1)throw new Error("Property name expected");if(t==2?i.text=="SHORTHANDS":i.text=="DEFAULTS")return e.consume(),null;let o=i.text;if(e.consume(),t!=2){if(e.token().type!=39)throw new Error("'=' expected");this.isBuiltIn(o)||(this.prefixes[o]=n)}else if(e.token().type!=18)throw new Error("':' expected");return o}parseValidators(e){for(;;){let t=this.readNameAndPrefixes(e,1);if(!t)return;let i=[],n=[],o="",r,s=!0,a=()=>{if(i.length==0)throw new Error("No values");return i.length==1?i[0]:this.newGroup(o,i)},h=c=>{if(s)throw new Error(`'${c}': unexpected`);if(o&&o!=c)throw new Error(`mixed operators: '${c}' and '${o}'`);o=c,s=!0},l=null;for(;!l;){e.consume();let c=e.token();switch(c.type){case 1:if(s||h(" "),this.isBuiltIn(c.text)){let d=this.namedValidators[c.text];if(!d)throw new Error(`'${c.text}' unexpected`);i.push(d.clone())}else{let d={};d[c.text.toLowerCase()]=B(c.text),i.push(this.primitive(new ue(0,d,te)))}s=!1;break;case 5:{let d={};d[`${c.num}`]=new lt(c.num),i.push(this.primitive(new ue(0,d,te))),s=!1;break}case 34:h("|");break;case 25:h("||");break;case 14:s||h(" "),n.push({vals:i,op:o,b:"["}),o="",i=[],s=!0;break;case 6:s||h(" "),n.push({vals:i,op:o,b:"(",fn:c.text}),o="",i=[],s=!0;break;case 15:{r=a();let d=n.pop();if(d.b!="[")throw new Error("']' unexpected");i=d.vals,i.push(r),o=d.op,s=!1;break}case 11:{r=a();let d=n.pop();if(d.b!="(")throw new Error("')' unexpected");i=d.vals,i.push(this.newFunc(d.fn,r)),o=d.op,s=!1;break}case 18:if(s)throw new Error("':' unexpected");e.consume(),i.push(this.addReplacement(i.pop(),e.token()));break;case 22:if(s)throw new Error("'?' unexpected");i.push(this.addCounts(i.pop(),0,1));break;case 36:if(s)throw new Error("'*' unexpected");i.push(this.addCounts(i.pop(),0,Number.POSITIVE_INFINITY));break;case 23:if(s)throw new Error("'+' unexpected");i.push(this.addCounts(i.pop(),1,Number.POSITIVE_INFINITY));break;case 12:{if(e.consume(),c=e.token(),c.type!=5)throw new Error("<int> expected");let d=c.num,p=d;if(e.consume(),c=e.token(),c.type==16){if(e.consume(),c=e.token(),c.type!=5)throw new Error("<int> expected");p=c.num,e.consume(),c=e.token()}if(c.type!=13)throw new Error("'}' expected");i.push(this.addCounts(i.pop(),d,p));break}case 17:if(l=a(),n.length>0)throw new Error(`unclosed '${n.pop().b}'`);break;default:throw new Error("unexpected token")}}e.consume(),this.isBuiltIn(t)?this.namedValidators[t]=l:l.isSimple()?this.validators[t]=l.nodes[0].validator:this.validators[t]=new Co(l)}}parseDefaults(e){for(;;){let t=this.readNameAndPrefixes(e,2);if(!t)return;let i=[];for(;;){e.consume();let n=e.token();if(n.type==17){e.consume();break}switch(n.type){case 1:i.push(B(n.text));break;case 4:i.push(new At(n.num));break;case 5:i.push(new lt(n.num));break;case 3:i.push(new O(n.num,n.text));break;default:throw new Error("unexpected token")}}this.defaultValues[t]=i.length>1?new J(i):i[0]}}parseShorthands(e){for(;;){let t=this.readNameAndPrefixes(e,3);if(!t)return;let i=e.nthToken(1),n;i.type==1&&Su[i.text]?(n=new Su[i.text],e.consume()):n=new Xn,n.setOwner(this);let o=!1,r=[],s=!1,a=[],h=[];for(;!o;)switch(e.consume(),i=e.token(),i.type){case 1:if(this.validators[i.text])r.push(n.syntaxNodeForProperty(i.text)),i.text.includes("_")||h.push(i.text);else if(this.shorthands[i.text]instanceof qp){let l=this.shorthands[i.text];r.push(l.createSyntaxNode()),h.push(...l.propList)}else throw new Error(`'${i.text}' is neither a simple property nor an inset shorthand`);break;case 19:if(r.length>0||s)throw new Error("unexpected slash");s=!0;break;case 14:a.push({slash:s,syntax:r}),r=[],s=!1;break;case 15:{let l=new ob(r,s),c=a.pop();r=c.syntax,s=c.slash,r.push(l);break}case 17:o=!0,e.consume();break;default:throw new Error("unexpected token")}n.init(r,h),this.shorthands[t]=n,this.invalidateAllPropertyNames()}}parse(e){let t=new xt(e,null);this.parseValidators(t),this.parseDefaults(t),this.parseShorthands(t),this.backgroundProps=this.makePropSet(["background"]),this.layoutProps=this.makePropSet(["margin","border","padding","columns","column-gap","column-rule","column-fill"])}makePropSet(e){var t;let i={};for(let n of e){let o=this.shorthands[n],r=o?o.propList:[n];for(let s of r)i[s]=(t=this.defaultValues[s])!=null?t:y.initial}return i}validatePropertyAndHandleShorthand(e,t,i,n){var o,r;let s=n.ruleType;if(Xe(e)||s==="font-face"){n.simpleProperty(e,t,i);return}if(s==="counter-style"){_w(e,t)?n.simpleProperty(e,t,i):n.invalidPropertyValue(e,t);return}let a="",h=e;e=e.toLowerCase();let l=e.match(/^-([a-z]+)-([-a-z0-9]+)$/);l&&(a=l[1],e=l[2]);let c=a?h:e;if(Cu(t)){this.getShorthand(c,t),n.simpleProperty(h,t,i);return}let d=this.prefixes[e];if(!d||!d[a]){if(CSS.supports(h,t.toString())){let f=(o=this.getShorthand(c,t))==null?void 0:o.clone();f?Z(t)?f.propagateDefaultingValue(t,i,n):(t.visit(f),f.finish(i,n)||n.invalidPropertyValue(h,t)):n.simpleProperty(h,t,i)}else a&&!Sc.includes(`-${a}-`)||n.unknownProperty(h,t);return}else if(ub.includes(e)&&!Object.keys(d).some(f=>Rr(f?`-${f}-`:"",e))){n.unknownProperty(h,t);return}let p=this.validators[e];if(p){let f=Z(t)||t.isExpr()?t:t.visit(p);f?n.simpleProperty(e,f,i):!a&&CSS.supports(e,t.toString())?n.simpleProperty(e,t,i):n.invalidPropertyValue(h,t)}else{let f=(r=this.getShorthand(e,t))==null?void 0:r.clone();if(!f){n.unknownProperty(h,t);return}Z(t)?f.propagateDefaultingValue(t,i,n):(t.visit(f),f.finish(i,n)||n.invalidPropertyValue(h,t))}}};function Zp(){let e=new cb;return e.initBuiltInValidators(),e.parse(kd),e}var db=class extends Kt{constructor(){super(...arguments),u(this,"varFound",!1)}visitFunc(e){return e.name==="var"?this.varFound=!0:this.varFound||this.visitValues(e.values),null}};function Cu(e){let t=new db;return e.visit(t),t.varFound}function Kp(e,t,i){return e-=i,t===0?e===0:e%t===0&&e/t>=0}var pb=class{constructor(e){u(this,"matchers",e)}matches(){return this.matchers.some(e=>e.matches())}},fb=class{constructor(e){u(this,"matchers",e)}matches(){return this.matchers.every(e=>e.matches())}},Jp=class jr{constructor(t,i,n){u(this,"elementOffset",t),u(this,"a",i),u(this,"b",n)}static registerFragmentIndex(t,i,n){let o=jr.fragmentIndices;(!o[t]||o[t].priority<=n)&&(o[t]={fragmentIndex:i,priority:n})}static clearFragmentIndices(){jr.fragmentIndices={}}matches(){let t=jr.fragmentIndices[this.elementOffset];return t!=null&&t.fragmentIndex!=null&&Kp(t.fragmentIndex,this.a,this.b)}};u(Jp,"fragmentIndices",{});var $s=Jp,Pr=class{static buildViewConditionMatcher(e,t){let i=t.split("_");return i[0]=="NFS"?new $s(e,parseInt(i[1],10),parseInt(i[2],10)):(`${t}`,null)}static buildAllMatcher(e){return new fb(e)}static buildAnyMatcher(e){return new pb(e)}},Qp={"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},gb=["image-resolution","orphans","widows"];function mb(){return _t("POLYFILLED_INHERITED_PROPS").reduce((e,t)=>e.concat(t()),[].concat(gb))}var yb={"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},Qa=["margin-%","padding-%","border-%-width","border-%-style","border-%-color","%"],vb=["max-%","min-%","%"],ku=(()=>{let e=["left","right","top","bottom"],t={width:!0,height:!0,"max-width":!0,"max-height":!0,"min-width":!0,"min-height":!0};for(let i=0;i<Qa.length;i++)for(let n=0;n<e.length;n++){let o=Qa[i].replace("%",e[n]);t[o]=!0}return t})();function qn(e,t){let i={};for(let n of Qa)for(let o in e){let r=n.replace("%",o),s=n.replace("%",e[o]);i[r]=s,i[s]=r}for(let n of vb)for(let o in t){let r=n.replace("%",o),s=n.replace("%",t[o]);i[r]=s,i[s]=r}return i}var ef=qn({"block-start":"right","block-end":"left","inline-start":"top","inline-end":"bottom"},{"block-size":"width","inline-size":"height"}),tf=qn({"block-start":"top","block-end":"bottom","inline-start":"left","inline-end":"right"},{"block-size":"height","inline-size":"width"}),wb=qn({"block-start":"right","block-end":"left","inline-start":"bottom","inline-end":"top"},{"block-size":"width","inline-size":"height"}),bb=qn({"block-start":"top","block-end":"bottom","inline-start":"right","inline-end":"left"},{"block-size":"height","inline-size":"width"}),xb=qn({inside:"right",outside:"left"},{}),Sb=qn({inside:"left",outside:"right"},{}),W=class el{constructor(t,i){u(this,"value",t),u(this,"priority",i)}getBaseValue(){return this}filterValue(t){let i=this.value.visit(t);return i===this.value?this:new el(i,this.priority)}increaseSpecificity(t){return t==0?this:new el(this.value,this.priority+t)}evaluate(t,i,n,o){return i&&Xe(i)?this.value:Ss(t,this.value,i,n,o)}isEnabled(t){return!0}},tl=class il extends W{constructor(t,i,n){super(t,i),u(this,"condition",n)}getBaseValue(){return new W(this.value,this.priority)}filterValue(t){let i=this.value.visit(t);return i===this.value?this:new il(i,this.priority,this.condition)}increaseSpecificity(t){return t==0?this:new il(this.value,this.priority+t,this.condition)}isEnabled(t){try{return!!this.condition.evaluate(t)}catch(i){Y.warn(i)}return!1}};function nl(e,t,i){return(!t||i.priority>=t.priority)&&i.isEnabled(e)?i.getBaseValue():t}function Jt(e,t,i,n){if(e)if(!i)delete e[t];else{let o=e[t];(!o||i.priority>=o.priority)&&(n?i.isEnabled(n)&&(e[t]=i.getBaseValue()):e[t]=i)}}var nf={"region-id":!0,"fragment-selector-id":!0},ko="data-viv-footnote-counter";function bs(e){let t=e.getAttribute(ko);if(!t)return Object.create(null);let i;try{i=JSON.parse(t)}catch{return Object.create(null)}if(!i||typeof i!="object"||Array.isArray(i))return Object.create(null);let n=Object.create(null);return Object.entries(i).forEach(([o,r])=>{if(Array.isArray(r)){let s=r.filter(a=>typeof a=="number"&&isFinite(a));n[o]=s}else typeof r=="number"&&isFinite(r)&&(n[o]=[r])}),n}function of(e,t,i){let n=bs(e);n[t]=i,e.setAttribute(ko,JSON.stringify(n))}function Cb(e,t){var i,n;if(!Gt(e)||e.hasAttribute(cp))return null;let o=bs(e)[t];if(o)return o;let r=e.getAttribute("href")||e.getAttributeNS("http://www.w3.org/1999/xlink","href");if(!r)return null;let s=e.baseURI||((i=e.ownerDocument)==null?void 0:i.baseURI)||"",a=Qr(r,s);if(a==="#"||a.replace(/#.*$/,"")!==s.replace(/#.*$/,""))return null;let h=a.indexOf("#");if(h<0||h===a.length-1)return null;let l=(n=e.ownerDocument)==null?void 0:n.getElementById(a.substring(h+1));if(!(l instanceof Element))return null;let c=bs(l)[t];return c?(of(e,t,c),c):null}function kb(e){let t=ve(e,"content");return!!t&&It(t.value)}function Eb(e){return!!nf[e]}function Xr(e){return e.charAt(0)==="_"&&e!=="_viewConditionalStyles"}function Xi(e){return e.charAt(0)!=="_"&&!nf[e]}function In(e){return!!Qp[e]||Xe(e)}function ve(e,t){return e[t]}function Fi(e,t,i){i?e[t]=i:delete e[t]}function ft(e,t){return e[t]}function si(e,t){let i=e[t];return i||(i={},e[t]=i),i}var rf=e=>{let t=e._viewConditionalStyles;return t||(t=[],e._viewConditionalStyles=t),t};function sf(e,t){return e[t]}function af(e,t){let i=e[t];return i||(i=[],e[t]=i),i}function xs(e,t,i,n,o,r,s){var a,h;if([{id:o,styleKey:"_pseudos"},{id:r,styleKey:"_regions"}].forEach(l=>{if(l.id){let c=si(t,l.styleKey);t=c[l.id],t||(t={},c[l.id]=t)}}),s){let l=rf(t);t={},l.push({styles:t,matcher:s})}for(let l in i)if(!Xr(l))if(Eb(l)){let c=sf(i,l),d=af(t,l);Array.prototype.push.apply(d,c)}else{let c=ve(i,l);if(!c.isEnabled(e))continue;let d=c.increaseSpecificity(n);Jt(t,l,d,e);let p=(a=e.style)==null?void 0:a.validatorSet,f=(h=p?.getShorthand(l,d.value))==null?void 0:h.propList;if(f)for(let g of f){let v=new W(Be,d.priority);Jt(t,g,v,e)}}}function Pb(e,t){let i={};for(let n=0;n<t.length;n++)xs(e,i,t[n],0,null,null,null);return i}function ih(e,t){if(e.length>0){e.sort((n,o)=>o.getPriority()-n.getPriority());let i=null;for(let n=e.length-1;n>=0;n--)i=e[n],i.chained=t,t=i;return i}return t}var Nb=class extends nn{constructor(e,t){super(),u(this,"props",e),u(this,"context",t),u(this,"propName","")}setPropName(e){this.propName=e}getFontSize(){let e=ve(this.props,"font-size");if(!e.value.isNumeric())return Zt.em;let t=e.value;if(!hm(t.unit))throw new Error("Unexpected state");return t.num*Zt[t.unit]}visitNumeric(e){return this.context,this.propName==="font-size"?ol(e,this.getFontSize(),this.context):e.unit==="em"||e.unit==="rem"||e.unit==="lh"||e.unit==="rlh"?nh(e,this.getFontSize(),this.context):e}visitExpr(e){return this.propName=="font-size"?Ss(this.context,e,this.propName).visit(this):e}};function nh(e,t,i){let n=e.unit,o=e.num;return n==="em"?new O(o*t,"px"):n==="rem"?new O(o*i.fontSize(),"px"):n==="rlh"?new O(o*i.rootLineHeight,"px"):e}function ol(e,t,i){e=nh(e,t,i);let n=e.unit,o=e.num;return n==="px"?e:n==="%"?new O(o/100*t,"px"):new O(o*i.queryUnitSize(n,!1),"px")}var Yn=class{apply(e){}mergeWith(e){return new Tb([this,e])}clone(){return this}},Nr=class extends Yn{constructor(e){super(),u(this,"conditionItem",e)}apply(e){e.pushConditionItem(this.conditionItem.fresh(e))}},Tb=class lf extends Yn{constructor(t){super(),u(this,"list",t)}apply(t){for(let i=0;i<this.list.length;i++)this.list[i].apply(t)}mergeWith(t){return this.list.push(t),this}clone(){return new lf([].concat(this.list))}},oh=class extends Yn{constructor(e,t,i,n,o){super(),u(this,"style",e),u(this,"specificity",t),u(this,"pseudoelement",i),u(this,"regionId",n),u(this,"viewConditionId",o)}apply(e){xs(e.context,e.currentStyle,this.style,this.specificity,this.pseudoelement,this.regionId,e.buildViewConditionMatcher(this.viewConditionId))}},Ne=class extends Yn{constructor(){super(),u(this,"chained",null)}apply(e){this.chained.apply(e)}getPriority(){return 0}makePrimary(e){return!1}},Ab=class extends Ne{constructor(e){super(),u(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}},Ib=class extends Ne{constructor(e){super(),u(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}},Eu=class extends Ne{constructor(e){super(),u(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}},Fb=class extends Ne{constructor(e,t){super(),u(this,"ns",e),u(this,"localName",t)}apply(e){e.currentLocalName==this.localName&&e.currentNamespace==this.ns&&this.chained.apply(e)}getPriority(){return 8}makePrimary(e){if(this.chained){let t=e.nsPrefix[this.ns];t||(t=`ns${e.nsCount++}:`,e.nsPrefix[this.ns]=t);let i=t+this.localName;e.insertInTable(e.nstags,i,this.chained)}return!0}},Rb=class extends Ne{constructor(e,t,i=!1){super(),u(this,"epubTypePatt",e),u(this,"targetLocalName",t),u(this,"useRoleAttr",i)}apply(e){let t=e.currentElement;if(t instanceof HTMLAnchorElement&&t.hash&&t.href==t.baseURI.replace(/#.*$/,"")+t.hash){let i=t.hash.substring(1),n=t.ownerDocument.getElementById(i);if(n&&(!this.targetLocalName||n.localName==this.targetLocalName)){let o=this.useRoleAttr?n.getAttribute("role"):n.getAttributeNS("http://www.idpf.org/2007/ops","type")||n.getAttribute("epub:type");o&&o.match(this.epubTypePatt)&&this.chained.apply(e)}}}},Lb=class extends Ne{constructor(e){super(),u(this,"ns",e)}apply(e){e.currentNamespace==this.ns&&this.chained.apply(e)}};function Hs(e,t,i,n){var o;if(!e)return!1;let r=((o=e.ownerDocument)==null?void 0:o.contentType)==="text/html",s=r?Mo(i):i;if(t!==null){let a=e.getAttributeNodeNS(t||null,s);return!!a&&n(a)}for(let a of Array.from(e.attributes))if((r?Mo(a.localName):a.localName)===s&&n(a))return!0;return!1}function Mo(e){return e.replace(/[A-Z]/g,t=>t.toLowerCase())}function hf(e){return e==="i"}function ro(e,t){return Array.from(e,i=>{let n=es(i);if(!hf(t))return n;let o=Mo(i),r=o.toUpperCase();return o!==r&&/^[a-z]$/i.test(i)?`[${o}${r}]`:n}).join("")}function so(e){return new RegExp(e)}function Ob(e,t,i){return hf(i)?Mo(e)===Mo(t):e===t}var Pu=class extends Ne{constructor(e,t){super(),u(this,"ns",e),u(this,"name",t)}apply(e){Hs(e.currentElement,this.ns,this.name,()=>!0)&&this.chained.apply(e)}},Bb=class extends Ne{constructor(e,t,i,n=null){super(),u(this,"ns",e),u(this,"name",t),u(this,"value",i),u(this,"caseSensitivity",n)}apply(e){Hs(e.currentElement,this.ns,this.name,t=>Ob(t.value,this.value,this.caseSensitivity))&&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}},Mb=class extends Ne{constructor(e,t){super(),u(this,"ns",e),u(this,"name",t)}apply(e){Hs(e.currentElement,this.ns,this.name,t=>!!yb[t.value])&&this.chained.apply(e)}getPriority(){return 0}makePrimary(e){return!1}},ao=class extends Ne{constructor(e,t,i,n=null){super(),u(this,"ns",e),u(this,"name",t),u(this,"regexp",i),u(this,"caseSensitivity",n)}apply(e){Hs(e.currentElement,this.ns,this.name,t=>!!t.value.match(this.regexp))&&this.chained.apply(e)}},_b=class extends Ne{constructor(e){super(),u(this,"langRegExp",e)}apply(e){e.lang.match(this.langRegExp)&&this.chained.apply(e)}},Nu=class extends Ne{constructor(){super()}apply(e){e.isFirst&&this.chained.apply(e)}getPriority(){return 6}},Db=class extends Ne{constructor(){super()}apply(e){e.isRoot&&this.chained.apply(e)}getPriority(){return 12}},sn=class extends Ne{constructor(e,t){super(),u(this,"a",e),u(this,"b",t)}matchANPlusB(e){return Kp(e,this.a,this.b)}},zb=class extends sn{constructor(e,t){super(e,t)}apply(e){this.matchANPlusB(e.currentSiblingOrder)&&this.chained.apply(e)}getPriority(){return 5}},rl=class extends sn{constructor(e,t){super(e,t)}apply(e){let t=e.currentSiblingTypeCounts[e.currentNamespace][e.currentLocalName];this.matchANPlusB(t)&&this.chained.apply(e)}getPriority(){return 5}},sl=class extends sn{constructor(e,t){super(e,t)}apply(e){let t=e.currentFollowingSiblingOrder;t===null&&(t=e.currentFollowingSiblingOrder=e.currentElement.parentNode.childElementCount-e.currentSiblingOrder+1),this.matchANPlusB(t)&&this.chained.apply(e)}getPriority(){return 4}},al=class extends sn{constructor(e,t){super(e,t)}apply(e){let t=e.currentFollowingSiblingTypeCounts;if(!t[e.currentNamespace]){let i=e.currentElement;do{let n=i.namespaceURI,o=i.localName,r=t[n];r||(r=t[n]={}),r[o]=(r[o]||0)+1}while(i=i.nextElementSibling)}this.matchANPlusB(t[e.currentNamespace][e.currentLocalName])&&this.chained.apply(e)}getPriority(){return 4}},Vb=class extends Ne{constructor(){super()}apply(e){let t=e.currentElement.firstChild;for(;t;){switch(t.nodeType){case Node.ELEMENT_NODE:return;case Node.TEXT_NODE:if(t.length>0)return}t=t.nextSibling}this.chained.apply(e)}getPriority(){return 4}},Ub=class extends Ne{constructor(){super()}apply(e){e.currentElement.disabled===!1&&this.chained.apply(e)}getPriority(){return 5}},$b=class extends Ne{constructor(){super()}apply(e){e.currentElement.disabled===!0&&this.chained.apply(e)}getPriority(){return 5}},Hb=class extends Ne{constructor(){super()}apply(e){let t=e.currentElement;(t.selected===!0||t.checked===!0)&&this.chained.apply(e)}getPriority(){return 5}},ot=class extends Ne{constructor(e){super(),u(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}},uf=class cf extends Yn{constructor(){super(),u(this,"applied",!1)}apply(t){this.applied=!0}clone(){let t=new cf;return t.applied=this.applied,t}},rh=class extends Ne{constructor(e){super(),u(this,"checkAppliedAction"),u(this,"firstActions",[]),this.checkAppliedAction=new uf;for(let t of e)this.firstActions.push(ih(t,this.checkAppliedAction))}apply(e){for(let t of this.firstActions)if(t.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 Ne?e.getPriority():0))}positive(){return!0}relational(){return!1}},Wb=class extends rh{positive(){return!1}},Gb=class extends rh{constructor(e){super([]),u(this,"selectorTexts",e)}apply(e){for(let t of this.selectorTexts){let i,n;/^\s*[+~]/.test(t)?(n=e.currentElement.parentNode,i=`:scope > :nth-child(${Array.from(n.children).indexOf(e.currentElement)+1}) ${t}`):(n=e.currentElement,i=`:scope ${t}`);try{if(n.querySelector(i)){this.checkAppliedAction.apply(e);break}}catch{}}this.checkAppliedAction.applied&&this.chained.apply(e),this.checkAppliedAction.applied=!1}relational(){return!0}},df=class extends sn{constructor(e,t,i){super(e,t),u(this,"checkAppliedAction"),u(this,"firstActions",[]),this.checkAppliedAction=new uf;for(let n of i)this.firstActions.push(ih(n,this.checkAppliedAction))}apply(e){for(let o of this.firstActions)if(o.apply(e),this.checkAppliedAction.applied)break;if(!this.checkAppliedAction.applied)return;this.checkAppliedAction.applied=!1;let t=e.currentElement,i=1,n=t.previousElementSibling;for(;n;)this.matchesSelector(n,e)&&i++,n=n.previousElementSibling;this.matchANPlusB(i)&&this.chained.apply(e)}matchesSelector(e,t){let i=t.currentElement,n=t.currentNamespace,o=t.currentLocalName,r=t.currentId,s=t.currentClassNames,a=t.currentSiblingOrder;t.currentElement=e,t.currentNamespace=e.namespaceURI||"",t.currentLocalName=e.localName,t.currentId=e.id,t.currentClassNames=e.classList?Array.from(e.classList):[];let h=1,l=e.previousElementSibling;for(;l;)h++,l=l.previousElementSibling;t.currentSiblingOrder=h;for(let d of this.firstActions)if(d.apply(t),this.checkAppliedAction.applied)break;let c=this.checkAppliedAction.applied;return this.checkAppliedAction.applied=!1,t.currentElement=i,t.currentNamespace=n,t.currentLocalName=o,t.currentId=r,t.currentClassNames=s,t.currentSiblingOrder=a,c}getPriority(){return 5}},jb=class extends df{constructor(e,t,i){super(e,t,i)}apply(e){for(let o of this.firstActions)if(o.apply(e),this.checkAppliedAction.applied)break;if(!this.checkAppliedAction.applied)return;this.checkAppliedAction.applied=!1;let t=e.currentElement,i=1,n=t.nextElementSibling;for(;n;)this.matchesSelector(n,e)&&i++,n=n.nextElementSibling;this.matchANPlusB(i)&&this.chained.apply(e)}getPriority(){return 4}},Ws=class{constructor(e,t,i){u(this,"condition",e),u(this,"viewConditionId",t),u(this,"viewCondition",i)}increment(e){e.increment(this.condition,this.viewCondition)}decrement(e){e.decrement(this.condition,this.viewCondition)}buildViewConditionMatcher(e){return e.buildViewConditionMatcher(this.viewConditionId)}},Xb=class pf extends Ws{constructor(t,i,n){super(t,i,n)}fresh(t){return new pf(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,i){return i==0&&this.increment(t),!1}pop(t,i){return i==0?(this.decrement(t),!0):!1}},qb=class ff extends Ws{constructor(t,i,n){super(t,i,n)}fresh(t){return new ff(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,i){return i==0?this.increment(t):i==1&&this.decrement(t),!1}pop(t,i){return i==0?(this.decrement(t),!0):(i==1&&this.increment(t),!1)}},Yb=class gf extends Ws{constructor(t,i,n){super(t,i,n),u(this,"fired",!1)}fresh(t){return new gf(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,i){return this.fired?(this.decrement(t),!0):!1}pop(t,i){return this.fired?(this.decrement(t),!0):(i==0&&(this.fired=!0,this.increment(t)),!1)}},Zb=class mf extends Ws{constructor(t,i,n){super(t,i,n),u(this,"fired",!1)}fresh(t){return new mf(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,i){return this.fired&&(i==-1?this.increment(t):i==0&&this.decrement(t)),!1}pop(t,i){if(this.fired){if(i==-1)return this.decrement(t),!0;i==0&&this.increment(t)}else i==0&&(this.fired=!0,this.increment(t));return!1}},Kb=class{constructor(e,t){u(this,"afterprop",e),u(this,"element",t)}fresh(e){return this}push(e,t){return!1}pop(e,t){return t==0?(e.processPseudoelementProps(this.afterprop,this.element),!0):!1}},Jb=class{constructor(e){u(this,"lang",e)}fresh(e){return this}push(e,t){return!1}pop(e,t){return t==0?(e.lang=this.lang,!0):!1}},Qb=class{constructor(e){u(this,"oldQuotes",e)}fresh(e){return this}push(e,t){return!1}pop(e,t){return t==0?(e.quotes=this.oldQuotes,!0):!1}},e0=class extends nn{constructor(e,t,i,n){super(),u(this,"element",e),u(this,"scope",t),u(this,"propName",i),u(this,"validatorSet",n),u(this,"hadAttrFunction",!1)}validatePropertyValue(e){var t,i;if(Z(e))return e;let n=(t=this.validatorSet)==null?void 0:t.validators[this.propName];return n?(i=e.visit(n))!=null?i:y.unset:!this.propName||CSS.supports(this.propName,e.toString())?e:y.unset}visitFunc(e){var t;if(e.name.toLowerCase()!=="attr")return super.visitFunc(e);this.hadAttrFunction=!0;let i=Ql(e);if(!i)return super.visitFunc(e);let n=((t=i.fallback)!=null?t:eb(i.type)).visit(this);return!this.element||!this.element.hasAttribute(i.attributeName)?n:tb(this.scope,this.element.getAttribute(i.attributeName),i.type)||n}};function _o(e,t){if(It(e)){if(e instanceof K)return e.stringValue();if(e instanceof j&&t){let i=e.expr.evaluate(t);return typeof i=="string"?i:typeof i=="number"?String(i):""}if(e instanceof J)return e.values.map(i=>_o(i,t)).join("")}return""}function sh(e){if(e instanceof j){let t=e.expr;return t instanceof we&&/^page-counters?-/.test(t.str)}return e instanceof J||e instanceof _e?e.values.some(t=>sh(t)):!1}function ll(e,t){return sh(e)?e instanceof J?new J(e.values.map(i=>ll(i,t))):e instanceof _e?new _e(e.values.map(i=>ll(i,t))):e:new K(_o(e,t))}var Do=class extends nn{constructor(e,t,i,n){super(),u(this,"cascade",e),u(this,"element",t),u(this,"counterResolver",i),u(this,"pseudoName",n)}getCounterStore(){var e,t;return(t=(e=this.cascade.context)==null?void 0:e.counterStore)!=null?t:null}getPageScope(){var e,t;return(t=(e=this.cascade.context)==null?void 0:e.style)==null?void 0:t.pageScope}hasLocalCounterResetOrSet(e){return this.hasLocalCounter(e,"counter-reset",{reset:!0})||this.hasLocalCounter(e,"counter-set",{defaultValue:0})}hasLocalCounterIncrement(e){return this.hasLocalCounter(e,"counter-increment",{})}hasLocalCounter(e,t,i){let n=this.cascade.currentStyle,o=n?.[t];if(!o)return!1;let r=o.evaluate(this.cascade.context);if(!r||Z(r))return!1;let s=qi(r,i);return Object.prototype.hasOwnProperty.call(s,e)}evaluateAndGetString(e){if(!e)return"";let t=this.cascade.quoteDepth,i=e.visit(this),n=_o(i,this.cascade.context);return this.cascade.quoteDepth=t,n}visitIdent(e){let t=this.cascade,i=t.quotes,n=Math.floor(i.length/2)-1;switch(e.name){case"open-quote":{let o=i[2*Math.min(n,t.quoteDepth)];return t.quoteDepth++,o}case"close-quote":return t.quoteDepth>0&&t.quoteDepth--,i[2*Math.min(n,t.quoteDepth)+1];case"no-open-quote":return t.quoteDepth++,new K("");case"no-close-quote":return t.quoteDepth>0&&t.quoteDepth--,new K("")}return e}format(e,t){return this.cascade.counterStyleStore.format(t,e)}formatCounterList(e,t,i){if(!e.length)return this.format(0,i);let n=new gi;for(let o=0;o<e.length;o++)o>0&&n.append(t),n.append(this.format(e[o],i));return n.toString()}formatLastValue(e,t){let i=e.length?e[e.length-1]:0;return this.format(i,t)}buildCounterText(e,t,i,n,o,r=!1,s=!1){var a,h,l,c,d,p,f,g,v;let w=typeof o=="string",x=A=>w?this.formatCounterList(A,o,i):this.formatLastValue(A,i),m=A=>{this.pseudoName==="footnote-call"&&this.element&&of(this.element,t,A)},S=(A,z)=>A.length===z.length&&A.every((U,X)=>U===z[X]);if(this.pseudoName==="footnote-call"&&this.element){let A=Cb(this.element,t);if(A)return x(A)}if(this.pseudoName==="footnote-marker"&&this.element){let A=bs(this.element)[t];if(A)return x(A)}let b;if(t==="pages")return x([]);if(!this.element){if(r&&n.length)return b=n,m(b),x(b);if((a=e.isPageControlledCounter)!=null&&a.call(e,t)&&s&&n.length){let A=((h=e.currentPageCounters)==null?void 0:h[t])||[];return b=[(A.length?A[A.length-1]:0)+n[n.length-1]],m(b),x(b)}if(!((l=e.isPageControlledCounter)!=null&&l.call(e,t))){let A=((c=e.currentPageCounters)==null?void 0:c[t])||[];if(A.length)return b=A,m(b),x(b)}}let C=((d=e.currentPageDocCounters)==null?void 0:d[t])||[],P=!this.element&&n.length&&!S(n,C),L=this.element||P?n:C.length?C:n;if((p=e.isPageControlledCounter)!=null&&p.call(e,t)){let A=((f=e.currentPageDocCounters)==null?void 0:f[t])||[],z=((g=e.currentPageCounters)==null?void 0:g[t])||[],U=z.length?z[z.length-1]:0,X=A.length?A[0]:0,oe=L.length?L[0]:0,k=U+(oe-X);return b=L.length?[k,...L.slice(1)]:z.length?z:[0],m(b),x(b)}return L.length?(b=L,m(b),x(b)):(b=((v=e.currentPageCounters)==null?void 0:v[t])||[],m(b),x(b))}visitFuncCounter(e){var t;let i=e[0].toString(),n=e.length>1?e[1].stringValue():"decimal",o=(this.cascade.counters[i]||[]).slice(),r=!this.element&&this.hasLocalCounterResetOrSet(i),s=!this.element&&this.hasLocalCounterIncrement(i),a=this.getCounterStore();if(a){let l=i==="pages"||((t=a?.isPageControlledCounter)==null?void 0:t.call(a,i)),c=this.getPageScope(),d=new we(c,()=>this.buildCounterText(a,i,n,o,void 0,r,s),l?`page-counter-${i}`:`counter-${i}`);if(l&&a!=null&&a.registerPageCounterExpr){let p=f=>this.formatLastValue(f,n);a.registerPageCounterExpr(i,p,d)}return new j(d)}let h=this.cascade.counters[i];if(h&&h.length){let l=h&&h.length&&h[h.length-1]||0;return new K(this.format(l,n))}else{let l=new j(this.counterResolver.getPageCounterVal(i,c=>this.format(c||0,n)));return new J([l])}}visitFuncCounters(e){var t;let i=e[0].toString(),n=e[1].stringValue(),o=e.length>2?e[2].stringValue():"decimal",r=(this.cascade.counters[i]||[]).slice(),s=!this.element&&this.hasLocalCounterResetOrSet(i),a=!this.element&&this.hasLocalCounterIncrement(i),h=this.getCounterStore();if(h){let p=i==="pages"||((t=h?.isPageControlledCounter)==null?void 0:t.call(h,i)),f=this.getPageScope(),g=new we(f,()=>this.buildCounterText(h,i,o,r,n,s,a),p?`page-counters-${i}`:`counters-${i}`);return p&&h!=null&&h.registerPageCounterExpr&&h.registerPageCounterExpr(i,v=>this.formatCounterList(v,n,o),g),new j(g)}let l=this.cascade.counters[i],c=new gi;if(l&&l.length)for(let p=0;p<l.length;p++)p>0&&c.append(n),c.append(this.format(l[p],o));let d=new j(this.counterResolver.getPageCountersVal(i,p=>{let f=[];if(p.length)for(let v=0;v<p.length;v++)f.push(this.format(p[v],o));let g=c.toString();return g.length&&f.push(g),f.length?f.join(n):this.format(0,o)}));return new J([d])}visitFuncTargetCounter(e){let t=e[0],i;t instanceof Qe?i=t.url:i=t.stringValue();let n=e[1].toString(),o=e.length>2?e[2].stringValue():"decimal",r=new j(this.counterResolver.getTargetCounterVal(i,n,s=>this.format(s||0,o)));return new J([r])}visitFuncTargetCounters(e){let t=e[0],i;t instanceof Qe?i=t.url:i=t.stringValue();let n=e[1].toString(),o=e[2].stringValue(),r=e.length>3?e[3].stringValue():"decimal",s=new j(this.counterResolver.getTargetCountersVal(i,n,a=>{let h=a.map(l=>this.format(l,r));return h.length?h.join(o):this.format(0,r)}));return new J([s])}visitFuncTargetText(e){let t=e[0],i;t instanceof Qe?i=t.url:i=t.stringValue();let n=e.length>1?e[1].stringValue():"content",o=new j(this.counterResolver.getTargetTextVal(i,n));return new J([o])}visitFuncString(e){let t=e.length>0?e[0].stringValue():"",i=e.length>1?e[1].stringValue():"first";return new j(this.counterResolver.getNamedStringVal(t,i))}visitFuncElement(e){let t=e.length>0?e[0].stringValue():"",i=e.length>1?e[1].stringValue():"first";return new j(this.counterResolver.getRunningElementVal(t,i))}visitFuncContent(e){var t,i,n,o,r,s,a,h;let l=e.length>0?e[0].stringValue():"text",c="";switch(l){case"text":c=this.element.textContent;break;case"before":case"after":case"marker":{let d=(t=this.element)==null?void 0:t.querySelectorAll(`[data-adapt-pseudo="${l}"]`),p=null;if(d&&this.element)for(let f=0;f<d.length;f++){let g=d[f];if(g.parentElement===this.element){p=g;break}}if(p)c=p.textContent||"";else{let f=ft(this.cascade.currentStyle,"_pseudos"),g=(n=(i=f?.[l])==null?void 0:i.content)==null?void 0:n.value;if(g)c=this.evaluateAndGetString(g);else if(l==="marker"){let v=(o=this.cascade.currentStyle["--viv-marker-content"])==null?void 0:o.value;c=_o(v,this.cascade.context)}}}break;case"first-letter":{let d=ft(this.cascade.currentStyle,"_pseudos"),p=(s=(r=d?.before)==null?void 0:r.content)==null?void 0:s.value,f=(h=(a=d?.after)==null?void 0:a.content)==null?void 0:h.value,g=(this.evaluateAndGetString(p)||this.element.textContent||this.evaluateAndGetString(f)).match(Jr);c=g?g[0]:""}break}return new K(c)}visitFuncLeader(e){let t="";if(e[0]instanceof he)switch(e[0].stringValue()){case"dotted":t=".";break;case"solid":t="_";break;case"space":t=" ";break}else e[0]instanceof K&&(t=e[0].stringValue());return t.length==0?new K(""):new j(new we(null,()=>t,"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}};function pa(e,t,i){let n;if(e.nodeType===1)n=Array.from(e.getClientRects());else{let o=e.ownerDocument.createRange();o.selectNodeContents(e),n=t.getRangeClientRects(o)}return n.reduce((o,r)=>o+(i==="vertical-rl"||i==="vertical-lr"?r.height:r.width),0)}var t0=(e,t,i)=>{let n=t.filter(h=>h.after&&h.viewNode.nodeType===1&&h.viewNode.getAttribute("data-viv-leader"));for(let h of n){let l=function(E){S==="rtl"?g.textContent=(E.startsWith("\u200F")?"":"\u200F")+E+(E.endsWith("\u200F")?"":"\u200F"):g.textContent=E},c=function(){let E=i.clientLayout.getElementClientRect(v);return m==="vertical-rl"||m==="vertical-lr"?S==="rtl"?E.top-=k:E.bottom+=k:S==="rtl"?E.left-=k:E.right+=k,L.left>E.left||L.right<E.right||L.top>E.top||L.bottom<E.bottom},d=function(){let E,N,R=x.repeat(1e4);if(l(R),c())E=1,N=1e4;else return;for(let $=0;$<16;$++){let V="",q=Math.floor((E+N)/2);for(let Q=0;Q<q;Q++)V+=x;if(l(V),c())N=q;else{if(E==q)return;E=q}}l(x)},p=function(E){let N=0,R=v.parentElement;for(;R&&R!==f.viewNode;)N+=i.getComputedInsets(R)[E],R=R.parentElement;return N};var o=l,r=c,s=d,a=p;let f=h.parent;for(;f&&f.inline;)f=f.parent;let g=h.viewNode,v=g.parentElement,w=v.getAttribute("data-adapt-pseudo"),x=g.getAttribute("data-viv-leader-value"),{writingMode:m,direction:S,marginInlineEnd:b}=i.clientLayout.getElementComputedStyle(v);g.style.marginInlineStart="1px",l(x),v.style.display="inline-block",v.style.textIndent="0";let C=tr(f.viewNode),P=C?.style.columnFill||null;C&&(C.style.columnFill="auto");let L=i.clientLayout.getElementClientRect(f.viewNode),A=i.clientLayout.getElementClientRect(v),z=i.parseComputedLength(b),U=[],X=v.parentElement;for(;X.parentElement&&X.parentElement!==f.viewNode;)X=X.parentElement;let oe=X.nextSibling;for(;oe;){if(oe.nodeType===1){let E=oe,{display:N,float:R,position:$}=i.clientLayout.getElementComputedStyle(E);if(R!=="none"||$==="absolute"||$==="fixed"){oe=oe.nextSibling;continue}if(Ut(N))U.push(E);else if(uv(N))break}else if(oe.nodeType===3){let E=oe;E.length>0&&U.push(E)}oe=oe.nextSibling}let k=U.reduce((E,N)=>E+pa(N,i.clientLayout,m),0);if(w!=="after"){let E=pa(X,i.clientLayout,m),N=pa(v,i.clientLayout,m);k+=E-N}m==="vertical-rl"||m==="vertical-lr"?(S==="rtl"?L.top+=z:L.bottom-=z,L.top=Math.min(A.top,L.top),L.bottom=Math.max(A.bottom,L.bottom)):(S==="rtl"?L.left+=z:L.right-=z,L.left=Math.min(A.left,L.left),L.right=Math.max(A.right,L.right)),d();let _=i.clientLayout.getElementClientRect(v);S=="rtl"?v.style.float="left":v.style.float="right";let F=i.clientLayout.getElementClientRect(v),D=0;S=="rtl"?m=="vertical-rl"||m=="vertical-lr"?D=_.top-F.top-p("top"):D=_.left-F.left-p("left"):m=="vertical-rl"||m=="vertical-lr"?D=F.bottom-_.bottom-p("bottom"):D=F.right-_.right-p("right"),D-=k,D=Math.max(0,D-.1),v.style.float="",g.style.marginInlineStart=`${D}px`,C&&(P?C.style.columnFill=P:C.style.removeProperty("column-fill"))}};Ft("POST_LAYOUT_BLOCK",t0);var ah=1/1048576;function cn(e,t){for(let i in e)t[i]=e[i].clone()}var i0=class yf{constructor(){u(this,"nsCount",0),u(this,"nsPrefix",{}),u(this,"tags",{}),u(this,"nstags",{}),u(this,"epubtypes",{}),u(this,"classes",{}),u(this,"ids",{}),u(this,"pagetypes",{}),u(this,"order",0)}clone(){let t=new yf;t.nsCount=this.nsCount;for(let i in this.nsPrefix)t.nsPrefix[i]=this.nsPrefix[i];return cn(this.tags,t.tags),cn(this.nstags,t.nstags),cn(this.epubtypes,t.epubtypes),cn(this.classes,t.classes),cn(this.ids,t.ids),cn(this.pagetypes,t.pagetypes),t.order=this.order,t}insertInTable(t,i,n){let o=t[i];o&&(n=o.mergeWith(n)),t[i]=n}createInstance(t,i,n,o,r,s){return new n0(this,t,i,n,o,r,s)}nextOrder(){return this.order+=ah}},vf=class wf{constructor(t,i,n,o,r,s,a){u(this,"context",i),u(this,"counterListener",n),u(this,"counterResolver",o),u(this,"counterStyleStore",s),u(this,"cmykStore",a),u(this,"code"),u(this,"stack",[[],[]]),u(this,"conditions",Object.create(null)),u(this,"currentElement",null),u(this,"currentElementOffset",null),u(this,"currentStyle",null),u(this,"currentClassNames",null),u(this,"currentLocalName",""),u(this,"currentNamespace",""),u(this,"currentId",""),u(this,"currentXmlId",""),u(this,"currentNSTag",""),u(this,"currentEpubTypes",null),u(this,"currentPageType",null),u(this,"previousPageType",null),u(this,"firstPageType",null),u(this,"pageTypePageIndices",Object.create(null)),u(this,"isFirst",!0),u(this,"isRoot",!0),u(this,"counters",Object.create(null)),u(this,"lastCounterChanges",[]),u(this,"lastCounterChangeTypes",Object.create(null)),u(this,"counterScoping",[Object.create(null)]),u(this,"quotes"),u(this,"quoteDepth",0),u(this,"lang",""),u(this,"siblingOrderStack",[0]),u(this,"currentSiblingOrder",0),u(this,"siblingTypeCountsStack",[{}]),u(this,"currentSiblingTypeCounts"),u(this,"currentFollowingSiblingOrder",null),u(this,"followingSiblingOrderStack"),u(this,"followingSiblingTypeCountsStack",[{}]),u(this,"currentFollowingSiblingTypeCounts"),u(this,"viewConditions",Object.create(null)),u(this,"dependentConditions",[]),u(this,"elementStack"),this.code=t,this.quotes=[new K("\u201C"),new K("\u201D"),new K("\u2018"),new K("\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,i){this.conditions[t]=(this.conditions[t]||0)+1,i&&(this.viewConditions[t]?this.viewConditions[t].push(i):this.viewConditions[t]=[i])}decrement(t,i){this.conditions[t]--,this.viewConditions[t]&&(this.viewConditions[t]=this.viewConditions[t].filter(n=>n!==i),this.viewConditions[t].length===0&&delete this.viewConditions[t])}buildViewConditionMatcher(t){let i=null;t&&(this.currentElementOffset,i=Pr.buildViewConditionMatcher(this.currentElementOffset,t));let n=this.dependentConditions.map(o=>{let r=this.viewConditions[o];return r&&r.length>0?r.length===1?r[0]:Pr.buildAnyMatcher([].concat(r)):null}).filter(o=>o);return n.length<=0?i:i===null?n.length===1?n[0]:Pr.buildAllMatcher(n):Pr.buildAllMatcher([i].concat(n))}applyAction(t,i){let n=t[i];n&&n.apply(this)}pushRule(t,i,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=fa,this.currentPageType=i,this.applyActions()}defineCounter(t,i){let n=this.counterScoping[this.counterScoping.length-1];n||(n=Object.create(null),this.counterScoping[this.counterScoping.length-1]=n),this.counters[t]?(n[t]&&this.counters[t].pop(),this.counters[t].push(i)):this.counters[t]=[i],n[t]=!0}pushCounters(t){var i,n,o,r,s,a,h,l,c,d;let p=new Set,f=Object.create(null),g=y.inline,v=t.display;if(v&&(g=v.evaluate(this.context)),g===y.none){(i=this.currentElement)==null||i.setAttribute("data-viv-display-none","true"),this.lastCounterChanges=[],this.lastCounterChangeTypes=Object.create(null),this.counterScoping.push(null);return}else if((n=this.currentElement)!=null&&n.closest("[data-viv-display-none]")){this.lastCounterChanges=[],this.lastCounterChangeTypes=Object.create(null),this.counterScoping.push(null);return}let w=y.inline,x=t.float;x&&(w=x.evaluate(this.context));let m=null,S=null,b=null,C=t["counter-reset"];if(C){let A=C.evaluate(this.context);A&&(m=qi(A,{reset:!0}))}let P=t["counter-set"];if(P){let A=P.evaluate(this.context);A&&(b=qi(A,{defaultValue:0}))}let L=t["counter-increment"];if(L){let A=L.evaluate(this.context);A&&(S=qi(A))}if((this.currentLocalName=="ol"||this.currentLocalName=="ul")&&this.currentNamespace=="http://www.w3.org/1999/xhtml"&&(m||(m=Object.create(null)),m["list-item"]=((r=(o=this.currentElement)==null?void 0:o.start)!=null?r:1)-1),uo(g)&&(S||(S=Object.create(null)),S["list-item"]=(s=S["list-item"])!=null?s:1,/^\s*[-+]?\d/.test((h=(a=this.currentElement)==null?void 0:a.getAttribute("value"))!=null?h:"")&&(b||(b=Object.create(null)),b["list-item"]=this.currentElement.value)),((c=(l=this.currentElement)==null?void 0:l.parentNode)==null?void 0:c.nodeType)===Node.DOCUMENT_NODE&&(m||(m=Object.create(null)),m.footnote===void 0&&(m.footnote=0)),w===y.footnote&&!this.currentStyle["--viv-semantic-footnote-content"]&&(S||(S=Object.create(null)),S.footnote===void 0)){let A=(d=this.currentStyle["counter-increment"])==null?void 0:d.value;(!A||!(A===y.footnote||A instanceof J&&A.values.includes(y.footnote)))&&(S.footnote=1)}if(m)for(let A in m)p.add(A),f[A]="reset";if(S)for(let A in S)p.add(A),f[A]||(f[A]="increment");if(b)for(let A in b)p.add(A),f[A]="set";if(this.lastCounterChanges=Array.from(p),this.lastCounterChangeTypes=f,m)for(let A in m)this.defineCounter(A,m[A]);if(S)for(let A in S){this.counters[A]||this.defineCounter(A,0);let z=this.counters[A];z[z.length-1]+=S[A]}if(b)for(let A in b)if(!this.counters[A])this.defineCounter(A,b[A]);else{let z=this.counters[A];z[z.length-1]=b[A]}if(uo(g)){let A=this.counters["list-item"],z=A[A.length-1];t["ua-list-item-count"]=new W(new At(z),0);let U=si(t,"_pseudos");U.marker||(U.marker={})}this.counterScoping.push(null)}popCounters(){let t=this.counterScoping.pop();if(t)for(let i in t){let n=this.counters[i];n&&(n.length==1?delete this.counters[i]:n.pop())}}setNamedStrings(t){let i=t["string-set"];if(!i)return;i=i.filterValue(new Do(this,this.currentElement,this.counterResolver));let n=i.value instanceof _e?i.value.values:[i.value];for(let o of n)if(o instanceof J){let r=o.values[0].stringValue(),s=o.values.slice(1);if(s.some(a=>sh(a)))this.counterResolver.setNamedString(r,ll(new J(s),this.context),this.currentElementOffset);else{let a=s.map(h=>_o(h,this.context)).join("");this.counterResolver.setNamedString(r,a,this.currentElementOffset)}}delete t["string-set"]}setRunningElement(t){let i=t.position;if(i?.value instanceof ai&&i.value.name==="running"){let n=i.value.values[0].stringValue();this.counterResolver.setRunningElement(n,this.currentElementOffset)}}processPseudoelementProps(t,i,n){this.pushCounters(t);let o=t.content;o&&(t.content=o.filterValue(new Do(this,i,this.counterResolver,n))),this.popCounters()}pushElement(t,i,n,o){var r,s,a;let h=this.currentPageType;this.currentPageType=null,this.currentElement=i,this.currentElementOffset=o,this.currentStyle=n,this.currentNamespace=i.namespaceURI,this.currentLocalName=i.localName;let l=this.code.nsPrefix[this.currentNamespace];l?this.currentNSTag=l+this.currentLocalName:this.currentNSTag="",this.currentId=i.getAttribute("id"),this.currentXmlId=i.getAttributeNS("http://www.w3.org/XML/1998/namespace","id");let c=i.getAttribute("class");c?this.currentClassNames=c.split(/\s+/):this.currentClassNames=fa;let d=i.getAttributeNS("http://www.idpf.org/2007/ops","type");d?this.currentEpubTypes=d.split(/\s+/):this.currentEpubTypes=fa;let p=Sa(i);p&&(this.stack[this.stack.length-1].push(new Jb(this.lang)),this.lang=p.toLowerCase());let f=this.isRoot,g=this.siblingOrderStack;this.currentSiblingOrder=++g[g.length-1],g.push(0);let v=this.siblingTypeCountsStack,w=this.currentSiblingTypeCounts=v[v.length-1],x=w[this.currentNamespace];x||(x=w[this.currentNamespace]={}),x[this.currentLocalName]=(x[this.currentLocalName]||0)+1,v.push({});let m=this.followingSiblingOrderStack;m[m.length-1]!==null?this.currentFollowingSiblingOrder=--m[m.length-1]:this.currentFollowingSiblingOrder=null,m.push(null);let S=this.followingSiblingTypeCountsStack,b=this.currentFollowingSiblingTypeCounts=S[S.length-1];b&&b[this.currentNamespace]&&b[this.currentNamespace][this.currentLocalName]--,S.push({}),this.applyActions(),this.currentPageType=h,this.applyVarFilter([this.currentStyle],t,i),this.applyCalcFilter(this.currentStyle,this.context),this.applyCmykFilter(this.currentStyle,this.currentElement),this.applyAttrFilter(i,t);let C=n.quotes,P=null;if(C){let z=C.evaluate(this.context);z&&(P=new Qb(this.quotes),z===y.none?this.quotes=[new K(""),new K("")]:z===y.auto||z===y.initial?this.quotes=[new K("\u201C"),new K("\u201D"),new K("\u2018"),new K("\u2019")]:z instanceof J&&(this.quotes=z.values))}this.pushCounters(this.currentStyle);let L=this.currentId||this.currentXmlId||i.getAttribute("name")||"";if(f||L){let z=Object.create(null);Object.keys(this.counters).forEach(U=>{z[U]=Array.from(this.counters[U])}),this.counterListener.countersOfId(L,z)}let A=ft(this.currentStyle,"_pseudos");if(A){let z=!0;for(let U of o0){U||(z=!1);let X=A[U];if(X){let oe=(r=ve(this.currentStyle,"float"))==null?void 0:r.value,k=i instanceof Element&&Gt(i),_=i instanceof Element&&Pt(i),F=!!ve(this.currentStyle,"--viv-semantic-footnote-content"),D=oe===y.footnote,E=(U==="before"||U==="after")&&(D||_||F)&&!!X.content,N=kb(X),R=U==="footnote-call"&&k&&N,$=U==="footnote-marker"&&(_||F)&&N;if((U==="before"||U==="after")&&!(E||It((s=X.content)==null?void 0:s.value)||this.hasNonTrivialViewConditionalPseudoContent(X))||U==="marker"&&!uo((a=ve(this.currentStyle,"display"))==null?void 0:a.value)||(U==="footnote-call"||U==="footnote-marker")&&oe!==y.footnote&&!R&&!$||(U==="footnote-call"||U==="footnote-marker")&&F&&!N)delete A[U];else if(z){if(this.processPseudoelementProps(X,i,U),U==="marker")this.processMarkerPseudoelementProps(X,i,t),delete A[U];else if(U==="footnote-marker"){if(this.resolvePseudoelementInheritedPropertyValue(X,"list-style-position",t,i)===y.outside){this.processMarkerPseudoelementProps(X,i,t);let V=X.content;V&&(this.currentStyle["_footnote-marker-content"]=V),this.currentStyle.display=new W(B("list-item"),0),this.currentStyle["list-style-position"]=new W(y.outside,0),this.currentStyle["list-style-type"]=new W(y.none,0),this.currentStyle["list-style-image"]=new W(y.none,0),delete A[U]}}else if(U==="first-letter"&&X["initial-letter"]){let V=X["initial-letter"].evaluate(this.context);V!==y.normal&&!Z(V)&&(this.currentStyle["--viv-initialLetter"]=new W(V,0)),delete X["initial-letter"]}}else this.stack[this.stack.length-2].push(new Kb(X,i))}}}this.setNamedStrings(this.currentStyle),this.setRunningElement(this.currentStyle),P&&this.stack[this.stack.length-2].push(P)}hasNonTrivialViewConditionalPseudoContent(t){let i=t._viewConditionalStyles;return!i||i.length<=0?!1:i.some(n=>{var o;return It((o=n.styles.content)==null?void 0:o.value)})}processMarkerPseudoelementProps(t,i,n){var o,r,s,a,h;let l=uo((o=this.currentStyle.display)==null?void 0:o.value);if(!It((r=t.content)==null?void 0:r.value)&&l){let d=this.getInheritedPropertyValue("list-style-type",n,i),p=this.getInheritedPropertyValue("list-style-image",n,i);if(p instanceof Qe)t.content=new W(new J([p,new K(" ")]),0);else if(d instanceof K)t.content=new W(d,0);else if(d instanceof he&&d!==y.none){let f=(a=(s=this.currentStyle["ua-list-item-count"])==null?void 0:s.value)==null?void 0:a.num;if(f!=null){let g=d.name.toLowerCase();g==="disc"||g==="circle"||g==="square"||g==="disclosure-open"||g==="disclosure-closed"||(t.content=new W(new K(this.counterStyleStore.formatMarker(d.name,f)),0))}}}let c=t.content;if(c){let d=c.value;if(It(d)){let p=this.resolveMarkerContentVal(d);this.currentStyle["--viv-marker-content"]=new W(p,0)}}for(let d of wf.markerAllowedProps){let p=t[d];if(p){let f=p.evaluate(this.context,d);f&&!Z(f)&&(this.currentStyle[`--viv-marker-${d}`]=new W(f,0))}}if(!Ut((h=ve(this.currentStyle,"display"))==null?void 0:h.value)){let d=this.getInheritedPropertyValue("list-style-position",n,i);d&&d!==y.outside&&!Z(d)&&(this.currentStyle["list-style-position"]=new W(d,0))}}resolveMarkerContentVal(t){if(t instanceof j){let i=t.expr.evaluate(this.context);return typeof i=="string"?new K(i):typeof i=="number"?new K(String(i)):t}if(t instanceof J){let i=t.values.map(n=>this.resolveMarkerContentVal(n));return new J(i)}return t}getInheritedPropertyValue(t,i,n){var o;for(let s=n;s;s=s.parentElement){let a=(s===this.currentElement?this.currentStyle:i.getStyle(s,!1))[t];if(a){let h=a.evaluate(this.context,t);if(h===y.inherit||h===y.unset||h===y.revert)continue;if(h===y.initial)break;return h}}let r=i.validatorSet;return(o=r?.defaultValues[t])!=null?o:null}resolvePseudoelementInheritedPropertyValue(t,i,n,o){var r;let s=t[i];if(s){let a=s.evaluate(this.context,i);if(a!==y.inherit&&a!==y.unset&&a!==y.revert){if(a===y.initial){let h=n.validatorSet;return(r=h?.defaultValues[i])!=null?r:null}return a}}return this.getInheritedPropertyValue(i,n,o)}applyAttrFilterInner(t,i,n){let o=t.scope,r=t.validatorSet;for(let s in n)if(Xi(s)&&!Xe(s)){let a=n[s],h=new e0(i,o,s,r),l=a.filterValue(h);if(!h.hadAttrFunction){n[s]=l;continue}let c=h.validatePropertyValue(l.value);n[s]=c===l.value?l:new W(c,l.priority)}}applyAttrFilter(t,i){let n=this.currentStyle,o=ft(n,"_pseudos");for(let r in o)this.applyAttrFilterInner(i,t,o[r]);this.applyAttrFilterInner(i,t,n)}applyVarFilter(t,i,n){let o=t[0],r=t.map(d=>({...d})),s=32,a={},h=ft(o,"_pseudos"),l=Object.keys(o).filter(Xi),c=d=>{var p,f,g;let v=ve(o,d),w=v.value,x=Xe(d)?r:t,m=new f0(x,i,n,Xe(d)?d:null);Xe(d)&&m.getFallbackCycleMembers(w,x,n)&&(w=y.initial);for(let S=0;;S++){if(S>=s){w=Xe(d)?y.initial:Be;break}let b=w.visit(m);if(m.error){w=Xe(d)?y.initial:Be,m.error=!1;break}if(b===w)break;w=b}if(w!==v.value){let S=i.validatorSet,b=(p=S?.getShorthand(d,w))==null?void 0:p.clone();if(b)if(Z(w)){for(let C of b.propList){let P=new W(w,v.priority),L=ve(o,C);Fi(a,C,nl(this.context,L,P))}delete o[d]}else{let C=Ri(i.scope,new xt(w.toString(),null),"");if(C&&(C.visit(b),!b.error)){for(let P of b.propList){let L=new W((g=(f=b.values[P])!=null?f:S.defaultValues[P])!=null?g:y.initial,v.priority),A=ve(o,P);Fi(a,P,nl(this.context,A,L))}delete o[d]}}else o[d]=new W(w,v.priority)}if(a[d]){let S=ve(o,d);S&&S.value!==Be&&Jt(a,d,S,this.context)}};for(let d in o)if(Xr(d)){if(d==="_pseudos")continue;let p=ft(o,d);for(let f in p)this.applyVarFilter([p[f],...t],i,n)}for(let d of l)Xe(d)&&c(d);for(let d of l)Xe(d)||c(d);if(h)for(let d in h)this.applyVarFilter([h[d],...t],i,n);for(let d in a)o[d]=a[d]}applyCalcFilter(t,i){let n=new Tf(i);for(let o in t)if(Xr(o)){let r=ft(t,o);for(let s in r)this.applyCalcFilter(r[s],i)}else if(Xi(o)&&!Xe(o)){let r=ve(t,o),s=r.value.visit(n);s!==r.value&&(t[o]=new W(s,r.priority))}}applyCmykFilter(t,i){let n=new td(this.cmykStore);if(this.applyCmykFilterInternal(t,n,""),i){let o=n.getConversions();o&&i.setAttribute("data-viv-device-cmyk",JSON.stringify(o))}}applyCmykFilterInternal(t,i,n){for(let o in t)if(Xr(o)){let r=ft(t,o);for(let s in r)this.applyCmykFilterInternal(r[s],i,`::${s}:`)}else if(Xi(o)&&!Xe(o)){let r=ve(t,o),s=r.value.toString();i.reset();let a=r.value.visit(i);a!==r.value&&(i.hadDeviceCmyk()&&i.recordConversion(n+o,s),t[o]=new W(a,r.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 i=1;i>=-1;--i){let n=this.stack[this.stack.length-i-2];for(t=0;t<n.length;)n[t].push(this,i)?n.splice(t,1):t++}this.isFirst=!0,this.isRoot=!1}pop(){for(let t=1;t>=-1;--t){let i=this.stack[this.stack.length-t-2],n=0;for(;n<i.length;)i[n].pop(this,t)?i.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()}};u(vf,"markerAllowedProps",["color","font-family","font-size","font-style","font-weight","font-variant","hyphens","line-height","tab-size","text-combine-upright","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-orientation","text-shadow","text-transform","unicode-bidi","direction","white-space"]);var n0=vf,fa=[],o0=["before","footnote-call","footnote-marker","marker","inner","first-letter","first-line","","after"],hl=null;function r0(e){hl=e}var zo=class extends rn{constructor(e,t,i,n,o,r,s){super(e,t,s),u(this,"condition",i),u(this,"regionId",o),u(this,"validatorSet",r),u(this,"chain",null),u(this,"specificity",0),u(this,"elementStyle",null),u(this,"conditionCount",0),u(this,"pseudoelement",null),u(this,"selectorFunctionContainsPseudoelement",!1),u(this,"footnoteContent",!1),u(this,"cascade"),u(this,"state"),u(this,"viewConditionId",null),u(this,"insideSelectorRule"),u(this,"invalid",!1),this.cascade=n?n.cascade:hl?hl.clone():new i0,this.state=0}insertNonPrimary(e){this.cascade.insertInTable(this.cascade.tags,"*",e)}processChain(e){let t=ih(this.chain,e);t!==e&&t.makePrimary(this.cascade)||this.insertNonPrimary(t)}invalidContinuationAfterPseudoelement(e){return this.pseudoelement?(this.invalidSelector(`::${this.pseudoelement} followed by ${e}`),!0):this.selectorFunctionContainsPseudoelement?(this.invalidSelector(`Selector containing pseudo-element followed by ${e}`),!0):!1}isInsideSelectorRule(e){return this.state!=0?(this.reportAndSkip(e),!0):!1}tagSelector(e,t){!t&&!e||this.invalidContinuationAfterPseudoelement(t||"*")||(t&&(this.specificity+=1),t&&e?this.chain.push(new Fb(e,t.toLowerCase())):t?this.chain.push(new Eu(t.toLowerCase())):this.chain.push(new Lb(e)))}invalidSelector(e){Y.warn(e),this.chain.push(new ot("")),this.setInvalid()}setInvalid(){this.invalid=!0;for(let e=this;e instanceof Hn;e=e.parent)e.parent.invalid=!0}classSelector(e){this.invalidContinuationAfterPseudoelement(`.${e}`)||(this.specificity+=256,this.chain.push(new Ab(e)))}pseudoclassSelector(e,t){if(!this.invalidContinuationAfterPseudoelement(`:${e}`)){switch(e.toLowerCase()){case"enabled":this.chain.push(new Ub);break;case"disabled":this.chain.push(new $b);break;case"checked":this.chain.push(new Hb);break;case"root":case"scope":this.chain.push(new Db);break;case"link":this.chain.push(new Eu("a")),this.chain.push(new Pu("","href"));break;case"href-epub-type":case"href-role-type":if(t&&t.length>=1&&typeof t[0]=="string"){let i=t[0],n=new RegExp(`(^|\\s)${es(i)}($|\\s)`),o=t[1];this.chain.push(new Rb(n,o,e==="href-role-type"))}else this.chain.push(new ot(""));break;case"footnote-content":this.footnoteContent=!0;break;case"visited":case"active":case"hover":case"focus":this.chain.push(new ot(""));break;case"lang":if(t&&t.length==1&&typeof t[0]=="string"){let i=t[0];this.chain.push(new _b(new RegExp(`^${es(i.toLowerCase())}($|-)`)))}else this.chain.push(new ot(""));break;case"nth-child":case"nth-last-child":case"nth-of-type":case"nth-last-of-type":{let i=s0[e.toLowerCase()];t&&t.length==2?this.chain.push(new i(t[0],t[1])):this.chain.push(new ot(""));break}case"first-child":this.chain.push(new Nu);break;case"last-child":this.chain.push(new sl(0,1));break;case"first-of-type":this.chain.push(new rl(0,1));break;case"last-of-type":this.chain.push(new al(0,1));break;case"only-child":this.chain.push(new Nu),this.chain.push(new sl(0,1));break;case"only-of-type":this.chain.push(new rl(0,1)),this.chain.push(new al(0,1));break;case"empty":this.chain.push(new Vb);break;case"before":case"after":case"first-line":case"first-letter":this.pseudoelementSelector(e,t);return;default:this.invalidSelector(`Unknown pseudo-class :${e}`);return}this.specificity+=256}}pseudoelementSelector(e,t){if(!this.invalidContinuationAfterPseudoelement(`::${e}`)){switch(e){case"before":case"after":case"first-line":case"first-letter":case"footnote-call":case"footnote-marker":case"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(t&&t.length==1&&typeof t[0]=="number"){let i=Math.round(t[0]);if(i>0&&i==t[0]){if(!this.pseudoelement)this.pseudoelement=`first-${i}-lines`;else{this.invalidSelector(`Double pseudo-element ::${this.pseudoelement}::${e}`);return}break}}this.chain.push(new ot(""));break;case"nth-fragment":t&&t.length==2?this.viewConditionId=`NFS_${t[0]}_${t[1]}`:this.chain.push(new ot(""));break;default:this.invalidSelector(`Unknown pseudo-element ::${e}`);return}this.specificity+=1}}idSelector(e){this.invalidContinuationAfterPseudoelement(`#${e}`)||(this.specificity+=65536,this.chain.push(new Ib(e)))}attributeSelector(e,t,i,n,o){if(this.invalidContinuationAfterPseudoelement(`[${t}]`))return;this.specificity+=256,n=n||"";let r;switch(i){case 0:r=new Pu(e,t);break;case 39:r=new Bb(e,t,n,o??null);break;case 45:!n||n.match(/\s/)?r=new ot(""):r=new ao(e,t,so(`(^|\\s)${ro(n,o??null)}($|\\s)`),o??null);break;case 44:r=new ao(e,t,so(`^${ro(n,o??null)}($|-)`),o??null);break;case 43:n?r=new ao(e,t,so(`^${ro(n,o??null)}`),o??null):r=new ot("");break;case 42:n?r=new ao(e,t,so(`${ro(n,o??null)}$`),o??null):r=new ot("");break;case 46:n?r=new ao(e,t,so(ro(n,o??null)),o??null):r=new ot("");break;case 50:if(n=="supported")r=new Mb(e,t);else{this.invalidSelector(`Unsupported :: attr selector op: ${n}`);return}break;default:this.invalidSelector(`Unsupported attr selector: ${i}`);return}this.chain.push(r)}descendantSelector(){if(this.invalidContinuationAfterPseudoelement("descendant selector"))return;let e=`d${Tr++}`;this.processChain(new Nr(new Xb(e,this.viewConditionId,null))),this.chain=[new ot(e)],this.viewConditionId=null}childSelector(){if(this.invalidContinuationAfterPseudoelement("child selector"))return;let e=`c${Tr++}`;this.processChain(new Nr(new qb(e,this.viewConditionId,null))),this.chain=[new ot(e)],this.viewConditionId=null}adjacentSiblingSelector(){if(this.invalidContinuationAfterPseudoelement("adjacent sibling selector"))return;let e=`a${Tr++}`;this.processChain(new Nr(new Yb(e,this.viewConditionId,null))),this.chain=[new ot(e)],this.viewConditionId=null}followingSiblingSelector(){if(this.invalidContinuationAfterPseudoelement("following sibling selector"))return;let e=`f${Tr++}`;this.processChain(new Nr(new Zb(e,this.viewConditionId,null))),this.chain=[new ot(e)],this.viewConditionId=null}nextSelector(){this.finishChain(),this.pseudoelement=null,this.selectorFunctionContainsPseudoelement=!1,this.footnoteContent=!1,this.specificity=0,this.chain=[]}startSelectorRule(){this.isInsideSelectorRule("E_CSS_UNEXPECTED_SELECTOR")||(this.state=1,this.elementStyle={},this.pseudoelement=null,this.selectorFunctionContainsPseudoelement=!1,this.specificity=0,this.footnoteContent=!1,this.chain=[],this.invalid=!1)}error(e,t){super.error(e,t),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.selectorFunctionContainsPseudoelement=!1,this.viewConditionId=null,this.footnoteContent=!1,this.specificity=0)}makeApplyRuleAction(e){let t=this.regionId;return this.footnoteContent&&(t?t="xxx-bogus-xxx":t="footnote"),new oh(this.elementStyle,e,this.pseudoelement,t,this.viewConditionId)}special(e,t){let i;this.condition?i=new tl(t,0,this.condition):i=new W(t,0),af(this.elementStyle,e).push(i)}property(e,t,i){this.validatorSet.validatePropertyAndHandleShorthand(e,t,i,this)}invalidPropertyValue(e,t){this.report(`E_INVALID_PROPERTY_VALUE ${e}: ${t.toString()}`)}unknownProperty(e,t){this.report(`E_INVALID_PROPERTY ${e}: ${t.toString()}`)}simpleProperty(e,t,i){e=="display"&&(t===y.oeb_page_head||t===y.oeb_page_foot)&&(this.simpleProperty("flow-options",new J([y.exclusive,y._static]),i),this.simpleProperty("flow-into",t,i),t=y.block),_t("SIMPLE_PROPERTY").forEach(r=>{let s=r({name:e,value:t,important:i});e=s.name,t=s.value,i=s.important});let n=(i?this.getImportantSpecificity():this.getBaseSpecificity())+this.cascade.nextOrder(),o=this.condition?new tl(t,n,this.condition):new W(t,n);Jt(this.elementStyle,e,o)}finish(){return this.cascade}startFuncWithSelector(e,t){let i;switch(e){case"is":i=new Hn(this);break;case"not":i=new a0(this);break;case"where":i=new l0(this);break;case"has":i=new h0(this);break;case"nth-child":t&&t.length>=2&&(i=new xf(this,t[0],t[1]));break;case"nth-last-child":t&&t.length>=2&&(i=new u0(this,t[0],t[1]));break}i&&(i.startSelectorRule(),this.owner.pushHandler(i))}},s0={"nth-child":zb,"nth-of-type":rl,"nth-last-child":sl,"nth-last-of-type":al},Tr=0,Hn=class bf extends zo{constructor(t){super(t.scope,t.owner,t.condition,t,t.regionId,t.validatorSet,!1),u(this,"parent",t),u(this,"parentChain"),u(this,"chains",[]),u(this,"maxSpecificity",0),u(this,"selectorTexts",[]),u(this,"containsPseudoelementSelector",!1),this.parentChain=t.chain}nextSelector(){this.containsPseudoelementSelector||(this.containsPseudoelementSelector=!!this.pseudoelement),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(){var t;this.containsPseudoelementSelector||(this.containsPseudoelementSelector=!!this.pseudoelement),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 Gb(this.selectorTexts):this.positive()?new rh(this.chains):new Wb(this.chains)),this.increasingSpecificity()&&(this.parent.specificity+=this.maxSpecificity),(t=this.parent).selectorFunctionContainsPseudoelement||(t.selectorFunctionContainsPseudoelement=this.containsPseudoelementSelector)):this.parentChain.push(new ot("")),this.owner.popHandler()}startRuleBody(){this.reportAndSkip("E_CSS_UNEXPECTED_RULE_BODY")}error(t,i){super.error(t,i),this.chain=null,this.pseudoelement=null,this.viewConditionId=null,this.footnoteContent=!1,this.specificity=0;let n=!1;for(let o=this;o instanceof bf;o=o.parent)if(o.forgiving()){n=!0;break}n||this.owner.popHandler()}pushSelectorText(t){this.chain&&this.relational()&&this.selectorTexts.push(t)}positive(){return!0}increasingSpecificity(){return!0}forgiving(){return!0}relational(){return!1}},a0=class extends Hn{positive(){return!1}forgiving(){return!1}},l0=class extends Hn{increasingSpecificity(){return!1}},h0=class extends Hn{relational(){return!0}},xf=class extends Hn{constructor(e,t,i){super(e),u(this,"a",t),u(this,"b",i)}endFuncWithSelector(){this.chain&&this.chains.push(this.chain),this.chains.length>0?(this.maxSpecificity=Math.max(this.maxSpecificity,this.specificity),this.parentChain.push(new df(this.a,this.b,this.chains)),this.parent.specificity+=256+this.maxSpecificity):this.parentChain.push(new ot("")),this.owner.popHandler()}forgiving(){return!0}},u0=class extends xf{endFuncWithSelector(){this.chain&&this.chains.push(this.chain),this.chains.length>0?(this.maxSpecificity=Math.max(this.maxSpecificity,this.specificity),this.parentChain.push(new jb(this.a,this.b,this.chains)),this.parent.specificity+=256+this.maxSpecificity):this.parentChain.push(new ot("")),this.owner.popHandler()}},c0=class extends rn{constructor(e,t){super(e,t,!1)}property(e,t,i){if(this.scope.values[e])this.error(`E_CSS_NAME_REDEFINED ${e}`,this.getCurrentToken());else{let n=e.match(/height|^(top|bottom)$/)?"vh":"vw",o=new qo(this.scope,100,n);this.scope.defineName(e,t.toExpr(this.scope,o))}}},qr=class extends rn{constructor(e,t,i,n,o,r){super(e,t,!1),u(this,"condition",i),u(this,"elementStyle",n),u(this,"validatorSet",o),u(this,"ruleType",r),u(this,"order"),this.order=0}property(e,t,i){i?Y.warn("E_IMPORTANT_NOT_ALLOWED"):this.validatorSet.validatePropertyAndHandleShorthand(e,t,i,this)}invalidPropertyValue(e,t){Y.warn("E_INVALID_PROPERTY_VALUE",`${e}:`,t.toString())}unknownProperty(e,t){Y.warn("E_INVALID_PROPERTY",`${e}:`,t.toString())}simpleProperty(e,t,i){let n=i?this.getImportantSpecificity():this.getBaseSpecificity();n+=this.order,this.order+=ah;let o=this.condition?new tl(t,n,this.condition):new W(t,n);Jt(this.elementStyle,e,o)}},d0=class extends Bd{constructor(e,t){super(e),u(this,"validatorSet",t),u(this,"elementStyle",{}),u(this,"order",0)}property(e,t,i){this.validatorSet.validatePropertyAndHandleShorthand(e,t,i,this)}invalidPropertyValue(e,t){Y.warn("E_INVALID_PROPERTY_VALUE",`${e}:`,t.toString())}unknownProperty(e,t){Y.warn("E_INVALID_PROPERTY",`${e}:`,t.toString())}simpleProperty(e,t,i){let n=i?Od:Ld;n+=this.order,this.order+=ah;let o=new W(t,n);Jt(this.elementStyle,e,o)}};function Sf(e,t){let i=rf(e);i&&i.forEach(n=>{n.matcher.matches()&&t(n.styles)})}function ul(e,t,i){Sf(i,n=>{Eo(e,n,t)})}function p0(e,t,i,n){let o=new d0(e,t),r=new xt(n,o);try{ov(r,o,i)}catch(s){Y.warn(s,"Style attribute parse error:")}return o.elementStyle}function Cf(e,t,i){let n=e["writing-mode"];if(n){let o=n.evaluate(t,"writing-mode");if(o&&o!==y.inherit&&o!==y.revert&&o!==y.unset)return o===y.vertical_rl}return i}function kf(e,t,i){let n=e.direction;if(n){let o=n.evaluate(t,"direction");if(o&&o!==y.inherit&&o!==y.revert&&o!==y.unset)return o===y.rtl}return i}function cl(e,t,i,n,o){let r={};for(let s in e)Xi(s)&&(r[s]=ve(e,s));return ul(r,t,e),Ef(e,i,n,(s,a)=>{Eo(r,a,t),ul(r,t,a)}),r}function Ef(e,t,i,n){let o=ft(e,"_regions");if((t||i)&&o){if(i){let r=["footnote"];t?t=t.concat(r):t=r}for(let r of t){let s=o[r];s&&n(r,s)}}}function Eo(e,t,i){for(let n in t)if(Xi(n)){let o=ve(t,n),r=e[n];e[n]=nl(i,r,o)}}var Pf=(e,t,i,n,o,r)=>{var s,a;let h=i?n?wb:ef:n?bb:tf,l=o?xb:Sb;for(let c in e){let d=e[c];if(!d)continue;let p=(s=h[c])!=null?s:h[l[c]],f=(a=l[c])!=null?a:l[h[c]],g=p??f,v;if(g){let w=e[g];if(w&&w.priority>d.priority||p&&f&&p!==f&&(g=f,w=e[g],w&&w.priority>d.priority))continue;v=ku[p]?p:ku[f]?f:c}else v=c,c.startsWith("text-align")&&(d.value===y.inside||d.value===y.outside)&&(d=new W(o===(d.value===y.inside)?y.right:y.left,d.priority));t[v]=r(c,d)}},f0=class Nf extends nn{constructor(t,i,n,o=null){super(),u(this,"elementStyles",t),u(this,"styler",i),u(this,"element",n),u(this,"currentCustomPropertyName",o),u(this,"resolvingCustomProperties",[]),u(this,"varResolutionState",{cycleMembers:new Set}),o&&this.resolvingCustomProperties.push(o)}getRawCustomPropertyLookup(t,i,n){var o,r;let s=n??this.styler.root;if(i!=null&&i.length){for(let a=0;a<i.length;a++){let h=(o=i[a][t])==null?void 0:o.value;if(h){if(h===y.initial)return{found:!0,value:null,elementStyles:i.slice(a),element:n};if(!(h===y.inherit||h===y.unset||h===y.revert))return{found:!0,value:h,elementStyles:i.slice(a),element:n}}}n&&(s=n.parentElement)}for(;s;s=s.parentElement){let a=this.styler.getStyle(s,!1),h=(r=a?.[t])==null?void 0:r.value;if(h){if(h===y.initial)return{found:!0,value:null,elementStyles:a?[a]:[],element:s};if(!(h===y.inherit||h===y.unset||h===y.revert))return{found:!0,value:h,elementStyles:a?[a]:[],element:s}}}return{found:!1,value:null,elementStyles:[],element:null}}collectReferencedCustomProperties(t){let i=new Set;class n extends Kt{visitFunc(r){let s=r.values[0]instanceof he&&r.values[0].name;return r.name==="var"&&s&&Xe(s)&&i.add(s),super.visitFunc(r)}}return t.visit(new n),Array.from(i)}findReferencedCycleStart(t,i,n,o=new Set){for(let r of this.collectReferencedCustomProperties(t)){if(this.resolvingCustomProperties.includes(r))return r;if(o.has(r))continue;o.add(r);let s=this.getRawCustomPropertyLookup(r,i,n),a=s.value&&this.findReferencedCycleStart(s.value,s.elementStyles,s.element,o);if(a)return a}return null}getFallbackCycleMembers(t,i,n){let o=null,r=this;class s extends Kt{visitFunc(l){if(l.name==="var")for(let c of l.values.slice(1)){let d=r.findReferencedCycleStart(c,i,n);if(d)return o=d,null}return super.visitFunc(l)}}if(t.visit(new s),!o)return null;let a=this.resolvingCustomProperties.indexOf(o);return new Set(this.resolvingCustomProperties.slice(a))}resolveCustomProperty(t,i,n,o){if(!i)return{found:!1,value:null,continueLookup:!1};if(i===y.initial)return{found:!0,value:null,continueLookup:!1};if(i===y.inherit||i===y.unset||i===y.revert)return{found:!0,value:null,continueLookup:!0};let r=this.getFallbackCycleMembers(i,n,o);return r?(r.forEach(s=>this.varResolutionState.cycleMembers.add(s)),{found:!0,value:null,continueLookup:!1}):{found:!0,value:this.resolveReferencedCustomProperty(t,i,n,o),continueLookup:!1}}resolveReferencedCustomProperty(t,i,n,o){let r=this.resolvingCustomProperties.indexOf(t);if(r>=0)return this.resolvingCustomProperties.slice(r).forEach(d=>this.varResolutionState.cycleMembers.add(d)),null;let s=new Set(this.varResolutionState.cycleMembers);this.varResolutionState.cycleMembers=new Set;let a=new Nf(n,this.styler,o,t);a.resolvingCustomProperties=this.resolvingCustomProperties,a.resolvingCustomProperties.push(t),a.varResolutionState=this.varResolutionState;let h=i,l=32;for(let d=0;;d++){if(d>=l){h=null;break}let p=h.visit(a);if(a.error){h=null;break}if(p===h)break;h=p}let c=this.varResolutionState.cycleMembers;return this.varResolutionState.cycleMembers=new Set([...s,...c]),this.resolvingCustomProperties.pop(),c.has(t)?null:h}getVarValue(t){var i,n,o,r;let s=(i=this.element)!=null?i:this.styler.root;if((n=this.elementStyles)!=null&&n.length){for(let a=0;a<this.elementStyles.length;a++){let h=this.elementStyles[a],l=this.resolveCustomProperty(t,(o=h[t])==null?void 0:o.value,this.elementStyles.slice(a),this.element);if(l.found){if(l.value)return l.value;if(!l.continueLookup)return null}}this.element&&(s=this.element.parentElement)}for(;s;s=s.parentElement){let a=this.styler.getStyle(s,!1),h=this.resolveCustomProperty(t,(r=a?.[t])==null?void 0:r.value,a?[a]:[],s);if(h.found){if(h.value)return h.value;if(!h.continueLookup)return null}}return null}visitFunc(t){if(t.name!=="var")return super.visitFunc(t);let i=t.values[0]instanceof he&&t.values[0].name;return!i||!Xe(i)?(this.error=!0,Be):this.getVarValue(i)||(this.currentCustomPropertyName&&this.varResolutionState.cycleMembers.has(this.currentCustomPropertyName)?(this.error=!0,Be):t.values.length<2?(this.error=!0,Be):t.values.length===2?t.values[1]:new _e(t.values.slice(1)))}},Tf=class extends nn{constructor(e,t,i,n){super(),u(this,"context",e),u(this,"resolveViewportUnit",t),u(this,"percentRef",i),u(this,"vertical",n)}visitFunc(e){let t=super.visitFunc(e);if(e.name!=="calc")return t;let i=t.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(i))return t;let n=Ri(this.context.rootScope,new xt(i,null),"");if(n instanceof j)try{let o=n.expr.evaluate(this.context);typeof o=="number"&&!isNaN(o)&&(/\d(px|in|pt|pc|cm|mm|q|rem|rlh)\W/i.test(i)?t=new O(o,"px"):/\d[a-z]/i.test(i)||(t=new At(o)))}catch(o){Y.warn(o)}return t}visitNumeric(e){return this.resolveViewportUnit&&Ac(e.unit)||this.context.rootFontSize!=null&&cm(e.unit)?new O(e.num*this.context.queryUnitSize(e.unit,!1,this.vertical),"px"):typeof this.percentRef=="number"&&e.unit==="%"?new O(e.num*this.percentRef/100,"px"):e}};function Ss(e,t,i,n,o){try{if(t instanceof j)return t.expr instanceof we&&(t.expr.str.startsWith("named-string-")||t.expr.str.startsWith("running-element-"))?t:av(e,t.expr,i);if(t instanceof O||t instanceof ai||t instanceof J||t instanceof _e)return t.visit(new Tf(e,!0,n,o))}catch(r){return Y.warn(r),Be}return t}var Tu={first:!1,forceEnd:!1,allowEnd:!1,last:!1};function Au(e){let t=e instanceof rt?e:typeof e=="string"?B(e):y.none;if(t===y.none)return Tu;let i=t instanceof J?t.values:[t],n=Object.create(Tu);for(let o of i)if(o instanceof he)switch(o.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 Iu(e){return!e.first&&!e.last&&!e.forceEnd&&!e.allowEnd}var g0={trimStart:!1,spaceFirst:!1,trimEnd:!1,allowEnd:!1,trimAdjacent:!1},Fu={trimStart:!1,spaceFirst:!1,trimEnd:!1,allowEnd:!0,trimAdjacent:!0},Ru={trimStart:!0,spaceFirst:!1,trimEnd:!0,allowEnd:!1,trimAdjacent:!0};function Lu(e){let t=e instanceof rt?e:typeof e=="string"?B(e):y.normal;if(t===y.normal)return Fu;if(t===y.auto)return Ru;let i=t instanceof J?t.values:[t],n=Object.create(Fu);for(let o of i)if(o instanceof he)switch(o.name){case"trim-both":case"trim-auto":return Ru;case"space-all":return g0;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 ga={ideographAlpha:!1,ideographNumeric:!1},m0={ideographAlpha:!0,ideographNumeric:!0};function Ou(e){let t=e instanceof rt?e:typeof e=="string"?B(e):y.normal;if(t===y.normal||t===y.auto)return m0;if(t===y.none)return ga;let i=t instanceof J?t.values:[t],n=Object.create(ga);for(let o of i)if(o instanceof he)switch(o.name){case"no-autospace":return ga;case"ideograph-alpha":n.ideographAlpha=!0;break;case"ideograph-numeric":n.ideographNumeric=!0;break}return n}function Bu(e,t){return!e.ideographAlpha&&!e.ideographNumeric&&!t.trimStart&&!t.spaceFirst&&!t.trimEnd&&!t.allowEnd&&!t.trimAdjacent}function Mu(e){return e?(e=e.toLowerCase(),/^zh\b.*-(hant|tw|hk)\b/.test(e)?"zh-hant":/^zh\b/.test(e)?"zh-hans":/^ja\b/.test(e)?"ja":/^ko\b/.test(e)?"ko":e):null}var y0=/^[‘’“”〰﹙﹚﹛﹜﹝﹞〚〛]\p{M}*$/u,v0=/^[‘“﹙﹛﹝〚]\p{M}*$/u;function w0(e,t){return jo==="chromium"&&t&&y0.test(e)}function b0(e){return v0.test(e)?"viv-ts-open":"viv-ts-close"}var x0=class{getPolyfilledInheritedProps(){return["hanging-punctuation","text-autospace","text-spacing-trim"]}preprocessSingleDocument(e){e.body&&this.preprocessForTextSpacing(e.body)}preprocessForTextSpacing(e){var t;let i=e.ownerDocument.createNodeIterator(e,NodeFilter.SHOW_TEXT);for(let n=i.nextNode();n;n=i.nextNode()){if(n.parentElement.namespaceURI!=="http://www.w3.org/1999/xhtml"||((t=n.parentElement.dataset)==null?void 0:t.mathTypeset)==="true")continue;let o=n.textContent.replace(/(?![()\[\]{}])[\p{Ps}\p{Pe}\p{Pf}\p{Pi}、。,.:;、。\u3000\u3030]\p{M}*(?=\P{M})|.(?=(?![()\[\]{}])[\p{Ps}\p{Pe}\p{Pf}\p{Pi}、。,.:;、。\u3000\u3030])|(?!\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 r=o.length-1;for(let s=0;s<r;s++)n.parentNode.insertBefore(document.createTextNode(o[s]),n);n.textContent=o[r]}}}processGeneratedContent(e,t,i,n,o,r){o=Mu(o);let s=Ou(t),a=Lu(i),h=Au(n);if(Iu(h)&&Bu(s,a))return;this.preprocessForTextSpacing(e);let l=e.style.whiteSpace;(r?e.offsetHeight:e.offsetWidth)===0&&(e.style.whiteSpace="pre");let c=e.ownerDocument.createNodeIterator(e,NodeFilter.SHOW_TEXT),d=null,p=null;for(let f=c.nextNode();f;f=p){p=c.nextNode();let g=!d,v=!d||/\n$/.test(d.textContent),w=!p||/^\n/.test(p.textContent),x=!p;this.processTextSpacing(f,g||v,g,v,w,x,d,p,s,a,h,o,r),d=f}e.style.whiteSpace=l}postLayoutBlock(e,t){var i,n,o,r,s,a,h,l;let c=!e||e.fragmentIndex===1&&f(),d=c||g();function p(m){var S;if(m?.nodeType!==1)return!1;let b=m;if(b.hasAttribute(zn))return!0;let{position:C,float:P}=(S=b.style)!=null?S:{};return C==="absolute"||C==="fixed"||P&&P!=="none"}function f(){let m=t[0];for(let S=m;;S=S.parent)if(!S||!S.inline){if(S?.fragmentIndex!==1)return!1;break}if(!m.inline)return!0;for(let S=m.viewNode.previousSibling;S;S=S.previousSibling)if(!Ee(S,m.whitespace)&&!p(S))return!1;return!0}function g(){var m,S;let b=t[0],C;for(;b&&b.inline&&(C=(m=b.viewNode)==null?void 0:m.previousSibling,!(C&&(C.nodeType===Node.TEXT_NODE&&/^[ \t\r\n\f]*$/.test(C.textContent)&&b.whitespace!==bt.PRESERVE&&(C=C.previousSibling),C)));)b=b.parent;for(;C;){if(C.nodeType===Node.ELEMENT_NODE){if(C.localName==="br")return!0;let P=(S=C.style)==null?void 0:S.display;if(P&&P!=="inline")return!/^(inline|ruby)\b/.test(P)}else if(C.nodeType===Node.TEXT_NODE){if(b.whitespace===bt.PRESERVE){if(/\n$/.test(C.textContent))return!0}else if(b.whitespace===bt.NEWLINE&&/\n[ \t\r\n\f]*$/.test(C.textContent))return!0}C=C.lastChild}return!1}let v=-1;for(let m=0;m<t.length;m++){let S=t[m];if(!S.after&&S.inline&&!S.display&&S.parent&&S.viewNode.parentNode&&S.viewNode.nodeType===Node.TEXT_NODE&&!Ee(S.viewNode,S.whitespace)){let b=function(E){var N,R,$;if(((N=E.viewNode)==null?void 0:N.nodeType)===Node.ELEMENT_NODE)return E.viewNode.localName==="br";if(((R=E.viewNode)==null?void 0:R.nodeType)===Node.TEXT_NODE){let V=E.viewNode;if(E.whitespace===bt.PRESERVE){if(/\n$/.test(V.textContent))return!0}else if(E.whitespace===bt.NEWLINE&&/\n[ \t\r\n\f]*$/.test(V.textContent))return!0;if((($=V.previousElementSibling)==null?void 0:$.localName)==="br")return Ee(V,E.whitespace)}return!1},C=function(E){var N,R,$;if(((N=E.viewNode)==null?void 0:N.nodeType)===Node.ELEMENT_NODE)return E.viewNode.localName==="br";if(((R=E.viewNode)==null?void 0:R.nodeType)===Node.TEXT_NODE){let V=E.viewNode;if(E.whitespace===bt.PRESERVE){if(/^\n/.test(V.textContent))return!0}else if(E.whitespace===bt.NEWLINE&&/^[ \t\r\n\f]*\n/.test(V.textContent))return!0;if((($=V.nextElementSibling)==null?void 0:$.localName)==="br")return Ee(V,E.whitespace)}return!1};var w=b,x=C;v<0&&(v=m);let P=Mu((r=(n=(i=S.lang)!=null?i:S.parent.lang)!=null?n:e?.lang)!=null?r:(o=e?.parent)==null?void 0:o.lang),L=Ou(S.inheritedProps["text-autospace"]),A=Lu(S.inheritedProps["text-spacing-trim"]),z=Au(S.inheritedProps["hanging-punctuation"]);if(Iu(z)&&Bu(L,A)||/\b(flex|grid)\b/.test(S.parent.display))continue;let U=null,X=null,oe=m===v,k=m===v&&c,_=m===v&&d,F=!1,D=!1;for(let E=m-1;E>=0;E--){let N=t[E];if(b(N)){_=!0;break}if(!N.display&&N.viewNode.nodeType===Node.TEXT_NODE&&N.viewNode.textContent.length>0){U=N.viewNode;break}if(((s=N.viewNode)==null?void 0:s.nodeType)===Node.ELEMENT_NODE&&Yt(N.viewNode)==="footnote-call"){if(N.viewNode.contains(S.viewNode))continue;let R=wv(N.viewNode);if(R){U=R;break}}if(N.display&&!/^(inline|ruby)\b/.test(N.display)||((a=N.viewNode)==null?void 0:a.nodeType)===Node.ELEMENT_NODE&&(N.viewNode.localName==="br"||ji[N.viewNode.localName]))break;E===0&&(oe=!0,c&&(k=!0,_=!0))}for(let E=m+1;E<t.length;E++){let N=t[E];if(C(N)){F=!0;break}if(N.viewNode!==S.viewNode&&!N.display&&N.viewNode.nodeType===Node.TEXT_NODE&&N.viewNode.textContent.length>0){X=N.viewNode;break}if(N.display&&!/^(inline|ruby)\b/.test(N.display)||((h=N.viewNode)==null?void 0:h.nodeType)===Node.ELEMENT_NODE&&(N.viewNode.localName==="br"||ji[N.viewNode.localName])){E===t.length-1&&p(N.viewNode)&&(D=!0);break}if(E===t.length-1){F=!0,D=!0;for(let R=N.viewNode.nextSibling;R;R=R.nextSibling)if(!p(R)){D=!1;break}}}if(((l=S.parent)==null?void 0:l.display)==="inline-block"){if(!k){let E=S.parent.viewNode.firstChild;for(;Ee(E,S.whitespace);)E=E.nextSibling;S.viewNode===E&&(k=!0)}if(!D){let E=S.parent.viewNode.lastChild;for(;Ee(E,S.whitespace);)E=E.previousSibling;S.viewNode===E&&(D=!0)}}if(this.processTextSpacing(S.viewNode,oe,k,_,F,D,U,X,L,A,z,P,S.vertical)>0)break}}}processTextSpacing(e,t,i,n,o,r,s,a,h,l,c,d,p){let f=e.textContent,g=e.ownerDocument,v=0,w,x,m;function S(){if(t)return!0;if(!s)return!1;w||(w=g.createRange(),w.selectNode(e));let E=w.getClientRects()[0];if(!E)return!1;x||(x=g.createRange(),x.selectNode(s));let N=x.getClientRects(),R=N[N.length-1];return R?(v||(v=Lo(R,p)),p?E.top<R.top+R.height-E.width||E.left+E.width<R.left+E.width/10||E.left>R.left+R.width-E.width/10:E.left<R.left+R.width-E.height||E.top>R.top+R.height-E.height/10||E.top+E.height<R.top+E.height/10):!1}function b(){if(!a)return!1;w||(w=g.createRange(),w.selectNode(e));let E=w.getClientRects()[0];if(!E)return!1;v||(v=Lo(E,p)),m||(m=g.createRange(),m.selectNode(a));let N=m.getClientRects()[0];return N?p?E.top+E.height>N.top+E.width||E.left>N.left+N.width-E.width/10||E.left+E.width<N.left+E.width/10:E.left+E.width>N.left+E.height||E.top+E.height<N.top+E.height/10||E.top>N.top+N.height-E.height/10:!1}let C=!1,P=!1,L=!1,A=!1,z=!1,U,X=w0(f,p);if(i&&c.first&&/^[\p{Ps}\p{Pf}\p{Pi}'"\u3000]\p{M}*$/u.test(f)?(U="viv-ts-open",C=!0,L=!0):r&&c.last&&/^[\p{Pe}\p{Pf}\p{Pi}'"]\p{M}*$/u.test(f)?(U="viv-ts-close",C=!0,A=!0):(c.forceEnd||c.allowEnd)&&/^[、。,.、。]\p{M}*$/u.test(f)?(U="viv-ts-close",C=!0,z=!0):(l.trimStart||l.spaceFirst||l.trimAdjacent)&&/^[‘“〝([{⦅〈〈《「『【〔〖〘〚]\p{M}*$/u.test(f)?(U="viv-ts-open",C=!0):(l.trimEnd||l.allowEnd||l.trimAdjacent)&&(/^[’”〞〟)]}⦆〉〉》」』】〕〗〙〛]\p{M}*$/u.test(f)||d==="zh-hans"&&/^[:;]\p{M}*$/u.test(f)||d!=="zh-hant"&&/^[、。,.]\p{M}*$/u.test(f))?(U="viv-ts-close",C=!0):X&&(U=b0(f),C=!0,P=!0),C){let E=function(q){let Q=parseFloat(g.defaultView.getComputedStyle(q).fontSize)*.7;return(p?q.offsetHeight:q.offsetWidth)>Q},N=function(){return p?R.offsetLeft:R.offsetTop};var oe=E,k=N;if(e.parentElement.localName==="viv-ts-inner")return 0;let R=g.createElement(U),$=g.createElement("viv-ts-inner");if(R.appendChild($),e.parentNode.insertBefore(R,e),$.appendChild(e),X&&g.defaultView.getComputedStyle($.parentElement).textOrientation==="mixed"&&($.style.textOrientation="sideways"),P)return 0;let V=E($);if(V||L||A||z){if(U==="viv-ts-open"){if(L)R.className="viv-hang-first";else if(i||n)l.trimStart?R.className="viv-ts-trim":R.className="viv-ts-space";else if(!(l.trimStart||l.spaceFirst)&&S())R.className="viv-ts-space";else if(l.trimAdjacent&&s&&/[\p{Ps}\p{Pi}\p{Pe}\p{Pf}\u00B7\u2027\u30FB\u3000:;、。,.]\p{M}*$/u.test(s.textContent)&&(!/[\p{Pe}\p{Pf}]\p{M}*$/u.test(s.textContent)||s.parentElement.localName==="viv-ts-inner"&&E(s.parentElement)))R.className="viv-ts-trim";else if((l.trimStart||l.spaceFirst)&&S()){let q=N();R.className="viv-ts-auto",q===N()&&!S()&&(R.className="viv-ts-trim")}}else if(U==="viv-ts-close"){if(A)R.className=V?"viv-hang-last":"viv-hang-last viv-hang-hw";else if(r||o){let q=N();z?(R.className=V?c.allowEnd&&l.allowEnd?"viv-ts-auto":"viv-hang-end":"viv-hang-end viv-hang-hw",c.allowEnd&&q===N()&&(l.trimEnd?R.className="viv-ts-trim":l.allowEnd?(R.className="viv-hang-end",q===N()&&(R.className="")):R.className="viv-ts-space")):l.trimEnd?R.className="viv-ts-trim":l.allowEnd?(R.className="viv-ts-auto",q===N()&&(R.className="")):R.className="viv-ts-space"}else if(a&&/^[\p{Pe}\p{Pf}\u00B7\u2027\u30FB\u3000:;、。,.]/u.test(a.textContent))V&&l.trimAdjacent&&(R.className="viv-ts-trim");else if(z){let q=b(),Q=q&&c.allowEnd;Q||(R.className=V?"viv-hang-end":"viv-hang-end viv-hang-hw"),V?Q&&l.trimEnd?R.className="viv-ts-auto":!Q&&!b()?R.className="":!q&&c.allowEnd&&(l.trimEnd?(R.className="viv-ts-auto",b()||(R.className="viv-hang-end")):(R.className="viv-ts-space",b()||(l.allowEnd?(R.className="viv-ts-auto",b()||(R.className="viv-hang-end")):R.className="viv-hang-end"))):!q&&!b()&&(R.className="")}else if(l.trimEnd||l.allowEnd)if(b())l.allowEnd?R.className="viv-ts-space":R.className="viv-ts-auto";else{let q=N();R.className="viv-ts-auto",q===N()&&(R.className="")}}}}let _=!1;function F(E){var N;let R=(N=E?.ownerDocument.defaultView)==null?void 0:N.getComputedStyle(E);return!!R&&(R.textOrientation==="upright"||R.textCombineUpright==="all"||R["-webkit-text-combine"]==="horizontal")}function D(E,N){if(E.nodeType===Node.ELEMENT_NODE){let V=g.defaultView.getComputedStyle(E);if(parseFloat(V.marginInlineEnd)||parseFloat(V.borderInlineEndWidth)||parseFloat(V.paddingInlineEnd))return!0}let R=E.parentElement;if(R&&!R.contains(N))return D(R,N);if(N.nodeType===Node.ELEMENT_NODE){let V=g.defaultView.getComputedStyle(N);if(parseFloat(V.marginInlineStart)||parseFloat(V.borderInlineStartWidth)||parseFloat(V.paddingInlineStart))return!0}let $=N.parentElement;return $&&!$.contains(E)?D(E,$):!1}return(h.ideographAlpha||h.ideographNumeric)&&(s&&/^(?!\p{P})[\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF]/u.test(f)&&(h.ideographAlpha&&/(?![\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF\uFF01-\uFF60])\p{L}\p{M}*$/u.test(s.textContent)||h.ideographNumeric&&/(?![\uFF01-\uFF60])\p{Nd}\p{M}*$/u.test(s.textContent))&&!(p&&F(s.parentElement))&&!D(s,e)&&(e.parentNode.insertBefore(g.createElement("viv-ts-thin-sp"),e),_=!0),a&&/(?!\p{P})[\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF]\p{M}*$/u.test(f)&&(h.ideographAlpha&&/^(?![\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF\uFF01-\uFF60])\p{L}/u.test(a.textContent)||h.ideographNumeric&&/^(?![\uFF01-\uFF60])\p{Nd}/u.test(a.textContent))&&!(p&&F(a.parentElement))&&!D(e,a)&&(e.parentNode.insertBefore(g.createElement("viv-ts-thin-sp"),e.nextSibling),_=!0)),v}registerHooks(){Ft("POLYFILLED_INHERITED_PROPS",this.getPolyfilledInheritedProps.bind(this)),Ft("PREPROCESS_SINGLE_DOCUMENT",this.preprocessSingleDocument.bind(this)),Ft("POST_LAYOUT_BLOCK",this.postLayoutBlock.bind(this),!0)}},lh=new x0;lh.registerHooks();function S0(e){lh.preprocessForTextSpacing(e)}function C0(e,t,i,n,o,r){lh.processGeneratedContent(e,t,i,n,o,r)}var fo=new DOMParser().parseFromString('<root xmlns="http://www.pyroxy.com/ns/shadow"/>',"text/xml"),k0=["footnote-marker","marker","first-5-lines","first-4-lines","first-3-lines","first-2-lines","first-line","first-letter","before","footnote-call","","after"],hh="data-adapt-pseudo";function Yt(e){return e.getAttribute(hh)||""}function Po(e,t){e.setAttribute(hh,t)}var ma=class{constructor(e,t,i,n,o){u(this,"element",e),u(this,"style",t),u(this,"styler",i),u(this,"context",n),u(this,"exprContentListener",o),u(this,"contentProcessed",{})}getStyle(e,t){let i=Yt(e);this.styler&&i&&i.match(/after$/)&&(this.style=this.styler.getStyle(this.element,!0),this.styler=null);let n=ft(this.style,"_pseudos"),o=n?.[i]||{};if(i.match(/^first-/)&&!o["x-first-pseudo"]){let r=1,s;i=="first-letter"?r=0:(s=i.match(/^first-([0-9]+)-lines$/))!=null&&(r=s[1]-0),o["x-first-pseudo"]=new W(new lt(r),0)}return o}processContent(e,t,i){let n=Yt(e);if(!this.contentProcessed[n]){this.contentProcessed[n]=!0;let o=t.content;It(o)&&(o.visit(new Oo(e,this.context,o,this.exprContentListener)),S0(e))}}},lC=ls.isInstanceOfAfterIfContinuesLayoutConstraint,E0=$s.registerFragmentIndex,hC=$s.clearFragmentIndices,P0=class{constructor(e,t){u(this,"sourceNode",e),u(this,"styler",t)}createElement(e,t){let i=t.viewNode.ownerDocument.createElement("div"),n=new uh(e,i,t),o=n.getColumn().pageBreakType;return n.getColumn().pageBreakType=null,n.layout(this.createNodePositionForPseudoElement(),!0).thenAsync(()=>{this.styler.contentProcessed["after-if-continues"]=!1,n.getColumn().pageBreakType=o;let r=i.firstChild;return I(r,"display","block"),T(r)})}createNodePositionForPseudoElement(){let e=fo.createElementNS("http://www.w3.org/1999/xhtml","div");Po(e,"after-if-continues");let t=this.createShadowContext(e),i={steps:[{node:e,shadowType:t.type,shadowContext:t,nodeShadow:null,shadowSibling:null}],offsetInNode:0,after:!1,preprocessedTextContent:null};return new Bi(i)}createShadowContext(e){return new Br(this.sourceNode,e,null,null,null,yi.ShadowType.ROOTED,this.styler)}},N0=class Af{constructor(t,i,n){u(this,"nodeContext",t),u(this,"afterIfContinues",i),u(this,"pseudoElementHeight",n),u(this,"flagmentLayoutConstraintType","AfterIfContinue")}allowLayout(t,i,n){return!(i&&!t||t&&t.overflow)}nextCandidate(t){return!1}postLayout(t,i,n,o){}finishBreak(t,i){return this.getRepetitiveElements().affectTo(t)?this.afterIfContinues.createElement(i,this.nodeContext).thenAsync(n=>(this.nodeContext.viewNode.appendChild(n),T(!0))):T(!0)}getRepetitiveElements(){return new T0(this.nodeContext,this.pseudoElementHeight)}equalsTo(t){return t instanceof Af?this.afterIfContinues==t.afterIfContinues:!1}getPriorityOfFinishBreak(){return 9}},T0=class{constructor(e,t){u(this,"nodeContext",e),u(this,"pseudoElementHeight",t)}calculateOffset(e){return this.affectTo(e)?this.pseudoElementHeight:0}calculateMinimumOffset(e){return this.calculateOffset(e)}affectTo(e){if(!e)return!1;let t=e.shadowContext?e.shadowContext.owner:e.sourceNode;if(t===this.nodeContext.sourceNode)return!!e.after;for(let i=t.parentNode;i;i=i.parentNode)if(i===this.nodeContext.sourceNode)return!0;return!1}};function If(e,t){if(!e||!e.afterIfContinues||e.after||t.isFloatNodeContext(e))return T(e);let i=e.afterIfContinues;return i.createElement(t,e).thenAsync(n=>{let o=I0(e,t,n);return t.fragmentLayoutConstraints.push(new N0(e,i,o)),T(e)})}function Ff(e,t){return e.thenAsync(i=>If(i,t))}function A0(e,t){let i=M("processAfterIfContinuesOfAncestors"),n=e;return i.loop(()=>{if(n!==null){let o=If(n,t);return n=n.parent,o.thenReturn(!0)}else return T(!1)}).then(()=>{i.finish(!0)}),i.result()}function I0(e,t,i){let n=e.viewNode;n.appendChild(i);let o=_a(i,t,e.vertical);return n.removeChild(i),o}var F0=class{constructor(e){u(this,"constraints",e)}allowLayout(e){return this.constraints.every(t=>t.allowLayout(e))}},go=class extends Gl{constructor(e,t){super(),u(this,"checkPoints",e),u(this,"penalty",t),u(this,"alreadyEvaluated",!1),u(this,"breakNodeContext",null)}findAcceptableBreak(e,t){return t<this.getMinBreakPenalty()?null:(this.alreadyEvaluated||(this.breakNodeContext=e.findBoxBreakPosition(this,t>0),this.alreadyEvaluated=!!this.breakNodeContext||t>0||!!e.pseudoParent),this.breakNodeContext)}getMinBreakPenalty(){return this.penalty}getNodeContext(){return this.alreadyEvaluated?this.breakNodeContext:this.checkPoints[this.checkPoints.length-1]}},Cs=class extends lp{constructor(e,t,i,n,o){super(e),u(this,"layoutContext",t),u(this,"clientLayout",i),u(this,"layoutConstraint",n),u(this,"pageFloatLayoutContext",o),u(this,"last"),u(this,"viewDocument"),u(this,"flowRootFormattingContext",null),u(this,"isNonFirstColumn",!1),u(this,"isFloat",!1),u(this,"isFootnote",!1),u(this,"startEdge",0),u(this,"endEdge",0),u(this,"beforeEdge",0),u(this,"afterEdge",0),u(this,"footnoteEdge",0),u(this,"box",null),u(this,"chunkPositions",null),u(this,"bands",null),u(this,"overflown",!1),u(this,"breakPositions",null),u(this,"pageBreakType",null),u(this,"forceNonfitting",!0),u(this,"leftFloatEdge",0),u(this,"rightFloatEdge",0),u(this,"bottommostFloatTop",0),u(this,"stopAtOverflow",!0),u(this,"lastAfterPosition",null),u(this,"fragmentLayoutConstraints",[]),u(this,"pseudoParent",null),u(this,"nodeContextOverflowingDueToRepetitiveElements",null),u(this,"blockDistanceToBlockEndFloats",NaN),u(this,"lastLineStride",0),u(this,"breakAtTheEdgeBeforeFloat",null),u(this,"lineFootnoteOverflowEdge",null),pv(this),this.last=e.lastChild,this.viewDocument=e.ownerDocument,o.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}almostEquals(e,t,i=this.clientLayout.pixelRatio===0?.5:1.5/(this.clientLayout.pixelRatio||1)){return Math.abs(e-t)<i}getFloatLayoutUnit(){return this.clientLayout.pixelRatio===0?0:1/(this.clientLayout.pixelRatio||1)}getFloatLayoutTolerance(e){return e||1}isOverflown(e){let t=1.5/(this.clientLayout.pixelRatio||1);return this.almostEquals(e,this.footnoteEdge,t)?!1:this.vertical?e<this.footnoteEdge:e>this.footnoteEdge}getExclusions(){let e=this.pageFloatLayoutContext.getFloatFragmentExclusions();return this.exclusions.concat(e)}openAllViews(e){let t=M("openAllViews"),i=e.steps;this.layoutContext.setViewRoot(this.element,this.isFootnote);let n=i.length-1,o=null;return t.loop(()=>{for(;n>=0;){let r=o,s=i[n];if(o=us(s,r),n===i.length-1&&!o.formattingContext&&(o.formattingContext=this.flowRootFormattingContext),n==0&&(o.offsetInNode=this.calculateOffsetInNodeForNodeContext(e),o.after=e.after,o.preprocessedTextContent=e.preprocessedTextContent,o.after))break;let a=this.layoutContext.setCurrent(o,n==0&&o.offsetInNode==0);if(n--,a.isPending())return a}return T(!1)}).then(()=>{t.finish(o)}),t.result()}calculateOffsetInNodeForNodeContext(e){return e.preprocessedTextContent?Iv(e.preprocessedTextContent,e.offsetInNode):e.offsetInNode}maybePeelOff(e,t){var i,n;if(e.firstPseudo&&e.inline&&!e.after&&e.firstPseudo.count==0&&e.viewNode.nodeType!=1){let o=e.viewNode.textContent,r=o.match(Jr),s=r?r[0].length:0;if(!r&&((i=e.sourceNode)==null?void 0:i.nodeType)===3&&((n=e.sourceNode.nextSibling)==null?void 0:n.nodeType)===3&&o===e.sourceNode.textContent){let a=o+e.sourceNode.nextSibling.textContent,h=a.match(Jr);if(h){let l=h[0];s=l.length,e.sourceNode.textContent=l,e.viewNode.textContent=l,e.sourceNode.nextSibling.textContent=a.substr(s)}}return this.layoutContext.peelOff(e,s)}return T(e)}buildViewToNextBlockEdge(e,t){let i=!1,n=M("buildViewToNextBlockEdge");return n.loopWithFrame(o=>{var r;if(e.viewNode&&!Pn(e)&&((r=e.viewNode.parentElement)==null?void 0:r.namespaceURI)==="http://www.w3.org/1999/xhtml"&&(t.push(e.copy()),t.length>1e3)){let s=e.viewNode.nodeType===1?e.viewNode:e.viewNode.parentElement,a=this.clientLayout.getElementClientRect(s);if(Lo(a,this.vertical)>=2){o.breakLoop();return}}this.maybePeelOff(e,0).then(s=>{let a=s;a!==e&&(e=a,Pn(e)||t.push(e.copy())),this.nextInTree(e).then(h=>{if(e=h,!e){o.breakLoop();return}(i||!this.layoutConstraint.allowLayout(e))&&(i=!0,e=e.modify(),e.overflow=!0),this.isFloatNodeContext(e)&&(Ii(e.floatReference)||e.floatSide==="footnote")?this.layoutFloatOrFootnote(e).then(l=>{if(e=l,this.pageFloatLayoutContext.isInvalidated()&&(e=null),!e){o.breakLoop();return}if(e.pluginProps.lineFootnoteOverflow){o.breakLoop();return}o.continueLoop()}):e.inline?o.continueLoop():o.breakLoop()})})}).then(()=>{n.finish(e)}),n.result()}nextInTree(e,t){let i=this.layoutContext.nextInTree(e,t);return Ff(i,this)}buildDeepElementView(e){if(!e.viewNode)return T(e);let t=[],i=e.sourceNode,n=M("buildDeepElementView");return n.loopWithFrame(o=>{e.viewNode&&e.inline&&!Pn(e)?t.push(e.copy()):(t.length>0&&this.postLayoutBlock(e,t),t=[]),this.maybePeelOff(e,0).then(r=>{let s=r;if(s!==e){let a=s;for(;a&&a.sourceNode!=i;)a=a.parent;if(a==null){e=s,o.breakLoop();return}Pn(s)||t.push(s.copy())}this.nextInTree(s).then(a=>{if(e=a,!e||e.sourceNode==i){o.breakLoop();return}if(!this.layoutConstraint.allowLayout(e)&&(e=e.modify(),e.overflow=!0,this.stopAtOverflow)){o.breakLoop();return}if(this.isFloatNodeContext(e)&&(Ii(e.floatReference)||e.floatSide==="footnote")){this.layoutFloatOrFootnote(e).then(h=>{if(e=h,this.pageFloatLayoutContext.isInvalidated()&&(e=null),!e){o.breakLoop();return}o.continueLoop()});return}o.continueLoop()})})}).then(()=>{t.length>0&&this.postLayoutBlock(e,t),n.finish(e)}),n.result()}createFloat(e,t,i,n){let o=this.viewDocument.createElement("div");return this.vertical?(n>=this.height&&(n-=.1),n<1&&(n=0),I(o,"height",`${i}px`),I(o,"width",`${n}px`)):(i>=this.width&&(i-=.1),i<1&&(i=0),I(o,"width",`${i}px`),I(o,"height",`${n}px`)),I(o,"float",t),I(o,"clear",t),this.element.insertBefore(o,e),o}killFloats(){let e=this.element.firstChild;for(;e;){let t=e.nextSibling;if(e.nodeType==1){let i=e,n=i.style.cssFloat;if(n=="left"||n=="right"||n==="none")this.element.removeChild(i);else break}e=t}}createFloats(){let e=this.element.firstChild,t=this.bands,i=this.vertical?this.getTopEdge():this.getLeftEdge(),n=this.vertical?this.getBottomEdge():this.getRightEdge(),o=this.vertical?-this.getRightEdge():this.getTopEdge(),r=this.vertical?-this.getLeftEdge():this.getBottomEdge(),s=null,a=1.5/(this.clientLayout.pixelRatio||1);for(let p of t){let f=Math.abs(p.x1-i)<a&&Math.abs(p.x2-n)<a?a:void 0;this.almostEquals(p.x1,i,f)?p.x1=i:this.almostEquals(p.x1,n,f)&&(p.x1=n),this.almostEquals(p.x2,n,f)?p.x2=n:this.almostEquals(p.x2,i,f)&&(p.x2=i),this.almostEquals(p.y1,o,f)?p.y1=o:this.almostEquals(p.y1,r,f)&&(p.y1=r),this.almostEquals(p.y2,r,f)?p.y2=r:this.almostEquals(p.y2,o,f)&&(p.y2=o)}let h=this.getFloatLayoutUnit(),l=jo==="webkit"?Math.floor:Math.round,c=t.map(p=>h>0?(l(p.y2/h)-l(p.y1/h))*h:p.y2-p.y1),d=.01;for(let p=0;p<t.length;p++){let f=p<t.length-1?t[p+1].x1:i,g=p<t.length-1?t[p+1].x2:n,v=f-t[p].x1,w=t[p].x2-g,x=0,m=0;v>d?x=1:v<-d&&(x=-1),w>d?m=1:w<-d&&(m=-1);let S=x!==0&&m!==0?x===m?x:0:x||m;if(h>0&&S!==0){let b=S*h;c[p]+b>=0&&(p>=t.length-1||c[p+1]-b>=0)&&(c[p]+=b,p<t.length-1&&(c[p+1]-=b))}}for(let p=0;p<t.length;p++){let f=t[p];f.left=this.createFloat(e,"left",f.x1-i,c[p]),f.right=this.createFloat(e,"right",n-f.x2,c[p]),f.x1<n&&f.x2>i?s=f:s||I(f.right,"float","none")}if(s){let p=t[t.length-1],f=1.5/(this.clientLayout.pixelRatio||1);if(s!==p&&(p.y2>=r||this.almostEquals(p.y2,r,f))&&(this.footnoteEdge=this.vertical?-s.y2:s.y2,s.x1===i&&s.x2===n))for(let g=t.indexOf(s);g<t.length;g++){let v=t[g];this.element.removeChild(v.left),this.element.removeChild(v.right),v.left=null,v.right=null}}this.adjustColumnBlockSizeForBlockEndFloats()}adjustColumnBlockSizeForBlockEndFloats(){var e;if(this.element.hasAttribute("data-vivliostyle-in-column-balancing")||(e=this.element.parentElement)!=null&&e.hasAttribute("data-vivliostyle-in-column-balancing"))return;let t=this.vertical?this.width:this.height,i=this.getBoxDir()*(this.footnoteEdge-this.beforeEdge),n=1.5/(this.clientLayout.pixelRatio||1);if(i>0&&i<t&&!this.almostEquals(i,t,n)){let o=this.vertical?"width":"height";if(I(this.element,o,`${i}px`),this.vertical){let r=this.left+(t-i);I(this.element,"left",`${r}px`)}this.element.setAttribute("data-vivliostyle-column-block-size-adjusted","true")}}calculateEdge(e,t,i,n){let o;if(e&&En(e.viewNode))return NaN;if(e&&e.after&&!e.inline&&(o=bn(e,this.clientLayout,0,this.vertical),!isNaN(o)))return o;e=t[i];let r=n-e.boxOffset;for(;;){if(o=bn(e,this.clientLayout,r,this.vertical),!isNaN(o))return o;if(r>0){r--;continue}if(i--,i<0)return this.beforeEdge;e=t[i],e.viewNode.nodeType!=1&&(r=e.viewNode.textContent.length)}}parseComputedLength(e){let t=e.match(/^(-?[0-9]*(\.[0-9]*)?)px$/);return t?this.clientLayout.adjustLengthValue(parseFloat(t[0])):0}getComputedMargin(e){let t=this.clientLayout.getElementComputedStyle(e),i=new ta(0,0,0,0);return t&&(i.left=this.parseComputedLength(t.marginLeft),i.top=this.parseComputedLength(t.marginTop),i.right=this.parseComputedLength(t.marginRight),i.bottom=this.parseComputedLength(t.marginBottom)),i}getComputedPaddingBorder(e){let t=this.clientLayout.getElementComputedStyle(e),i=new ta(0,0,0,0);return t&&(i.left=this.parseComputedLength(t.borderLeftWidth)+this.parseComputedLength(t.paddingLeft),i.top=this.parseComputedLength(t.borderTopWidth)+this.parseComputedLength(t.paddingTop),i.right=this.parseComputedLength(t.borderRightWidth)+this.parseComputedLength(t.paddingRight),i.bottom=this.parseComputedLength(t.borderBottomWidth)+this.parseComputedLength(t.paddingBottom)),i}getComputedInsets(e){let t=this.clientLayout.getElementComputedStyle(e),i=new ta(0,0,0,0);if(t){if(t.boxSizing=="border-box")return this.getComputedMargin(e);i.left=this.parseComputedLength(t.marginLeft)+this.parseComputedLength(t.borderLeftWidth)+this.parseComputedLength(t.paddingLeft),i.top=this.parseComputedLength(t.marginTop)+this.parseComputedLength(t.borderTopWidth)+this.parseComputedLength(t.paddingTop),i.right=this.parseComputedLength(t.marginRight)+this.parseComputedLength(t.borderRightWidth)+this.parseComputedLength(t.paddingRight),i.bottom=this.parseComputedLength(t.marginBottom)+this.parseComputedLength(t.borderBottomWidth)+this.parseComputedLength(t.paddingBottom)}return i}setComputedInsets(e,t){let i=this.clientLayout.getElementComputedStyle(e);i&&(t.marginLeft=this.parseComputedLength(i.marginLeft),t.borderLeft=this.parseComputedLength(i.borderLeftWidth),t.paddingLeft=this.parseComputedLength(i.paddingLeft),t.marginTop=this.parseComputedLength(i.marginTop),t.borderTop=this.parseComputedLength(i.borderTopWidth),t.paddingTop=this.parseComputedLength(i.paddingTop),t.marginRight=this.parseComputedLength(i.marginRight),t.borderRight=this.parseComputedLength(i.borderRightWidth),t.paddingRight=this.parseComputedLength(i.paddingRight),t.marginBottom=this.parseComputedLength(i.marginBottom),t.borderBottom=this.parseComputedLength(i.borderBottomWidth),t.paddingBottom=this.parseComputedLength(i.paddingBottom))}setComputedWidthAndHeight(e,t){let i=this.clientLayout.getElementComputedStyle(e);i&&(t.width=this.parseComputedLength(i.width),t.height=this.parseComputedLength(i.height))}layoutUnbreakable(e){return this.buildDeepElementView(e)}layoutFloat(e){let t=M("layoutFloat"),i=e.viewNode,n=aa(e.floatSide,e.vertical,e.direction,this.layoutContext.page.side);return I(i,"float","none"),I(i,"display","inline-block"),I(i,"vertical-align","top"),this.buildDeepElementView(e).then(o=>{let r=Bt(this.clientLayout,i,this.vertical),s=this.getComputedMargin(i),a=new Mt(r.left-s.left,r.top-s.top,r.right+s.right,r.bottom+s.bottom),h=this.rtl?this.endEdge:this.startEdge,l=this.rtl?this.startEdge:this.endEdge,c=e.parent;for(;c&&c.inline;)c=c.parent;if(c){let b=c.viewNode.ownerDocument.createElement("div");b.style.left="0px",b.style.top="0px",this.vertical?(b.style.bottom="0px",b.style.width="1px"):(b.style.right="0px",b.style.height="1px"),c.viewNode.appendChild(b);let C=Bt(this.clientLayout,b,this.vertical);h=Math.max(this.rtl?this.getEndEdge(C):this.getStartEdge(C),h),l=Math.min(this.rtl?this.getStartEdge(C):this.getEndEdge(C),l),c.viewNode.removeChild(b);let P=this.vertical?a.y2-a.y1:a.x2-a.x1;n=="left"?l=Math.max(l,h+P):h=Math.min(h,l-P),c!==e.parent&&!e.firstPseudo&&(c.viewNode.appendChild(i),i.setAttribute("data-vivliostyle-float-box-moved","true"))}let d=new Mt(h,this.getBoxDir()*this.beforeEdge,l,this.getBoxDir()*this.afterEdge),p=a;this.vertical&&(p=ns(a));let f=this.getBoxDir();if(p.y1<this.bottommostFloatTop*f){let b=p.y2-p.y1;p.y1=this.bottommostFloatTop*f,p.y2=p.y1+b}if(e.clearSide){let b=/^(top|bottom|inside|outside|(block|inline)-(start|end))$/.test(e.clearSide)?aa(e.clearSide,e.vertical,e.direction,this.layoutContext.page.side):e.clearSide==="same"?n:e.clearSide,C=this.beforeEdge;b!=="right"&&(C=f*Math.max(C*f,this.leftFloatEdge*f)),b!=="left"&&(C=f*Math.max(C*f,this.rightFloatEdge*f));let P=C*f;if(p.y1<P){let L=p.y2-p.y1;p.y1=P,p.y2=p.y1+L}}d.y2+=this.getFloatLayoutUnit(),zm(d,this.bands,p,n),this.vertical&&(a=rd(p));let g=this.getComputedInsets(i);I(i,"width",`${a.x2-a.x1-g.left-g.right}px`),I(i,"height",`${a.y2-a.y1-g.top-g.bottom}px`),I(i,"position","absolute"),e.display,I(i,"display",e.display);let v,w=null;if(c&&(c.containingBlockForAbsolute?w=c:w=c.getContainingBlockForAbsolute()),w){let b=w.viewNode.ownerDocument.createElement("div");b.style.position="absolute",w.vertical?b.style.right="0":b.style.left="0",b.style.top="0",w.viewNode.appendChild(b),v=Bt(this.clientLayout,b,this.vertical),w.viewNode.removeChild(b)}else v={left:this.getLeftEdge()-this.paddingLeft,right:this.getRightEdge()+this.paddingRight,top:this.getTopEdge()-this.paddingTop};if(w?w.vertical:this.vertical){let b=Math.max(0,v.right-a.x2);I(i,"right",`${b}px`)}else{let b=Math.max(0,a.x1-v.left);I(i,"left",`${b}px`)}let x=Math.max(0,a.y1-v.top);I(i,"top",`${x}px`),e.clearSpacer&&(e.clearSpacer.parentNode.removeChild(e.clearSpacer),e.clearSpacer=null);let m=this.vertical?a.x1:a.y2,S=this.vertical?a.x2:a.y1;!this.isOverflown(m)||this.breakPositions.length==0?(this.killFloats(),d=new Mt(this.getLeftEdge(),this.getTopEdge(),this.getRightEdge(),this.getBottomEdge()),this.vertical&&(d=ns(d)),Vm(d,this.bands,p,null,n),this.createFloats(),n=="left"?this.leftFloatEdge=m:this.rightFloatEdge=m,this.bottommostFloatTop=S,this.updateMaxReachedAfterEdge(m),t.finish(o)):(e=e.modify(),e.overflow=!0,t.finish(e))}),t.result()}setupFloatArea(e,t,i,n,o,r){let s=this.pageFloatLayoutContext,a=s.getContainer(t),h=e.element;a.element.parentNode.appendChild(h),e.isFloat=!0,e.originX=a.originX,e.originY=a.originY,e.vertical=a.vertical,e.rtl=a.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=(a.exclusions||[]).concat(),e.forceNonfitting=!s.hasFloatFragments(),e.innerShape=null;let l=a.getPaddingRect();return e.setHorizontalPosition(l.x1-a.originX,l.x2-l.x1),e.setVerticalPosition(l.y1-a.originY,l.y2-l.y1),o.adjustPageFloatArea(e,a,this).thenAsync(()=>{e.init();let c=!!s.setFloatAreaDimensions(e,t,i,n,!0,e.isFootnote||!s.hasFloatFragments(),r);if(c){if(e.isFootnote){let d=getComputedStyle(e.element);if(e.vertical){let p=parseFloat(d.maxWidth);!isNaN(p)&&e.width>p&&(e.width=p,I(e.element,"width",`${p}px`))}else{let p=parseFloat(d.maxHeight);!isNaN(p)&&e.height>p&&(e.height=p,I(e.element,"height",`${p}px`))}}e.killFloats(),e.init()}else a.element.parentNode.removeChild(h);return T(c)})}createPageFloatArea(e,t,i,n,o){let r=this.element.ownerDocument.createElement("div");I(r,"position","absolute");let s=this.pageFloatLayoutContext.getPageFloatLayoutContext(e.floatReference),a=new Sn(null,Pe.COLUMN,null,this.pageFloatLayoutContext.flowName,e.nodePosition,null,null);a.setOuterContext(this.pageFloatLayoutContext);let h=s.getContainer(),l=new O0(t,r,this.layoutContext.clone(),this.clientLayout,this.layoutConstraint,a,h);return a.setContainer(l),this.setupFloatArea(l,e.floatReference,t,i,n,o).thenAsync(c=>T(c?l:null))}layoutSinglePageFloatFragment(e,t,i,n,o,r,s){let a=this.pageFloatLayoutContext;e=(s?s.continuations:[]).concat(e);let h=e[0].float,l=a.getPageFloatPlacementCondition(h,t,i),c={floatArea:null,pageFloatFragment:null,newPosition:null},d=M("layoutSinglePageFloatFragment");return this.createPageFloatArea(h,t,r,o,l).then(p=>{if(c.floatArea=p,!p){d.finish(c);return}let f=!1,g=0;d.loopWithFrame(v=>{if(g>=e.length){v.breakLoop();return}let w=e[g],x=new Bi(w.nodePosition),m=p.getRootViewNodeCount();p.layout(x,!0).then(S=>{if(c.newPosition=S,!S||n){if(S&&p.isFootnote&&p.breakPositions&&!(p.breakPositions.some(b=>b instanceof go)&&p.hasNonPseudoTextContentAfter(m))){f=!0,v.breakLoop();return}g++,v.continueLoop()}else f=!0,v.breakLoop()})}).then(()=>{if(!f&&p.isFootnote&&p.computedBlockSize<=0&&c.newPosition){let v=a.getPageFloatLayoutContext(h.floatReference);if(v.footnoteMaxBlockSize==null){if(v.initFootnoteRetryFromEmptyFragment(h,p)){p.element.parentNode&&p.element.parentNode.removeChild(p.element),this.layoutSinglePageFloatFragment(e,t,i,n,o,r,s).then(w=>{d.finish(w)});return}f=!0}}if(!f){p.isFootnote&&p.applyCompactFootnoteDisplay();let v=a.setFloatAreaDimensions(p,h.floatReference,t,r,!1,n,l);if(!v)f=!0;else{let w=o.createPageFloatFragment(e,v,i,p,!!c.newPosition);a.addPageFloatFragment(w,!0),c.pageFloatFragment=w}}d.finish(c)})}),d.result()}layoutPageFloatInner(e,t,i,n){let o=this.pageFloatLayoutContext,r=e.float,s=r instanceof Bo,a=s&&r.footnotePolicy===y.line&&!!n&&!n.hasFloat(r),h=new Set;for(let d=o;d;d=d.effectiveParent)for(let p of d.floatFragments)p.continuations.some(f=>f.float.insidePageFloatArea)&&h.add(p);a||o.stashEndFloatFragments(r);function l(d,p){p?o.removePageFloatFragment(p,!0):d&&d.element.parentNode.removeChild(d.element);let f=[];for(let g=o;g;g=g.effectiveParent)for(let v of g.floatFragments)!h.has(v)&&v.continuations.some(w=>w.float.insidePageFloatArea)&&f.push(v);for(let g of f)o.removePageFloatFragment(g,!0);o.restoreStashedFragments(r.floatReference),o.deferPageFloat(e)}let c=M("layoutPageFloatInner");return this.layoutSinglePageFloatFragment([e],r.floatSide,r.clearSide,s||!o.hasFloatFragments(),t,i,a?null:n).then(d=>{let p=d.floatArea,f=d.pageFloatFragment,g=d.newPosition;f?this.layoutStashedPageFloats(r.floatReference,[n]).then(v=>{if(v){let w=f;if(a&&n){let b=n.area,C=b.getRootViewNodeCount();if(b.appendContentFrom(f.area),o.removePageFloatFragment(f,!0),!o.setFloatAreaDimensions(b,r.floatReference,n.floatSide,i,!1,!0,o.getPageFloatPlacementCondition(r,r.floatSide,r.clearSide))){b.removeContentAfter(C),l(p,f),c.finish(!1);return}n.addContinuations(f.continuations),w=n}let x=!!o.generatingNodePosition,m=!x&&r instanceof Bo&&r.footnotePolicy===y.line,S=m&&o.hasInvalidatedForLineFootnote(r);if(o.addPageFloatFragment(w,x||S),m&&!S&&o.markInvalidatedForLineFootnote(r),o.discardStashedFragments(r.floatReference),g){let b=new uu(r,g.primary);o.deferPageFloat(b)}c.finish(!0)}else l(p,f),c.finish(!1)}):(l(p,f),c.finish(!1))}),c.result()}layoutStashedPageFloats(e,t){let i=this.pageFloatLayoutContext,n=i.getStashedFloatFragments(e),o=[],r=[],s=!1,a=M("layoutStashedPageFloats"),h=0;return a.loopWithFrame(l=>{if(h>=n.length){l.breakLoop();return}let c=n[h];if(t.includes(c)){h++,l.continueLoop();return}let d=new Vn().findByFloat(c.continuations[0].float);this.layoutSinglePageFloatFragment(c.continuations,c.floatSide,c.clearSide,!1,d,null).then(p=>{let f=p.floatArea;f&&o.push(f);let g=p.pageFloatFragment;g?(r.push(g),h++,l.continueLoop()):(s=!0,l.breakLoop())})}).then(()=>{s?(r.forEach(l=>{i.removePageFloatFragment(l,!0)}),o.forEach(l=>{let c=l.element;c&&c.parentNode&&c.parentNode.removeChild(c)})):n.forEach(l=>{let c=l.area.element;c&&c.parentNode&&c.parentNode.removeChild(c)}),a.finish(!s)}),a.result()}findFootnoteCallElement(e){let t=e.previousSibling;for(;t;){if(t.nodeType===Node.ELEMENT_NODE&&Yt(t)==="footnote-call")return t;t=t.previousSibling}return null}setFloatAnchorViewNode(e){let t=e.viewNode.parentNode,i=t.ownerDocument.createElement("span");if(i.setAttribute(zn,"1"),e.floatSide==="footnote"){let o=this.findFootnoteCallElement(e.viewNode);o?i=o:t.insertBefore(i,e.viewNode)}else t.appendChild(i);t.removeChild(e.viewNode);let n=e.modify();return n.after=!0,n.viewNode=i,e.floatSide==="footnote"&&(n.display="inline"),n}resolveFloatReferenceFromColumnSpan(e,t,i){let n=M("resolveFloatReferenceFromColumnSpan"),o=this.pageFloatLayoutContext,r=o.getPageFloatLayoutContext(Pe.REGION);return o.getContainer().width<r.getContainer().width&&e===Pe.COLUMN?t===y.auto?this.buildDeepElementView(i.copy()).then(s=>{let a=s.viewNode,h=Vl(this.clientLayout,a,["min-content inline size"])["min-content inline size"],l=this.getComputedMargin(a);this.vertical?h+=l.top+l.bottom:h+=l.left+l.right,h>this.width?n.finish(Pe.REGION):n.finish(e)}):t===y.all?n.finish(Pe.REGION):n.finish(e):n.finish(e),n.result()}layoutPageFloat(e){let t=this.pageFloatLayoutContext,i=new Vn().findByNodeContext(e),n,o=t.findPageFloatByNodePosition(e.toNodePosition());return o?n=T(o):n=i.createPageFloat(e,t,this),n.thenAsync(r=>{let s=hs(e,0),a=this.setFloatAnchorViewNode(e);t.markPageFloatAnchorSeen(r);let h=i.findPageFloatFragment(r,t),l=new uu(r,s);if(h&&h.hasFloat(r))return t.registerPageFloatAnchor(r,a.viewNode),T(a);if(t.isForbidden(r)||t.hasPrecedingFloatsDeferredToNext(r))return t.deferPageFloat(l),t.registerPageFloatAnchor(r,a.viewNode),T(a);if(this.nodeContextOverflowingDueToRepetitiveElements)return T(null);{let c=p=>{if(!p||p.nodeType!==1)return NaN;let f=Bt(this.clientLayout,p,this.vertical);return f.right>=f.left&&f.bottom>=f.top?this.vertical?f.left:f.bottom:NaN},d=bn(a,this.clientLayout,0,this.vertical);if(e.floatSide==="footnote"){let p=r;if(p.footnotePolicy===y.line||isNaN(d)){let f=a;for(;f;){if((f.shadowContext?f.shadowContext.owner:f.sourceNode)===p.policyAnchorNode){let g=c(f.viewNode);isNaN(g)||(d=g);break}f=f.parent}}}return isNaN(d)&&e.floatSide==="footnote"&&(d=c(a.viewNode)),!(e.floatSide==="footnote"&&r.footnotePolicy===y.line)&&this.isOverflown(d)?T(a):(e.floatSide==="footnote"&&t.registerPageFloatAnchor(r,a.viewNode),this.layoutPageFloatInner(l,i,d,h).thenAsync(p=>{if(!p)return t.registerPageFloatAnchor(r,a.viewNode),T(a);if(e.floatSide==="footnote"){if(r.footnotePolicy===y.line&&t.hasInvalidatedForLineFootnote(r)){if(t.isInvalidated())return T(null);let f=i.findPageFloatFragment(r,t);if(f!=null&&f.hasFloat(r)&&f.continues)return this.registerLineFootnoteOverflowEdge(d),T(a)}return T(a)}return t.generatingNodePosition?T(a):T(null)}))}})}processLineStyling(e,t,i){let n=M("processLineStyling"),o=i.concat([]);i.splice(0,i.length);let r=0,s=e.firstPseudo;return s?.count===0&&(s=s.outer),n.loopWithFrame(a=>{if(!s){a.breakLoop();return}let h=this.findLinePositions(o),l=s.count-r;if(h.length<=l){a.breakLoop();return}let c=this.findAcceptableBreakInside(o,h[l-1],!0);if(c==null){a.breakLoop();return}this.finishBreak(c,!1,!1).then(()=>{r+=l,this.layoutContext.peelOff(c,0).then(d=>{e=d,s=e.firstPseudo,o=[],this.buildViewToNextBlockEdge(e,o).then(p=>{t=p,a.continueLoop()})})})}).then(()=>{Array.prototype.push.apply(i,o),n.finish(t)}),n.result()}registerLineFootnoteOverflowEdge(e){if(!isFinite(e))return;let t=this.getBoxDir();(this.lineFootnoteOverflowEdge==null||t*e<t*this.lineFootnoteOverflowEdge)&&(this.lineFootnoteOverflowEdge=e)}findLineFootnoteOverflowBreak(e){if(this.lineFootnoteOverflowEdge==null||e.length===0)return null;let t=this.findLinePositions(e),i=this.getBoxDir(),n=1.5/(this.clientLayout.pixelRatio||1),o=t.find(r=>i*(r-this.lineFootnoteOverflowEdge)>=-n);return o==null?null:this.findAcceptableBreakInside(e,o,!0)}isLoneImage(e){return e.length!=2&&this.breakPositions.length>0?!1:e[0].sourceNode==e[1].sourceNode&&ji[e[0].sourceNode.localName]}getTrailingMarginEdgeAdjustment(e){let t=0,i=0;for(let n=e.length-1;n>=0;n--){let o=e[n];if(!o||!o.after||!o.viewNode||o.viewNode.nodeType!=1)break;let r=this.getComputedMargin(o.viewNode),s=this.vertical?-r.left:r.bottom;s>0?t=Math.max(t,s):i=Math.min(i,s)}return t+i}layoutBreakableBlock(e){let t=M("layoutBreakableBlock"),i=[];return this.lineFootnoteOverflowEdge=null,this.buildViewToNextBlockEdge(e,i).then(n=>{let o=i.length-1;if(o<0){t.finish(n);return}this.postLayoutBlock(n,i);let r=this.suppressOpenAncestorBlockEndInset(n??e),s=this.calculateEdge(n,i,o,i[o].boxOffset);r();let a=!1;if(!n||!En(n.viewNode)){let l=Ln(n,this.collectElementsOffset());a=this.isOverflown(s+(this.vertical?-1:1)*l.minimum),this.isOverflown(s+(this.vertical?-1:1)*l.current)&&!this.nodeContextOverflowingDueToRepetitiveElements&&(this.nodeContextOverflowingDueToRepetitiveElements=n)}n==null&&(s+=this.getTrailingMarginEdgeAdjustment(i)),this.updateMaxReachedAfterEdge(s);let h;e.firstPseudo?h=this.processLineStyling(e,n,i):h=T(n),h.then(l=>{let c=this.findLineFootnoteOverflowBreak(i);if(c){let d=c.modify();d.overflow=!0,d.pluginProps.lineFootnoteOverflow=1,this.breakPositions=[],this.saveEdgeBreakPosition(d,null,!0),this.lineFootnoteOverflowEdge=null,t.finish(d);return}this.lineFootnoteOverflowEdge=null,i.length>0&&(this.saveBoxBreakPosition(i),a&&!this.isLoneImage(i)&&l&&(l=l.modify(),l.overflow=!0)),t.finish(l)})}),t.result()}postLayoutBlock(e,t){_t("POST_LAYOUT_BLOCK").forEach(i=>{i(e,t,this)})}findEndOfLine(e,t,i){let n=this.vertical?e-1:e+1,o=0,r=t[0].boxOffset,s=o,a=t.length-1,h=t[a].boxOffset,l;for(;r<h;){l=r+Math.ceil((h-r)/2),s=o;let c=a;for(;s<c;){let p=s+Math.ceil((c-s)/2);t[p].boxOffset>l?c=p-1:s=p}let d=this.calculateEdge(null,t,s,l);if(this.vertical?d<=n:d>=n){for(h=l-1;t[s].boxOffset==l;)s--;a=s}else i&&this.updateMaxReachedAfterEdge(d),r=l,o=s}return{nodeContext:t[s],index:r,checkPointIndex:s}}findAcceptableBreakInside(e,t,i){var n,o,r;let s=this.findEndOfLine(t,e,!0),a=s.nodeContext;if(s.checkPointIndex===0&&s.index===a.boxOffset)return null;let h=a.viewNode;if(h.nodeType!=1&&((n=h.parentElement)==null?void 0:n.localName)!=="viv-ts-inner"){let l=h;a=this.resolveTextNodeBreaker(a).breakTextNode(l,a,s.index,e,s.checkPointIndex,i)}else{let l=su(a);if(l){if(((o=this.breakPositions)==null?void 0:o[0])instanceof go&&l!=null&&l.viewNode.contains(this.breakPositions[0].checkPoints[0].viewNode))return null;for(a=l;!a.after&&a.inline&&a.parent;){let c=(r=a.viewNode)==null?void 0:r.previousSibling;for(;c&&(Ee(c,a.parent.whitespace)||Ot(c));)c=c.previousSibling;if(c)break;a=a.parent}}}return this.clearOverflownViewNodes(a,!1),a}resolveTextNodeBreaker(e){return _t("RESOLVE_TEXT_NODE_BREAKER").reduce((t,i)=>i(e)||t,ks.instance)}getRangeBoxes(e,t){let i=[],n=e.ownerDocument.createRange(),o=!1,r=e,s=null,a=!1,h=!0;for(;h;){let l=!0;do{let c=null;r==t&&(t.nodeType===1?h=!(!t.firstChild||o):h=!1);let d=r.nodeType===1?r:null;d?o?o=!1:zl(d)?l=!a:!d.firstChild||ji[d.localName]||/^r(uby|[bt]c?)$/.test(d.localName)||vv(this.clientLayout.getElementComputedStyle(d).display)?(l=!a,l?(d.localName==="ruby"&&r.firstChild&&(r=r.firstChild),n.setStartBefore(r),a=!0,s=r):/^r(uby|tc?)$/.test(d.localName)||(s=r),r.contains(t)&&(h=!1)):c=r.firstChild:(a||(r.parentNode==null?h=!1:(n.setStartBefore(r),a=!0)),s=r),c||(c=r.nextSibling,c||(o=!0,c=r.parentNode)),r=c}while(l&&h);if(a){n.setEndAfter(s);let c=this.clientLayout.getRangeClientRects(n);ss(c,this.vertical);for(let d=0;d<c.length;d++)i.push(c[d]);a=!1}}return i}findLinePositions(e){let t=[],i=this.getRangeBoxes(e[0].viewNode,e[e.length-1].viewNode);i.sort(this.vertical?zv:Dv);let n=0,o=0,r=0,s=0,a=0,h=this.getBoxDir();for(;;){if(a<i.length){let l=i[a],c=1;if(s>0){let d=Math.max(this.getBoxSize(l),1);h*this.getBeforeEdge(l)<h*n?c=h*(this.getAfterEdge(l)-n)/d:h*this.getAfterEdge(l)>h*o?c=h*(o-this.getBeforeEdge(l))/d:c=1}if(s==0||c>=.6||c>=.2&&this.getStartEdge(l)>=r-1){r=this.getEndEdge(l),this.vertical?(n=s==0?l.right:Math.max(n,l.right),o=s==0?l.left:Math.min(o,l.left)):(n=s==0?l.top:Math.min(n,l.top),o=s==0?l.bottom:Math.max(o,l.bottom)),s++,a++;continue}}if(s>0&&(t.push(o),s=0),a>=i.length)break}return t.sort(kc),this.vertical&&t.reverse(),t}calculateClonedPaddingBorder(e){let t=0;for(let i=e;i;i=i.parent)if(!i.inline&&Nn(i.viewNode)){let n=this.getComputedPaddingBorder(i.viewNode);t+=i.vertical?-n.left:n.bottom,i.display==="table"&&(t+=(i.vertical?-1:1)*i.blockBorderSpacing)}return t}getOffsetByRepetitiveElements(e){let t;return e?t=e.calculateOffset(this):t=Ln(null,this.collectElementsOffset()),t.current}findBoxBreakPosition(e,t){let i=this.element.parentNode,n=this.element.nextSibling;i.removeChild(this.element),i.insertBefore(this.element,n);let o=e.checkPoints,r=o[0];for(;r.parent&&r.inline;)r=r.parent;let s,a;t&&!this.isFootnote?(s=1,a=1):(s=Math.max((r.inheritedProps.widows||2)-0,1),a=Math.max((r.inheritedProps.orphans||2)-0,1));let h=this.calculateClonedPaddingBorder(r),l=this.findLinePositions(o),c=this.footnoteEdge-h,d=this.getBoxDir(),p=this.getOffsetByRepetitiveElements(e);c-=d*p;let f=this.findFirstOverflowingEdgeAndCheckPoint(o);isNaN(f.edge)&&(f.edge=d*(1/0));let g=mi(l.length,m=>{let S=l[m];return this.vertical?S<c||S<=f.edge:S>c||S>=f.edge}),v=g<=0;v&&(g=mi(l.length,m=>this.vertical?l[m]<c:l[m]>c));let w=o[o.length-1].viewNode;if(w?.parentElement.localName==="viv-ts-inner"&&(w=w.parentElement.parentElement),(g===l.length&&w.nextSibling||g>=l.length-1&&w.parentElement.querySelector(".MJXc-display"))&&(s=0,a=1),g=Math.min(l.length-s,g),g<a)return null;c=l[g-1];let x;if(v?x=f.checkPoint:x=this.findAcceptableBreakInside(e.checkPoints,c,t),x){let m=this.getAfterEdgeOfBlockContainer(x);if(!isNaN(m)&&d*(c-m)>0&&(c=m),this.computedBlockSize=d*(c-this.beforeEdge)+p,l.length>=2){let S=Math.max(1,Math.min(g-1,l.length-1));this.lastLineStride=Math.abs(l[S]-l[S-1])}}return x}getAfterEdgeOfBlockContainer(e){let t=e;do t=t.parent;while(t&&t.inline);return t?(t=t.copy().modify(),t.after=!0,bn(t,this.clientLayout,0,this.vertical)):NaN}findFirstOverflowingEdgeAndCheckPoint(e){let t=e.findIndex(n=>n.overflow);if(t<0)return{edge:NaN,checkPoint:null};let i=e[t];return{edge:this.calculateEdge(null,e,t,i.boxOffset),checkPoint:i}}findEdgeBreakPosition(e){return this.computedBlockSize=e.computedBlockSize+this.getOffsetByRepetitiveElements(e),e.position}finishBreak(e,t,i){e.formattingContext;let n=new io().find(e.formattingContext).finishBreak(this,e,t,i);return n||(n=Xl.finishBreak(this,e,t,i)),n}findAcceptableBreakPosition(){let e=null,t=null,i=0,n=0;do{i=n,n=Number.MAX_VALUE;for(let o=this.breakPositions.length-1;o>=0&&!t;--o){e=this.breakPositions[o],t=e.findAcceptableBreak(this,i);let r=e.getMinBreakPenalty();r>i&&(n=Math.min(n,r))}}while(n>i&&!t&&this.forceNonfitting);return{breakPosition:t?e:null,nodeContext:t}}doFinishBreak(e,t,i,n){if(this.pageFloatLayoutContext.isInvalidated()||this.pageBreakType||!t)return T(e);let o=M("doFinishBreak"),r=!1;if(!e){if(this.forceNonfitting&&!this.isFootnote)return Y.warn("Could not find any page breaks?!!"),this.skipTailEdges(t).then(s=>{s?(s=s.modify(),s.overflow=!1,this.finishBreak(s,r,!0).then(()=>{o.finish(s)})):o.finish(s)}),o.result();e=i,r=!0,this.computedBlockSize=n}return this.finishBreak(e,r,!0).then(()=>{o.finish(e)}),o.result()}isBreakable(e){for(let t=e;t;t=t.parent)if(Ot(t.viewNode))return!1;return e.after?!0:e.sourceNode.namespaceURI==="http://www.w3.org/2000/svg"?!1:!e.flexContainer}isZeroLength(e){let t=e.trim();return t===""||/^0+(?:\.0+)?(?:[a-z%]*)$/i.test(t)}hasNonZeroBlockStartInset(e){return this.vertical?!(this.isZeroLength(e.paddingRight)&&this.isZeroLength(e.borderRightWidth)):!(this.isZeroLength(e.paddingTop)&&this.isZeroLength(e.borderTopWidth))}hasNonZeroBlockEndInset(e){return this.vertical?!(this.isZeroLength(e.paddingLeft)&&this.isZeroLength(e.borderLeftWidth)):!(this.isZeroLength(e.paddingBottom)&&this.isZeroLength(e.borderBottomWidth))}suppressOpenAncestorBlockEndInset(e){if(!rs(this))return()=>{};let t=[];for(let i=e?.parent;i;i=i.parent){if(i.after||i.inline)continue;let n=i.viewNode;if(!n||n.nodeType!==1||Nn(n))continue;let o=this.clientLayout.getElementComputedStyle(n);if(o&&!this.hasNonZeroBlockEndInset(o))continue;let r=n.getAttribute("data-viv-box-break");Ct(n,"block-end"),t.push({element:n,original:r})}return()=>{for(let{element:i,original:n}of t)n===null?i.removeAttribute("data-viv-box-break"):i.setAttribute("data-viv-box-break",n)}}checkOverflowAndSaveEdge(e,t){if(!e)return!1;for(let s=e;s;s=s.parent)if(Ot(s.viewNode))return!1;if(En(e.viewNode))return!1;let i=this.suppressOpenAncestorBlockEndInset(e),n=bn(e,this.clientLayout,0,this.vertical);i();let o=Ln(e,this.collectElementsOffset()),r=this.isOverflown(n+(this.vertical?-1:1)*o.minimum);if(this.isOverflown(n+(this.vertical?-1:1)*o.current)&&!this.nodeContextOverflowingDueToRepetitiveElements)this.nodeContextOverflowingDueToRepetitiveElements=e;else if(t){let s=n+this.getTrailingMarginEdgeAdjustment(t),a=this.footnoteEdge-this.getBoxDir()*o.current;n=this.vertical?Math.min(n,Math.max(s,a)):Math.max(n,Math.min(s,a))}return this.updateMaxReachedAfterEdge(n),r}checkOverflowAndSaveEdgeAndBreakPosition(e,t,i,n){if(!e||En(e.viewNode))return!1;let o=this.checkOverflowAndSaveEdge(e,t);return(i||!o)&&this.saveEdgeBreakPosition(e,n,o),o}applyClearance(e){if(!e.viewNode.parentNode||e.floatReference!==Pe.INLINE||e.floatSide)return!1;let t=e.clearSide==="same"?e.floatSide:e.clearSide,i=/^(page|column|region)$/.test(t),n=this.getComputedMargin(e.viewNode),o=e.viewNode.ownerDocument.createElement("div");this.vertical?(o.style.bottom="0px",o.style.width="1px",o.style.marginRight=`${n.right}px`):(o.style.right="0px",o.style.height="1px",o.style.marginTop=`${n.top}px`);let r=()=>i?this.clientLayout.getElementClientRect(o):Bt(this.clientLayout,o,this.vertical);e.viewNode.parentNode.insertBefore(o,e.viewNode);let s=r(),a=this.getBeforeEdge(s),h=this.getBoxDir(),l=/^(top|bottom|inside|outside|(block|inline)-(start|end))$/.test(t)?aa(t,e.vertical,e.direction,this.layoutContext.page.side):t,c=l==="left"||l==="right"?e.direction==="rtl"==(l==="left")?"inline-end":"inline-start":l,d=this.pageFloatLayoutContext.getPageFloatClearEdge(c,this),p=d;switch(l){case"left":d=h*Math.max(d*h,this.leftFloatEdge*h);break;case"right":d=h*Math.max(d*h,this.rightFloatEdge*h);break;default:d=h*Math.max(d*h,Math.max(this.rightFloatEdge*h,this.leftFloatEdge*h))}let f=this.getFloatLayoutUnit(),g=this.leftFloatEdge*h>this.beforeEdge*h||this.rightFloatEdge*h>this.beforeEdge*h;if(f>0&&g){let w=d*h>p*h;d=h*(Math.ceil(d*h/f)+(w?1:0))*f}let v=this.getFloatLayoutTolerance(f);if(a*h+v>d*h)return e.viewNode.parentNode.removeChild(o),!1;{let w=Math.max(1,(d-a)*h);this.vertical?o.style.width=`${w}px`:o.style.height=`${w}px`,s=r();let x=this.getAfterEdge(s);if(!e.floatSide)if(this.vertical){let m=x-n.right-d;m>0==n.right>=0&&(m+=n.right),o.style.marginLeft=`${m}px`}else{let m=d-(x+n.top);m>0==n.top>=0&&(m+=n.top),o.style.marginBottom=`${m}px`}return e.clearSpacer=o,!0}}isBFC(e){return!!(hw(e)||Yi.isInstanceOfRepetitiveElementsOwnerFormattingContext(e))}hasFixedPositionAncestor(e){for(let t=e;t;t=t.parent)if(ru(t.viewNode))return!0;return!1}skipEdges(e,t,i){var n;let o=e.after?(n=e.parent)==null?void 0:n.formattingContext:e.formattingContext;if(o&&!this.isBFC(o))return T(e);let r=M("skipEdges"),s=this,a=!i&&t&&e&&e.after,h=i,l=null,c=[],d=[],p=!1;function f(C){var P,L;if(!(!t||s.isNonFirstColumn||i||!au(h))){for(let A=C;A;A=A.parent)if(A.breakBefore==="column"&&(A.breakBefore=null),((P=A.viewNode)==null?void 0:P.nodeType)===1){let z=A.viewNode;((L=z.style)==null?void 0:L.breakBefore)==="column"&&(z.style.breakBefore="")}}}function g(C){var P,L;if(!(!t||!s.isNonFirstColumn||i||h!=="column")){for(let A=C;A;A=A.parent)if(A.breakBefore==="column"&&(A.breakBefore=null),((P=A.viewNode)==null?void 0:P.nodeType)===1){let z=A.viewNode;((L=z.style)==null?void 0:L.breakBefore)==="column"&&(z.style.breakBefore="")}h=null}}function v(C){var P,L;if(!(i||!au(h))){for(let A=C;A;A=A.parent)if(A.breakAfter==="column"&&(A.breakAfter=null),((P=A.viewNode)==null?void 0:P.nodeType)===1){let z=A.viewNode;((L=z.style)==null?void 0:L.breakAfter)==="column"&&(z.style.breakAfter="")}}}function w(C){h=nt(h,C)}function x(){return i?!0:Ze(h)?t?s.isNonFirstColumn&&h!=="column"&&h!=="region":!m()&&!S():!1}function m(){var C;if(!l||!e||e.floatSide)return!1;for(let P=l;P!=null&&P.parent;P=P.parent){if(P.parent.viewNode&&Ot(P.parent.viewNode))continue;let L=P.after?P.viewNode:(C=P.viewNode)==null?void 0:C.previousSibling;for(;L&&(Ee(L,P.parent.whitespace)||Ot(L));)L=L.previousSibling;if(L)return!1}return!0}function S(){var C,P;if(l||!(e!=null&&e.viewNode)||e.shadowContext||e.after||e.floatSide||!((C=e.parent)!=null&&C.viewNode)||Ot(e.parent.viewNode))return!1;let L=!1;for(let A=e;A!=null&&A.parent&&!A.after;A=A.parent){if(A!==e&&Ot(A.viewNode))return!1;let z=(P=A.viewNode)==null?void 0:P.previousSibling;for(;z&&(Ee(z,A.parent.whitespace)||Ot(z));)Ot(z)&&(L=!0),z=z.previousSibling;if(z)return!1}return L}let b=()=>{e=c[0]||e,e.viewNode.parentNode.removeChild(e.viewNode),this.pageBreakType=h};return r.loopWithFrame(C=>{for(var P;e;){e.formattingContext;let L=new io().find(e.formattingContext);do{if(!e.viewNode)break;if(e.inline&&e.viewNode.nodeType!=1){if(Ee(e.viewNode,e.whitespace)||this.hasFixedPositionAncestor(e))break;if(!e.after){w(e.breakBefore),f(e),g(e),x()?b():this.checkOverflowAndSaveEdgeAndBreakPosition(l,null,!0,h)?(e=(this.stopAtOverflow&&l||e).modify(),e.overflow=!0):(!l&&!t&&c.length===0&&this.saveEdgeBreakPosition(e,h,!1),e=e.modify(),e.breakBefore=h),C.breakLoop();return}}if(!e.after){if(e.floatSide&&(this.breakAtTheEdgeBeforeFloat=as(h)?h:null),L&&L.startNonInlineElementNode(e))break;if(e.clearSide&&this.applyClearance(e)&&t&&this.breakPositions.length===0&&this.saveEdgeBreakPosition(e.copy(),h,!1),!e.inline&&!e.repeatOnBreak&&(l?su(l):this.breakPositions[this.breakPositions.length-1]instanceof go||!t&&c.length===0)&&this.saveEdgeBreakPosition(e.copy(),h,!1),!this.isBFC(e.formattingContext)||Yi.isInstanceOfRepetitiveElementsOwnerFormattingContext(e.formattingContext)||this.isFloatNodeContext(e)||e.flexContainer||!e.nodeShadow&&!e.sourceNode.firstElementChild&&Ee(e.sourceNode.firstChild,e.whitespace)){c.push(e.copy()),w(e.breakBefore),f(e),g(e),x()?b():(this.checkOverflowAndSaveEdgeAndBreakPosition(l,null,!0,h)||!this.layoutConstraint.allowLayout(e))&&(e=(this.stopAtOverflow&&l||e).modify(),e.overflow=!0),C.breakLoop();return}}if(e.viewNode.nodeType!=1)break;let z=e.viewNode,U=z.style;if(e.after){$d(z,this),e.floatSide&&(h=h??this.breakAtTheEdgeBeforeFloat,this.breakAtTheEdgeBeforeFloat=null);let X=e.sourceNode;if(X.localName==="svg"||X.localName==="math"||X.getAttribute("data-math-typeset")==="true"){p=!1,l=e.copy(),d.push(l),h=null,w(e.breakAfter),v(e),this.checkOverflowAndSaveEdgeAndBreakPosition(l,null,!this.stopAtOverflow,h);break}if(e.inline||L&&L.afterNonInlineElementNode(e,this.stopAtOverflow))break;if(p){if(ru(e.viewNode))break;if(x()){b(),C.breakLoop();return}c=[],t=!1,a=!1,h=null}p=!1,Wd(e.viewNode)||(l=e.copy(),d.push(l)),w(e.breakAfter),v(e),U&&!Ot(e.viewNode)&&this.hasNonZeroBlockEndInset(U)&&(d=l?[l]:[])}else{if(c.push(e.copy()),w(e.breakBefore),f(e),g(e),l&&Ze(h)&&fv(l.viewNode,e.viewNode),(e.pageType!=((P=e.parent)==null?void 0:P.pageType)||!Ze(h))&&!this.layoutConstraint.allowLayout(e)&&(this.checkOverflowAndSaveEdgeAndBreakPosition(l,null,!this.stopAtOverflow,h),e=e.modify(),e.overflow=!0,this.stopAtOverflow)){C.breakLoop();return}let X=e.viewNode.localName;if(ji[X]){x()?b():this.checkOverflowAndSaveEdgeAndBreakPosition(l,null,!0,h)&&(e=(this.stopAtOverflow&&l||e).modify(),e.overflow=!0),C.breakLoop();return}U&&this.hasNonZeroBlockStartInset(U)&&(a=!1,d=[]),p=!0}}while(!1);let A=this.nextInTree(e,a);if(A.isPending()){A.then(z=>{e=z,C.continueLoop()});return}else e=A.get()}this.checkOverflowAndSaveEdgeAndBreakPosition(l,d,!this.stopAtOverflow,h)?l&&this.stopAtOverflow&&(e=l.modify(),e.overflow=!0):Ze(h)&&(this.pageBreakType=h),C.breakLoop()}).then(()=>{l&&(this.lastAfterPosition=l.toNodePosition()),r.finish(e)}),r.result()}skipTailEdges(e){let t=e.copy(),i=M("skipEdges"),n=null,o=!1;return i.loopWithFrame(r=>{for(;e;){do{if(!e.viewNode)break;if(e.inline&&e.viewNode.nodeType!=1){if(Ee(e.viewNode,e.whitespace))break;if(!e.after){Ze(n)&&(this.pageBreakType=n),r.breakLoop();return}}if(!e.after&&(this.isFloatNodeContext(e)||e.flexContainer)){n=nt(n,e.breakBefore),Ze(n)&&(this.pageBreakType=n),r.breakLoop();return}if(e.viewNode.nodeType!=1)break;let a=e.viewNode.style;if(e.after){if(o){if(Ze(n)){this.pageBreakType=n,r.breakLoop();return}n=null}o=!1,n=nt(n,e.breakAfter)}else{n=nt(n,e.breakBefore);let h=e.viewNode.localName;if(ji[h]){Ze(n)&&(this.pageBreakType=n),r.breakLoop();return}if(a&&this.hasNonZeroBlockStartInset(a)){r.breakLoop();return}}o=!0}while(!1);let s=this.layoutContext.nextInTree(e);if(s.isPending()){s.then(a=>{e=a,r.continueLoop()});return}else e=s.get()}t=null,r.breakLoop()}).then(()=>{i.finish(t)}),i.result()}layoutFloatOrFootnote(e){if(Ii(e.floatReference)||e.floatSide==="footnote"){let t=this.pageFloatLayoutContext.generatingNodePosition;if(t&&e.sourceNode===t.steps[0].node){let i=e.modify();return i.floatSide=null,i.floatReference=Pe.INLINE,i.clearSide=null,this.isBreakable(i)?this.layoutBreakableBlock(i):this.layoutUnbreakable(i)}return this.layoutPageFloat(e)}else return this.layoutFloat(e)}layoutNext(e,t,i){let n=M("layoutNext");return this.skipEdges(e,t,i||null).then(o=>{if(e=o,!e||this.pageBreakType||this.stopByOverflow(e))n.finish(e);else{let r=e.formattingContext;new io().find(r).layout(e,this,t).thenFinish(n)}}),n.result()}clearOverflownViewNodes(e,t){if(e)for(let i=e.parent;e;e=i,i=i?i.parent:null){let n=(i||e).formattingContext;new io().find(n).clearOverflownViewNodes(this,i,e,t),t=!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 t=this.clientLayout.getElementClientRect(e);this.element.removeChild(e);let i=this.originX+this.left+this.getInsetLeft(),n=this.originY+this.top+this.getInsetTop();this.box=new Mt(i,n,i+this.width,n+this.height),this.startEdge=t?this.vertical?this.rtl?t.bottom:t.top:this.rtl?t.right:t.left:0,this.endEdge=t?this.vertical?this.rtl?t.top:t.bottom:this.rtl?t.left:t.right:0,this.beforeEdge=t?this.vertical?t.right:t.top:0,this.afterEdge=t?this.vertical?t.left:t.bottom:0,this.leftFloatEdge=this.beforeEdge,this.rightFloatEdge=this.beforeEdge,this.bottommostFloatTop=this.beforeEdge,this.footnoteEdge=this.afterEdge,this.bands=Mm(this.box,[this.getInnerShape()],this.getExclusions(),8,this.snapHeight,this.vertical),this.createFloats()}init(){this.chunkPositions=[],I(this.element,"width",`${this.width}px`),I(this.element,"height",`${this.height}px`),this.initGeom(),this.computedBlockSize=0,this.overflown=!1,this.pageBreakType=null,this.lastAfterPosition=null,this.lastLineStride=0}saveEdgeBreakPosition(e,t,i){e.formattingContext;let n=e.copy(),o=new io().find(e.formattingContext),r=this.calculateClonedPaddingBorder(n),s=o.createEdgeBreakPosition(n,t,i,this.computedBlockSize+r);this.breakPositions.push(s)}saveBoxBreakPosition(e){let t=e[0].breakPenalty;if(t){let n=e[0];for(;n.parent&&n.inline;)n=n.parent;t=n.breakPenalty}let i=new go(e,t);this.breakPositions.push(i)}updateMaxReachedAfterEdge(e){if(!isNaN(e)){let t=this.getBoxDir()*(e-this.beforeEdge);this.computedBlockSize=Math.max(t,this.computedBlockSize)}}layout(e,t,i){if(this.chunkPositions.push(e),e.primary.after&&(this.lastAfterPosition=e.primary),this.stopAtOverflow&&this.overflown)return T(e);if(this.isFullWithPageFloats())return e.primary.after&&e.primary.steps.length===1?T(null):T(e);_l(this);let n=M("layout");return this.openAllViews(e.primary).then(o=>{let r=null;if(o.viewNode)r=o.copy();else{let a=h=>{h.nodeContext.viewNode&&(r=h.nodeContext,this.layoutContext.removeEventListener("nextInTree",a))};this.layoutContext.addEventListener("nextInTree",a)}let s=new R0(t,i);s.layout(o,this).then(a=>{this.doFinishBreak(a,s.context.overflownNodeContext,r,s.initialComputedBlockSize).then(h=>{let l=null;this.pseudoParent?l=T(null):l=this.doFinishBreakOfFragmentLayoutConstraints(h),l.then(()=>{if(rs(this)&&(yv(this),_s(this)),this.element.hasAttribute("data-vivliostyle-column-block-size-adjusted")&&(this.vertical?(I(this.element,"width",`${this.width}px`),I(this.element,"left",`${this.left}px`)):I(this.element,"height",`${this.height}px`),this.element.removeAttribute("data-vivliostyle-column-block-size-adjusted")),this.pageFloatLayoutContext.isInvalidated()){n.finish(null);return}if(!h)n.finish(null);else{this.overflown=!0;let c=new Bi(h.toNodePosition());n.finish(c)}})})})}),n.result()}isFullWithPageFloats(){return this.pageFloatLayoutContext.isColumnFullWithPageFloats(this)}getMaxBlockSizeOfPageFloats(){return this.pageFloatLayoutContext.getMaxBlockSizeOfPageFloats()}doFinishBreakOfFragmentLayoutConstraints(e){let t=M("doFinishBreakOfFragmentLayoutConstraints"),i=[].concat(this.fragmentLayoutConstraints);i.sort((o,r)=>o.getPriorityOfFinishBreak()-r.getPriorityOfFinishBreak());let n=0;return t.loop(()=>n<i.length?i[n++].finishBreak(e,this).thenReturn(!0):T(!1)).then(()=>{t.finish(!0)}),t.result()}doLayout(e,t,i){let n=M("doLayout"),o=null;return this.breakPositions=[],this.nodeContextOverflowingDueToRepetitiveElements=null,n.loopWithFrame(r=>{for(;e;){let s=!0;if(this.layoutNext(e,t,i||null).then(a=>{if(t=!1,i=null,this.nodeContextOverflowingDueToRepetitiveElements&&this.stopAtOverflow?(this.pageBreakType=null,e=this.nodeContextOverflowingDueToRepetitiveElements,e.overflow=!0):e=a,this.pageFloatLayoutContext.isInvalidated())r.breakLoop();else if(this.pageBreakType)r.breakLoop();else if(e&&this.stopByOverflow(e)){o=e;let h=this.findAcceptableBreakPosition();e=h.nodeContext,h.breakPosition&&h.breakPosition.breakPositionChosen(this),r.breakLoop()}else s?s=!1:r.continueLoop()}),s){s=!1;return}}this.computedBlockSize+=this.getOffsetByRepetitiveElements(),r.breakLoop()}).then(()=>{n.finish({nodeContext:e,overflownNodeContext:o})}),n.result()}redoLayout(){let e=this.chunkPositions,t=this.element.lastChild;for(;t!=this.last;){let s=t.previousSibling;this.element===t.parentNode&&this.layoutContext.isPseudoelement(t)||this.element.removeChild(t),t=s}this.killFloats(),this.init();let i=M("redoLayout"),n=0,o=null,r=!0;return i.loopWithFrame(s=>{if(n<e.length){let a=e[n++];this.layout(a,r).then(h=>{r=!1,h?(o=h,s.breakLoop()):s.continueLoop()});return}s.breakLoop()}).then(()=>{i.finish(o)}),i.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 t=this;t;t=t.pseudoParent)t.fragmentLayoutConstraints.forEach(i=>{if(Yi.isInstanceOfRepetitiveElementsOwnerLayoutConstraint(i)){let n=i.getRepetitiveElements();e.push(n)}if(ls.isInstanceOfAfterIfContinuesLayoutConstraint(i)){let n=i.getRepetitiveElements();e.push(n)}Li.isInstanceOfTableRowLayoutConstraint(i)&&i.getElementsOffsetsForTableCell(this).forEach(n=>{e.push(n)})});return e}},uh=class{constructor(e,t,i){u(this,"startNodeContexts",[]),u(this,"column"),u(this,"flowRootSourceNode"),this.flowRootSourceNode=i.sourceNode,this.column=Object.create(e),this.column.element=t,this.column.layoutContext=e.layoutContext.clone(),this.column.stopAtOverflow=!1,this.column.flowRootFormattingContext=i.formattingContext,this.column.pseudoParent=e;let n=this.column.calculateClonedPaddingBorder(i);this.column.footnoteEdge=this.column.footnoteEdge-n;let o=this;this.column.openAllViews=function(r){return Cs.prototype.openAllViews.call(this,r).thenAsync(s=>(o.startNodeContexts.push(s.copy()),T(s)))}}layout(e,t){return this.column.layout(e,t)}findAcceptableBreakPosition(e){let t=this.column.findAcceptableBreakPosition();if(e){let i=this.startNodeContexts[0].copy(),n=new ir(i,null,i.overflow,0);if(n.findAcceptableBreak(this.column,0),!t.nodeContext)return{breakPosition:n,nodeContext:i}}return t}finishBreak(e,t,i){return this.column.finishBreak(e,t,i)}doFinishBreakOfFragmentLayoutConstraints(e){this.column.doFinishBreakOfFragmentLayoutConstraints(e)}isStartNodeContext(e){let t=this.startNodeContexts[0];return t.viewNode===e.viewNode&&t.after===e.after&&t.offsetInNode===e.offsetInNode}isLastAfterNodeContext(e){return Oi(e.toNodePosition(),this.column.lastAfterPosition)||this.isEffectivelyLastAfterNodeContext(e)}isEffectivelyLastAfterNodeContext(e){var t;let i=this.flowRootSourceNode,n=e.sourceNode;if(!i||!n||!e.after||i!==n&&!((t=i.contains)!=null&&t.call(i,n)))return!1;if(n.nodeType===Node.TEXT_NODE){let o=n;if(e.offsetInNode<o.length){let r=o.data.slice(e.offsetInNode);if(!tp(r,e.whitespace))return!1}}for(let o=n;o&&o!==i;o=o.parentNode)for(let r=o.nextSibling;r;r=r.nextSibling)if(!Ee(r,e.whitespace))return!1;return!0}getColumnElement(){return this.column.element}getColumn(){return this.column}},ks=class{breakTextNode(e,t,i,n,o,r){if(t.after)t.offsetInNode=e.length;else{let s=i-t.boxOffset,a=e.data;a.charCodeAt(s)==173?s=this.breakAfterSoftHyphen(e,a,s,t):s=this.breakAfterOtherCharacter(e,a,s,t),s>0&&(t=this.updateNodeContext(t,s,e))}return t}breakAfterSoftHyphen(e,t,i,n){let o=/[\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(t.slice(0,i))?"\u200D":"";if(e.replaceData(i,t.length-i,n.breakWord?"":o+_u(n)),o){let r=n.preprocessedTextContent[0][1];n.preprocessedTextContent[0][1]=r.slice(0,i+1)+o+r.slice(i+1)}return i+1}breakAfterOtherCharacter(e,t,i,n){let o=t.charAt(i);i++;let r=t.charAt(i);return e.replaceData(i,t.length-i,!n.breakWord&&Ih(o)&&Ih(r)?_u(n):""),i}updateNodeContext(e,t,i){return e=e.modify(),e.offsetInNode+=t,e.breakBefore=null,e}};u(ks,"instance");ks.instance=new ks;function _u(e){return e.hyphenateCharacter||e.parent&&e.parent.hyphenateCharacter||"-"}var R0=class extends ql{constructor(e,t){super(),u(this,"leadingEdge",e),u(this,"breakAfter"),u(this,"initialPageBreakType",null),u(this,"initialComputedBlockSize",0),u(this,"initialOverflown",!1),u(this,"initialLastLineStride",0),u(this,"context",{overflownNodeContext:null}),this.breakAfter=t||null}resolveLayoutMode(e){return new L0(this.leadingEdge,this.breakAfter,this.context)}prepareLayout(e,t){t.fragmentLayoutConstraints=[],t.pseudoParent||cw()}clearNodes(e){super.clearNodes(e);let t=e;for(;t;){let i=t.viewNode;i&&Hd(i.parentNode,i),t=t.parent}}saveState(e,t){super.saveState(e,t),this.initialPageBreakType=t.pageBreakType,this.initialComputedBlockSize=t.computedBlockSize,this.initialOverflown=t.overflown,this.initialLastLineStride=t.lastLineStride}restoreState(e,t){super.restoreState(e,t),t.pageBreakType=this.initialPageBreakType,t.computedBlockSize=this.initialComputedBlockSize,t.overflown=this.initialOverflown,t.lastLineStride=this.initialLastLineStride}},L0=class{constructor(e,t,i){u(this,"leadingEdge",e),u(this,"breakAfter",t),u(this,"context",i)}doLayout(e,t){let i=M("DefaultLayoutMode.doLayout");return A0(e,t).then(()=>{t.doLayout(e,this.leadingEdge,this.breakAfter).then(n=>{this.context.overflownNodeContext=n.overflownNodeContext,i.finish(n.nodeContext)})}),i.result()}accept(e,t){return t.pageFloatLayoutContext.isInvalidated()||t.pageBreakType||t.fragmentLayoutConstraints.length<=0?!0:t.fragmentLayoutConstraints.every(i=>i.allowLayout(e,this.context.overflownNodeContext,t))}postLayout(e,t,i,n){return n||(n=!i.fragmentLayoutConstraints.some(o=>o.nextCandidate(e))),i.fragmentLayoutConstraints.forEach(o=>{o.postLayout(n,e,t,i)}),n}},O0=class extends Cs{constructor(e,t,i,n,o,r,s){super(t,i,n,o,r),u(this,"floatSide",e),u(this,"parentContainer",s),u(this,"rootViewNodes",[]),u(this,"floatMargins",[]),u(this,"adjustContentRelativeSize",!0),u(this,"parentElement"),this.parentElement=s.element}openAllViews(e){return super.openAllViews(e).thenAsync(t=>(t&&this.fixFloatSizeAndPosition(t),T(t)))}convertPercentageSizesToPx(e){let t=this.parentContainer.getPaddingRect(),i=t.x2-t.x1,n=t.y2-t.y1;function o(r,s){r.forEach(a=>{let h=ki(e,a);if(h&&h.charAt(h.length-1)==="%"){let l=parseFloat(h),c=s*l/100;I(e,a,`${c}px`)}})}o(["width","max-width","min-width"],i),o(["height","max-height","min-height"],n),o(["margin-top","margin-right","margin-bottom","margin-left","padding-top","padding-right","padding-bottom","padding-left"],this.vertical?n:i),["margin-top","margin-right","margin-bottom","margin-left"].forEach(r=>{ki(e,r)==="auto"&&I(e,r,"0")})}fixFloatSizeAndPosition(e){for(;e.parent;)e=e.parent;e.viewNode.nodeType;let t=e.viewNode;if(this.rootViewNodes.push(t),this.adjustContentRelativeSize&&this.convertPercentageSizesToPx(t),this.floatMargins.push(this.getComputedMargin(t)),this.adjustContentRelativeSize){let i=this.floatSide;if(this.parentContainer.vertical){if(i==="block-end"||i==="left"){let n=ki(t,"height");n!==""&&n!=="auto"&&I(t,"margin-top","auto")}}else if(i==="block-end"||i==="bottom"){let n=ki(t,"width");n!==""&&n!=="auto"&&I(t,"margin-left","auto")}}}getRootViewNodeCount(){return this.rootViewNodes.length}hasNonPseudoTextContentAfter(e){let t=i=>{var n;return i.nodeType===Node.TEXT_NODE?!!((n=i.textContent)!=null&&n.trim()):i.nodeType!==Node.ELEMENT_NODE||Yt(i)?!1:Array.from(i.childNodes).some(t)};return this.rootViewNodes.slice(e).some(t)}appendContentFrom(e){e.rootViewNodes.forEach(t=>{this.element.appendChild(t)}),this.rootViewNodes.push(...e.rootViewNodes),this.floatMargins.push(...e.floatMargins),e.rootViewNodes.splice(0),e.floatMargins.splice(0),e.element.parentNode&&e.element.parentNode.removeChild(e.element),this.applyCompactFootnoteDisplay(),this.updateComputedBlockSizeForFootnoteArea(!0)}removeContentAfter(e){let t=this.rootViewNodes.splice(e);this.floatMargins.splice(e),t.forEach(i=>{i.parentNode&&i.parentNode.removeChild(i)}),this.applyCompactFootnoteDisplay(),this.updateComputedBlockSizeForFootnoteArea(!0)}getContentInlineSize(){return Math.max.apply(null,this.rootViewNodes.map((e,t)=>{let i=Bt(this.clientLayout,e,this.vertical),n=this.floatMargins[t];return this.vertical?n.top+i.height+n.bottom:n.left+i.width+n.right}))}getContentBlockMarginAfter(){return this.rootViewNodes.length===0?0:Math.max.apply(null,this.rootViewNodes.map((e,t)=>{let i=this.floatMargins[t];return this.vertical?i.left:i.bottom}))}applyCompactFootnoteDisplay(){let e=this.layoutContext,t=e?.styler,i=e?.xmldoc,n=this.rootViewNodes.filter(h=>{var l,c,d,p;let f=(l=h.ownerDocument.defaultView)==null?void 0:l.getComputedStyle(h);if((f?.getPropertyValue("--viv-footnote-display").trim()||"")==="compact")return!(f?.display==="list-item"&&f.getPropertyValue("list-style-position").trim()==="outside");let g=h.getAttribute(Ht);if(!g||!t||!i)return!1;let v=i.getNodeByOffset(parseInt(g,10));if(!v||v.nodeType!==Node.ELEMENT_NODE)return!1;let w=t.getStyle(v,!1),x=(d=(c=ve(w,"footnote-display"))==null?void 0:c.value)==null?void 0:d.toString(),m=!!((p=ve(w,"--viv-marker-content"))!=null&&p.value);return x==="compact"&&!m});if(n.length===0){this.updateInlineFootnoteSeparators(),this.updateComputedBlockSizeForFootnoteArea(!0);return}let o=this.element.getBoundingClientRect(),r=this.vertical?o.height:o.width;n.forEach(h=>{I(h,"display","inline"),h.style.setProperty("--viv-footnote-white-space","nowrap")});let s=1.5/(this.clientLayout.pixelRatio||1),a=h=>{let l=h.cloneNode(!0);I(l,"display","inline-block"),I(l,"position","absolute"),I(l,"visibility","hidden"),I(l,"white-space","nowrap"),I(l,"max-width","none"),I(l,"left","0"),I(l,"top","0"),this.element.appendChild(l);let c=l.getBoundingClientRect();return this.element.removeChild(l),this.vertical?c.height:c.width};n.forEach(h=>{a(h)>r+s&&(I(h,"display","block"),h.style.removeProperty("--viv-footnote-white-space"))}),this.updateInlineFootnoteSeparators(),this.updateComputedBlockSizeForFootnoteArea(!0)}updateComputedBlockSizeForFootnoteArea(e=!1){if(this.rootViewNodes.length===0){this.computedBlockSize=0;return}let t=this.getBoxDir(),i=this.beforeEdge;if(e){let n=Bt(this.clientLayout,this.element,this.vertical),o=this.vertical?this.borderRight+this.paddingRight:this.borderTop+this.paddingTop;i=this.getBeforeEdge(n)+t*o}this.computedBlockSize=Math.max(0,...this.rootViewNodes.map(n=>{let o=Bt(this.clientLayout,n,this.vertical),r=this.getComputedMargin(n),s=this.vertical?r.left:r.bottom;return t*(this.getAfterEdge(o)-i)+Math.max(0,s)}))}getFootnoteAfterPseudo(e){return Array.from(e.children).find(t=>Yt(t)==="after")}hasAuthorFootnoteAfterPseudo(e){let t=this.getFootnoteAfterPseudo(e);if(t&&!t.hasAttribute("data-vivliostyle-default-footnote-separator"))return!0;let i=Array.from(e.children).find(o=>o instanceof Element&&Pt(o)),n=i?this.getFootnoteAfterPseudo(i):null;return!!n&&!n.hasAttribute("data-vivliostyle-default-footnote-separator")}createDefaultFootnoteAfterPseudo(e){let t=e.ownerDocument.createElement("span");Po(t,"after"),t.setAttribute("data-vivliostyle-default-footnote-separator","1"),t.style.whiteSpace="normal",t.textContent=" ",e.appendChild(t)}getFootnoteBreakOpportunity(e){let t=e.nextElementSibling;return t!=null&&t.hasAttribute("data-vivliostyle-footnote-break")?t:null}createFootnoteBreakOpportunity(e){let t=e.ownerDocument.createElement("wbr");t.setAttribute("data-vivliostyle-footnote-break","1"),e.insertAdjacentElement("afterend",t)}updateInlineFootnoteSeparators(){this.rootViewNodes.forEach((e,t)=>{var i,n;let o=e,r=(i=o.ownerDocument.defaultView)==null?void 0:i.getComputedStyle(o).display,s=this.rootViewNodes[t+1],a=(n=s?.ownerDocument.defaultView)==null?void 0:n.getComputedStyle(s).display,h=this.getFootnoteAfterPseudo(o),l=this.hasAuthorFootnoteAfterPseudo(o),c=!!(h!=null&&h.hasAttribute("data-vivliostyle-default-footnote-separator")),d=this.getFootnoteBreakOpportunity(o);if(r==="inline"&&a==="inline"){let p=!h&&!l;p&&this.createDefaultFootnoteAfterPseudo(o),!p&&!d?this.createFootnoteBreakOpportunity(o):p&&d?.remove()}else c&&h.remove(),d?.remove()})}},tn=class{constructor(e,t){u(this,"parent",e),u(this,"rootSourceNode",t),u(this,"formattingContextType","RepetitiveElementsOwner"),u(this,"isRoot",!1),u(this,"repetitiveElements",null)}getName(){return"Repetitive elements owner formatting context (RepetitiveElementsOwnerFormattingContext)"}isFirstTime(e,t){return t}getParent(){return this.parent}getRepetitiveElements(){return this.repetitiveElements}getRootViewNode(e){let t=this.getRootNodeContext(e);return t?t.viewNode:null}getRootNodeContext(e){do if(!e.belongsTo(this)&&e.sourceNode===this.rootSourceNode)return e;while(e=e.parent);return null}initializeRepetitiveElements(e){this.repetitiveElements||Ga.some(t=>t.root===this.rootSourceNode?(this.repetitiveElements=t.elements,!0):!1)||(this.repetitiveElements=new B0(e,this.rootSourceNode),Ga.push({root:this.rootSourceNode,elements:this.repetitiveElements}))}saveState(){}restoreState(e){}},B0=class{constructor(e,t){u(this,"vertical",e),u(this,"ownerSourceNode",t),u(this,"headerSourceNode",null),u(this,"footerSourceNode",null),u(this,"headerViewNode",null),u(this,"footerViewNode",null),u(this,"headerNodePosition",null),u(this,"footerNodePosition",null),u(this,"headerHeight",0),u(this,"footerHeight",0),u(this,"isSkipHeader",!1),u(this,"isSkipFooter",!1),u(this,"enableSkippingFooter",!0),u(this,"enableSkippingHeader",!0),u(this,"doneInitialLayout",!1),u(this,"firstContentSourceNode",null),u(this,"lastContentSourceNode",null),u(this,"affectedNodeCache",[]),u(this,"afterLastContentNodeCache",[]),u(this,"allowInsert",!1),u(this,"allowInsertRepeatitiveElements")}setHeaderNodeContext(e){this.headerNodePosition||(this.headerNodePosition=hs(e,0),this.headerSourceNode=e.sourceNode,this.headerViewNode=e.viewNode)}setFooterNodeContext(e){this.footerNodePosition||(this.footerNodePosition=hs(e,0),this.footerSourceNode=e.sourceNode,this.footerViewNode=e.viewNode)}updateHeight(e){this.headerViewNode&&(this.headerHeight=_a(this.headerViewNode,e,this.vertical),this.headerViewNode=null),this.footerViewNode&&(this.footerHeight=_a(this.footerViewNode,e,this.vertical),this.footerViewNode=null)}prepareLayoutFragment(){this.isSkipHeader=this.isSkipFooter=!1,this.enableSkippingFooter=!0,this.enableSkippingHeader=!0}appendHeaderToFragment(e,t,i){return!this.headerNodePosition||this.isSkipHeader?T(!0):this.appendElementToFragment(this.headerNodePosition,e,t,i)}appendFooterToFragment(e,t,i){return!this.footerNodePosition||this.isSkipFooter?T(!0):this.appendElementToFragment(this.footerNodePosition,e,t,i)}appendElementToFragment(e,t,i,n){let o=t.viewNode.ownerDocument,r=t.viewNode,s=o.createElement("div");r.appendChild(s);let a=new uh(n,s,t),h=a.getColumn().pageBreakType;return a.getColumn().pageBreakType=null,this.allowInsertRepeatitiveElements=!0,a.layout(new Bi(e),!0).thenAsync(()=>(this.allowInsertRepeatitiveElements=!1,r.removeChild(s),this.moveChildren(s,r,i),a.getColumn().pageBreakType=h,T(!0)))}moveChildren(e,t,i){if(t)for(;e.firstChild;){let n=e.firstChild;e.removeChild(n),n.setAttribute(zn,"1"),i?t.insertBefore(n,i):t.appendChild(n)}}calculateOffset(e){let t=0;return e&&!this.affectTo(e)||((!this.isSkipFooter||e&&this.isAfterLastContent(e))&&(t+=this.footerHeight),this.isSkipHeader||(t+=this.headerHeight)),t}calculateMinimumOffset(e){let t=0;return e&&!this.affectTo(e)||(!this.enableSkippingFooter&&e&&this.isAfterLastContent(e)&&(t+=this.footerHeight),this.enableSkippingHeader||(t+=this.headerHeight)),t}isAfterLastContent(e){return this.findResultFromCache(e,this.afterLastContentNodeCache,t=>this.isAfterNodeContextOf(this.lastContentSourceNode,e,!1))}affectTo(e){return this.findResultFromCache(e,this.affectedNodeCache,t=>this.isAfterNodeContextOf(this.ownerSourceNode,e,!0))}findResultFromCache(e,t,i){let n=t.filter(o=>o.nodeContext.sourceNode===e.sourceNode&&o.nodeContext.after===e.after);if(n.length>0)return n[0].result;{let o=i(e);return t.push({nodeContext:e,result:o}),o}}isAfterNodeContextOf(e,t,i){let n=[];for(let o=e;o;o=o.parentNode){if(t.sourceNode===o)return t.after;n.push(o)}for(let o=t.sourceNode;o;o=o.parentNode){let r=n.indexOf(o);if(r>=0)return i?r===0:!1;for(let s=o;s;s=s.previousElementSibling)if(n.includes(s))return!0}return t.after}isFirstContentNode(e){return e&&this.firstContentSourceNode===e.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(e){return this.headerSourceNode===e}isFooterSourceNode(e){return this.footerSourceNode===e}},Rf=class{constructor(e){u(this,"formattingContext",e)}accept(e,t){return!!e}postLayout(e,t,i,n){let o=this.formattingContext.getRepetitiveElements();return o&&(i.clientLayout,o.doneInitialLayout||(o.updateHeight(i),o.doneInitialLayout=!0)),n}},Lf=class{constructor(e){u(this,"formattingContext",e)}accept(e,t){return!0}postLayout(e,t,i,n){return n}},M0=class extends Rf{constructor(e,t){super(e),u(this,"processor",t)}doLayout(e,t){return this.processor.doInitialLayout(e,t)}accept(e,t){return!1}},_0=class extends Lf{constructor(e,t){super(e),u(this,"processor",t)}doLayout(e,t){return!e.belongsTo(this.formattingContext)&&!e.after&&t.fragmentLayoutConstraints.unshift(new ch(e)),this.processor.doLayout(e,t)}},ch=class Of{constructor(t){u(this,"flagmentLayoutConstraintType","RepetitiveElementsOwner"),u(this,"nodeContext");let i=di(t.formattingContext);this.nodeContext=i.getRootNodeContext(t)}allowLayout(t,i,n){let o=this.getRepetitiveElements();return!o||En(this.nodeContext.viewNode)||!o.isEnableToUpdateState()?!0:i&&!t||t&&t.overflow?!Mf(t,i,o):!0}nextCandidate(t){let i=this.getRepetitiveElements();return i&&i.isEnableToUpdateState()?(i.updateState(),!0):!1}postLayout(t,i,n,o){let r=this.getRepetitiveElements();r&&t&&o.stopAtOverflow&&(i==null||r.isAfterLastContent(i))&&r.preventSkippingFooter()}finishBreak(t,i){let n=di(this.nodeContext.formattingContext),o=this.getRepetitiveElements();if(!o)return T(!0);let r=this.nodeContext;return $0(n,r,i).thenAsync(()=>H0(n,r,i).thenAsync(()=>(o.prepareLayoutFragment(),T(!0))))}getRepetitiveElements(){return di(this.nodeContext.formattingContext).getRepetitiveElements()}equalsTo(t){return t instanceof Of?di(this.nodeContext.formattingContext)===di(t.nodeContext.formattingContext):!1}getPriorityOfFinishBreak(){return 10}},D0=class extends ql{constructor(e,t){super(),u(this,"formattingContext",e),u(this,"processor",t)}resolveLayoutMode(e){let t=this.formattingContext.getRepetitiveElements();return!e.belongsTo(this.formattingContext)&&!t.doneInitialLayout?new M0(this.formattingContext,this.processor):(!e.belongsTo(this.formattingContext)&&!e.after&&t&&t.preventSkippingHeader(),new _0(this.formattingContext,this.processor))}},z0=class extends xo{constructor(e,t){super(),u(this,"formattingContext",e),u(this,"column",t)}startNonInlineElementNode(e){let t=this.formattingContext,i=e.nodeContext,n=t.getRepetitiveElements();if(i.parent&&t.rootSourceNode===i.parent.sourceNode){switch(i.repeatOnBreak){case"header":if(n.isHeaderRegistered())i.repeatOnBreak="none";else return n.setHeaderNodeContext(i),T(!0);break;case"footer":if(n.isFooterRegistered())i.repeatOnBreak="none";else return n.setFooterNodeContext(i),T(!0);break}n.firstContentSourceNode||(n.firstContentSourceNode=i.sourceNode)}return xo.prototype.startNonInlineElementNode.call(this,e)}afterNonInlineElementNode(e){let t=this.formattingContext,i=e.nodeContext;return i.sourceNode===t.rootSourceNode&&(t.getRepetitiveElements().lastContentSourceNode=e.lastAfterNodeContext&&e.lastAfterNodeContext.sourceNode,e.break=!0),i.repeatOnBreak==="header"||i.repeatOnBreak==="footer"?T(!0):xo.prototype.afterNonInlineElementNode.call(this,e)}},V0=class extends Tn{layout(e,t,i){if(t.isFloatNodeContext(e))return t.layoutFloatOrFootnote(e);let n=di(e.formattingContext);return n.getRootViewNode(e)?(i&&Bf(e.parent,t),e.belongsTo(n)?Tn.prototype.layout.call(this,e,t,i):new D0(n,this).layout(e,t)):t.buildDeepElementView(e)}startNonInlineElementNode(e){let t=W0(e).getRepetitiveElements();return t&&!t.allowInsertRepeatitiveElements&&(t.isHeaderSourceNode(e.sourceNode)||t.isFooterSourceNode(e.sourceNode))&&e.viewNode.parentNode.removeChild(e.viewNode),!1}doInitialLayout(e,t){let i=di(e.formattingContext),n=M("BlockLayoutProcessor.doInitialLayout");return this.layoutEntireBlock(e,t).thenFinish(n),n.result()}layoutEntireBlock(e,t){let i=di(e.formattingContext),n=new z0(i,t);return new Wa(n,t.layoutContext).iterate(e)}doLayout(e,t){let i=di(e.formattingContext),n=M("doLayout"),o=t.layoutContext.nextInTree(e,!1);return Ff(o,t).then(r=>{let s=r;n.loopWithFrame(a=>{for(;s;){let h=!0;if(t.layoutNext(s,!1).then(l=>{s=l,t.pageFloatLayoutContext.isInvalidated()||t.pageBreakType||s&&t.stopByOverflow(s)||s&&s.after&&s.sourceNode==i.rootSourceNode?a.breakLoop():h?h=!1:a.continueLoop()}),h){h=!1;return}}a.breakLoop()}).then(()=>{n.finish(s)})}),n.result()}finishBreak(e,t,i,n){return Tn.prototype.finishBreak.call(this,e,t,i,n)}clearOverflownViewNodes(e,t,i,n){Tn.prototype.clearOverflownViewNodes(e,t,i,n)}};function U0(e,t){for(let i=e;i;i=i.parent){let n=i.formattingContext;n&&n instanceof tn&&!i.belongsTo(n)&&t(n,i)}}function Bf(e,t){e&&U0(e.after?e.parent:e,(i,n)=>{Li.isInstanceOfTableFormattingContext(i)||t.fragmentLayoutConstraints.push(new ch(n))})}function $0(e,t,i){let n=e.getRepetitiveElements();if(n){let o=e.getRootNodeContext(t);if(o.viewNode){let r=o.viewNode.firstChild;return n.appendHeaderToFragment(o,r,i)}}return T(!0)}function H0(e,t,i){let n=e.getRepetitiveElements();if(n&&!n.isSkipFooter){let o=e.getRootNodeContext(t);if(o.viewNode)return n.appendFooterToFragment(o,null,i)}return T(!0)}function Mf(e,t,i){let n=i.ownerSourceNode,o=e||t;return!o||n.contains(o.sourceNode)}function W0(e){let t=e.formattingContext;return!t||!(t instanceof tn)?null:t}function di(e){return e instanceof tn,e}var G0=new V0;Ft("RESOLVE_LAYOUT_PROCESSOR",e=>e instanceof tn&&!Li.isInstanceOfTableFormattingContext(e)?G0:null);var _f=class{constructor(e,t){u(this,"rowIndex",e),u(this,"sourceNode",t),u(this,"cells",[]),u(this,"breakBefore",null),u(this,"breakAfter",null)}addCell(e){this.cells.push(e)}getMinimumHeight(){return Math.min.apply(null,this.cells.map(e=>e.height))}},j0=class{constructor(e,t,i){u(this,"rowIndex",e),u(this,"columnIndex",t),u(this,"viewElement"),u(this,"colSpan"),u(this,"rowSpan"),u(this,"height",0),u(this,"anchorSlot",null),this.viewElement=i,this.colSpan=i.colSpan||1,this.rowSpan=i.rowSpan||1}setHeight(e){this.height=e}setAnchorSlot(e){this.anchorSlot=e}},X0=class{constructor(e,t,i){u(this,"rowIndex",e),u(this,"columnIndex",t),u(this,"cell",i)}},q0=class{constructor(e,t,i){u(this,"column",e),u(this,"cellNodeContext",i),u(this,"pseudoColumn"),u(this,"empty",!1),this.pseudoColumn=new uh(e,t,i)}findAcceptableBreakPosition(){let e=this.cellNodeContext.viewNode,{verticalAlign:t,alignContent:i}=e.style;t!=="top"&&t!=="baseline"&&I(e,"vertical-align","top"),i&&i!=="normal"&&I(e,"align-content","normal");let n=this.pseudoColumn.findAcceptableBreakPosition(!0);return I(e,"vertical-align",t),i&&i!=="normal"&&I(e,"align-content",i),n}},Y0=class{constructor(e,t){u(this,"viewNode",e),u(this,"side",t)}},Z0=class extends ir{constructor(e,t,i,n){super(e,t,i,n),u(this,"formattingContext"),u(this,"acceptableCellBreakPositions",null),u(this,"rowIndex",null),this.formattingContext=e.formattingContext}findAcceptableBreak(e,t){let i=super.findAcceptableBreak(e,t);return t<this.getMinBreakPenalty()?null:this.getAcceptableCellBreakPositions().every(n=>!!n.nodeContext)?this.hasUnfinishedCells()?null:i:null}hasUnfinishedCells(){let e=this.getRowIndex(),t=this.formattingContext.getCellsFallingOnRow(e);for(let i of t){if(i.rowIndex+i.rowSpan-1>e)continue;let n=this.formattingContext.getCellFragmentOfCell(i);if(n){let o=n.findAcceptableBreakPosition();if(o.nodeContext&&!n.pseudoColumn.isLastAfterNodeContext(o.nodeContext))return!0}}return!1}getMinBreakPenalty(){let e=super.getMinBreakPenalty();this.getAcceptableCellBreakPositions().forEach(i=>{e+=i.breakPosition.getMinBreakPenalty()});let t=this.getCellFragments();return e+=Math.max(0,...t.map(i=>i.cellNodeContext.breakPenalty)),e}getAcceptableCellBreakPositions(){if(!this.acceptableCellBreakPositions){let e=this.formattingContext,t=this.getCellFragments();this.acceptableCellBreakPositions=t.map(i=>i.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)}},K0=class extends Gl{constructor(e,t,i){super(),u(this,"rowIndex",e),u(this,"beforeNodeContext",t),u(this,"formattingContext",i),u(this,"acceptableCellBreakPositions",null)}findAcceptableBreak(e,t){if(this!==e.breakPositions[0]&&t<this.getMinBreakPenalty())return null;let i=this.getCellFragments(),n=this.getAcceptableCellBreakPositions(),o=n.every(r=>!!r.nodeContext)&&n.some((r,s)=>{let a=i[s].pseudoColumn,h=r.nodeContext;return!a.isStartNodeContext(h)&&!a.isLastAfterNodeContext(h)});return this.beforeNodeContext.overflow=n.some(r=>r.nodeContext&&r.nodeContext.overflow),o?this.beforeNodeContext:null}getMinBreakPenalty(){let e=this.formattingContext.getRowByIndex(this.rowIndex),t=this.beforeNodeContext.breakPenalty,i=this.getAcceptableCellBreakPositions(),n=this.getCellFragments();t+=Math.max(0,...n.map(r=>r.cellNodeContext.breakPenalty));let o=i.some((r,s)=>r.breakPosition instanceof go&&n[s].cellNodeContext.sourceNode.rowSpan>1);return i.forEach((r,s)=>{let a=r.breakPosition.getMinBreakPenalty();o&&r.breakPosition instanceof ir&&r.breakPosition.overflows&&a>=3&&(n[s].column.checkOverflowAndSaveEdge(r.nodeContext,null)||(a-=3)),t+=a}),t}getAcceptableCellBreakPositions(){if(!this.acceptableCellBreakPositions){let e=this.getCellFragments();this.acceptableCellBreakPositions=e.map(t=>t.findAcceptableBreakPosition())}return this.acceptableCellBreakPositions}getCellFragments(){return this.formattingContext.getCellsFallingOnRow(this.rowIndex).map(this.formattingContext.getCellFragmentOfCell,this.formattingContext)}},Bn=class extends tn{constructor(e,t){super(e,t),u(this,"tableSourceNode",t),u(this,"formattingContextType","Table"),u(this,"vertical",!1),u(this,"columnCount",-1),u(this,"tableWidth",0),u(this,"captions",[]),u(this,"colGroups",null),u(this,"colWidths",null),u(this,"inlineBorderSpacing",0),u(this,"rows",[]),u(this,"slots",[]),u(this,"cellFragments",[]),u(this,"lastRowViewNode",null),u(this,"cellBreakPositions",[]),u(this,"repetitiveElements",null)}getName(){return"Table formatting context (Table.TableFormattingContext)"}isFirstTime(e,t){var i;if(!t)return t;switch(e.display){case"table-row":{let n=this.findRowIndexBySourceNode(e.sourceNode);return this.cellBreakPositions.every(o=>this.isPreviousFragmentRowSpanningCellBreakPosition(o,n))&&e.fragmentIndex<=1}case"table-cell":return e.fragmentIndex>1||((i=e.parent)==null?void 0:i.display)==="table-row"&&e.parent.fragmentIndex>1?!1:!this.cellBreakPositions.some(n=>n.cellNodePosition.steps[0].node===e.sourceNode);default:return t}}getParent(){return this.parent}finishFragment(){this.cellFragments=[]}addRow(e,t){this.rows[e]=t}getRowSlots(e){let t=this.slots[e];return t||(t=this.slots[e]=[]),t}addCell(e,t){let i=this.rows[e];i||(this.addRow(e,new _f(e,null)),i=this.rows[e]),i.addCell(t);let n=e+t.rowSpan,o=this.getRowSlots(e),r=0;for(;o[r];)r++;for(;e<n;e++){o=this.getRowSlots(e);for(let s=r;s<r+t.colSpan;s++){let a=o[s]=new X0(e,s,t);t.anchorSlot||t.setAnchorSlot(a)}}}getRowByIndex(e){return this.rows[e]}findRowIndexBySourceNode(e){return this.rows.findIndex(t=>e===t.sourceNode)}isPreviousFragmentRowSpanningCellBreakPosition(e,t){let i=e.cell;return t>=0&&i.rowIndex<t&&i.rowIndex+i.rowSpan>t}addCellFragment(e,t,i){let n=this.cellFragments[e];n||(n=this.cellFragments[e]=[]),n[t]=i}getCellsFallingOnRow(e){return this.getRowSlots(e).reduce((t,i)=>i.cell!==t[t.length-1]?t.concat(i.cell):t,[])}getRowSpanningCellsOverflowingTheRow(e){return this.getCellsFallingOnRow(e).filter(t=>t.rowIndex+t.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((t,i)=>t+i.colSpan,0)))),this.columnCount}updateCellSizes(e){this.rows.forEach(t=>{t.cells.forEach(i=>{let n=Bt(e,i.viewElement,this.vertical);i.viewElement=null,i.setHeight(this.vertical?n.width:n.height)})})}findCellFromColumn(e){if(!e)return null;let t=null,i=0,n=0;e:for(i=0;i<this.cellFragments.length;i++)if(this.cellFragments[i]){for(n=0;n<this.cellFragments[i].length;n++)if(this.cellFragments[i][n]&&e===this.cellFragments[i][n].pseudoColumn.getColumn()){t=this.rows[i].cells[n];break e}}if(!t)return null;for(;i<this.slots.length;i++)for(;n<this.slots[i].length;n++){let o=this.slots[i][n];if(o.cell===t)return{rowIndex:o.rowIndex,columnIndex:o.columnIndex}}return null}collectElementsOffsetOfUpperCells(e){let t=[];return this.slots.reduce((i,n,o)=>{if(o>=e.rowIndex)return i;let r=n[e.columnIndex]&&this.getCellFragmentOfCell(n[e.columnIndex].cell);return!r||t.includes(r)||(this.collectElementsOffsetFromColumn(r.pseudoColumn.getColumn(),i),t.push(r)),i},[])}collectElementsOffsetOfHighestColumn(){let e=[];return this.rows.forEach(t=>{t.cells.forEach((i,n)=>{e[n]||(e[n]={collected:[],elements:[]});let o=e[n],r=this.getCellFragmentOfCell(i);!r||o.collected.includes(r)||(this.collectElementsOffsetFromColumn(r.pseudoColumn.getColumn(),o.elements),o.collected.push(r))})}),[new J0(e.map(t=>t.elements))]}collectElementsOffsetFromColumn(e,t){e.fragmentLayoutConstraints.forEach(i=>{if(Yi.isInstanceOfRepetitiveElementsOwnerLayoutConstraint(i)){let n=i.getRepetitiveElements();t.push(n)}Li.isInstanceOfTableRowLayoutConstraint(i)&&i.getElementsOffsetsForTableCell(null).forEach(n=>{t.push(n)})})}saveState(){return[].concat(this.cellBreakPositions)}restoreState(e){this.cellBreakPositions=[].concat(e)}},J0=class{constructor(e){u(this,"repeatitiveElementsInColumns",e)}calculateOffset(e){return this.calculateMaxOffsetOfColumn(e,t=>t.current)}calculateMinimumOffset(e){return this.calculateMaxOffsetOfColumn(e,t=>t.minimum)}calculateMaxOffsetOfColumn(e,t){let i=0;return this.repeatitiveElementsInColumns.forEach(n=>{let o=Ln(e,n);i=Math.max(i,t(o))}),i}};function $t(e){return e instanceof Bn,e}function Q0(e){return e==="table-row-group"||e==="table-header-group"||e==="table-footer-group"}function ex(e){return e==="table"||e==="inline-table"}function Du(e){return Q0(e)||ex(e)}function Df(e,t,i){let n=e.nodeContext,o=n.display,r=n.parent?n.parent.display:null,s=!1;if(r==="inline-table"&&!(n.formattingContext instanceof Bn)){for(let a=n.parent;a;a=a.parent)if(a.formattingContext instanceof Bn){s=a.formattingContext===t;break}}return s||o==="table-row"&&!Du(r)||o==="table-cell"&&r!=="table-row"&&!Du(r)||n.formattingContext instanceof Bn&&n.formattingContext!==t?i.buildDeepElementView(n).thenAsync(a=>(e.nodeContext=a,T(!0))):null}function zf(e,t){let i=t.nodeContext;return!(i!=null&&i.floatSide)||!(Ii(i.floatReference)||i.floatSide==="footnote")?null:e.layoutFloatOrFootnote(i).thenAsync(n=>(n&&(t.nodeContext=n),T(!0)))}var tx=class extends xo{constructor(e,t){super(),u(this,"formattingContext",e),u(this,"column",t),u(this,"rowIndex",-1),u(this,"columnIndex",0),u(this,"inRow",!1),u(this,"checkPoints",[]),u(this,"inHeaderOrFooter",!1)}startNonInlineElementNode(e){let t=this.formattingContext,i=Df(e,t,this.column);if(i)return i;this.postLayoutBlockContents(e);let n=zf(this.column,e);if(n)return n;let o=e.nodeContext,r=o.display,s=t.getRepetitiveElements();switch(r){case"table":t.inlineBorderSpacing=o.inlineBorderSpacing;break;case"table-caption":{let a=new Y0(o.viewNode,o.captionSide);t.captions.push(a);break}case"table-header-group":return s.isHeaderRegistered()||(this.inHeaderOrFooter=!0,s.setHeaderNodeContext(o)),T(!0);case"table-footer-group":return s.isFooterRegistered()||(this.inHeaderOrFooter=!0,s.setFooterNodeContext(o)),T(!0);case"table-row":this.inHeaderOrFooter||(this.inRow=!0,this.rowIndex++,o.sourceNode,this.columnIndex=0,t.addRow(this.rowIndex,new _f(this.rowIndex,o.sourceNode)),o.breakBefore&&(t.rows[this.rowIndex].breakBefore=o.breakBefore),s.firstContentSourceNode||(s.firstContentSourceNode=o.sourceNode));break}return super.startNonInlineElementNode(e)}afterNonInlineElementNode(e){let t=this.formattingContext,i=e.nodeContext,n=i.display,o=this.column.clientLayout;if(this.postLayoutBlockContents(e),i.sourceNode===t.tableSourceNode){let r=o.getElementComputedStyle(t.getRootViewNode(i));t.tableWidth=parseFloat(r[t.vertical?"height":"width"]),t.getRepetitiveElements().lastContentSourceNode=e.lastAfterNodeContext&&e.lastAfterNodeContext.sourceNode,e.break=!0}else switch(n){case"table-header-group":case"table-footer-group":if(this.inHeaderOrFooter)return this.inHeaderOrFooter=!1,T(!0);break;case"table-row":if(!this.inHeaderOrFooter){t.lastRowViewNode=i.viewNode,this.inRow=!1;let r=t.rows[this.rowIndex];r&&i.breakAfter&&(r.breakAfter=nt(r.breakAfter,i.breakAfter))}break;case"table-cell":if(!this.inHeaderOrFooter){this.inRow||(this.rowIndex++,this.columnIndex=0,this.inRow=!0);let r=i.viewNode;t.addCell(this.rowIndex,new j0(this.rowIndex,this.columnIndex,r)),this.columnIndex++,Hf(r);let s=t.rows[this.rowIndex];s&&(i.breakBefore&&(s.breakBefore=nt(s.breakBefore,i.breakBefore)),i.breakAfter&&(s.breakAfter=nt(s.breakAfter,i.breakAfter)))}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 t=e.nodeContext;t&&t.viewNode&&!Pn(t)&&this.checkPoints.push(t.clone())}postLayoutBlockContents(e){this.checkPoints.length>0&&this.column.postLayoutBlock(e.nodeContext,this.checkPoints),this.checkPoints=[]}},Vf=class Uf extends xo{constructor(t,i){super(!0),u(this,"formattingContext",t),u(this,"column",i),u(this,"inRow",!1),u(this,"currentRowIndex",-1),u(this,"currentColumnIndex",0),u(this,"originalStopAtOverflow"),u(this,"inHeader"),u(this,"inFooter"),u(this,"didExtractRowSpanningCellBreakPositions",!1),this.originalStopAtOverflow=i.stopAtOverflow,i.stopAtOverflow=!1}startNonInlineElementNode(t){return zf(this.column,t)||super.startNonInlineElementNode(t)}resetColumn(){this.column.stopAtOverflow=this.originalStopAtOverflow}getColSpanningCellWidth(t){let i=this.formattingContext.colWidths,n=0;for(let o=0;o<t.colSpan;o++)n+=i[t.anchorSlot.columnIndex+o];return n+=this.formattingContext.inlineBorderSpacing*(t.colSpan-1),n}layoutCell(t,i,n){let o=t.rowIndex,r=t.columnIndex,s=t.colSpan,a=i.viewNode;s>1&&(I(a,"box-sizing","border-box"),I(a,this.formattingContext.vertical?"height":"width",`${this.getColSpanningCellWidth(t)}px`));let h=a.ownerDocument.createElement("div");a.appendChild(h);let l=new q0(this.column,h,i);return this.formattingContext.addCellFragment(o,r,l),n.primary.steps.length===1&&n.primary.after&&(l.empty=!0),l.pseudoColumn.layout(n,!0).thenAsync(()=>(Hf(a),T(!0)))}findBrokenCellAtSlot(t,i){let n=this.formattingContext.cellBreakPositions;for(let o=0;o<n.length;o++){let r=n[o];if(r.cell.anchorSlot.columnIndex===t&&r.cellNodePosition.steps[0].node===i)return{position:r,index:o}}return null}extractRowSpanningCellBreakPositions(){if(this.didExtractRowSpanningCellBreakPositions)return[];let t=this.formattingContext.cellBreakPositions;if(t.length===0)return[];let i=[];return t.forEach(n=>{let o=n.cell,r=o.rowIndex;if(r<this.currentRowIndex&&r+o.rowSpan>this.currentRowIndex){let s=i[r];s||(s=i[r]=[]),s.push(n)}}),this.didExtractRowSpanningCellBreakPositions=i.length>0,i}layoutRowSpanningCellsFromPreviousFragment(t){let i=this.formattingContext,n=this.extractRowSpanningCellBreakPositions(),o=n.reduce(d=>d+1,0);if(o===0)return T(!0);let r=this.column.layoutContext,s=t.nodeContext;s.viewNode.parentNode.removeChild(s.viewNode);let a=M("layoutRowSpanningCellsFromPreviousFragment"),h=T(!0),l=0,c=[];return n.forEach(d=>{h=h.thenAsync(()=>{let p=us(d[0].cellNodePosition.steps[1],s.parent);return r.setCurrent(p,!1).thenAsync(()=>{let f=T(!0),g=0;function v(w){for(;g<w;){if(!c.includes(g)){let x=p.viewNode.ownerDocument.createElement("td");I(x,"padding","0"),p.viewNode.appendChild(x)}g++}}return d.forEach(w=>{f=f.thenAsync(()=>{let x=w.cell;v(x.anchorSlot.columnIndex);let m=w.cellNodePosition,S=us(m.steps[0],p);return S.offsetInNode=m.offsetInNode,S.after=m.after,S.fragmentIndex=m.steps[0].fragmentIndex+1,r.setCurrent(S,!1).thenAsync(()=>{let b=w.breakChunkPosition;for(let C=0;C<x.colSpan;C++)c.push(g+C);return g+=x.colSpan,this.layoutCell(x,S,b).thenAsync(()=>(S.viewNode.rowSpan=x.rowIndex+x.rowSpan-this.currentRowIndex+o-l,T(!0)))})})}),f.thenAsync(()=>(v(i.getColumnCount()),l++,T(!0)))})})}),h.then(()=>{r.setCurrent(s,!0,t.atUnforcedBreak).then(()=>{a.finish(!0)})}),a.result()}startTableRow(t){if(this.inHeader||this.inFooter)return T(!0);let i=t.nodeContext,n=this.formattingContext;return this.currentRowIndex<0?(i.sourceNode,this.currentRowIndex=n.findRowIndexBySourceNode(i.sourceNode)):this.currentRowIndex++,this.currentColumnIndex=0,this.inRow=!0,this.layoutRowSpanningCellsFromPreviousFragment(t).thenAsync(()=>{var o;this.registerCellFragmentIndex();let r=t.breakAtTheEdge;if(this.currentRowIndex>0){let a=n.rows[this.currentRowIndex-1];a!=null&&a.breakAfter&&(r=nt(r,a.breakAfter))}let s=n.rows[this.currentRowIndex];return s!=null&&s.breakBefore&&(r=nt(r,s.breakBefore)),!t.leadingEdge&&Ze(r)?(this.column.checkOverflowAndSaveEdgeAndBreakPosition(t.lastAfterNodeContext,null,!0,r),(o=i.viewNode)!=null&&o.parentNode&&i.viewNode.parentNode.removeChild(i.viewNode),t.lastAfterNodeContext&&this.column.layoutContext.processFragmentedBlockEdge(t.lastAfterNodeContext),this.column.pageBreakType=r,this.resetColumn(),t.break=!0,T(!0)):(this.column.checkOverflowAndSaveEdgeAndBreakPosition(t.lastAfterNodeContext,null,!0,r)&&n.getRowSpanningCellsOverflowingTheRow(this.currentRowIndex-1).length===0&&(this.resetColumn(),i.overflow=!0,t.break=!0),T(!0))})}registerCellFragmentIndex(){this.formattingContext.getRowByIndex(this.currentRowIndex).cells.forEach(t=>{let i=this.formattingContext.cellBreakPositions.find(n=>n.cell===t);if(i){let n=i.cellNodePosition.steps[0],o=this.column.layoutContext.xmldoc.getElementOffset(n.node);E0(o,n.fragmentIndex+1,1)}})}startTableCell(t){if(this.inHeader||this.inFooter)return T(!0);let i=t.nodeContext;this.inRow||(this.currentRowIndex<0?this.currentRowIndex=0:this.currentRowIndex++,this.currentColumnIndex=0,this.inRow=!0);let n=this.formattingContext.getRowByIndex(this.currentRowIndex).cells[this.currentColumnIndex];if(!n)return t.break=!0,T(!0);let o=i.copy().modify();o.after=!0,t.nodeContext=o;let r=M("startTableCell"),s,a=this.findBrokenCellAtSlot(n.anchorSlot.columnIndex,i.sourceNode);if(a){let h=a.position;this.formattingContext.cellBreakPositions.splice(a.index,1),i.fragmentIndex=h.cellNodePosition.steps[0].fragmentIndex+1,s=T(h.breakChunkPosition)}else s=this.column.nextInTree(i,t.atUnforcedBreak).thenAsync(h=>{h.viewNode&&i.viewNode.removeChild(h.viewNode);let l=hs(h,0);return T(new Bi(l))});return s.then(h=>{this.layoutCell(n,i,h).then(()=>{this.afterNonInlineElementNode(t),this.currentColumnIndex++,r.finish(!0)})}),r.result()}startNonInlineBox(t){let i=Df(t,$t(this.formattingContext),this.column);if(i)return i;let n=t.nodeContext,o=this.formattingContext.getRepetitiveElements(),r=n.display;return r==="table-header-group"&&o&&o.isHeaderSourceNode(n.sourceNode)?(this.inHeader=!0,T(!0)):r==="table-footer-group"&&o&&o.isFooterSourceNode(n.sourceNode)?(this.inFooter=!0,T(!0)):r==="table-row"?this.startTableRow(t):r==="table-cell"?this.startTableCell(t):T(!0)}endNonInlineBox(t){let i=t.nodeContext;if(i.display==="table-row"&&(this.inRow=!1,!this.inHeader&&!this.inFooter)){let n=i.copy().modify();n.after=!1;let o=new K0(this.currentRowIndex,n,this.formattingContext);this.column.breakPositions.push(o)}return T(!0)}afterNonInlineElementNode(t){let i=t.nodeContext,n=this.formattingContext.getRepetitiveElements(),o=i.display;if(o==="table-header-group"?n&&!n.allowInsertRepeatitiveElements&&n.isHeaderSourceNode(i.sourceNode)?(this.inHeader=!1,i.viewNode.parentNode.removeChild(i.viewNode)):I(i.viewNode,"display","table-row-group"):o==="table-footer-group"&&(n&&!n.allowInsertRepeatitiveElements&&n.isFooterSourceNode(i.sourceNode)?(this.inFooter=!1,i.viewNode.parentNode.removeChild(i.viewNode)):I(i.viewNode,"display","table-row-group")),o&&Uf.ignoreList[o])i.viewNode.parentNode.removeChild(i.viewNode);else if(i.sourceNode===this.formattingContext.tableSourceNode)i.overflow=this.column.checkOverflowAndSaveEdge(i,null),this.resetColumn(),t.break=!0;else if(o==="table-row"&&!this.inHeader&&!this.inFooter){let r=super.afterNonInlineElementNode(t);return(r&&r.isPending()?r:T(!0)).thenAsync(()=>{if(!t.break){let s=this.column.checkOverflowAndSaveEdge(i,null),a=this.formattingContext.getRepetitiveElements(),h=this.column.nodeContextOverflowingDueToRepetitiveElements===i,l=!s&&h&&!!(a!=null&&a.isFooterRegistered());(s||h)&&!l&&this.formattingContext.getRowSpanningCellsOverflowingTheRow(this.currentRowIndex).length===0&&(this.resetColumn(),i.overflow=!0,t.break=!0)}return T(!0)})}else return super.afterNonInlineElementNode(t);return T(!0)}};u(Vf,"ignoreList",{"table-caption":!0,"table-column-group":!0,"table-column":!0});var ix=Vf,Vo=[];function nx(e){let t=Vo.findIndex(n=>n.root===e),i=Vo[t];return i?i.tableLayoutOption:null}function ox(e){let t=Vo.findIndex(i=>i.root===e);t>=0&&Vo.splice(t,1)}var $f=class{layoutEntireTable(e,t){let i=$t(e.formattingContext),n=new tx(i,t);return new Wa(n,t.layoutContext).iterate(e)}getColumnWidths(e,t,i,n){let o=e.ownerDocument,r=o.createElement("tr"),s=[];for(let h=0;h<t;h++){let l=o.createElement("td");r.appendChild(l),s.push(l)}e.parentNode.insertBefore(r,e.nextSibling);let a=s.map(h=>{let l=Bt(n,h,i),c=i?l.height:l.width;return Math.ceil(c)});return e.parentNode.removeChild(r),a}getColGroupElements(e){let t=[],i=e.firstElementChild;for(;i;)i.localName==="colgroup"&&t.push(i),i=i.nextElementSibling;return t}normalizeAndGetColElements(e){let t=[];return e.forEach(i=>{let n=i.span;i.removeAttribute("span");let o=i.firstElementChild;for(;o;){if(o.localName==="col"){let r=o.span;for(o.removeAttribute("span"),n-=r;r-- >1;){let s=o.cloneNode(!0);i.insertBefore(s,o),t.push(s)}t.push(o)}o=o.nextElementSibling}for(;n-- >0;)o=i.ownerDocument.createElement("col"),i.appendChild(o),t.push(o)}),t}addMissingColElements(e,t,i,n){if(e.length<i){let o=n.ownerDocument.createElement("colgroup");t.push(o);for(let r=e.length;r<i;r++){let s=n.ownerDocument.createElement("col");o.appendChild(s),e.push(s)}}}normalizeColGroups(e,t,i){let n=e.vertical,o=e.lastRowViewNode;if(!o)return;e.lastRowViewNode=null;let r=o.ownerDocument.createDocumentFragment(),s=e.getColumnCount();if(!(s>0)){e.colGroups=r;return}let a=e.colWidths=this.getColumnWidths(o,s,n,i.clientLayout),h=this.getColGroupElements(t),l=this.normalizeAndGetColElements(h);this.addMissingColElements(l,h,s,t),l.forEach((c,d)=>{I(c,n?"height":"width",`${a[d]}px`)}),h.forEach(c=>{r.appendChild(c.cloneNode(!0))}),e.colGroups=r}doInitialLayout(e,t){let i=$t(e.formattingContext);i.vertical=e.vertical,i.initializeRepetitiveElements(e.vertical),e.sourceNode;let n=nx(e.sourceNode);ox(e.sourceNode);let o=M("TableLayoutProcessor.doInitialLayout"),r=e.copy();return this.layoutEntireTable(e,t).then(s=>{var a;let h=s.viewNode,l=i.rows[0];if(l&&Ze(l.breakBefore)&&this.hasInFlowContentBefore(h,t)){(a=h.parentNode)==null||a.removeChild(h),t.pageBreakType=l.breakBefore,o.finish(r);return}let c=Bt(t.clientLayout,h,t.vertical),d=t.vertical?c.left:c.bottom;if(d+=(t.vertical?-1:1)*Ln(e,t.collectElementsOffset()).current,!t.isOverflown(d)&&(!n||!n.calculateBreakPositionsInside)&&!this.hasForcedBreakInRows(i)){t.breakPositions.push(new lx(r)),o.finish(s);return}this.normalizeColGroups(i,h,t),i.updateCellSizes(t.clientLayout),o.finish(null)}),o.result()}hasForcedBreakInRows(e){for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(i&&(t>0&&Ze(i.breakBefore)||t<e.rows.length-1&&Ze(i.breakAfter)))return!0}return!1}hasInFlowContentBefore(e,t){let i=e;for(;i&&i!==t.element;){let n=i.previousSibling;for(;n;){if(n.nodeType===1&&!Ot(n)||n.nodeType===3&&!Ee(n))return!0;n=n.previousSibling}i=i.parentNode}return!1}addCaptions(e,t,i){let n=e.captions;n.forEach((o,r)=>{o&&(t.insertBefore(o.viewNode,i),o.side==="top"&&(n[r]=null))})}addColGroups(e,t,i){e.colGroups&&this.getColGroupElements(t).length===0&&(t.insertBefore(e.colGroups.cloneNode(!0),i),I(t,"table-layout","fixed"),I(t,e.vertical?"height":"width",`${e.tableWidth}px`))}removeColGroups(e,t){if(e.colGroups&&t){let i=this.getColGroupElements(t);i&&i.forEach(n=>{t.removeChild(n)})}}doLayout(e,t){let i=$t(e.formattingContext),n=i.getRootViewNode(e),o=n.firstChild;this.addCaptions(i,n,o),this.addColGroups(i,n,o);let r=new ix(i,t),s=new Wa(r,t.layoutContext),a=M("TableFormattingContext.doLayout");return s.iterate(e).thenFinish(a),a.result()}layout(e,t,i){let n=$t(e.formattingContext);if(n.getRootViewNode(e)){if(i){let o=n.getRepetitiveElements();o&&e.sourceNode!==n.tableSourceNode&&!e.after&&!o.isFooterRegistered()&&o.preventSkippingHeader(),Bf(e.parent,t)}return new sx(n,this).layout(e,t)}else return t.buildDeepElementView(e)}createEdgeBreakPosition(e,t,i,n){return new Z0(e,t,i,n)}startNonInlineElementNode(e){return!1}afterNonInlineElementNode(e,t){return ya(e),!1}finishBreak(e,t,i,n){let o=$t(t.formattingContext);if(t.display==="table-row"){t.sourceNode;let r=o.findRowIndexBySourceNode(t.sourceNode),s;if(t.after?s=o.getRowSpanningCellsOverflowingTheRow(r):s=o.getCellsFallingOnRow(r),o.cellBreakPositions=o.cellBreakPositions.filter(a=>!s.includes(a.cell)),s.length){let a=M("TableLayoutProcessor.finishBreak"),h=0;return a.loopWithFrame(l=>{if(h===s.length){l.breakLoop();return}let c=s[h++],d=o.getCellFragmentOfCell(c),p=d.findAcceptableBreakPosition().nodeContext,f=d.cellNodeContext,g=f.toNodePosition(),v=new Bi(p.toNodePosition());o.cellBreakPositions.push({cellNodePosition:g,breakChunkPosition:v,cell:c});let w=f.viewNode;d.column.layoutContext.processFragmentedBlockEdge(d.cellNodeContext),r<c.rowIndex+c.rowSpan-1&&(w.rowSpan=r-c.rowIndex+1),d.empty?l.continueLoop():d.pseudoColumn.finishBreak(p,!1,!0).then(()=>{rx(d,o,p),l.continueLoop()})}).then(()=>{e.clearOverflownViewNodes(t,!1),e.layoutContext.processFragmentedBlockEdge(t),ya(t),o.finishFragment(),a.finish(!0)}),a.result()}}return ya(t),o.finishFragment(),Xl.finishBreak(e,t,i,n)}clearOverflownViewNodes(e,t,i,n){Tn.prototype.clearOverflownViewNodes(e,t,i,n)}};function rx(e,t,i){let n=t.getRepetitiveElements();if(!n||!(n.isHeaderRegistered()||n.isFooterRegistered()))return;let o=t.vertical,r=e.column,s=e.pseudoColumn.getColumnElement(),a=e.cellNodeContext.viewNode,h=Bt(r.clientLayout,a,o),l=r.getComputedPaddingBorder(a);if(o){let c=h.right-r.footnoteEdge-n.calculateOffset(i)-l.right;I(s,"max-width",`${c}px`)}else{let c=r.footnoteEdge-n.calculateOffset(i)-h.top-l.top;I(s,"max-height",`${c}px`)}}function Hf(e){let t=e.matches("td, th")?e:e.closest("td, th");if(!t||t.style.verticalAlign!=="baseline")return;let i=t.querySelector(".-vivliostyle-table-cell-container");if(!i)return;let n=i.children;if(n.length!==0){for(let o=0;o<n.length;o++){let r=n[o].style.position;if(r!=="absolute"&&r!=="fixed")return}I(i,"display","contents")}}function ya(e){let t=e.display==="table-row"?e.viewNode.parentElement:e.display==="table"?e.viewNode.querySelector("tbody"):null;if(!t)return;let i;try{i=t.querySelectorAll(":scope>tr:has(>:empty):not(:has(>:not([rowspan]:not([rowspan='1']),:empty)))")}catch{return}if(i.length===0)return;let n=Array.from(i).reduce((d,p)=>{let f=p.getBoundingClientRect(),g=e.vertical?f.width:f.height;return d+g},0),o=i[i.length-1],r=Array.from(t.children).indexOf(o),s=Array.from(o.children).reduce((d,p)=>{let f=p.rowSpan;return f>1&&r+f<t.childElementCount?Math.max(d,f):d},0),a=s?t.children[r+s-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 h=a.getBoundingClientRect(),l=e.vertical?h.width:h.height,c=n+l;I(a,e.vertical?"width":"height",`${c}px`)}var sx=class extends ql{constructor(e,t){super(),u(this,"tableFormattingContext",e),u(this,"processor",t)}resolveLayoutMode(e){let t=this.tableFormattingContext.getRepetitiveElements();return!t||!t.doneInitialLayout?new ax(this.tableFormattingContext,this.processor):(e.sourceNode===this.tableFormattingContext.tableSourceNode&&!e.after&&t&&t.preventSkippingHeader(),new ux(this.tableFormattingContext,this.processor))}clearNodes(e){super.clearNodes(e);let t=this.tableFormattingContext.getRootViewNode(e);this.processor.removeColGroups(this.tableFormattingContext,t)}restoreState(e,t){super.restoreState(e,t),this.tableFormattingContext.finishFragment()}},ax=class extends Rf{constructor(e,t){super(e),u(this,"processor",t)}doLayout(e,t){return this.processor.doInitialLayout(e,t)}},lx=class extends ir{constructor(e){super(e,null,e.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(e){e.fragmentLayoutConstraints.push(new hx(this.position.sourceNode))}},hx=class Wf{constructor(t){u(this,"tableRootNode",t),u(this,"flagmentLayoutConstraintType","EntireTable")}allowLayout(t,i,n){return t.overflow,!1}nextCandidate(t){return!0}postLayout(t,i,n,o){i.sourceNode,Vo.push({root:i.sourceNode,tableLayoutOption:{calculateBreakPositionsInside:!0}})}finishBreak(t,i){return T(!0)}equalsTo(t){return t instanceof Wf&&t.tableRootNode===this.tableRootNode}getPriorityOfFinishBreak(){return 0}},ux=class extends Lf{constructor(e,t){super(e),u(this,"processor",t)}doLayout(e,t){let i=this.formattingContext.getRepetitiveElements();if(i&&!i.isAfterLastContent(e)){let n=new cx(e);t.fragmentLayoutConstraints.some(o=>n.equalsTo(o))||t.fragmentLayoutConstraints.unshift(n)}return this.processor.doLayout(e,t)}},cx=class Gf extends ch{constructor(t){super(t),u(this,"flagmentLayoutConstraintType","TableRow"),u(this,"cellFragmentLayoutConstraints",[])}allowLayout(t,i,n){let o=this.getRepetitiveElements();return!o||n.pseudoParent||En(this.nodeContext.viewNode)||!o.isEnableToUpdateState()?!0:i&&!t||t&&t.overflow?!Mf(t,i,o):!0}nextCandidate(t){let i=$t(this.nodeContext.formattingContext);return this.collectCellFragmentLayoutConstraints(t,i).some(n=>n.constraints.some(o=>o.nextCandidate(t)))?!0:super.nextCandidate(t)}postLayout(t,i,n,o){let r=$t(this.nodeContext.formattingContext);if(this.cellFragmentLayoutConstraints=this.collectCellFragmentLayoutConstraints(i,r),this.cellFragmentLayoutConstraints.forEach(s=>{s.constraints.forEach(a=>{a.postLayout(t,s.breakPosition,n,o)})}),!t){let s=r.getRootViewNode(this.nodeContext);new $f().removeColGroups(r,s),this.removeDummyRowNodes(n)}super.postLayout(t,i,n,o)}finishBreak(t,i){let n=$t(this.nodeContext.formattingContext),o=M("finishBreak"),r=this.cellFragmentLayoutConstraints.reduce((a,h)=>a.concat(h.constraints.map(l=>({constraint:l,breakPosition:h.breakPosition}))),[]),s=0;return o.loop(()=>{if(s<r.length){let a=r[s++];return a.constraint.finishBreak(a.breakPosition,i).thenReturn(!0)}else return T(!1)}).then(()=>{o.finish(!0)}),o.result().thenAsync(()=>super.finishBreak(t,i))}removeDummyRowNodes(t){if(!(!t||t.display!=="table-row"||!t.viewNode))for(;t.viewNode.previousElementSibling;){let i=t.viewNode.previousElementSibling;i.parentNode&&i.parentNode.removeChild(i)}}collectCellFragmentLayoutConstraints(t,i){return this.getCellFragemnts(t,i).map(n=>({constraints:n.fragment.pseudoColumn.getColumn().fragmentLayoutConstraints,breakPosition:n.breakPosition}))}getCellFragemnts(t,i){let n=Number.MAX_VALUE;t&&t.display==="table-row"&&(t.sourceNode,n=i.findRowIndexBySourceNode(t.sourceNode)+1),n=Math.min(i.cellFragments.length,n);let o=[];for(let r=0;r<n;r++)i.cellFragments[r]&&i.cellFragments[r].forEach(s=>{s&&o.push({fragment:s,breakPosition:s.findAcceptableBreakPosition().nodeContext})});return o}getElementsOffsetsForTableCell(t){let i=$t(this.nodeContext.formattingContext),n=i.findCellFromColumn(t);return n?i.collectElementsOffsetOfUpperCells(n):i.collectElementsOffsetOfHighestColumn()}equalsTo(t){return t instanceof Gf?$t(this.nodeContext.formattingContext)===$t(t.nodeContext.formattingContext):!1}},dx=new $f;function px(e,t,i,n,o,r){if(!t)return null;if(i===y.table){let s=e.parent;return new Bn(s?s.formattingContext:null,e.sourceNode)}return null}function fx(e){return e instanceof Bn?dx:null}Ft("RESOLVE_FORMATTING_CONTEXT",px);Ft("RESOLVE_LAYOUT_PROCESSOR",fx);function zu(e){return e.reduce((t,i)=>t+i,0)/e.length}function gx(e){let t=zu(e);return zu(e.map(i=>{let n=i-t;return n*n}))}var mx=class{constructor(e,t){u(this,"layoutResult",e),u(this,"penalty",t)}};function Uo(e){return e.vertical?e.width:e.height}function $o(e,t){e.vertical?e.width=t:e.height=t}var jf=class{constructor(e,t,i){u(this,"layoutContainer",e),u(this,"columnGenerator",t),u(this,"regionPageFloatLayoutContext",i),u(this,"originalContainerBlockSize"),this.originalContainerBlockSize=Uo(e)}balanceColumns(e){let t=M("ColumnBalancer#balanceColumns");this.layoutContainer.element.setAttribute("data-vivliostyle-in-column-balancing","true"),this.preBalance(e),this.savePageFloatLayoutContexts(e),this.layoutContainer.clear();let i=[this.createTrialResult(e)];return t.loopWithFrame(n=>{if(!this.hasNextCandidate(i)){n.breakLoop();return}this.updateCondition(i),this.columnGenerator().then(o=>{if(this.savePageFloatLayoutContexts(o),this.layoutContainer.clear(),!o){n.breakLoop();return}i.push(this.createTrialResult(o)),n.continueLoop()})}).then(()=>{let n=i.reduce((o,r)=>r.penalty<o.penalty?r:o,i[0]);this.layoutContainer.element.removeAttribute("data-vivliostyle-in-column-balancing"),this.restoreContents(n.layoutResult),this.tightenColumnBlockSizes(n.layoutResult.columns),this.postBalance(),t.finish(n.layoutResult)}),t.result()}createTrialResult(e){let t=this.calculatePenalty(e);return new mx(e,t)}preBalance(e){}postBalance(){$o(this.layoutContainer,this.originalContainerBlockSize)}tightenColumnBlockSizes(e){if(e.length<=1)return;let t=Math.max.apply(null,e.map(i=>i.computedBlockSize));if(!(t<=0))for(let i of e)if(i.vertical){let n=parseFloat(i.element.style.width),o=parseFloat(i.element.style.left);if(isFinite(n)&&isFinite(o)&&n>t){let r=o+n-t;I(i.element,"width",`${t}px`),I(i.element,"left",`${r}px`),i.width=t,i.left=r}}else{let n=parseFloat(i.element.style.height);isFinite(n)&&n>t&&(I(i.element,"height",`${t}px`),i.height=t)}}savePageFloatLayoutContexts(e){let t=this.regionPageFloatLayoutContext.detachChildren();e&&(e.columnPageFloatLayoutContexts=t)}restoreContents(e){let t=this.layoutContainer.element;e.columns.forEach(i=>{t.appendChild(i.element)}),e.columnPageFloatLayoutContexts,this.regionPageFloatLayoutContext.attachChildren(e.columnPageFloatLayoutContexts)}},dl=1;function Xf(e){let t=e[e.length-1];if(t.penalty===0)return!1;let i=e[e.length-2];if(i&&t.penalty>=i.penalty)return!1;let n=t.layoutResult.columns,o=Math.max.apply(null,n.map(s=>s.computedBlockSize)),r=Math.max.apply(null,n.map(s=>s.getMaxBlockSizeOfPageFloats()));return o>r+dl}function qf(e,t){let i=e[e.length-1].layoutResult.columns,n=Math.max.apply(null,i.map(o=>isNaN(o.blockDistanceToBlockEndFloats)?o.computedBlockSize:o.computedBlockSize-o.blockDistanceToBlockEndFloats+dl))-dl;n<Uo(t)?$o(t,n):$o(t,Uo(t)-1)}var yx=class extends jf{constructor(e,t,i,n){super(i,e,t),u(this,"columnCount",n),u(this,"originalPosition",null),u(this,"foundUpperBound",!1)}preBalance(e){let t=e.columns.reduce((i,n)=>i+n.computedBlockSize,0);$o(this.layoutContainer,t/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 t=e.columns;return Vu(t)?1/0:Math.max.apply(null,t.map(i=>i.computedBlockSize))}hasNextCandidate(e){if(e.length===1)return!0;if(this.foundUpperBound)return Xf(e);{let t=e[e.length-1];return this.checkPosition(t.layoutResult.position)&&!Vu(t.layoutResult.columns)?(this.foundUpperBound=!0,!0):Uo(this.layoutContainer)<this.originalContainerBlockSize}}updateCondition(e){if(this.foundUpperBound)qf(e,this.layoutContainer);else{let t=Math.min(this.originalContainerBlockSize,Uo(this.layoutContainer)+this.originalContainerBlockSize*.1);$o(this.layoutContainer,t)}}};function Vu(e){if(e.length<=1)return!1;let t=e[e.length-1].computedBlockSize,i=e.slice(0,e.length-1),n=Math.max(...e.map(r=>r.lastLineStride||0)),o=n>0?n/2:6;return i.every(r=>t>r.computedBlockSize+o)}var vx=class extends jf{constructor(e,t,i){super(i,e,t)}calculatePenalty(e){if(e.columns.every(i=>i.computedBlockSize===0))return 1/0;let t=e.columns.filter(i=>!i.pageBreakType).map(i=>i.computedBlockSize);return gx(t)}hasNextCandidate(e){return Xf(e)}updateCondition(e){qf(e,this.layoutContainer)}};function wx(e,t,i,n,o,r,s){if(t===y.auto)return null;{let a=s.positions.length===0,h=r[r.length-1],l=!!(h&&h.pageBreakType);return a||l?new yx(i,n,o,e):t===y.balance_all?new vx(i,n,o):(y.balance,null)}}var va=class{constructor(e,t,i){u(this,"endStuckFixed"),u(this,"endFixed"),u(this,"endSlipped"),this.endStuckFixed=e,this.endFixed=t,this.endSlipped=i}},bx=class{constructor(){u(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(e){if(this.map.length==0)this.map.push(new va(e,e,e));else{let t=this.map[this.map.length-1],i=t.endSlipped+e-t.endFixed;t.endFixed==t.endStuckFixed?(t.endFixed=e,t.endStuckFixed=e,t.endSlipped=i):this.map.push(new va(e,e,i))}}addSlippedRange(e){this.map.length==0?this.map.push(new va(e,0,0)):this.map[this.map.length-1].endFixed=e}slippedByFixed(e){let t=mi(this.map.length,n=>e<=this.map[n].endFixed),i=this.map[t];return i.endSlipped-Math.max(0,i.endStuckFixed-e)}fixedBySlipped(e){let t=mi(this.map.length,n=>e<=this.map[n].endSlipped),i=this.map[t];return i.endStuckFixed-(i.endSlipped-e)}};function xx(e){let t={};return Object.keys(e).forEach(i=>{t[i]=Array.from(e[i])}),t}var Sx=class pl{constructor(t,i,n,o,r,s,a,h){if(u(this,"context",t),u(this,"style",i),u(this,"offset",n),u(this,"isRoot",o),u(this,"flowChunk",r),u(this,"atBlockStart",s),u(this,"atFlowStart",a),u(this,"isParentBoxDisplayed",h),u(this,"flowName"),u(this,"isBlockValue",null),u(this,"hasBoxValue",null),u(this,"styleValues",{}),u(this,"beforeBox",null),u(this,"afterBox",null),u(this,"breakBefore",null),this.flowName=r.flowName,this.hasBox()){let l=i._pseudos;if(l&&l.before){let c=new pl(t,l.before,n,!1,r,this.isBlock(),a,!0),d=c.styleValue("content");It(d)&&(this.beforeBox=c,this.breakBefore=c.breakBefore)}}this.breakBefore=nt(this.getBreakValue("before"),this.breakBefore),this.atFlowStart&&Ze(this.breakBefore)&&(r.breakBefore=nt(r.breakBefore,this.breakBefore))}buildAfterPseudoElementBox(t,i,n){if(this.hasBox()){let o=this.style._pseudos;if(o&&o.after){let r=new pl(this.context,o.after,t,!1,this.flowChunk,i,n,!0),s=r.styleValue("content");It(s)&&(this.afterBox=r)}}}styleValue(t,i){if(!(t in this.styleValues)){let n=this.style[t];this.styleValues[t]=n?n.evaluate(this.context,t):i||null}return this.styleValues[t]}displayValue(){return this.styleValue("display",y.inline)}isBlock(){if(this.isBlockValue===null){let t=this.displayValue(),i=this.styleValue("position"),n=this.styleValue("float");this.isBlockValue=Vd(t,i,n,this.isRoot)}return this.isBlockValue}hasBox(){return this.hasBoxValue===null&&(this.hasBoxValue=this.isParentBoxDisplayed&&this.displayValue()!==y.none&&!wo(this.styleValue("position"))),this.hasBoxValue}getBreakValue(t){let i=null;if(this.isBlock()){let n=this.styleValue(`break-${t}`);n&&(i=n.toString())}return i}},Cx=class{constructor(e){u(this,"context",e),u(this,"stack",[]),u(this,"atBlockStart",!0),u(this,"atFlowStart",!0),u(this,"atStartStack",[])}empty(){return this.stack.length===0}lastBox(){return this.stack[this.stack.length-1]}lastFlowName(){let e=this.lastBox();return e?e.flowChunk.flowName:null}isCurrentBoxDisplayed(){return this.stack.every(e=>e.displayValue()!==y.none)}push(e,t,i,n){let o=this.lastBox();n&&o&&n.flowName!==o.flowName&&this.atStartStack.push({atBlockStart:this.atBlockStart,atFlowStart:this.atFlowStart});let r=n||o.flowChunk,s=this.atFlowStart||!!n,a=this.isCurrentBoxDisplayed(),h=new Sx(this.context,e,t,i,r,s||this.atBlockStart,s,a);return this.stack.push(h),this.atBlockStart=h.hasBox()?!h.beforeBox&&h.isBlock():this.atBlockStart,this.atFlowStart=h.hasBox()?!h.beforeBox&&s:this.atFlowStart,h}encounteredTextNode(e){let t=this.lastBox();if((e.nodeType===Node.TEXT_NODE||e.nodeType===Node.CDATA_SECTION_NODE)&&(this.atBlockStart||this.atFlowStart)&&t.hasBox()){let i=t.styleValue("white-space",y.normal).toString(),n=ep(i);n&&!Ee(e,n)&&(this.atBlockStart=!1,this.atFlowStart=!1)}}pop(e){let t=this.stack.pop();if(t.buildAfterPseudoElementBox(e,this.atBlockStart,this.atFlowStart),this.atFlowStart&&t.afterBox){let n=t.afterBox.getBreakValue("before");t.flowChunk.breakBefore=nt(t.flowChunk.breakBefore,n)}let i=this.lastBox();if(i)if(i.flowName===t.flowName)t.hasBox()&&(this.atBlockStart=this.atFlowStart=!1);else{let n=this.atStartStack.pop();this.atBlockStart=n.atBlockStart,this.atFlowStart=n.atFlowStart}return t}nearestBlockStartOffset(e){if(!e.atBlockStart)return e.offset;let t=this.stack.length-1,i=this.stack[t];for(i===e&&(t--,i=this.stack[t]);t>=0;){if(i.flowName!==e.flowName)return e.offset;if(!i.atBlockStart||i.isRoot)return i.offset;e=i,i=this.stack[--t]}throw new Error("No block start offset found!")}},Uu=class{constructor(e,t,i,n,o,r,s,a,h,l){u(this,"xmldoc",e),u(this,"scope",i),u(this,"context",n),u(this,"primaryFlows",o),u(this,"validatorSet",r),u(this,"counterListener",s),u(this,"root"),u(this,"cascadeHolder"),u(this,"last"),u(this,"rootStyle",{}),u(this,"styleMap",{}),u(this,"counterSnapshots",[]),u(this,"flows",{}),u(this,"flowChunks",[]),u(this,"flowListener",null),u(this,"flowToReach",null),u(this,"idToReach",null),u(this,"cascade"),u(this,"offsetMap"),u(this,"primary",!0),u(this,"primaryStack",[]),u(this,"rootBackgroundAssigned",!1),u(this,"rootLayoutAssigned",!1),u(this,"lastOffset"),u(this,"breakBeforeValues",{}),u(this,"boxStack"),u(this,"bodyReached",!0),this.root=e.root,this.cascadeHolder=t,this.last=this.root,this.cascade=t.createInstance(n,s,a,e.lang,h,l),this.offsetMap=new bx;let c=e.getElementOffset(this.root);this.lastOffset=c,this.boxStack=new Cx(n),this.offsetMap.addStuckRange(c);let d=this.getAttrStyle(this.root);this.cascade.pushElement(this,this.root,d,c),this.recordCounterSnapshot(c,this.cascade.counters,this.cascade.lastCounterChanges,this.cascade.lastCounterChangeTypes),this.postprocessTopStyle(d,!1),this.root.namespaceURI==="http://www.w3.org/1999/xhtml"&&(this.bodyReached=!1),this.primaryStack.push(!0),this.styleMap={},this.styleMap[`e${c}`]=d,this.lastOffset++,this.replayFlowElementsFromOffset(-1)}hasProp(e,t,i){let n=e[i];return n&&n.evaluate(this.context)!==t[i]}transferPropsToRoot(e,t){for(let i in t){let n=e[i];if(n)this.rootStyle[i]=n,delete e[i];else{let o=t[i];o&&(this.rootStyle[i]=new W(o,Rd))}}}postprocessTopStyle(e,t){var i;if(t)for(let n of["writing-mode","direction"])e[n]&&!(t&&this.rootStyle[n])&&(this.rootStyle[n]=e[n]);else for(let n in e)In(n)&&(this.rootStyle[n]=e[n]);if(!this.rootBackgroundAssigned){let n=this.hasProp(e,this.validatorSet.backgroundProps,"background-color")?e["background-color"].evaluate(this.context):null,o=this.hasProp(e,this.validatorSet.backgroundProps,"background-image")?e["background-image"].evaluate(this.context):null;(n&&!Z(n)||o&&!Z(o))&&(this.transferPropsToRoot(e,this.validatorSet.backgroundProps),this.rootBackgroundAssigned=!0)}if(!this.rootLayoutAssigned){for(let n=0;n<$u.length;n++)if(this.hasProp(e,this.validatorSet.layoutProps,$u[n])){this.transferPropsToRoot(e,this.validatorSet.layoutProps),this.rootLayoutAssigned=!0;break}}if(!t){let n=e["font-size"],o=!0;if(n&&!Z(n.value)){let a=n.evaluate(this.context);if(a instanceof O){let h=a.num;switch(a.unit){case"em":case"rem":h*=this.context.initialFontSize;break;case"%":h*=this.context.initialFontSize/100;break;case"lh":case"rlh":h*=this.context.initialFontSize*Zt.lh/Zt.em;break;default:{let l=Zt[a.unit];l&&(h*=l),o=!1}}this.context.rootFontSize=h,this.context.isRelativeRootFontSize=o}}let r=(i=this.context.rootFontSize)!=null?i:this.context.initialFontSize,s=e["line-height"];if(s&&!Z(s.value)){let a=s.evaluate(this.context);if(a instanceof At)this.context.rootLineHeight=a.num*r;else if(a instanceof O){let h=a.num;switch(a.unit){case"em":case"rem":h*=r;break;case"%":h*=r/100;break;case"lh":case"rlh":h*=this.context.initialFontSize*this.context.pref.lineHeight;break;default:{let l=Zt[a.unit];l&&(h*=l)}}this.context.rootLineHeight=h}}else this.context.rootLineHeight=this.context.fontSize()*this.context.pref.lineHeight}}getTopContainerStyle(){let e=0;for(;!this.bodyReached&&(e+=5e3,this.styleUntil(e,0)!=Number.POSITIVE_INFINITY););return this.rootStyle}getAttrStyle(e){if(e.style instanceof CSSStyleDeclaration){let t=e.getAttribute("style");if(t)return p0(this.scope,this.validatorSet,this.xmldoc.url,t)}return{}}recordCounterSnapshot(e,t,i=[],n){let o={offset:e,counters:xx(t),changes:Array.from(i||[]),changeTypes:n?{...n}:void 0},r=this.counterSnapshots[this.counterSnapshots.length-1];if(r&&r.offset===e){this.counterSnapshots[this.counterSnapshots.length-1]=o;return}this.counterSnapshots.push(o)}getCounterSnapshotAtOffset(e){if(!this.counterSnapshots.length)return null;let t=mi(this.counterSnapshots.length,n=>e<this.counterSnapshots[n].offset),i=t===0?0:t-1;return this.counterSnapshots[i]||null}getLastCounterSnapshot(){return this.counterSnapshots.length?this.counterSnapshots[this.counterSnapshots.length-1]:null}getReachedOffset(){return this.lastOffset}replayFlowElementsFromOffset(e){if(e>=this.lastOffset)return;let t=this.context,i=this.xmldoc.getElementOffset(this.root);if(e<i){let r=this.getStyle(this.root,!1);if(!this.cascade.firstPageType){let l=r.page,c=l&&!Z(l.value)&&l.value.toString();c&&c.toLowerCase()!=="auto"&&(this.cascade.firstPageType=c)}let s=ve(r,"flow-into"),a=s?s.evaluate(t,"flow-into").toString():"body",h=this.encounteredFlowElement(a,r,this.root,i);this.boxStack.empty()&&this.boxStack.push(r,i,!0,h)}let n=this.xmldoc.getNodeByOffset(e),o=this.xmldoc.getNodeOffset(n,0,!1);if(!(o>=this.lastOffset))for(;;){if(n.nodeType!=1)o+=n.textContent.length;else{let s=n,a=this.getStyle(s,!1),h=a["flow-into"];if(h){let l=h.evaluate(t,"flow-into").toString();this.encounteredFlowElement(l,a,s,o)}o++}if(o>=this.lastOffset)break;let r=n.firstChild;if(r==null){for(;r=n.nextSibling,!r;)if(n=n.parentNode,n===this.root)return}n=r}}resetFlowChunkStream(e){this.flowListener=e;for(let t=0;t<this.flowChunks.length;t++)this.flowListener.encounteredFlowChunk(this.flowChunks[t],this.flows[this.flowChunks[t].flowName])}styleUntilFlowIsReached(e){this.flowToReach=e;let t=0;for(;!(this.flowToReach==null||(t+=5e3,this.styleUntil(t,0)==Number.POSITIVE_INFINITY)););}styleUntilIdIsReached(e){if(!e)return;this.idToReach=e;let t=0;for(;!(!this.idToReach||(t+=5e3,this.styleUntil(t,0)===Number.POSITIVE_INFINITY)););this.idToReach=null}encounteredFlowElement(e,t,i,n){let o=0,r=Number.POSITIVE_INFINITY,s=!1,a=!1,h=!1,l=t["flow-options"];if(l){let v=$m(l.evaluate(this.context,"flow-options"));s=!!v.exclusive,a=!!v.static,h=!!v.last}let c=t["flow-linger"];c&&(r=Zh(c.evaluate(this.context,"flow-linger"),Number.POSITIVE_INFINITY));let d=t["flow-priority"];d&&(o=Zh(d.evaluate(this.context,"flow-priority"),0));let p=this.breakBeforeValues[n]||null,f=this.flows[e];if(!f){let v=this.boxStack.lastFlowName();f=this.flows[e]=new Mv(e,v)}let g=new _v(e,i,n,o,r,s,a,h,p);return this.flowChunks.push(g),this.flowToReach==e&&(this.flowToReach=null),this.flowListener&&this.flowListener.encounteredFlowChunk(g,f),g}registerForcedBreakOffset(e,t,i){if(Ze(e)){let o=this.flows[i].forcedBreakOffsets;(o.length===0||o[o.length-1]<t)&&o.push(t)}let n=this.breakBeforeValues[t];this.breakBeforeValues[t]=nt(n,e)}styleUntil(e,t){let i=-1,n;if(e<=this.lastOffset&&(n=this.offsetMap.slippedByFixed(e),i=n+t,i<this.offsetMap.getMaxSlipped()))return this.offsetMap.fixedBySlipped(i);if(this.last==null)return Number.POSITIVE_INFINITY;let o=this.context;for(;this.last;){let r=this.last.firstChild;if(r==null)for(;this.last;){if(this.last.nodeType==1){this.cascade.popElement(this.last),this.primary=this.primaryStack.pop();let s=this.boxStack.pop(this.lastOffset),a=null;if(s.afterBox){let h=s.afterBox.getBreakValue("before");this.registerForcedBreakOffset(h,s.afterBox.atBlockStart?this.boxStack.nearestBlockStartOffset(s):s.afterBox.offset,s.flowName),a=s.afterBox.getBreakValue("after")}a=nt(a,s.getBreakValue("after")),this.registerForcedBreakOffset(a,this.lastOffset,s.flowName)}if(r=this.last.nextSibling,r)break;if(this.last=this.last.parentNode,!this.last||this.last===this.root)return this.last=null,e<this.lastOffset&&(i<0&&(n=this.offsetMap.slippedByFixed(e),i=n+t),i<=this.offsetMap.getMaxSlipped())?this.offsetMap.fixedBySlipped(i):Number.POSITIVE_INFINITY}if(this.last=r,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 s=this.last,a=this.getAttrStyle(s);this.primaryStack.push(this.primary),this.cascade.pushElement(this,s,a,this.lastOffset),this.cascade.lastCounterChanges.length>0&&this.recordCounterSnapshot(this.lastOffset,this.cascade.counters,this.cascade.lastCounterChanges,this.cascade.lastCounterChangeTypes);let h=s.getAttribute("id")||s.getAttributeNS("http://www.w3.org/XML/1998/namespace","id");h&&h===this.idToReach&&(this.idToReach=null),!this.bodyReached&&s.localName=="body"&&s.parentNode==this.root&&(this.postprocessTopStyle(a,!0),this.bodyReached=!0);let l,c=a["flow-into"];if(c){let p=c.evaluate(o,"flow-into").toString(),f=this.encounteredFlowElement(p,a,s,this.lastOffset);this.primary=!!this.primaryFlows[p],l=this.boxStack.push(a,this.lastOffset,s===this.root,f)}else l=this.boxStack.push(a,this.lastOffset,s===this.root),s===this.xmldoc.body&&(l.breakBefore=nt(l.flowChunk.breakBefore,l.breakBefore));let d=this.boxStack.nearestBlockStartOffset(l);if(d===0||s===this.xmldoc.body){let p=a.page,f=p&&!Z(p.value)&&p.value.toString();!this.cascade.firstPageType&&f&&f.toLowerCase()!=="auto"&&(this.cascade.firstPageType=f)}if(this.registerForcedBreakOffset(l.breakBefore,d,l.flowName),l.beforeBox){let p=l.beforeBox.getBreakValue("after");this.registerForcedBreakOffset(p,l.beforeBox.atBlockStart?d:l.offset,l.flowName)}if(this.primary&&l.displayValue()===y.none&&(this.primary=!1),this.styleMap[`e${this.lastOffset}`]=a,this.lastOffset++,this.primary?this.offsetMap.addStuckRange(this.lastOffset):this.offsetMap.addSlippedRange(this.lastOffset),this.bodyReached&&d===0)continue;if(e<this.lastOffset&&(i<0&&(n=this.offsetMap.slippedByFixed(e),i=n+t),i<=this.offsetMap.getMaxSlipped()))return this.offsetMap.fixedBySlipped(i)}}return Number.POSITIVE_INFINITY}getStyle(e,t){let i=this.xmldoc.getElementOffset(e),n=`e${i}`;return t&&(i=this.xmldoc.getNodeOffset(e,0,!0)),this.lastOffset<=i&&this.styleUntil(i,0),this.styleMap[n]}processContent(e,t,i){}},$u=["column-count","column-width","column-fill"],uC=`OTTO${new Date().valueOf()}`;function dh(e){return Object.keys(e).filter(t=>!["src","font-family","font-display"].includes(t)).sort()}function kx(e){let t=new gi;for(let i of dh(e))t.append(`${i}:${e[i].toString()};`);return t.toString()}function Ex(e,t){let i={};for(let n in e)i[n]=ve(e,n).evaluate(t,n);return i}var Yf=class{constructor(e){u(this,"properties",e),u(this,"fontTraitKey"),u(this,"src"),u(this,"blobURLs",[]),u(this,"blobs",[]),u(this,"family"),this.fontTraitKey=kx(this.properties),this.src=this.properties.src?this.properties.src.toString():null;let t=this.properties["font-family"];this.family=t?t.stringValue():null}traitsEqual(e){return this.fontTraitKey==e.fontTraitKey}makeAtRule(e,t){let i=new gi;i.append(`@font-face {
1873
+ }`;function Os(e,t,i){let n=M("fetchFromURL"),r={method:i||"GET",mode:"cors"},o=n.suspend(),s={status:0,statusText:"",url:e,contentType:null,responseText:null,responseXML:null,responseBlob:null};return fetch(e,r).then(a=>{var h;if(s.status=a.status,s.url=a.url,s.statusText=a.statusText,s.contentType=(h=a.headers.get("Content-Type"))==null?void 0:h.replace(/;.*$/,"").toLowerCase(),!a.ok)throw new Error(`HTTP ${a.status}${a.statusText?` ${a.statusText}`:""}`);return t==="blob"?a.blob():t==="arraybuffer"?a.arrayBuffer():t==="json"?a.json():/\/aozorabunko\/[^/]+\/cards\/[^/]+\/files\/[^/.]+\.html$/.test(e)?(s.contentType="text/html",a.arrayBuffer().then(l=>new TextDecoder("Shift_JIS").decode(l))):(/^data:,(<|%3c)/i.test(e)&&(s.contentType="text/html"),a.text())}).then(a=>{t==="blob"&&a instanceof Blob?s.responseBlob=a:t==="arraybuffer"&&a instanceof ArrayBuffer?s.responseBlob=Fd([a]):t==="json"?s.responseText=JSON.stringify(a):typeof a=="string"&&(s.responseText=a),o.schedule(s)}).catch(a=>{s.status>=400?Y.warn(`Error fetching ${e} (${s.status}${s.statusText?" "+s.statusText:""})`):Y.warn(a,`Error fetching ${e}`),o.schedule(s)}),n.result()}function Fd(e,t){let i=t||"application/octet-stream";return new Blob(e,{type:i})}function Zy(e){let t=M("readBlob"),i=new FileReader,n=t.suspend(i);return i.addEventListener("load",()=>{n.schedule(i.result)},!1),i.readAsArrayBuffer(e),t.result()}function Ky(e){return URL.createObjectURL(e)}var Bl=class{constructor(e,t){u(this,"parser",e),u(this,"type",t),u(this,"resources",{}),u(this,"fetchers",{})}load(e,t,i){e=pt(e);let n=this.resources[e];return typeof n<"u"?T(n):this.fetch(e,t,i).get()}fetchInner(e,t,i){let n=M("fetch"),r=As(e);r&&(e=dn(e));let o=Ae("user-agent.xml",Ni),s=!r&&e===o;return s&&(e=`data:application/xml,${encodeURIComponent(Ed)}`),Os(e,this.type).then(a=>{if(a.status>=400&&t)throw new Error((i||`Failed to fetch required resource: ${e}`)+` (${a.status}${a.statusText?" "+a.statusText:""})`);r?(e=xa(e),a.url=xa(a.url)):s&&(a.url=e=o),this.parser(a,this).then(h=>{delete this.fetchers[e],this.resources[e]=h,n.finish(h)})}),n.result()}fetch(e,t,i){if(e=pt(e),this.resources[e])return null;let n=this.fetchers[e];return n||(n=new Jr(()=>this.fetchInner(e,t,i),`Fetch ${e}`),this.fetchers[e]=n,n.start()),n}get(e){return this.resources[pt(e)]}delete(e){delete this.resources[pt(e)]}};function Jy(e,t){let i=e.responseText;return T(i?kl(i):null)}function Qy(){return new Bl(Jy,"text")}function Et(e,t,i){let n=new Jr(()=>{let r=M("loadElement"),o=r.suspend(e),s=!1,a=null,h=l=>{s||(s=!0,a!==null&&(clearTimeout(a),a=null),o.schedule(l?l.type:"timeout"))};if(e.addEventListener("load",h,!1),e.addEventListener("error",h,!1),e.addEventListener("abort",h,!1),e.namespaceURI=="http://www.w3.org/2000/svg")t&&e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",t),a=setTimeout(h,300);else if(e.localName==="script")a=setTimeout(h,3e3);else if(t)if(e.localName==="img"){let l=e;l.loading==="lazy"&&(l.loading="eager"),l.src=t,i&&(l.alt=i),l.complete?setTimeout(()=>h(new Event("load")),0):a=setTimeout(h,3e4)}else e.src=t,i&&(e.alt=i);else(e.localName==="img"||e.localName==="embed"||e.localName==="object"||e.localName==="iframe")&&(e.complete?setTimeout(()=>h(new Event("load")),0):a=setTimeout(h,3e4));return r.result()},`loadElement ${t||e.localName}`);return n.start(),n}var tu=0,ev=16777216,Rd=33554432,Ld=50331648,Od=67108864,tv=83886080,iv=100663296,Bs=class{constructor(e){u(this,"scope",e),u(this,"flavor"),this.flavor="Author"}getCurrentToken(){return null}getScope(){return this.scope}error(e,t){}startStylesheet(e){this.flavor=e}tagSelector(e,t){}classSelector(e){}pseudoclassSelector(e,t){}pseudoelementSelector(e,t){}idSelector(e){}attributeSelector(e,t,i,n,r){}descendantSelector(){}childSelector(){}adjacentSiblingSelector(){}followingSiblingSelector(){}nextSelector(){}startSelectorRule(){}startFontFaceRule(){}startCounterStyleRule(e){}startFootnoteRule(e){}startViewportRule(){}startDefineRule(){}startRegionRule(){}startPageRule(){}startPageMarginBoxRule(e){}startWhenRule(e){}startMediaRule(e){this.startWhenRule(e)}startFlowRule(e){}startPageTemplateRule(){}startPageMasterRule(e,t,i){}startPartitionRule(e,t,i){}startPartitionGroupRule(e,t,i){}startRuleBody(){}property(e,t,i){}endRule(){}startFuncWithSelector(e,t){}endFuncWithSelector(){}pushSelectorText(e){}getImportantSpecificity(){switch(this.flavor){case"UA":return tu;case"User":return iv;default:return tv}}getBaseSpecificity(){switch(this.flavor){case"UA":return tu;case"User":return ev;default:return Rd}}},Ba=class extends Bs{constructor(){super(null),u(this,"stack",[]),u(this,"tokenizer",null),u(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,t){this.slave.error(e,t)}errorMsg(e,t){var i;Y.warn(e,(i=t?.toString())!=null?i:"")}startStylesheet(e){super.startStylesheet(e),this.stack.length>0&&(this.slave=this.stack[0],this.stack=[]),this.slave.startStylesheet(e)}tagSelector(e,t){this.slave.tagSelector(e,t)}classSelector(e){this.slave.classSelector(e)}pseudoclassSelector(e,t){this.slave.pseudoclassSelector(e,t)}pseudoelementSelector(e,t){this.slave.pseudoelementSelector(e,t)}idSelector(e){this.slave.idSelector(e)}attributeSelector(e,t,i,n,r){this.slave.attributeSelector(e,t,i,n,r)}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()}startCounterStyleRule(e){this.slave.startCounterStyleRule(e)}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,t,i){this.slave.startPageMasterRule(e,t,i)}startPartitionRule(e,t,i){this.slave.startPartitionRule(e,t,i)}startPartitionGroupRule(e,t,i){this.slave.startPartitionGroupRule(e,t,i)}startRuleBody(){this.slave.startRuleBody()}property(e,t,i){this.slave.property(e,t,i)}endRule(){this.slave.endRule()}startFuncWithSelector(e,t){this.slave.startFuncWithSelector(e,t)}endFuncWithSelector(){this.slave.endFuncWithSelector()}pushSelectorText(e){this.slave.pushSelectorText(e)}},iu=class extends Bs{constructor(e,t,i){super(e),u(this,"owner",t),u(this,"topLevel",i),u(this,"depth",0),t&&(this.flavor=t.flavor)}getCurrentToken(){var e;return(e=this.owner)==null?void 0:e.getCurrentToken()}error(e,t){var i;(i=this.owner)==null||i.errorMsg(e,t)}startRuleBody(){this.depth++}endRule(){--this.depth==0&&!this.topLevel&&this.owner.popHandler()}},on=class extends iu{constructor(e,t,i){super(e,t,i)}report(e){this.error(e,this.getCurrentToken())}reportAndSkip(e){this.report(e),this.owner.pushHandler(new iu(this.scope,this.owner,!1))}startSelectorRule(){this.reportAndSkip("E_CSS_UNEXPECTED_SELECTOR")}startFontFaceRule(){this.reportAndSkip("E_CSS_UNEXPECTED_FONT_FACE")}startCounterStyleRule(e){this.reportAndSkip("E_CSS_UNEXPECTED_COUNTER_STYLE")}startFootnoteRule(e){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(e){this.reportAndSkip("E_CSS_UNEXPECTED_WHEN")}startFlowRule(e){this.reportAndSkip("E_CSS_UNEXPECTED_FLOW")}startPageTemplateRule(){this.reportAndSkip("E_CSS_UNEXPECTED_PAGE_TEMPLATE")}startPageMasterRule(e,t,i){this.reportAndSkip("E_CSS_UNEXPECTED_PAGE_MASTER")}startPartitionRule(e,t,i){this.reportAndSkip("E_CSS_UNEXPECTED_PARTITION")}startPartitionGroupRule(e,t,i){this.reportAndSkip("E_CSS_UNEXPECTED_PARTITION_GROUP")}startFuncWithSelector(e,t){this.reportAndSkip("E_CSS_UNEXPECTED_SELECTOR_FUNC")}endFuncWithSelector(){this.reportAndSkip("E_CSS_UNEXPECTED_END_SELECTOR_FUNC")}property(e,t,i){this.error("E_CSS_UNEXPECTED_PROPERTY",this.getCurrentToken())}},$e=[],rs=[],Se=[],_e=[],Vt=[],at=[],Ue=[],Ke=[],xe=[],tt=[],ct=[],je=[],Ve=[],vn=55,wn=56,co=57;$e[1]=28,$e[36]=29,$e[7]=29,$e[9]=29,$e[14]=29,$e[18]=29,$e[50]=29,$e[20]=30,$e[13]=27,$e[0]=200,rs[1]=46,rs[0]=200,at[1]=2,at[36]=4,at[7]=6,at[9]=8,at[14]=10,at[18]=14,at[50]=42,Se[37]=11,Se[23]=12,Se[35]=56,Se[1]=1,Se[36]=3,Se[7]=5,Se[9]=7,Se[14]=9,Se[12]=13,Se[18]=55,Se[50]=58,Se[16]=41,_e[37]=11,_e[23]=12,_e[35]=56,_e[1]=1,_e[36]=3,_e[7]=5,_e[9]=7,_e[14]=9,_e[18]=55,Vt[1]=2,Vt[36]=4,Vt[7]=6,Vt[9]=8,Vt[18]=14,Vt[50]=42,Vt[14]=10,Vt[12]=13,Ue[1]=15,Ue[7]=16,Ue[4]=17,Ue[5]=18,Ue[3]=19,Ue[2]=20,Ue[8]=21,Ue[27]=57,Ue[16]=22,Ue[19]=23,Ue[6]=24,Ue[11]=25,Ue[17]=26,Ue[13]=48,Ue[31]=47,Ue[23]=54,Ue[0]=44,Ke[1]=31,Ke[4]=32,Ke[5]=32,Ke[3]=33,Ke[2]=34,Ke[10]=40,Ke[6]=38,Ke[31]=36,Ke[24]=36,Ke[32]=35,xe[1]=45,xe[16]=37,xe[37]=37,xe[38]=37,xe[47]=37,xe[48]=37,xe[39]=37,xe[49]=37,xe[41]=37,xe[26]=37,xe[25]=37,xe[23]=37,xe[24]=37,xe[19]=37,xe[21]=37,xe[36]=37,xe[18]=37,xe[22]=37,xe[11]=39,xe[12]=43,xe[17]=49,tt[0]=200,tt[12]=50,tt[13]=51,tt[14]=50,tt[15]=51,tt[10]=50,tt[11]=51,tt[17]=53,ct[0]=200,ct[12]=50,ct[13]=52,ct[14]=50,ct[15]=51,ct[10]=50,ct[11]=51,ct[17]=53,je[0]=200,je[12]=50,je[13]=51,je[14]=50,je[15]=51,je[10]=50,je[11]=51,Ve[11]=0,Ve[16]=0,Ve[22]=1,Ve[18]=1,Ve[26]=2,Ve[25]=2,Ve[38]=3,Ve[37]=3,Ve[48]=3,Ve[47]=3,Ve[39]=3,Ve[49]=3,Ve[41]=3,Ve[23]=4,Ve[24]=4,Ve[36]=5,Ve[19]=5,Ve[21]=5,Ve[0]=6,Ve[vn]=2,Ve[wn]=2;var Qr=class{constructor(e,t,i,n){u(this,"actions",e),u(this,"tokenizer",t),u(this,"handler",i),u(this,"baseURL",n),u(this,"valStack",[]),u(this,"namespacePrefixToURI",{}),u(this,"defaultNamespaceURI",null),u(this,"propName",null),u(this,"propImportant",!1),u(this,"exprContext"),u(this,"result",null),u(this,"importReady",!1),u(this,"importURL",null),u(this,"importCondition",null),u(this,"errorBrackets",[]),u(this,"ruleStack",[]),u(this,"regionRule",!1),u(this,"pageRule",!1),u(this,"inStyleDeclaration",!1),this.exprContext=2}extractVals(e,t){let i=[],n=this.valStack;for(;t<n.length&&(i.push(n[t++]),t!==n.length);){if(n[t++]!==e)throw new Error("Unexpected state");t===n.length&&i.push(Me)}return i}valStackReduce(e,t){let i=this.valStack,n=i.length,r=0,o;do if(o=i[--n],e===")"&&o instanceof fn){if(o.text===")")r++;else if(o.text==="("){if(r===0)return null;r--}}while(typeof o<"u"&&typeof o!="string");let s=i.length-(n+1);if(s>1&&i.splice(n+1,s,new J(i.slice(n+1,i.length))),e==",")return null;n++;do o=i[--n];while(typeof o<"u"&&(typeof o!="string"||o==","));if(s=i.length-(n+1),o=="("){if(e!=")"&&t.type!==0)return this.handler.error("E_CSS_MISMATCHED_C_PAR",t),this.actions=ct,null;let h=new ai(i[n-1],this.extractVals(",",n+1));if(i.splice(n-1,s+2,h),h.name==="var"){let l=h.values[0]instanceof he&&h.values[0].name;Xe(l)||(this.handler.error(`E_CSS_INVALID_VAR ${h.toString()}`,t),this.actions=ct)}return h}if(e!=";"||n>=0)return this.handler.error("E_CSS_UNEXPECTED_VAL_END",t),this.actions=ct,null;if(s>1)return new Oe(this.extractVals(",",n+1));let a=i[0];return a instanceof ot?a:a?new fn(a.toString()):Me}exprError(e,t){this.actions=this.propName?ct:tt,Y.warn(e,t.toString())}exprStackReduce(e,t){let i=this.valStack,n=this.handler,r=i.pop(),o;for(;;){let s=i.pop();if(e==11){let a=[r];for(;s==16;)a.unshift(i.pop()),s=i.pop();if(typeof s=="string"){if(s=="{"){for(;a.length>=2;){let h=a.shift(),l=a.shift(),c=new fm(n.getScope(),h,l);a.unshift(c)}return i.push(new j(a[0])),!0}else if(s=="("){let h=i.pop(),l=i.pop();r=new yr(n.getScope(),Ca(l,h),a),e=0;continue}}if(s==10){r.isMediaName()&&(r=new Oh(n.getScope(),r,null)),e=0;continue}}else if(typeof s=="string"){i.push(s);break}if(s<0)if(s==-31)r=new Ai(n.getScope(),r);else if(s==-24)r=new Cn(n.getScope(),r);else if(s==-co)r=new dm(n.getScope(),r);else return this.exprError("F_UNEXPECTED_STATE",t),!1;else{if(Ve[e]>Ve[s]){i.push(s);break}switch(o=i.pop(),s){case 26:r=new Al(n.getScope(),o,r);break;case vn:r=new pm(n.getScope(),o,r);break;case wn:r=new gm(n.getScope(),o,r);break;case 25:r=new Il(n.getScope(),o,r);break;case 38:r=new mm(n.getScope(),o,r);break;case 37:r=new vm(n.getScope(),o,r);break;case 48:r=new ym(n.getScope(),o,r);break;case 47:r=new Ea(n.getScope(),o,r);break;case 39:case 49:r=new Fl(n.getScope(),o,r);break;case 41:r=new wm(n.getScope(),o,r);break;case 23:r=new Oc(n.getScope(),o,r);break;case 24:r=new Bc(n.getScope(),o,r);break;case 36:r=new Rl(n.getScope(),o,r);break;case 19:r=new Mc(n.getScope(),o,r);break;case 21:r=new _c(n.getScope(),o,r);break;case 18:if(i.length>1)switch(i[i.length-1]){case 22:i.pop(),r=new Sm(n.getScope(),i.pop(),o,r);break;case 10:if(o.isMediaName())r=new Oh(n.getScope(),o,r);else return this.exprError("E_CSS_MEDIA_TEST",t),!1;break}else return this.exprError("E_CSS_EXPR_COND",t),!1;break;case 22:if(e!=18)return this.exprError("E_CSS_EXPR_COND",t),!1;case 10:return i.push(o),i.push(s),i.push(r),!1;default:return this.exprError("F_UNEXPECTED_STATE",t),!1}}}return i.push(r),!1}readSupportsTest(e){let t=e.type===6,i=this.tokenizer,n,r;if(t)r=e.text,n=e.position+r.length+1;else if(e.type===10){let d=i.nthToken(1),p=i.nthToken(2);if(d.type===1&&p.type===18)i.consume(),i.consume(),r=d.text,n=p.position+1;else{if(d.type===10||d.type===6||d.type===1&&d.text.toLowerCase()==="not"&&(p.type===10||p.type===6))return null;n=e.position+1}}else return null;let o=0,s,a=0;for(;o>=0;)switch(i.consume(),s=i.token(),s.type){case 11:o--;break;case 10:case 6:o++;break;case 16:o===0&&a++;break;case 0:return this.exprError("E_CSS_UNEXPECTED_EOF",s),null}i.consume();let h=s.position,l=i.input.substring(n,h),c=t&&r==="selector"&&a>0?"":Xe(r)?l:l.trim();return new Cm(this.handler.getScope(),r,c,t)}readPseudoParams(){let e=[];for(;;){let t=this.tokenizer.token();switch(t.type){case 1:e.push(t.text);break;case 23:e.push("+");break;case 4:case 5:e.push(t.num);break;default:return e}this.tokenizer.consume()}}skipPseudoFunctionContents(){let e=0;for(;;){switch(this.tokenizer.token().type){case 0:return!1;case 11:if(e===0)return!0;e--;break;case 10:case 6:e++;break}this.tokenizer.consume()}}readNthPseudoParams(){let e=!1,t=this.tokenizer.token();if(t.type===23)e=!0,this.tokenizer.consume(),t=this.tokenizer.token();else if(t.type===1&&(t.text==="even"||t.text==="odd"))return this.tokenizer.consume(),[2,t.text==="odd"?1:0];switch(t.type){case 3:if(e&&t.num<0)return null;case 1:if(e&&t.text.charAt(0)==="-")return null;if(t.text==="n"||t.text==="-n"){if(e&&t.precededBySpace)return null;let i=t.text==="-n"?-1:1;t.type===3&&(i=t.num);let n=0;this.tokenizer.consume(),t=this.tokenizer.token();let r=t.type===24,o=t.type===23||r;if(o&&(this.tokenizer.consume(),t=this.tokenizer.token()),t.type===5){if(n=t.num,1/n===-1/0){if(n=0,o)return null}else if(n<0){if(o)return null}else if(n>=0&&!o)return null;this.tokenizer.consume()}else if(o)return null;return[i,r&&n>0?-n:n]}else if(t.text==="n-"||t.text==="-n-"){if(e&&t.precededBySpace)return null;let i=t.text==="-n-"?-1:1;if(t.type===3&&(i=t.num),this.tokenizer.consume(),t=this.tokenizer.token(),t.type===5)return t.num<0||1/t.num===-1/0?null:(this.tokenizer.consume(),[i,t.num])}else{let i=t.text.match(/^n(-[0-9]+)$/);if(i)return e&&t.precededBySpace?null:(this.tokenizer.consume(),[t.type===3?t.num:1,parseInt(i[1],10)]);if(i=t.text.match(/^-n(-[0-9]+)$/),i)return this.tokenizer.consume(),[-1,parseInt(i[1],10)]}return null;case 5:return e&&(t.precededBySpace||t.num<0)?null:(this.tokenizer.consume(),[0,t.num])}return null}makeCondition(e,t){let i=this.handler.getScope();if(!i)return null;if(t=t||i._true,e){let n=e.split(/\s+/);for(let r of n)switch(r){case"vertical":t=Wt(i,t,new Ai(i,new Je(i,"pref-horizontal")));break;case"horizontal":t=Wt(i,t,new Je(i,"pref-horizontal"));break;case"day":t=Wt(i,t,new Ai(i,new Je(i,"pref-night-mode")));break;case"night":t=Wt(i,t,new Je(i,"pref-night-mode"));break;default:t=i._false}}return t===i._true?null:new j(t)}isInsidePropertyOnlyRule(){switch(this.ruleStack[this.ruleStack.length-1]){case"[selector]":case"font-face":case"counter-style":case"-epubx-flow":case"-epubx-viewport":case"-epubx-define":case"-adapt-footnote-area":case"footnote":return!0}return!1}runParser(e,t,i,n,r,o){let s=this.handler,a=this.tokenizer,h=this.valStack,l,c,d,p,f,g,v,w=null;for(i&&(this.inStyleDeclaration=!0),n&&(this.exprContext=2,this.valStack.push("{"));e>0;--e){if(l=a.token(),r&&w===null&&(w=l.position-1,a.input[w]==="("&&w++),this.actions===Ue&&this.errorBrackets.length>0&&(l.type===this.errorBrackets[this.errorBrackets.length-1]||l.type===17||l.type===31)){if(l.type===this.errorBrackets[this.errorBrackets.length-1]&&(this.errorBrackets.pop(),l.type===11&&this.valStackReduce(")",l))){a.consume();continue}h.push(new fn(l.toString())),a.consume();continue}switch(this.actions[l.type]){case 28:if(!this.inStyleDeclaration||a.nthToken(1).type!=18){this.isInsidePropertyOnlyRule()?(s.error("E_CSS_COLON_EXPECTED",a.nthToken(1)),this.actions=ct):(this.actions=at,s.startSelectorRule());continue}this.propName=l.text,this.propImportant=!1,a.consume(),a.consume(),this.actions=Ue,h.splice(0,h.length);continue;case 46:if(a.nthToken(1).type!=18){this.actions=ct,s.error("E_CSS_COLON_EXPECTED",a.nthToken(1));continue}this.propName=l.text,this.propImportant=!1,a.consume(),a.consume(),this.actions=Ue,h.splice(0,h.length);continue;case 29:this.actions=at,s.startSelectorRule();continue;case 1:if(!l.precededBySpace){this.actions=je,s.error("E_CSS_SPACE_EXPECTED",l);continue}s.descendantSelector();case 2:if(a.nthToken(1).type==34)if(a.consume(),a.consume(),d=this.namespacePrefixToURI[l.text],d!=null)switch(l=a.token(),l.type){case 1:s.tagSelector(d,l.text),r?this.actions=_e:this.actions=Se,a.consume();break;case 36:s.tagSelector(d,null),r?this.actions=_e:this.actions=Se,a.consume();break;default:this.actions=tt,s.error("E_CSS_NAMESPACE",l)}else this.actions=tt,s.error("E_CSS_UNDECLARED_PREFIX",l);else s.tagSelector(this.defaultNamespaceURI,l.text),r?this.actions=_e:this.actions=Se,a.consume();continue;case 3:if(!l.precededBySpace){this.actions=je,s.error("E_CSS_SPACE_EXPECTED",l);continue}s.descendantSelector();case 4:if(a.nthToken(1).type==34)switch(a.consume(),a.consume(),l=a.token(),l.type){case 1:s.tagSelector(null,l.text),r?this.actions=_e:this.actions=Se,a.consume();break;case 36:s.tagSelector(null,null),r?this.actions=_e:this.actions=Se,a.consume();break;default:this.actions=tt,s.error("E_CSS_NAMESPACE",l)}else s.tagSelector(this.defaultNamespaceURI,null),r?this.actions=_e:this.actions=Se,a.consume();continue;case 5:l.precededBySpace&&s.descendantSelector();case 6:if(!l.text){s.error("E_CSS_SYNTAX",l),a.consume();continue}s.idSelector(l.text),r?this.actions=_e:this.actions=Se,a.consume();continue;case 7:l.precededBySpace&&s.descendantSelector();case 8:s.classSelector(l.text),r?this.actions=_e:this.actions=Se,a.consume();continue;case 55:l.precededBySpace&&s.descendantSelector();case 14:a.consume(),l=a.token();e:switch(l.type){case 1:s.pseudoclassSelector(l.text,null),a.consume(),r?this.actions=_e:this.actions=Se;continue;case 6:switch(p=l.text,a.consume(),p){case"is":case"not":case"where":case"has":this.actions=at,s.startFuncWithSelector(p),this.runParser(Number.POSITIVE_INFINITY,!1,!1,!1,!0,p==="has")?this.actions=Se:this.actions=je;continue;case"lang":case"href-epub-type":case"href-role-type":if(l=a.token(),l.type===1){v=[l.text],a.consume(),(p==="href-epub-type"||p==="href-role-type")&&a.token().type===16&&(a.consume(),l=a.token(),l.type===1&&(v.push(l.text),a.consume()));break}else break e;case"nth-child":case"nth-of-type":case"nth-last-child":case"nth-last-of-type":case"nth":if(v=this.readNthPseudoParams(),v)if(p==="nth-child"||p==="nth-last-child"){if(c=a.nthToken(0),c.type===1&&c.text==="of"){a.consume(),this.actions=at,s.startFuncWithSelector(p,v),this.runParser(Number.POSITIVE_INFINITY,!1,!1,!1,!0,!1)?r?this.actions=_e:this.actions=Se:this.actions=je;continue}break}else if(p==="nth"){if(c=a.nthToken(0),c.type===1&&c.text==="of")if(a.consume(),c=a.token(),c.type===1)v.push(c.text),a.consume();else break e;break}else break;else break e;default:if(v=[],!this.skipPseudoFunctionContents())break e}if(l=a.token(),l.type==11){s.pseudoclassSelector(p,v),a.consume(),r?this.actions=_e:this.actions=Se;continue}break}s.error("E_CSS_PSEUDOCLASS_SYNTAX",l),this.actions=tt;continue;case 58:l.precededBySpace&&s.descendantSelector();case 42:switch(a.consume(),l=a.token(),l.type){case 1:s.pseudoelementSelector(l.text,null),r?this.actions=_e:this.actions=Se,a.consume();continue;case 6:if(p=l.text,a.consume(),p=="nth-fragment"){if(v=this.readNthPseudoParams(),v===null)break}else v=this.readPseudoParams();if(l=a.token(),l.type==11){s.pseudoelementSelector(p,v),r?this.actions=_e:this.actions=Se,a.consume();continue}break}s.error("E_CSS_PSEUDOELEM_SYNTAX",l),this.actions=tt;continue;case 9:l.precededBySpace&&s.descendantSelector();case 10:{if(a.consume(),l=a.token(),l.type==1)p=l.text,a.consume();else if(l.type==36)p=null,a.consume();else if(l.type==34)p="";else{this.actions=je,s.error("E_CSS_ATTR",l),a.consume();continue}if(l=a.token(),l.type==34){if(d=p&&this.namespacePrefixToURI[p],d===void 0){this.actions=je,s.error("E_CSS_UNDECLARED_PREFIX",l),a.consume();continue}if(a.consume(),l=a.token(),l.type!=1){this.actions=je,s.error("E_CSS_ATTR_NAME_EXPECTED",l);continue}p=l.text,a.consume(),l=a.token()}else d="";switch(l.type){case 39:case 45:case 44:case 43:case 42:case 46:case 50:f=l.type,a.consume(),l=a.token();break;case 15:s.attributeSelector(d,p,0,null,null),r?this.actions=_e:this.actions=Se,a.consume();continue;default:this.actions=je,s.error("E_CSS_ATTR_OP_EXPECTED",l);continue}let x=p,m=null;switch(l.type){case 1:case 2:{let S=l.text;if(a.consume(),l=a.token(),l.type==1){let b=l.text.toLowerCase();(b=="i"||b=="s")&&(m=b,a.consume(),l=a.token())}s.attributeSelector(d,x,f,S,m);break}default:this.actions=je,s.error("E_CSS_ATTR_VAL_EXPECTED",l);continue}if(l.type!=15){this.actions=je,s.error("E_CSS_ATTR",l);continue}r?this.actions=_e:this.actions=Se,a.consume();continue}case 11:s.childSelector(),this.actions=Vt,a.consume();continue;case 12:s.adjacentSiblingSelector(),this.actions=Vt,a.consume();continue;case 56:s.followingSiblingSelector(),this.actions=Vt,a.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),s.startRuleBody(),this.actions=$e,a.consume();continue;case 41:s.nextSelector(),this.actions=at,a.consume();continue;case 15:h.push(B(l.text)),a.consume();continue;case 16:f=parseInt(l.text,16),h.push(new jc(l.text)),a.consume();continue;case 17:h.push(new At(l.num)),a.consume();continue;case 18:h.push(new lt(l.num)),a.consume();continue;case 19:h.push(new O(l.num,l.text)),a.consume();continue;case 20:h.push(new K(l.text)),a.consume();continue;case 21:h.push(new Qe(Ae(l.text,this.baseURL))),a.consume();continue;case 57:h.push(new Xc(l.text)),a.consume();continue;case 22:this.valStackReduce(",",l),h.push(","),a.consume();continue;case 23:h.push(jn),a.consume();continue;case 24:p=l.text.toLowerCase(),p=="-epubx-expr"||p=="env"?(this.actions=Ke,this.exprContext=0,h.push("{")):(h.push(p),h.push("("),this.errorBrackets.length>0&&this.errorBrackets.push(11)),a.consume();continue;case 25:this.valStackReduce(")",l),a.consume();continue;case 47:if(a.consume(),l=a.token(),c=a.nthToken(1),l.type==1&&l.text.toLowerCase()=="important"&&(c.type==17||c.type==0||c.type==13)){a.consume(),this.propImportant=!0;continue}this.exprError("E_CSS_SYNTAX",l);continue;case 54:switch(c=a.nthToken(1),c.type){case 4:case 3:case 5:if(!c.precededBySpace){a.consume();continue}}h.push(new fn("+")),a.consume();continue;case 26:a.consume();case 48:g=this.valStackReduce(";",l),g&&this.propName&&s.property(this.propName,g,this.propImportant),this.actions=i?rs:$e;continue;case 44:for(a.consume();h.length>0;){let x=h.length;if(g=this.valStackReduce(";",l),!g||h.length===x)break}return t?(this.result=g,!0):(this.propName&&g&&s.property(this.propName,g,this.propImportant),!0);case 31:if(c=a.nthToken(1),c.type==9)a.nthToken(2).type==10&&!a.nthToken(2).precededBySpace?(h.push(l.text,c.text,"("),a.consume()):(h.push(new Je(s.getScope(),Ca(l.text,c.text))),this.actions=xe),a.consume();else{if(this.exprContext==2||this.exprContext==3)l.text.toLowerCase()=="not"?(a.consume(),h.push(new Lh(s.getScope(),!0,c.text))):(l.text.toLowerCase()=="only"&&(a.consume(),l=c),h.push(new Lh(s.getScope(),!1,l.text)));else if(this.exprContext===4&&l.text.toLowerCase()==="not"&&h[h.length-1]!==vn&&h[h.length-1]!==wn&&(c.type===10||c.type===6)){h.push(-co),a.consume();continue}else h.push(new Je(s.getScope(),l.text));this.actions=xe}a.consume();continue;case 38:if(this.exprContext===4){h.push(this.readSupportsTest(l)),this.actions=xe;continue}h.push(null,l.text,"("),a.consume();continue;case 32:h.push(new it(s.getScope(),l.num)),a.consume(),this.actions=xe;continue;case 33:p=l.text,p=="%"&&(this.propName&&this.propName.match(/height|^(top|bottom)$/)?p="vh":p="vw"),h.push(new Xr(s.getScope(),l.num,p)),a.consume(),this.actions=xe;continue;case 34:h.push(new it(s.getScope(),l.text)),a.consume(),this.actions=xe;continue;case 35:a.consume(),l=a.token(),l.type!=5||l.precededBySpace?this.exprError("E_CSS_SYNTAX",l):(h.push(new Uc(s.getScope(),l.num)),a.consume(),this.actions=xe);continue;case 36:h.push(-l.type),a.consume();continue;case 37:this.actions=Ke,this.exprStackReduce(l.type,l),h.push(l.type),a.consume();continue;case 45:l.text.toLowerCase()==="and"&&h[h.length-2]!==wn&&h[h.length-2]!==-co?(this.actions=Ke,this.exprStackReduce(vn,l),h.push(vn),a.consume()):l.text.toLowerCase()==="or"&&h[h.length-2]!==vn&&h[h.length-2]!==-co?(this.actions=Ke,this.exprStackReduce(wn,l),h.push(wn),a.consume()):this.exprError("E_CSS_SYNTAX",l);continue;case 39:this.exprStackReduce(l.type,l)&&(this.actions=Ue),a.consume();continue;case 43:this.exprStackReduce(11,l)&&(this.propName||this.exprContext==3?this.exprError("E_CSS_UNEXPECTED_BRC",l):(this.exprContext==1?s.startWhenRule(h.pop()):s.startMediaRule(h.pop()),this.ruleStack.push("media"),s.startRuleBody(),this.actions=$e)),a.consume();continue;case 49:if(this.exprStackReduce(11,l))return this.propName||this.exprContext!=3?(this.exprError("E_CSS_UNEXPECTED_SEMICOL",l),this.actions=$e,a.consume(),!1):(this.importCondition=h.pop(),this.importReady=!0,this.actions=$e,a.consume(),!1);a.consume();continue;case 40:if(this.exprContext===4){let x=this.readSupportsTest(l);if(x){h.push(x),this.actions=xe;continue}}h.push(l.type),a.consume();continue;case 27:if(this.actions=$e,a.consume(),s.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(p=l.text.toLowerCase(),p){case"import":if(a.consume(),l=a.token(),l.type==2||l.type==8){if(this.importURL=l.text,a.consume(),l=a.token(),l.type==17||l.type==0)return this.importReady=!0,a.consume(),!1;this.propName=null,this.exprContext=3,this.actions=Ke,h.push("{");continue}s.error("E_CSS_IMPORT_SYNTAX",l),this.actions=tt;continue;case"namespace":switch(a.consume(),l=a.token(),l.type){case 1:if(p=l.text,a.consume(),l=a.token(),(l.type==2||l.type==8)&&a.nthToken(1).type==17){this.namespacePrefixToURI[p]=l.text,a.consume(),a.consume();continue}break;case 2:case 8:if(a.nthToken(1).type==17){this.defaultNamespaceURI=l.text,a.consume(),a.consume();continue}break}s.error("E_CSS_NAMESPACE_SYNTAX",l),this.actions=tt;continue;case"charset":if(a.consume(),l=a.token(),l.type==2&&a.nthToken(1).type==17){p=l.text.toLowerCase(),p!="utf-8"&&p!="utf-16"&&s.error(`E_CSS_UNEXPECTED_CHARSET ${p}`,l),a.consume(),a.consume();continue}s.error("E_CSS_CHARSET_SYNTAX",l),this.actions=tt;continue;case"font-face":case"-epubx-page-template":case"-epubx-define":case"-epubx-viewport":if(a.nthToken(1).type==12){switch(a.consume(),a.consume(),p){case"font-face":s.startFontFaceRule(),this.inStyleDeclaration=!0;break;case"-epubx-page-template":s.startPageTemplateRule();break;case"-epubx-define":s.startDefineRule(),this.inStyleDeclaration=!0;break;case"-epubx-viewport":s.startViewportRule(),this.inStyleDeclaration=!0;break}this.ruleStack.push(p),s.startRuleBody();continue}break;case"-epubx-region":a.consume(),s.startRegionRule(),this.regionRule=!0,this.actions=at;continue;case"page":a.consume(),s.startPageRule(),this.pageRule=!0,this.actions=Vt;continue;case"-adapt-footnote-area":case"footnote":switch(a.consume(),l=a.token(),l.type){case 12:a.consume(),s.startFootnoteRule(null),this.ruleStack.push(p),s.startRuleBody(),this.inStyleDeclaration=!0;continue;case 50:if(a.consume(),l=a.token(),l.type==1&&a.nthToken(1).type==12){let x=l.text;a.consume(),a.consume(),s.startFootnoteRule(x),this.ruleStack.push(p==="footnote"?"footnote":"-adapt-footnote-area"),s.startRuleBody(),this.inStyleDeclaration=!0;continue}break}break;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(a.consume(),l=a.token(),l.type==12){a.consume(),s.startPageMarginBoxRule(p),this.ruleStack.push(p),s.startRuleBody(),this.inStyleDeclaration=!0;continue}break;case"-epubx-when":a.consume(),this.propName=null,this.exprContext=1,this.actions=Ke,h.push("{");continue;case"media":a.consume(),this.propName=null,this.exprContext=2,this.actions=Ke,h.push("{");continue;case"supports":a.consume(),this.propName=null,this.exprContext=4,this.actions=Ke,h.push("{");continue;case"-epubx-flow":if(a.nthToken(1).type==1&&a.nthToken(2).type==12){s.startFlowRule(a.nthToken(1).text),a.consume(),a.consume(),a.consume(),this.ruleStack.push(p),s.startRuleBody(),this.inStyleDeclaration=!0;continue}break;case"counter-style":if(a.nthToken(1).type==1&&a.nthToken(2).type==12){s.startCounterStyleRule(a.nthToken(1).text),a.consume(),a.consume(),a.consume(),this.ruleStack.push(p),s.startRuleBody(),this.inStyleDeclaration=!0;continue}break;case"-epubx-page-master":case"-epubx-partition":case"-epubx-partition-group":{a.consume(),l=a.token();let x=null,m=null,S=[];for(l.type==1&&(x=l.text,a.consume(),l=a.token()),l.type==18&&a.nthToken(1).type==1&&(m=a.nthToken(1).text,a.consume(),a.consume(),l=a.token());l.type==6&&l.text.toLowerCase()=="class"&&a.nthToken(1).type==1&&a.nthToken(2).type==11;)S.push(a.nthToken(1).text),a.consume(),a.consume(),a.consume(),l=a.token();if(l.type==12){switch(a.consume(),p){case"-epubx-page-master":s.startPageMasterRule(x,m,S);break;case"-epubx-partition":s.startPartitionRule(x,m,S);break;case"-epubx-partition-group":s.startPartitionGroupRule(x,m,S);break}this.ruleStack.push(p),s.startRuleBody(),this.inStyleDeclaration=!0;continue}break}case"":s.error(`E_CSS_UNEXPECTED_AT${p}`,l),this.actions=je;continue;default:s.error(`E_CSS_AT_UNKNOWN ${p}`,l),this.actions=tt;continue}s.error(`E_CSS_AT_SYNTAX ${p}`,l),this.actions=tt;continue;case 50:this.errorBrackets.push(l.type+1),a.consume();continue;case 52:if(this.errorBrackets.length==0){this.actions=$e;continue}case 51:if(r&&this.errorBrackets.length==0&&l.type==11)return a.consume(),s.endFuncWithSelector(),!0;this.errorBrackets.length>0&&this.errorBrackets[this.errorBrackets.length-1]==l.type&&this.errorBrackets.pop(),this.errorBrackets.length==0&&l.type==13&&(this.actions=$e),a.consume();continue;case 53:if(r&&this.errorBrackets.length==0&&l.type==16){s.nextSelector(),this.actions=at,w=l.position+1,a.consume();continue}this.errorBrackets.length==0&&(this.actions=$e),a.consume();continue;case 200:return!0;default:if(n)return this.exprStackReduce(11,l)?(this.result=h.pop(),!0):!1;if(r){if(this.actions===je)switch(l.type){case 16:this.errorBrackets.length==0&&(s.nextSelector(),w=l.position+1,this.actions=at),a.consume();continue;case 11:if(this.errorBrackets.length==0)return s.endFuncWithSelector(),a.consume(),!0;this.errorBrackets.length>0&&this.errorBrackets[this.errorBrackets.length-1]==l.type&&this.errorBrackets.pop(),a.consume();continue;case 12:case 14:case 10:this.errorBrackets.push(l.type+1),a.consume();continue;case 6:this.errorBrackets.push(11),a.consume();continue;case 13:case 15:this.errorBrackets.length>0&&this.errorBrackets[this.errorBrackets.length-1]==l.type&&this.errorBrackets.pop(),a.consume();continue;default:a.consume();continue}switch(l.type){case 16:case 11:if(this.actions===at)s.error("E_CSS_SYNTAX",l);else{let x=a.input.substring(w,l.position);s.pushSelectorText(x),w=l.position+1}if(l.type===16){s.nextSelector(),this.actions=at,a.consume();continue}else return s.endFuncWithSelector(),a.consume(),!0;case 37:case 23:case 35:if(o){this.actions=Se;continue}break;case 12:case 14:case 10:this.errorBrackets.push(l.type+1);break}s.error("E_CSS_SYNTAX",l),a.consume(),this.actions=je;continue}if(this.actions!==tt&&this.actions!==je&&this.actions!==ct){if(l.type==54)s.error("E_CSS_SYNTAX",l);else if(this.actions===Ue){switch(l.type){case 10:case 12:case 14:this.errorBrackets.push(l.type+1);break}h.push(new fn(l.toString())),a.consume();continue}else if(l.type===12&&this.actions==Ke&&h.length>0){s.startMediaRule(h.pop()),this.ruleStack.push("media"),s.startRuleBody(),this.actions=$e,a.consume();continue}else{if(l.type===17&&this.actions==Ke)return this.actions=$e,a.consume(),!1;s.error("E_CSS_SYNTAX",l)}this.isInsidePropertyOnlyRule()?this.actions=ct:this.actions=je;continue}a.consume();continue}}return!1}},Bd=class extends Bs{constructor(e){super(null),u(this,"scope",e)}error(e,t){Y.warn(e,t.toString())}getScope(){return this.scope}};function nv(e,t,i,n,r){let o=Md(t),s=ny(e.input);return s!==e.input?nu(new xt(s,o),o,i,n,r):nu(e,o,i,n,r)}function nu(e,t,i,n,r){let o=M("parseStylesheet"),s=new Qr($e,e,t,i),a=null;return r&&(a=Dd(new xt(r,t),t,i)),a=s.makeCondition(n,a&&a.toExpr()),a&&(t.startMediaRule(a),t.startRuleBody()),o.loop(()=>{for(;!s.runParser(100,!1,!1,!1,!1);){if(s.importReady){let l=Ae(s.importURL,i);s.importCondition&&(t.startMediaRule(s.importCondition),t.startRuleBody());let c=M("parseStylesheet.import");return _d(l,t,null,null).then(()=>{s.importCondition&&t.endRule(),s.importReady=!1,s.importURL=null,s.importCondition=null,c.finish(!0)}),c.result()}let h=o.timeSlice();if(h.isPending)return h}return T(!1)}).then(()=>{a&&t.endRule(),o.finish(!0)}),o.result()}function Ml(e,t,i,n,r){let o=Md(t);return _n("parseStylesheetFromText",s=>{let a=new xt(e,o);nv(a,o,i,n,r).thenFinish(s)},(s,a)=>{Y.warn(a,`Failed to parse stylesheet text: ${e}`),s.finish(!1)})}function Md(e){if(e instanceof Ba)return e;if(e instanceof on){if(e.owner)return e.owner;let t=new Ba;return t.flavor=e.flavor,t.slave=e,e.owner=t,t}return e}function _d(e,t,i,n){return _n("parseStylesheetFromURL",r=>{Os(e).then(o=>{o.responseText?Ml(o.responseText,t,e,i,n).then(s=>{s||Y.warn(`Failed to parse stylesheet from ${e}`),r.finish(!0)}):r.finish(!0)})},(r,o)=>{Y.warn(o,"Exception while fetching and parsing:",e),r.finish(!0)})}function Ri(e,t,i){let n=new Qr(Ue,t,new Bd(e),i);return n.runParser(Number.POSITIVE_INFINITY,!0,!1,!1,!1),n.result}function rv(e,t,i){new Qr(rs,e,t,i).runParser(Number.POSITIVE_INFINITY,!1,!0,!1,!1)}function Dd(e,t,i){let n=new Qr(Ke,e,t,i);return n.runParser(Number.POSITIVE_INFINITY,!1,!1,!0,!1),n.result}var ov={"z-index":!0,"column-count":!0,"flow-linger":!0,opacity:!0,page:!0,"flow-priority":!0,utilization:!0};function sv(e){return!!ov[e]}function av(e,t,i){if(t instanceof we&&t.str==="viv-leader")return new j(t);if(i==="content"&&t instanceof we)return new j(t);let n=t.evaluate(e);switch(typeof n){case"number":return sv(i)?n==Math.round(n)?new lt(n):new At(n):new O(n,"px");case"string":return n?i==="content"?new K(n):Ri(t.scope,new xt(n,null),""):Me;case"boolean":return n?y._true:y._false;case"undefined":return Me}throw new Error("E_UNEXPECTED")}var lv="data-vivliostyle-flow-root";function hv(e){return e.getAttribute(lv)==="true"}function ru(e){let t=e?.toString()||"block",i;switch(t){case"inline-flex":i="flex";break;case"inline-grid":i="grid";break;case"inline-table":i="table";break;case"initial":case"unset":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":i="block";break;default:i=t}return B(i)}function Fr(e){return e===y.absolute||e===y.fixed}function vr(e){return e instanceof ai&&e.name==="running"}function zd(e,t,i,n){return e===y.none||(Fr(t)?(i=y.none,e=ru(e)):(i&&i!==y.none&&!Z(i)||n)&&(e=ru(e))),{display:e,position:t,float:i}}function Vd(e,t,i,n){return zd(e,t,i,n).display===y.block}function Ms(e){return e instanceof he||e instanceof J||typeof e=="string"}function Ut(e){if(!Ms(e))return!1;let t=e.toString();switch(t){case"inline":case"inline-block":case"inline-flex":case"inline-grid":case"ruby":case"inline-table":return!0;default:return t.includes("inline")}}function ur(e){return Ms(e)?e.toString().includes("list-item"):!1}function uv(e){if(!Ms(e))return!1;switch(e.toString()){case"block":case"flex":case"grid":case"table":case"list-item":case"flow-root":return!0;default:return!1}}function Ud(e){if(!Ms(e))return!1;switch(e.toString()){case"ruby-base":case"ruby-text":case"ruby-base-container":case"ruby-text-container":return!0;default:return!1}}function cv(e,t,i,n,r,o,s){return r=r||o||y.horizontal_tb,!!s||!!i&&i!==y.none&&!Z(i)||Fr(t)||e===y.inline_block||e===y.table_cell||e===y.table_caption||e==y.flex||e==y.grid||e==y.flow_root||(e===y.block||e===y.list_item)&&!!n&&n!==y.visible&&n!==y.clip&&!Z(n)||!!o&&r!==o}function dv(e){return e===y.relative||e===y.absolute||e===y.fixed}var ii=1e5;function _l(e){let t=e.element.style;t.columnGap=`${ii-(e.vertical?e.height:e.width)}px`,t.columnFill="auto",t.columnCount="1",t.columnWidth="0"}function _s(e){let t=("element"in e?e.element:e).style;t.columnWidth="",t.columnCount="",t.columnGap="",t.columnFill=""}function os(e){return e.element.style.columnCount==="1"}function pv(e){e.element.setAttribute("data-vivliostyle-column","true")}function Rr(e,t){let i=t?e.bottom:Math.max(Math.abs(e.left),Math.abs(e.right));return Math.round(i/ii)}function Dl(e,t){let i=Rr(e,t);if(i===0)return 0;let n=t?e.top:Math.min(Math.abs(e.left),Math.abs(e.right)),r=Math.round(n/ii),o=r*ii,s=i*ii;return t?(e.top-=o,e.bottom-=s,e.bottom<e.top&&(e.bottom+=ii),e.right-=o,e.left-=s):e.left<-ii/2?(e.right+=o,e.left+=s,e.left>e.right&&(e.left-=ii),e.top+=o,e.bottom+=s):(e.left-=o,e.right-=s,e.right<e.left&&(e.right+=ii),e.top+=o,e.bottom+=s),e.width=e.right-e.left,e.height=e.bottom-e.top,r}function ss(e,t){for(let i=0;i<e.length;i++)Dl(e[i],t)}function Bt(e,t,i){let n=e.getElementClientRect(t);if(Dl(n,i)>0&&e.getElementComputedStyle(t).display.startsWith("table")&&!eo(t)){let r=t.closest("[data-vivliostyle-column]");if(r)return _s(r),e.getElementClientRect(t)}return n}function fv(e,t){var i,n;if(e.nodeType===1){let r=e;((i=r.style)==null?void 0:i.breakAfter)==="column"&&(r.style.breakAfter="")}if(t.nodeType===1){let r=t;((n=r.style)==null?void 0:n.breakBefore)==="column"&&(r.style.breakBefore="")}}function Ma(e){let t=e.style;return t?!isNaN(parseFloat(t.columnCount))||!isNaN(parseFloat(t.columnWidth)):!1}function gv(e){if(!e.hasAttribute("data-vivliostyle-column")&&Ma(e))return!0;for(let t of e.querySelectorAll("*"))if(!t.hasAttribute("data-vivliostyle-column")&&Ma(t))return!0;return!1}function eo(e){for(let t=e.nodeType===1?e:e.parentElement;t;t=t.parentElement){let i=t.style;if(!i||t.hasAttribute("data-vivliostyle-column"))break;if(Ma(t))return t;if(i.position==="absolute")break}return null}function mv(e){var t;if(e.nodeType!==1)return;let i=e,n=i.style,r=n?.breakBefore==="column",o=i.previousElementSibling,s=o&&((t=o.style)==null?void 0:t.breakAfter)==="column";if(!r&&!s)return;let a=eo(i);if(!a)return;let h=a.ownerDocument.defaultView.getComputedStyle(a),{writingMode:l,direction:c,columnGap:d,fontSize:p}=h,f=l==="vertical-rl"||l==="vertical-lr",g=c==="rtl",v=(parseFloat(d)||parseFloat(p)||16)/2,w=a.getBoundingClientRect(),x=i.getBoundingClientRect();(f?x.top>w.bottom+v:g?x.right<w.left-v:x.left>w.right+v)&&(r&&(n.breakBefore=""),s&&o&&(o.style.breakAfter=""),n.marginBlockStart=`${ii}px`)}function po(e){let t=e.element.lastElementChild,i=t&&e.clientLayout.getElementClientRect(t);return i?Rr(i,e.vertical):0}function $d(e,t){if(e.getAttribute("data-viv-saved-column-fill")!=="auto"||po(t))return;let i=t.clientLayout.getElementComputedStyle(e),n=parseFloat(i.blockSize);e.style.columnFill="auto";let r=parseFloat(i.blockSize);if(r<=0||e.parentElement&&eo(e.parentElement)){e.removeAttribute("data-viv-saved-column-fill");return}let o=NaN;if(e.style.blockSize=`${r}px`,po(t)){if(e.style.blockSize=`${n}px`,!po(t)){let s=1/(t.clientLayout.pixelRatio||1),a=n,h=r;for(;h-a>s;){let l=(a+h)/2;e.style.blockSize=`${l}px`,po(t)?h=l:a=l}o=a,e.style.blockSize=`${o}px`}}else if(o=parseFloat(i.blockSize),o<r){let s=1/t.clientLayout.layoutUnitPerPixel;o=r+s,e.style.blockSize=`${o}px`}if(isNaN(o)){e.style.blockSize="",e.style.columnFill="balance";return}e.removeAttribute("data-viv-saved-column-fill")}function yv(e){let t=e.element.querySelectorAll('[data-viv-saved-column-fill="auto"]');for(let i of t)$d(i,e)}function bn(e,t,i,n){let r=e.viewNode;if(!r)return NaN;let o=r.nodeType===1?r:r.parentElement;if(o&&o.namespaceURI==="http://www.w3.org/1999/xhtml"){let s=o.style;if(o.localName==="wbr"||s&&Ut(s.display)&&/^([\d\.]|super|(text-)?top)/.test(s.verticalAlign))return NaN}if(r===o){if(o.localName==="br"){let s=o.ownerDocument.createElement("span");o.parentNode.insertBefore(s,o);let a=t.getElementClientRect(s);if(s.remove(),a){let h=[a];ss(h,n);let l=h[0],c=n?l.left:l.bottom;if(!isNaN(c)&&c!==0)return c}return NaN}if(e.after||!e.inline){if(e.after&&!e.inline&&o.querySelector("ruby")){let a=o.parentNode,h=o.nextSibling;a.removeChild(o),a.insertBefore(o,h)}let s=Bt(t,o,n);if(s.left===0&&s.top===0&&s.right===0&&s.bottom===0)return NaN;if(s.right>=s.left&&s.bottom>=s.top)return e.after?n?s.left:s.bottom:n?s.right:s.top}return NaN}else{let s=NaN,a=r.ownerDocument.createRange(),h=r.textContent.length;if(!h)return NaN;e.after&&(i+=h),i>=h&&(i=h-1),a.setStart(r,i),a.setEnd(r,i+1);let l=t.getRangeClientRects(a);ss(l,n);let c=l.filter(d=>d.right>d.left&&d.bottom>d.top);if(c.length>0)l=c;else{let d=o?t.getElementComputedStyle(o).whiteSpace:"";l=d==="pre"||d==="pre-wrap"||d==="pre-line"||d==="break-spaces"?l.filter(p=>n?p.right>p.left:p.bottom>p.top):[]}return l.length?(n?s=Math.min.apply(null,l.map(d=>d.left)):s=Math.max.apply(null,l.map(d=>d.bottom)),s):NaN}}function _a(e,t,i){let n=os(t);n&&_s(t);let r=t.clientLayout.getElementClientRect(e);n&&_l(t);let o=t.getComputedMargin(e);return i?r.width+o.left+o.right:r.height+o.top+o.bottom}function En(e){for(;e;){if(e.parentNode===e.ownerDocument)return!1;e=e.parentNode}return!0}function Hd(e,t){var i;if(e)for(let n=e.lastChild,r=n;n!==t;n=r)r=n.previousSibling,!(n.nodeType===1&&n.hasAttribute("data-vivliostyle-float-box-moved")&&((i=t.style)==null?void 0:i.display)==="inline")&&e.removeChild(n)}var zn="data-adapt-spec";function zl(e){return!!e.getAttribute(zn)}function Ot(e){return e?.nodeType!==1?!1:zl(e)?!0:Wd(e)}function Wd(e){var t,i;if(e?.nodeType!==1)return!1;let n=e,r=(t=n.style)==null?void 0:t.position;if(r==="absolute"||r==="fixed")return!0;let o=(i=n.style)==null?void 0:i.float;return o==="left"||o==="right"||o==="inline-start"||o==="inline-end"}function ou(e){var t;return e?.nodeType!==1?!1:((t=e.style)==null?void 0:t.position)==="fixed"}function Pn(e){let t=e?.viewNode;return t?.nodeType===1&&zl(t)}function vv(e){return e!=="inline"&&(Ut(e)||Ud(e))}function su(e){var t;for(let i=e.parent;i;i=i.parent)if((i.display!=="inline"||i.vertical!==((t=i.parent)==null?void 0:t.vertical))&&Ut(i.display))return i;return null}function wv(e){let t=e;for(;t;){if(t.nodeType===Node.TEXT_NODE&&t.textContent.length>0)return t;if(t.lastChild)t=t.lastChild;else{for(;t&&!t.previousSibling;)if(t=t.parentNode,t===e||!t)return null;t=t?.previousSibling||null}}return null}function Gd(e,t){let i={};return Object.keys(e).forEach(n=>{let r=i[n]={},o=e[n];Object.keys(o).forEach(s=>{r[s]=o[s].map(a=>{let h=t?a.logical:a.physical,l=t?a.physical:a.logical;return{regexp:new RegExp(`(-?)${h}(-?)`),to:`$1${l}$2`}})})}),i}function jd(e,t,i,n){let r=n[t];if(!r)throw new Error(`unknown writing-mode: ${t}`);let o=r[i||"ltr"];if(!o)throw new Error(`unknown direction: ${i}`);for(let s of o){let a=e.replace(s.regexp,s.to);if(a!==e)return a}return e}var Xd={"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"}]}},bv=Gd(Xd,!0);function qd(e,t,i){return jd(e,t,i||null,bv)}var xv=Gd(Xd,!1);function Yd(e,t,i){return jd(e,t,i||null,xv)}var Sv={"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 Cv(e,t){let i=Sv[t];if(!i)throw new Error(`unknown writing-mode: ${t}`);for(let n=0;n<i.length;n++)if(i[n].physical===e)return i[n].logical;return e}function Vl(e,t,i){var n;let r=t,o={width:r.style.width,height:r.style.height};function s(p){return e.getElementComputedStyle(t).getPropertyValue(p)}let a=s("writing-mode")!=="horizontal-tb",h=a?"height":"width",l=a?"width":"height";function c(p,f){r.style[p]=f;let g=s(p);return r.style[p]=o[p],g}let d={};for(let p of i){let f;switch(p){case"max-content inline size":f=c(h,"max-content");break;case"min-content inline size":f=c(h,"min-content");break;case"fit-content inline size":f=c(h,"fit-content");break;case"max-content block size":f=c(l,"max-content");break;case"min-content block size":f=c(l,"min-content");break;case"fit-content block size":f=c(l,"fit-content");break;case"max-content width":f=c("width","max-content");break;case"max-content height":f=c("height","max-content");break;case"min-content width":f=c("width","min-content");break;case"min-content height":f=c("height","min-content");break;case"fit-content width":f=c("width","fit-content");break;case"fit-content height":f=c("height","fit-content");break}f==="0px"&&t.childNodes.length===1&&((n=t.firstElementChild)==null?void 0:n.localName)==="img"&&!t.firstElementChild.complete&&(f="1px"),d[p]=parseFloat(f)}return d}function Nn(e){var t,i;return((t=e?.style)==null?void 0:t["box-decoration-break"])==="clone"||((i=e?.style)==null?void 0:i["-webkit-box-decoration-break"])==="clone"}function Zd(e){let t=e.getAttribute("data-viv-box-break");return t?t.split(" "):[]}function Kd(e,t){e.setAttribute("data-viv-box-break",t.join(" "))}function Ct(e,t){let i=Zd(e);i.includes(t)||(i.push(t),Kd(e,i))}function kv(e){let t=e.getAttribute("data-viv-margin-discard");return t?t.split(" "):[]}function Ev(e,t){e.setAttribute("data-viv-margin-discard",t.join(" "))}function sa(e,t){let i=kv(e);i.includes(t)||(i.push(t),Ev(e,i))}function Pv(e){let t=e.name,i=e.value;switch(t){case"page-break-before":case"page-break-after":case"page-break-inside":return{name:t.replace(/^page-/,""),value:i===y.always?y.page:i,important:e.important};default:return e}}var Da={page:!0,left:!0,right:!0,recto:!0,verso:!0,column:!0,region:!0};function Ze(e){return!!Da[e]}var Nv={left:!0,right:!0,recto:!0,verso:!0};function en(e){return!!Nv[e]}function au(e){return Ze(e)&&e!=="column"&&e!=="region"}var Tv={avoid:!0,"avoid-page":!0,"avoid-column":!0,"avoid-region":!0};function as(e){return!!Tv[e]}function nt(e,t){if(e)if(t){if(en(t))return t;if(en(e))return e;{let i=Ze(e),n=Ze(t);if(i&&n)switch(t){case"column":return e;case"region":return e==="column"?t:e;default:return t}else return n?t:i?e:as(t)?t:as(e)?e:t}}else return e;else return t}function lu(e){return Ze(e)?e:"auto"}Ft("SIMPLE_PROPERTY",Pv);var wr=$g(Wg());function Av(e,t){return(0,wr.default)(e,t,0)}function hu(e){return e.reduce((t,i)=>i[0]===wr.default.DELETE?t:t+i[1],"")}function Iv(e,t){return Jd(e,t,1)}function Fv(e,t){return Jd(e,t,-1)}function Jd(e,t,i){let n=0,r=0;return e.some(o=>{for(let s=0;s<o[1].length;s++){switch(o[0]*i){case wr.default.INSERT:n++;break;case wr.default.DELETE:n--,r++;break;case wr.default.EQUAL:r++;break}if(r>t)return!0}return!1}),Math.max(Math.min(t,r-1)+n,0)}var za;(e=>{function t(i){return i&&i.formattingContextType==="Block"}e.isInstanceOfBlockFormattingContext=t})(za||(za={}));var Rn;(e=>{let t;(i=>(i.INLINE="inline",i.COLUMN="column",i.REGION="region",i.PAGE="page"))(t=e.FloatReference||(e.FloatReference={}))})(Rn||(Rn={}));var ls;(e=>{function t(i){return i&&i.flagmentLayoutConstraintType=="AfterIfContinue"}e.isInstanceOfAfterIfContinuesLayoutConstraint=t})(ls||(ls={}));var Yi;(e=>{function t(n){return n?n.formattingContextType==="RepetitiveElementsOwner"||Li.isInstanceOfTableFormattingContext(n):!1}e.isInstanceOfRepetitiveElementsOwnerFormattingContext=t;function i(n){return n?n.flagmentLayoutConstraintType==="RepetitiveElementsOwner"||Li.isInstanceOfTableRowLayoutConstraint(n):!1}e.isInstanceOfRepetitiveElementsOwnerLayoutConstraint=i})(Yi||(Yi={}));var Li;(e=>{function t(n){return n&&n.formattingContextType==="Table"}e.isInstanceOfTableFormattingContext=t;function i(n){return n&&n.flagmentLayoutConstraintType==="TableRow"}e.isInstanceOfTableRowLayoutConstraint=i})(Li||(Li={}));var yi;(e=>{let t;(n=>(n[n.IGNORE=0]="IGNORE",n[n.NEWLINE=1]="NEWLINE",n[n.PRESERVE=2]="PRESERVE"))(t=e.Whitespace||(e.Whitespace={}));let i;(n=>(n[n.NONE=0]="NONE",n[n.CONTENT=1]="CONTENT",n[n.ROOTLESS=2]="ROOTLESS",n[n.ROOTED=3]="ROOTED"))(i=e.ShadowType||(e.ShadowType={}))})(yi||(yi={}));var Rv={transform:!0,"transform-origin":!0},Lv={top:!0,bottom:!0,left:!0,right:!0},Ul=class{constructor(e,t,i){u(this,"target",e),u(this,"name",t),u(this,"value",i)}},Ov={show:function(e){e.style.visibility="visible"},hide:function(e){e.style.visibility="hidden"},play:function(e){e.currentTime=0,e.play()},pause:function(e){e.pause()},resume:function(e){e.play()},mute:function(e){e.muted=!0},unmute:function(e){e.muted=!1}};function Bv(e,t){let i=Ov[t];return i?()=>{for(let n=0;n<e.length;n++)try{i(e[n])}catch{}}:null}var Va=class cr extends Nl{constructor(t,i){super(),u(this,"container",t),u(this,"bleedBox",i),u(this,"pageAreaElement",null),u(this,"delayedItems",[]),u(this,"hrefHandler"),u(this,"elementsById",{}),u(this,"dimensions",{width:0,height:0}),u(this,"isFirstPage",!1),u(this,"isLastPage",!1),u(this,"isBlankPage",!1),u(this,"isAutoPageWidth",!0),u(this,"isAutoPageHeight",!0),u(this,"spineIndex",0),u(this,"position",null),u(this,"offset",-1),u(this,"side",null),u(this,"fetchers",[]),u(this,"marginBoxes",{top:{},bottom:{},left:{},right:{}}),u(this,"pageFloatLayoutContext",null),u(this,"pageType",null),this.hrefHandler=n=>{let r=n.currentTarget,o=r.getAttribute("href")||r.getAttributeNS("http://www.w3.org/1999/xlink","href");if(o){let s={type:"hyperlink",target:null,currentTarget:null,anchorElement:r,href:o,preventDefault(){n.preventDefault()}};this.dispatchEvent(s)}}}setAutoPageWidth(t){this.isAutoPageWidth=t,t?this.container.setAttribute(cr.AUTO_PAGE_WIDTH_ATTRIBUTE,"true"):this.container.removeAttribute(cr.AUTO_PAGE_WIDTH_ATTRIBUTE)}setAutoPageHeight(t){this.isAutoPageHeight=t,t?this.container.setAttribute(cr.AUTO_PAGE_HEIGHT_ATTRIBUTE,"true"):this.container.removeAttribute(cr.AUTO_PAGE_HEIGHT_ATTRIBUTE)}registerElementWithId(t,i){let n=this.elementsById[i];n?n.push(t):this.elementsById[i]=[t]}finish(t,i){Object.keys(this.elementsById).forEach(o=>{let s=this.elementsById[o];for(let a=0;a<s.length;)this.container.contains(s[a])?a++:s.splice(a,1);s.length===0&&delete this.elementsById[o]});let n=this.delayedItems;for(let o=0;o<n.length;o++){let s=n[o];s.target===this.container&&s.name==="transform"&&!this.isAutoPageWidth&&!this.isAutoPageHeight||I(s.target,s.name,s.value.toString())}let r=i.getElementClientRect(this.container);this.dimensions.width=r.width,this.dimensions.height=r.height;for(let o=0;o<t.length;o++){let s=t[o],a=this.elementsById[s.ref],h=this.elementsById[s.observer];if(a&&h){let l=Bv(a,s.action);if(l)for(let c=0;c<h.length;c++)h[c].addEventListener(s.event,l,!1)}}}};u(Va,"AUTO_PAGE_WIDTH_ATTRIBUTE","data-vivliostyle-auto-page-width"),u(Va,"AUTO_PAGE_HEIGHT_ATTRIBUTE","data-vivliostyle-auto-page-height");var Qd=Va,bt=yi.Whitespace;function ep(e){switch(e){case"normal":case"nowrap":return bt.IGNORE;case"pre-line":return bt.NEWLINE;case"pre":case"pre-wrap":case"break-spaces":return bt.PRESERVE;default:return null}}function Ee(e,t){return e?e.nodeType==1?!1:tp(e.textContent,t):!0}function tp(e,t){switch(t){case bt.PRESERVE:return e.length==0;case bt.NEWLINE:return!!e.match(/^[ \t]*$/);case bt.IGNORE:default:return!!e.match(/^[ \t\r\n\f]*$/)}}var Mv=class{constructor(e,t){u(this,"flowName",e),u(this,"parentFlowName",t),u(this,"forcedBreakOffsets",[]),u(this,"formattingContext",null)}},_v=class{constructor(e,t,i,n,r,o,s,a,h){u(this,"flowName",e),u(this,"element",t),u(this,"startOffset",i),u(this,"priority",n),u(this,"linger",r),u(this,"exclusive",o),u(this,"repeated",s),u(this,"last",a),u(this,"breakBefore",h),u(this,"startPage",-1)}isBetter(e){return this.exclusive?!e.exclusive||this.priority>e.priority?!0:this.last:!1}};function Dv(e,t){return e.top-t.top}function zv(e,t){return t.right-e.right}function ip(e,t){var i,n;return e===t?!0:!e||!t?!1:(e.node===t.node||!!e.shadowContext&&!!t.shadowContext&&e.shadowType===yi.ShadowType.ROOTLESS&&t.shadowType===yi.ShadowType.ROOTLESS&&((i=e.node)==null?void 0:i.outerHTML)===((n=t.node)==null?void 0:n.outerHTML))&&e.shadowType===t.shadowType&&Ua(e.shadowContext,t.shadowContext)&&Ua(e.nodeShadow,t.nodeShadow)&&ip(e.shadowSibling,t.shadowSibling)}function Oi(e,t){if(e===t)return!0;if(!e||!t||e.offsetInNode!==t.offsetInNode||e.after!==t.after||e.steps.length!==t.steps.length)return!1;for(let i=0;i<e.steps.length;i++)if(!ip(e.steps[i],t.steps[i]))return!1;return!0}function Vv(e){return{steps:[{node:e,shadowType:st.NONE,shadowContext:null,nodeShadow:null,shadowSibling:null,formattingContext:null,fragmentIndex:0}],offsetInNode:0,after:!1,preprocessedTextContent:null}}function hs(e,t){return{steps:[{node:e.sourceNode,shadowType:st.NONE,shadowContext:e.shadowContext,nodeShadow:null,shadowSibling:null,formattingContext:e.formattingContext,fragmentIndex:t??e.fragmentIndex}],offsetInNode:0,after:!1,preprocessedTextContent:e.preprocessedTextContent}}function us(e,t){let i=new xn(e.node,t,0);return i.shadowType=e.shadowType,i.shadowContext=e.shadowContext,i.nodeShadow=e.nodeShadow,i.shadowSibling=e.shadowSibling?us(e.shadowSibling,t.copy()):null,i.formattingContext=e.formattingContext,i.fragmentIndex=e.fragmentIndex+1,i}var st=yi.ShadowType,Bo=class{constructor(e,t,i,n,r,o,s){u(this,"owner",e),u(this,"root",t),u(this,"xmldoc",i),u(this,"parentShadow",n),u(this,"type",o),u(this,"styler",s),u(this,"subShadow",null),r&&(r.subShadow=this)}equals(e){return e?this.owner===e.owner&&this.xmldoc===e.xmldoc&&this.type===e.type&&Ua(this.parentShadow,e.parentShadow):!1}};function Ua(e,t){return e===t||!!e&&!!t&&e.equals(t)}var Uv=class{constructor(e,t){u(this,"outer",e),u(this,"count",t)}},xn=class np{constructor(t,i,n){u(this,"sourceNode",t),u(this,"parent",i),u(this,"boxOffset",n),u(this,"offsetInNode",0),u(this,"after",!1),u(this,"shadowType"),u(this,"shadowContext"),u(this,"nodeShadow",null),u(this,"shadowSibling",null),u(this,"shared",!1),u(this,"inline",!0),u(this,"overflow",!1),u(this,"breakPenalty"),u(this,"display",null),u(this,"floatReference"),u(this,"floatSide",null),u(this,"clearSide",null),u(this,"floatMinWrapBlock",null),u(this,"columnSpan",null),u(this,"captionSide","top"),u(this,"inlineBorderSpacing",0),u(this,"blockBorderSpacing",0),u(this,"flexContainer",!1),u(this,"whitespace"),u(this,"hyphenateCharacter"),u(this,"breakWord"),u(this,"establishesBFC",!1),u(this,"containingBlockForAbsolute",!1),u(this,"breakBefore",null),u(this,"breakAfter",null),u(this,"viewNode",null),u(this,"clearSpacer",null),u(this,"inheritedProps"),u(this,"vertical"),u(this,"direction"),u(this,"firstPseudo"),u(this,"lang",null),u(this,"preprocessedTextContent",null),u(this,"formattingContext"),u(this,"repeatOnBreak",null),u(this,"pluginProps",{}),u(this,"fragmentIndex",1),u(this,"afterIfContinues",null),u(this,"footnotePolicy",null),u(this,"pageType"),this.shadowType=st.NONE,this.shadowContext=i?i.shadowContext:null,this.breakPenalty=i?i.breakPenalty:0,this.floatReference=Rn.FloatReference.INLINE,this.whitespace=i?i.whitespace:bt.IGNORE,this.hyphenateCharacter=i?i.hyphenateCharacter:null,this.breakWord=i?i.breakWord:!1,this.inheritedProps=i?i.inheritedProps:{},this.vertical=i?i.vertical:!1,this.direction=i?i.direction:"ltr",this.firstPseudo=i?i.firstPseudo:null,this.formattingContext=i?i.formattingContext:null,this.pageType=i?i.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=Rn.FloatReference.INLINE,this.floatSide=null,this.clearSide=null,this.floatMinWrapBlock=null,this.columnSpan=null,this.flexContainer=!1,this.whitespace=this.parent?this.parent.whitespace:bt.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,this.pageType=this.parent?this.parent.pageType:null}cloneItem(){let t=new np(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.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.pageType=this.pageType,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(),i=t,n;for(;(n=i.parent)!=null;)n=n.cloneItem(),i.parent=n,i=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 t,i,n;let r=this,o=[];r.shadowType===yi.ShadowType.ROOTLESS&&(r.floatReference!==Rn.FloatReference.INLINE||r.floatSide==="footnote")&&(n=(i=(t=r.shadowContext)==null?void 0:t.styler)==null?void 0:i.style)!=null&&n._pseudos&&(r=r.parent);do(!r.firstPseudo||!r.parent||r.parent.firstPseudo===r.firstPseudo)&&o.push(r.toNodePositionStep()),r=r.parent;while(r);let s=this.preprocessedTextContent?Fv(this.preprocessedTextContent,this.offsetInNode):this.offsetInNode;return{steps:o,offsetInNode:s,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}},Bi=class rp{constructor(t){u(this,"primary",t),u(this,"floats",null)}clone(){let t=new rp(this.primary);if(this.floats){t.floats=[];for(let i=0;i<this.floats.length;++i)t.floats[i]=this.floats[i]}return t}isSamePosition(t){if(!t)return!1;if(this===t)return!0;if(!Oi(this.primary,t.primary))return!1;if(this.floats){if(!t.floats||this.floats.length!==t.floats.length)return!1;for(let i=0;i<this.floats.length;i++)if(!Oi(this.floats[i],t.floats[i]))return!1}else if(t.floats)return!1;return!0}},$v=class op{constructor(t,i){u(this,"chunkPosition",t),u(this,"flowChunk",i)}clone(){return new op(this.chunkPosition.clone(),this.flowChunk)}isSamePosition(t){return!!t&&(this===t||this.chunkPosition.isSamePosition(t.chunkPosition))}},Hv=class sp{constructor(){u(this,"positions",[]),u(this,"startBreakType",null),u(this,"breakAfter",null)}clone(){let t=new sp,i=this.positions,n=t.positions;for(let r=0;r<i.length;r++)n[r]=i[r].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 i=0;i<this.positions.length;i++)if(!this.positions[i].isSamePosition(t.positions[i]))return!1;return!0}hasContent(t){return this.positions.length>0&&this.positions[0].flowChunk.startOffset<=t}},Wv=class ap{constructor(){u(this,"page",0),u(this,"flows",{}),u(this,"flowPositions",{}),u(this,"isBlankPage",!1),u(this,"highestSeenOffset",0),u(this,"highestSeenNode"),u(this,"lookupPositionOffset")}clone(){let t=new ap;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 i in this.flowPositions)t.flowPositions[i]=this.flowPositions[i].clone();return t}isSamePosition(t){if(this===t)return!0;if(!t||this.page!==t.page)return!1;let i=Object.keys(this.flowPositions),n=Object.keys(t.flowPositions);if(i.length!==n.length)return!1;for(let r of i)if(!this.flowPositions[r].isSamePosition(t.flowPositions[r]))return!1;return!0}hasContent(t,i){let n=this.flowPositions[t];return n?n.hasContent(i):!1}startSideOfFlow(t){var i;let n=(i=this.flowPositions[t])==null?void 0:i.startBreakType;return n&&en(n)?n:"any"}firstFlowChunkOfFlow(t){let i=this.flowPositions[t];if(!i)return null;let n=i.positions[0];return n?n.flowChunk:null}},lp=class{constructor(e){u(this,"element",e),u(this,"left",0),u(this,"top",0),u(this,"marginLeft",0),u(this,"marginRight",0),u(this,"marginTop",0),u(this,"marginBottom",0),u(this,"borderLeft",0),u(this,"borderRight",0),u(this,"borderTop",0),u(this,"borderBottom",0),u(this,"paddingLeft",0),u(this,"paddingRight",0),u(this,"paddingTop",0),u(this,"paddingBottom",0),u(this,"width",0),u(this,"height",0),u(this,"originX",0),u(this,"originY",0),u(this,"exclusions",null),u(this,"innerShape",null),u(this,"computedBlockSize",0),u(this,"snapWidth",0),u(this,"snapHeight",0),u(this,"snapOffsetX",0),u(this,"snapOffsetY",0),u(this,"vertical",!1),u(this,"rtl",!1),u(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(e){return this.vertical?e.right:e.top}getAfterEdge(e){return this.vertical?e.left:e.bottom}getStartEdge(e){return this.vertical?this.rtl?e.bottom:e.top:this.rtl?e.right:e.left}getEndEdge(e){return this.vertical?this.rtl?e.top:e.bottom:this.rtl?e.left:e.right}getInlineSize(e){return this.vertical?e.bottom-e.top:e.right-e.left}getBoxSize(e){return this.vertical?e.right-e.left:e.bottom-e.top}getBoxDir(){return this.vertical?-1:1}getInlineDir(){return this.rtl?-1:1}copyFrom(e){this.element=e.element,this.left=e.left,this.top=e.top,this.marginLeft=e.marginLeft,this.marginRight=e.marginRight,this.marginTop=e.marginTop,this.marginBottom=e.marginBottom,this.borderLeft=e.borderLeft,this.borderRight=e.borderRight,this.borderTop=e.borderTop,this.borderBottom=e.borderBottom,this.paddingLeft=e.paddingLeft,this.paddingRight=e.paddingRight,this.paddingTop=e.paddingTop,this.paddingBottom=e.paddingBottom,this.width=e.width,this.height=e.height,this.originX=e.originX,this.originY=e.originY,this.innerShape=e.innerShape,this.exclusions=e.exclusions,this.computedBlockSize=e.computedBlockSize,this.snapWidth=e.snapWidth,this.snapHeight=e.snapHeight,this.vertical=e.vertical,this.rtl=e.rtl,this.borderBoxSizing=e.borderBoxSizing}setVerticalPosition(e,t){this.top=e,this.height=t,I(this.element,"top",`${e}px`),I(this.element,"height",`${t}px`)}setHorizontalPosition(e,t){this.left=e,this.width=t,I(this.element,"left",`${e}px`),I(this.element,"width",`${t}px`)}setBlockPosition(e,t){if(this.vertical){let i=t+this.marginLeft+this.marginRight+(this.borderBoxSizing?0:this.paddingLeft+this.paddingRight+this.borderLeft+this.borderRight);this.setHorizontalPosition(e+i*this.getBoxDir(),t)}else this.setVerticalPosition(e,t)}setInlinePosition(e,t){if(this.vertical)if(this.rtl){let i=t+this.marginTop+this.marginBottom+(this.borderBoxSizing?0:this.paddingTop+this.paddingBottom+this.borderTop+this.borderBottom);this.setVerticalPosition(e+i*this.getInlineDir(),t)}else this.setVerticalPosition(e,t);else if(this.rtl){let i=t+this.marginLeft+this.marginRight+(this.borderBoxSizing?0:this.paddingLeft+this.paddingRight+this.borderLeft+this.borderRight);this.setHorizontalPosition(e+i*this.getInlineDir(),t)}else this.setHorizontalPosition(e,t)}clear(){let e=this.element,t;for(;t=e.lastChild;)e.removeChild(t)}getInnerShape(){let e=this.getInnerRect();return this.innerShape?this.innerShape.withOffset(e.x1,e.y1):Ol(e.x1,e.y1,e.x2,e.y2)}getInnerRect(){let e=this.originX+this.left+this.getInsetLeft(),t=this.originY+this.top+this.getInsetTop();return new Mt(e,t,e+this.width,t+this.height)}getPaddingRect(){let e=this.originX+this.left+this.marginLeft+this.borderLeft,t=this.originY+this.top+this.marginTop+this.borderTop,i=this.paddingLeft+this.width+this.paddingRight,n=this.paddingTop+this.height+this.paddingBottom;return new Mt(e,t,e+i,t+n)}getOuterShape(e,t){let i=this.getOuterRect();return ld(e,i.x1,i.y1,i.x2-i.x1,i.y2-i.y1,t)}getOuterRect(){let e=this.originX+this.left,t=this.originY+this.top,i=this.getInsetLeft()+this.width+this.getInsetRight(),n=this.getInsetTop()+this.height+this.getInsetBottom();return new Mt(e,t,e+i,t+n)}},Lr=class extends Kt{constructor(e,t,i,n){super(),u(this,"elem",e),u(this,"context",t),u(this,"rootContentValue",i),u(this,"exprContentListener",n)}visitStrInner(e,t){var i;if(!t){if(((i=this.elem.lastChild)==null?void 0:i.nodeType)===3){this.elem.lastChild.textContent+=e;return}t=this.elem.ownerDocument.createTextNode(e)}this.elem.appendChild(t)}visitStr(e){return this.visitStrInner(e.str),null}visitURL(e){if(this.rootContentValue instanceof Qe)this.elem.setAttribute("src",e.url);else{let t=this.elem.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml","img");t.setAttribute("src",e.url),this.elem.appendChild(t)}return null}visitSpaceList(e){return this.visitValues(e.values),null}visitExpr(e){let t=e.toExpr();if(t instanceof we){let n=t;if(typeof n.getContentList=="function"){let r=n.getContentList();if(r)return r.visit(this),null}}let i=t.evaluate(this.context);if(typeof i=="string"){this.elem.ownerDocument;let n=this.exprContentListener(t,i,this.elem.ownerDocument);!n&&i&&t instanceof we&&t.str.startsWith("running-element-")&&(i=""),this.visitStrInner(i,n)}return null}};function It(e){return e!=null&&e!==Me&&e!==y.normal&&e!==y.none&&!Z(e)}var Pe=Rn.FloatReference,Gv=20;function jv(e){switch(e){case"inline":return Pe.INLINE;case"column":return Pe.COLUMN;case"region":return Pe.REGION;case"page":return Pe.PAGE;default:throw new Error(`Unknown float-reference: ${e}`)}}function Ii(e){switch(e){case Pe.INLINE:return!1;case Pe.COLUMN:case Pe.REGION:case Pe.PAGE:return!0;default:throw new Error(`Unknown float-reference: ${e}`)}}function aa(e,t,i,n){let r=t?"vertical-rl":"horizontal-tb";if((e==="top"||e==="bottom")&&(e=Yd(e,r,i)),e==="block-start"&&(e="inline-start"),e==="block-end"&&(e="inline-end"),e==="inline-start"||e==="inline-end"){let o=qd(e,r,i),s=Cv(o,r);s==="line-left"?e="left":s==="line-right"&&(e="right")}else e==="inside"?e=n==="left"?"right":"left":e==="outside"&&(e=n==="left"?"left":"right");return e!=="left"&&e!=="right"&&(Y.warn(`Invalid float value: ${e}. Fallback to left.`),e="left"),e}var hp=class{constructor(e,t,i,n,r,o){u(this,"nodePosition",e),u(this,"floatReference",t),u(this,"floatSide",i),u(this,"clearSide",n),u(this,"flowName",r),u(this,"floatMinWrapBlock",o),u(this,"order",null),u(this,"id",null),u(this,"insidePageFloatArea",!1),u(this,"parentPageFloat",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(e){return e.isAnchorAlreadyAppeared(this.getId())?!0:this.insidePageFloatArea&&this.parentPageFloat?!!e.findPageFloatFragment(this.parentPageFloat):!1}isAllowedToPrecede(e){return!1}},Xv=class{constructor(){u(this,"floats",[]),u(this,"nextPageFloatIndex",0)}nextOrder(){return this.nextPageFloatIndex++}createPageFloatId(e){return`pf${e}`}addPageFloat(e){if(this.floats.findIndex(t=>Oi(t.nodePosition,e.nodePosition))>=0)throw new Error("A page float with the same source node is already registered");{let t=e.order=this.nextOrder();e.id=this.createPageFloatId(t),this.floats.push(e)}}findPageFloatByNodePosition(e){let t=this.floats.findIndex(n=>Oi(n.nodePosition,e));if(t>=0)return this.floats[t];let i=e?.steps;if(i!=null&&i.length){let n=this.floats.findIndex(r=>{let o=r.nodePosition.steps;if(!(o!=null&&o.length)||o.length===i.length||r.nodePosition.offsetInNode!==e.offsetInNode||r.nodePosition.after!==e.after)return!1;let s=Math.min(o.length,i.length);for(let a=0;a<s;a++)if(o[a].node!==i[a].node)return!1;return!0});if(n>=0)return this.floats[n]}return null}findPageFloatById(e){let t=this.floats.findIndex(i=>i.id===e);return t>=0?this.floats[t]:null}},up=class{constructor(e,t,i,n,r,o){u(this,"floatReference",e),u(this,"floatSide",t),u(this,"clearSide",i),u(this,"continuations",n),u(this,"area",r),u(this,"continues",o)}hasFloat(e){return this.continuations.some(t=>t.float===e)}findNotAllowedFloat(e){for(let t=this.continuations.length-1;t>=0;t--){let i=this.continuations[t].float;if(!i.isAllowedOnContext(e))return i}return null}getOuterShape(){return this.area.getOuterShape(null,null)}getOuterRect(){return this.area.getOuterRect()}getOrder(){let e=this.continuations.map(t=>t.float);return Math.min.apply(null,e.map(t=>t.getOrder()))}shouldBeStashedBefore(e){return this.getOrder()<e.getOrder()}addContinuations(e){e.forEach(t=>{this.continuations.push(t)})}getFlowName(){let e=this.continuations[0].float.flowName;return this.continuations.every(t=>t.float.flowName===e),e}},uu=class{constructor(e,t){u(this,"float",e),u(this,"nodePosition",t)}equals(e){return e?this===e?!0:this.float===e.float&&Oi(this.nodePosition,e.nodePosition):!1}},Sn=class{constructor(e,t,i,n,r,o,s){u(this,"parent",e),u(this,"floatReference",t),u(this,"container",i),u(this,"flowName",n),u(this,"generatingNodePosition",r),u(this,"children",[]),u(this,"writingMode"),u(this,"direction"),u(this,"invalidated",!1),u(this,"floatStore"),u(this,"forbiddenFloats",[]),u(this,"floatFragments",[]),u(this,"stashedFloatFragments",[]),u(this,"floatAnchors",{}),u(this,"floatsDeferredToNext",[]),u(this,"floatsDeferredFromPrevious"),u(this,"layoutConstraints",[]),u(this,"locked",!1),u(this,"footnoteMaxBlockSize",null),u(this,"ignoreFootnoteAreaMaxHeight",!1),u(this,"footnoteAnchorsSeen",new Set),u(this,"lineFootnoteInvalidationMaxBlockSize",new Map),u(this,"lineFootnoteFinishInvalidatedOnce",new Set),u(this,"outerContext",null),e&&e.children.push(this),this.writingMode=!Z(o)&&o||e&&e.writingMode||y.horizontal_tb,this.direction=!Z(s)&&s||e&&e.direction||y.ltr,this.floatStore=e?e.floatStore:new Xv;let a=this.getPreviousSibling();this.floatsDeferredFromPrevious=a?[].concat(a.floatsDeferredToNext):[]}get effectiveParent(){var e;return(e=this.parent)!=null?e:this.outerContext}getParent(e){if(this.parent)return this.parent;if(this.outerContext)return this.outerContext;throw new Error(`No PageFloatLayoutContext for ${e}`)}setOuterContext(e){this.outerContext=e,this.floatStore=e.floatStore}addPageFloatLayoutContextAsPreviousSibling(e){this.children.push(e)}getPreviousSiblingOf(e,t,i,n){let r=this.children.indexOf(e);r<0&&(r=this.children.length);for(let o=r-1;o>=0;o--){let s=this.children[o];if(s.floatReference===t&&s.flowName===i&&Oi(s.generatingNodePosition,n)||(s=s.getPreviousSiblingOf(null,t,i,n),s))return s}return null}getPreviousSibling(){let e=this,t=this.parent,i;for(;t;){if(i=t.getPreviousSiblingOf(e,this.floatReference,this.flowName,this.generatingNodePosition),i)return i;e=t,t=t.parent}return null}getContainer(e){return!e||e===this.floatReference?this.container:this.getParent(e).getContainer(e)}setContainer(e){this.container=e,this.reattachFloatFragments()}addPageFloat(e){this.floatStore.addPageFloat(e)}getPageFloatLayoutContext(e){return e===this.floatReference?this:this.getParent(e).getPageFloatLayoutContext(e)}findPageFloatByNodePosition(e){return this.floatStore.findPageFloatByNodePosition(e)}forbid(e){let t=e.getId(),i=e.floatReference;i===this.floatReference?this.forbiddenFloats.includes(t)||(this.forbiddenFloats.push(t),new Vn().findByFloat(e).forbid(e,this)):this.getParent(i).forbid(e)}isForbidden(e){let t=e.getId(),i=e.floatReference;return i===this.floatReference?this.forbiddenFloats.includes(t):this.getParent(i).isForbidden(e)}addPageFloatFragment(e,t){let i=e.floatReference;i!==this.floatReference?this.getParent(i).addPageFloatFragment(e,t):this.floatFragments.includes(e)||(this.floatFragments.push(e),this.floatFragments.sort((n,r)=>n.getOrder()-r.getOrder())),t||this.invalidate()}removePageFloatFragment(e,t){let i=e.floatReference;if(i!==this.floatReference)this.getParent(i).removePageFloatFragment(e,t);else{let n=this.floatFragments.indexOf(e);if(n>=0){let r=this.floatFragments.splice(n,1)[0],o=r.area&&r.area.element;o&&o.parentNode&&o.parentNode.removeChild(o),t||this.invalidate()}}}findPageFloatFragment(e){if(e.floatReference!==this.floatReference)return this.getParent(e.floatReference).findPageFloatFragment(e);let t=this.floatFragments.findIndex(i=>i.hasFloat(e));return t>=0?this.floatFragments[t]:null}hasFloatFragments(e){return this.floatFragments.length>0&&(!e||this.floatFragments.some(e))?!0:this.parent?this.parent.hasFloatFragments(e):!1}hasContinuingFloatFragmentsInFlow(e){return this.hasFloatFragments(t=>t.continues&&t.getFlowName()===e&&t.floatSide!=="block-end")}markPageFloatAnchorSeen(e){var t;if(!("footnotePolicy"in e))return;let i=this;for(;i;)i.footnoteAnchorsSeen.add(e.getId()),i=(t=i.parent)!=null?t:i.outerContext}registerPageFloatAnchor(e,t){this.floatAnchors[e.getId()]=t,this.markPageFloatAnchorSeen(e)}collectPageFloatAnchors(){let e=Object.assign({},this.floatAnchors);return this.children.reduce((t,i)=>Object.assign(t,i.collectPageFloatAnchors()),e)}findPageFloatAnchor(e){var t;for(let i=this.children.length-1;i>=0;i--){let n=this.children[i].findPageFloatAnchor(e);if(n)return n}return(t=this.floatAnchors[e])!=null?t:null}hasCurrentAnchor(e){var t,i;let n=this.findPageFloatAnchor(e);return n?!!((i=(t=this.container)==null?void 0:t.element)!=null&&i.contains(n)):!1}hasInvalidatedForLineFootnote(e){return e.floatReference===this.floatReference?this.lineFootnoteInvalidationMaxBlockSize.get(e.getId())===this.footnoteMaxBlockSize:this.getParent(e.floatReference).hasInvalidatedForLineFootnote(e)}markInvalidatedForLineFootnote(e){e.floatReference===this.floatReference?this.lineFootnoteInvalidationMaxBlockSize.set(e.getId(),this.footnoteMaxBlockSize):this.getParent(e.floatReference).markInvalidatedForLineFootnote(e)}isAnchorAlreadyAppeared(e){if(this.getDeferredPageFloatContinuations().some(i=>i.float.getId()===e))return!0;let t=this.findPageFloatAnchor(e);return t&&this.container&&this.container.element?this.container.element.contains(t):!1}deferPageFloat(e){let t=e.float;if(t.floatReference===this.floatReference){let i=this.floatsDeferredToNext.findIndex(n=>n.float===t);i>=0?this.floatsDeferredToNext.splice(i,1,e):this.floatsDeferredToNext.push(e)}else this.getParent(t.floatReference).deferPageFloat(e)}removeFloatDeferredToNext(e){let t=this.floatsDeferredToNext.findIndex(i=>i.float===e);t>=0&&this.floatsDeferredToNext.splice(t,1)}hasPrecedingFloatsDeferredToNext(e,t){if(!t&&e.floatReference!==this.floatReference)return this.getParent(e.floatReference).hasPrecedingFloatsDeferredToNext(e,!1);let i=e.getOrder();return this.floatsDeferredToNext.some(n=>n.float.getOrder()<i&&!e.isAllowedToPrecede(n.float))?!0:this.parent?this.parent.hasPrecedingFloatsDeferredToNext(e,!0):!1}getLastFollowingFloatInFragments(e){let t=e.getOrder(),i=null;if(this.floatFragments.forEach(n=>{n.continuations.forEach(r=>{let o=r.float,s=o.getOrder();s>t&&(!i||s>i.getOrder())&&(i=o)})}),this.parent){let n=this.parent.getLastFollowingFloatInFragments(e);n&&(!i||n.getOrder()>i.getOrder())&&(i=n)}return i}getDeferredPageFloatContinuations(e){e=e||this.flowName;let t=this.floatsDeferredFromPrevious.filter(i=>!e||i.float.flowName===e);return this.parent&&(t=this.parent.getDeferredPageFloatContinuations(e).concat(t)),t.sort((i,n)=>i.float.getOrder()-n.float.getOrder())}getPageFloatContinuationsDeferredToNext(e){e=e||this.flowName;let t=this.floatsDeferredToNext.filter(i=>!e||i.float.flowName===e);return this.parent?this.parent.getPageFloatContinuationsDeferredToNext(e).concat(t):t}getFloatsDeferredToNextInChildContexts(){let e=[],t=[];for(let i=this.children.length-1;i>=0;i--){let n=this.children[i];t.includes(n.flowName)||(t.push(n.flowName),e=e.concat(n.floatsDeferredToNext.map(r=>r.float)),e=e.concat(n.getFloatsDeferredToNextInChildContexts()))}return e}hasRootMultiColumnFootnoteContext(){return this.children.some(e=>{let t=0;for(let i of e.children)if(!i.generatingNodePosition&&(t+=1,t>1))return!0;return!1})}hasNonRootMultiColumnFootnoteContext(){return this.children.some(e=>e.children.some(t=>{var i;let n=(i=t.getContainer())==null?void 0:i.element;return n!=null&&gv(n)}))}hasMultiColumnFootnoteContext(){return this.hasRootMultiColumnFootnoteContext()||this.hasNonRootMultiColumnFootnoteContext()}trySetFootnoteRetryMaxBlockSize(e){let t=this.footnoteMaxBlockSize!=null?this.footnoteMaxBlockSize/2:e/2;return t<Gv?!1:(this.footnoteMaxBlockSize=t,!0)}initFootnoteRetryFromEmptyFragment(e,t){if(!("footnotePolicy"in e&&this.footnoteMaxBlockSize==null&&this.footnoteAnchorsSeen.has(e.getId())&&this.hasMultiColumnFootnoteContext()))return!1;let i=(t.vertical?t.width:t.height)+t.getInsetBefore()+t.getInsetAfter();return this.trySetFootnoteRetryMaxBlockSize(i)}checkAndForbidNotAllowedFloat(){if(this.checkAndForbidFloatFollowingDeferredFloat())return!0;for(let e=this.floatFragments.length-1;e>=0;e--){let t=this.floatFragments[e],i=t.findNotAllowedFloat(this);if(i){let n=t.area&&"isFootnote"in t.area&&t.area.isFootnote;if(this.locked)this.invalidate();else{let r=n&&"footnotePolicy"in i&&i.footnotePolicy===y.line;if(n&&this.footnoteAnchorsSeen.has(i.getId())&&(r||this.hasMultiColumnFootnoteContext())){let o=t.area.computedBlockSize+t.area.getInsetBefore()+t.area.getInsetAfter();if(this.trySetFootnoteRetryMaxBlockSize(o))return this.removePageFloatFragment(t),this.removeEndFloatFragments(t.floatSide),!0}this.removePageFloatFragment(t),this.forbid(i),this.removeEndFloatFragments(t.floatSide)}return!0}}return this.floatReference===Pe.REGION&&this.parent.locked?this.parent.checkAndForbidNotAllowedFloat():!1}checkAndForbidFloatFollowingDeferredFloat(){let e=this.getFloatsDeferredToNextInChildContexts(),t=this.floatFragments.reduce((i,n)=>i.concat(n.continuations.map(r=>r.float)),[]);t.sort((i,n)=>n.getOrder()-i.getOrder());for(let i of t){let n=i.getOrder();if(e.some(r=>!i.isAllowedToPrecede(r)&&n>r.getOrder())){if(this.locked)this.invalidate();else{this.forbid(i);let r=this.findPageFloatFragment(i);this.removePageFloatFragment(r)}return!0}}return!1}finish(){for(let e=this.floatFragments.length-1;e>=0;e--){let t=this.floatFragments[e];if(t.continuations.some(i=>{let n=i.float;return"footnotePolicy"in n&&n.footnotePolicy===y.line&&!this.hasCurrentAnchor(n.getId())&&!this.floatsDeferredFromPrevious.some(r=>r.float===n)})){if(this.locked){this.invalidate();return}this.removePageFloatFragment(t);return}}if(!this.checkAndForbidNotAllowedFloat()){for(let e=this.floatsDeferredToNext.length-1;e>=0;e--){let t=this.floatsDeferredToNext[e].float,i=this.findPageFloatFragment(t);if("footnotePolicy"in t&&t.footnotePolicy===y.line&&this.hasCurrentAnchor(t.getId())&&!i&&!this.lineFootnoteFinishInvalidatedOnce.has(t.getId())){if(this.locked){this.invalidate();return}this.lineFootnoteFinishInvalidatedOnce.add(t.getId()),this.removeFloatDeferredToNext(t),this.forbid(t),this.invalidate();return}}for(let e=this.floatsDeferredToNext.length-1;e>=0;e--)if(!this.floatsDeferredToNext[e].float.isAllowedOnContext(this)){if(this.locked){this.invalidate();return}this.floatsDeferredToNext.splice(e,1)}this.floatsDeferredFromPrevious.forEach(e=>{this.floatsDeferredToNext.findIndex(t=>e.equals(t))>=0||this.floatFragments.some(t=>t.hasFloat(e.float))||this.floatsDeferredToNext.push(e)})}}hasSameContainerAs(e){return!!this.container&&!!e.container&&this.container.element===e.container.element}invalidate(){this.invalidated=!0,!this.locked&&(this.container&&(this.children.forEach(e=>{this.hasSameContainerAs(e)&&e.floatFragments.forEach(t=>{let i=t.area.element;i&&i.parentNode&&i.parentNode.removeChild(i)})}),this.container.clear()),this.children.forEach(e=>{e.layoutConstraints.splice(0)}),this.children.splice(0),Object.keys(this.floatAnchors).forEach(e=>{delete this.floatAnchors[e]}))}detachChildren(){let e=this.children.splice(0);return e.forEach(t=>{t.floatFragments.forEach(i=>{let n=i.area.element;n&&n.parentNode&&n.parentNode.removeChild(n)})}),e}attachChildren(e){e.forEach(t=>{this.children.push(t),t.reattachFloatFragments()})}isInvalidated(){return this.invalidated||!!this.parent&&this.parent.isInvalidated()}validate(){this.invalidated=!1}toLogical(e){let t=this.writingMode.toString(),i=this.direction.toString();if(e==="inside"||e==="outside"){let n=!!this.container.element.closest("[data-vivliostyle-page-side='left']");e=e==="inside"?n?"right":"left":n?"left":"right"}return Yd(e,t,i)}toPhysical(e){let t=this.writingMode.toString(),i=this.direction.toString();return qd(e,t,i)}toLogicalFloatSides(e){let t=e.split(" "),i=[];for(let s of t){let a=this.toLogical(s);i.includes(a)||i.push(a)}let n=[],r=!1,o=!1;for(let s=0;s<i.length;s++){let a=i[s];a.includes("block")?r||(i.slice(s+1).some(h=>h.includes("block"))?(n.push("snap-block"),r=!0):n.push(a)):a.includes("inline")&&(o||(i.slice(s+1).some(h=>h.includes("inline"))?(n.push("snap-inline"),o=!0):n.push(a)))}return n}removeEndFloatFragments(e){let t=this.toLogicalFloatSides(e)[0];if(t==="block-end"||t==="inline-end"){let i=0;for(;i<this.floatFragments.length;){let n=this.floatFragments[i];this.toLogicalFloatSides(n.floatSide)[0]===t?this.removePageFloatFragment(n):i++}}}isFragmentInCurrentContainer(e){var t;if(this.floatReference!==Pe.REGION)return!0;let i=e.area;return!i.parentElement||!((t=this.container)!=null&&t.element)||i.parentElement===this.container.element}stashEndFloatFragments(e){let t=e.floatReference;if(t!==this.floatReference){this.getParent(t).stashEndFloatFragments(e);return}let i=this.toLogicalFloatSides(e.floatSide)[0];if(i==="block-end"||i==="snap-block"||i==="inline-end"||i==="snap-inline"){let n=0;for(;n<this.floatFragments.length;){let r=this.floatFragments[n],o=this.toLogicalFloatSides(r.floatSide)[0];this.isFragmentInCurrentContainer(r)&&(o===i||i==="snap-block"&&o==="block-end"||i==="snap-inline"&&o==="inline-end")&&r.shouldBeStashedBefore(e)?(this.stashedFloatFragments.push(r),this.floatFragments.splice(n,1)):n++}}}restoreStashedFragments(e){if(e!==this.floatReference){this.getParent(e).restoreStashedFragments(e);return}this.stashedFloatFragments.forEach(t=>{this.addPageFloatFragment(t,!0)}),this.stashedFloatFragments.splice(0)}discardStashedFragments(e){if(e!==this.floatReference){this.getParent(e).discardStashedFragments(e);return}this.stashedFloatFragments.splice(0)}getStashedFloatFragments(e){return e===this.floatReference?this.stashedFloatFragments.concat().sort((t,i)=>i.getOrder()-t.getOrder()):this.getParent(e).getStashedFloatFragments(e)}getLimitValue(e,t,i,n,r,o=!0,s){this.container;let a=this.toLogical(e),h=this.toPhysical(e),l=t&&this.toLogical(t),c=t&&this.toPhysical(t),d=this.getLimitValueInner(a,l,i,n,r,s);if(o&&this.parent&&this.parent.container){let p=this.parent.getLimitValue(h,c,i,n,r,o,s);switch(h){case"top":return Math.max(d,p);case"left":return Math.max(d,p);case"bottom":return Math.min(d,p);case"right":return Math.min(d,p);default:}}return d}getLimitValueInner(e,t,i,n,r,o){this.container;let s=this.getLimitValuesInner(i,n,r,e,t,o);switch(e){case"block-start":return this.container.vertical?s.right:s.top;case"block-end":return this.container.vertical?s.left:s.bottom;case"inline-start":return this.container.vertical?this.container.rtl?s.bottom:s.top:this.container.rtl?s.right:s.left;case"inline-end":return this.container.vertical?this.container.rtl?s.top:s.bottom:this.container.rtl?s.left:s.right;default:throw new Error(`Unknown logical side: ${e}`)}}getLimitValuesInner(e,t,i,n,r,o){var s,a,h,l;this.container;let c=this.container.originX,d=this.container.originY,p=this.container.getPaddingRect(),f={top:p.y1-d,left:p.x1-c,bottom:p.y2-d,right:p.x2-c,floatMinWrapBlockStart:0,floatMinWrapBlockEnd:0};if(this.container.vertical){let w=parseFloat((a=(s=this.container.element)==null?void 0:s.style)==null?void 0:a.width);isFinite(w)&&w>this.container.width&&(f.right+=w-this.container.width)}else{let w=parseFloat((l=(h=this.container.element)==null?void 0:h.style)==null?void 0:l.height);isFinite(w)&&w>this.container.height&&(f.bottom+=w-this.container.height)}function g(w,x,m){return w.unit==="%"?m*w.num/100:e.convertLengthToPx(w,x,t)}let v=this.floatFragments;return v.length>0&&(f=v.reduce((w,x)=>{if(x.area===o||!this.isFragmentInCurrentContainer(x)||i&&!i(x,this))return w;let[m,S]=this.toLogicalFloatSides(x.floatSide);if(S&&(n&&S.includes("block")===n.includes("block")&&S!==n||r&&S.includes("block")===r.includes("block")&&S!==r))return w;let b=x.area,C=x.continuations[0].float.floatMinWrapBlock,P=b.vertical?b.left+b.getInsetLeft()+b.width+b.getInsetRight():b.top+b.getInsetTop()+b.height+b.getInsetBottom(),L=b.vertical?b.top+b.getInsetTop()+b.height+b.getInsetBottom():b.left+b.getInsetLeft()+b.width+b.getInsetRight(),A=w.top,z=w.left,U=w.bottom,X=w.right,re=w.floatMinWrapBlockStart,k=w.floatMinWrapBlockEnd;switch(m){case"inline-start":b.vertical?A=Math.max(A,L):z=Math.max(z,L);break;case"block-start":b.vertical?(C&&b.left<X&&(re=g(C,b.rootViewNodes[0],p.x2-p.x1)),X=Math.min(X,b.left)):(C&&P>A&&(re=g(C,b.rootViewNodes[0],p.y2-p.y1)),A=Math.max(A,P));break;case"inline-end":b.vertical?U=Math.min(U,b.top):X=Math.min(X,b.left);break;case"block-end":b.vertical?(C&&P>z&&(k=g(C,b.rootViewNodes[0],p.x2-p.x1)),z=Math.max(z,P)):(C&&b.top<U&&(k=g(C,b.rootViewNodes[0],p.y2-p.y1)),U=Math.min(U,b.top));break;default:throw new Error(`Unknown logical float side: ${m}`)}return{top:A,left:z,bottom:U,right:X,floatMinWrapBlockStart:re,floatMinWrapBlockEnd:k}},f)),f.left+=c,f.right+=c,f.top+=d,f.bottom+=d,f}setFloatAreaDimensions(e,t,i,n,r,o,s){if(t!==this.floatReference)return this.getParent(t).setFloatAreaDimensions(e,t,i,n,r,o,s);let a=this.toLogicalFloatSides(i);if(a[0]==="snap-block"){if(!s["block-start"]&&!s["block-end"])return null}else if(a[0].includes("block")&&!s[a[0]])return null;e.clientLayout;let h=a.find(P=>P.includes("inline")&&s[P==="inline-start"?"inline-end":"inline-start"]),l=a.find(P=>P.includes("block")),c=!0,d=this.getLimitValue("block-start",h,e.layoutContext,e.clientLayout,void 0,c,e),p=this.getLimitValue("block-end",h,e.layoutContext,e.clientLayout,void 0,c,e),f=this.getLimitValue("inline-start",l,e.layoutContext,e.clientLayout,void 0,c,e),g=this.getLimitValue("inline-end",l,e.layoutContext,e.clientLayout,void 0,c,e),v=e.vertical?e.originX:e.originY,w=e.vertical?e.originY:e.originX;e.isFootnote||(d=e.vertical?Math.min(d,e.left+e.getInsetLeft()+e.width+e.getInsetRight()+v):Math.max(d,e.top+v),p=e.vertical?Math.max(p,e.left+v):Math.min(p,e.top+e.getInsetTop()+e.height+e.getInsetBottom()+v));function x(P,L){let A=P(e.bands,L);return A?(e.vertical&&(A=od(A)),d=e.vertical?Math.min(d,A.x2):Math.max(d,A.y1),p=e.vertical?Math.max(p,A.x1):Math.min(p,A.y2),!0):o}let m,S,b,C;if(r){let P=e.vertical?ns(new Mt(p,f,d,g)):new Mt(f,d,g,p);if((a[0]==="block-start"||a[0]==="snap-block"||a[0]==="inline-start"||a[0]==="snap-inline")&&!x(_m,P)||(a[0]==="block-end"||a[0]==="snap-block"||a[0]==="inline-end"||a[0]==="snap-inline")&&!x(Dm,P)||(e.isFootnote&&n!==null&&isFinite(n)&&a[0]==="block-end"&&(e.vertical?d=Math.min(d,n):d=Math.max(d,n)),b=(p-d)*e.getBoxDir(),e.isFootnote&&this.footnoteMaxBlockSize!=null&&(b=Math.min(b,this.footnoteMaxBlockSize),e.vertical?d=p+b:d=p-b),m=Math.max(0,b-e.getInsetBefore()-e.getInsetAfter()),C=(g-f)*e.getInlineDir(),S=C-e.getInsetStart()-e.getInsetEnd(),!o&&(m<=0||S<=0)))return null}else{let P=e.getContentBlockMarginAfter();m=Math.max(0,e.computedBlockSize+Math.min(0,P)),b=m+e.getInsetBefore()+e.getInsetAfter();let L=(p-d)*e.getBoxDir();if(a[0]==="snap-block"){if(n===null)a[0]="block-start";else{let z=this.container.getPaddingRect(),U=this.container.getBoxDir()*(n-(this.container.vertical?z.x2:z.y1)),X=this.container.getBoxDir()*((this.container.vertical?z.x1:z.y2)-n-b);U<=X?a[0]="block-start":a[0]="block-end"}if(!s[a[0]])if(s["block-end"])a[0]="block-end";else return null}else if(a[0]==="snap-inline")if(n===null)a[0]="inline-start";else if(s["inline-start"])a[0]="inline-start";else if(s["inline-end"])a[0]="inline-end";else return null;if(!o&&L<b)return null;a[0]==="inline-start"||a[0]==="inline-end"||a[1]?S=Vl(e.clientLayout,e.element,["fit-content inline size"])["fit-content inline size"]:e.adjustContentRelativeSize?S=e.getContentInlineSize():S=e.vertical?e.height:e.width,C=S+e.getInsetStart()+e.getInsetEnd();let A=(g-f)*e.getInlineDir();if(!o&&A<C)return null}if(d-=v,p-=v,f-=w,g-=w,a.some(P=>P==="inline-start"||P==="snap-inline")||a.length===1&&(a[0]==="block-start"||a[0]==="snap-block")?e.setInlinePosition(f,S):(a.some(P=>P==="inline-end")||a.length===1&&a[0]==="block-end")&&e.setInlinePosition(g-C*e.getInlineDir(),S),a.some(P=>P==="block-start"||P==="snap-block")||a.length===1&&(a[0]==="inline-start"||a[0]==="snap-inline"))e.setBlockPosition(d,m);else if(a.some(P=>P==="block-end")||a.length===1&&a[0]==="inline-end"){let P=p-b*e.getBoxDir();e.setBlockPosition(P,m)}return a.join(" ")}getFloatFragmentExclusions(){let e=this.floatFragments.map(t=>t.getOuterShape());return this.parent?this.parent.getFloatFragmentExclusions().concat(e):e}reattachFloatFragments(){let e=this.container.element&&this.container.element.parentNode;e&&this.floatFragments.forEach(t=>{e.appendChild(t.area.element)})}getMaxReachedAfterEdge(){let e=this.getContainer().vertical;return this.floatFragments.reduce((t,i)=>{let n=i.getOuterRect();return e?Math.min(t,n.x1):Math.max(t,n.y2)},e?1/0:0)}getBlockEndEdgeOfBlockStartFloats(e){let t=this,i=null;for(;t&&!i;)i=t.container,t=t.parent;let n=!!(i!=null&&i.vertical),r=NaN;if(this.floatFragments.filter(o=>o.floatSide.includes("block-start")).filter(o=>{if(!isFinite(e))return!0;let s=o.getOuterRect();return n?s.y1<=e&&e<=s.y2:s.x1<=e&&e<=s.x2}).forEach(o=>{let s=o.getOuterRect(),a=n?s.x1:s.y2;r=isFinite(r)?n?Math.min(r,a):Math.max(r,a):a}),this.parent){let o=this.parent.getBlockEndEdgeOfBlockStartFloats(e);isFinite(o)&&(r=isFinite(r)?n?Math.min(r,o):Math.max(r,o):o)}return r}getBlockStartEdgeOfBlockEndFloats(e){let t=this,i=null;for(;t&&!i;)i=t.container,t=t.parent;let n=!!(i!=null&&i.vertical),r=NaN;if(this.floatFragments.filter(o=>o.floatSide.includes("block-end")).filter(o=>{if(!isFinite(e))return!0;let s=o.getOuterRect();return n?s.y1<=e&&e<=s.y2:s.x1<=e&&e<=s.x2}).forEach(o=>{let s=o.getOuterRect(),a=n?s.x2:s.y1;r=isFinite(r)?n?Math.max(r,a):Math.min(r,a):a}),this.parent){let o=this.parent.getBlockStartEdgeOfBlockEndFloats(e);isFinite(o)&&(r=isFinite(r)?n?Math.max(r,o):Math.min(r,o):o)}return r}getPageFloatClearEdge(e,t){let i=c=>{let d=this.toLogicalFloatSides(c),p=d[0];return e==="both"?p==="block-end":e==="inline-start"?d.includes("inline-end")||p==="block-end":e==="inline-end"?d.includes("inline-start")||p==="block-start"||p==="block-end":!1};function n(c){return d=>!i(d.float.floatSide)&&c.isAnchorAlreadyAppeared(d.float.getId())}function r(c,d){return i(c.floatSide)?!1:c.continuations.some(n(d))}let o=t.getPaddingRect(),s=t.vertical?o.x1:o.y2,a=this;for(;a;){if(a.floatsDeferredToNext.some(n(a)))return s;a=a.parent}function h(c){return c.floatFragments.some(d=>r(d,c))||c.children.some(d=>h(d))}if(e==="column"||e==="region"||e==="page"){for(a=this;a;a=a.parent)if(a.floatReference===e){if(h(a))return s;break}}t.clientLayout;let l=this.getLimitValue("block-start",null,t.layoutContext,t.clientLayout,r);return this.getLimitValue("block-end",null,t.layoutContext,t.clientLayout,r)*t.getBoxDir()<s*t.getBoxDir()?s:l}getPageFloatPlacementCondition(e,t,i){if(e.floatReference!==this.floatReference)return this.getParent(e.floatReference).getPageFloatPlacementCondition(e,t,i);let n={"block-start":!0,"block-end":!0,"inline-start":!0,"inline-end":!0};if(!i)return n;let r=this.toLogicalFloatSides(t)[0],o=this.toLogical(i),s;o==="all"?s=["block-start","block-end","inline-start","inline-end"]:o==="both"?s=["inline-start","inline-end"]:o==="same"?r==="snap-block"?s=["block-start","block-end"]:s=[r]:s=[o];let a=e.getOrder();function h(d){return p=>(!d||p.floatSide.includes(d))&&p.getOrder()<a}function l(d,p){return d.children.some(f=>f.floatFragments.some(h(p))||l(f,p))}function c(d,p){let f=d.parent;return!!f&&(f.floatFragments.some(h(p))||c(f,p))}if(i==="column"||i==="region"||i==="page"){for(let d=this;d;d=d.parent)if(d.floatReference===i){(d.floatFragments.some(h(null))||l(d,null))&&(n["block-start"]=!1,n["block-end"]=!1,n["inline-start"]=!1,n["inline-end"]=!1);break}return n}return s.forEach(d=>{switch(d){case"block-start":n[d]=!l(this,d);break;case"block-end":n[d]=!c(this,d);break;case"inline-start":case"inline-end":n[d]=!this.floatFragments.some(h(d));break;default:throw new Error(`Unexpected side: ${d}`)}}),n}getLayoutConstraints(){return(this.parent?this.parent.getLayoutConstraints():[]).concat(this.layoutConstraints)}addLayoutConstraint(e,t){t===this.floatReference?this.layoutConstraints.push(e):this.getParent(t).addLayoutConstraint(e,t)}isColumnFullWithPageFloats(e){let t=e.layoutContext,i=e.clientLayout,n=this,r=null;for(;n&&n.container;){let s=n.getLimitValuesInner(t,i);r?e.vertical?(s.right<r.right&&(r.right=s.right,r.floatMinWrapBlockStart=s.floatMinWrapBlockStart),s.left>r.left&&(r.left=s.left,r.floatMinWrapBlockEnd=s.floatMinWrapBlockEnd)):(s.top>r.top&&(r.top=s.top,r.floatMinWrapBlockStart=s.floatMinWrapBlockStart),s.bottom<r.bottom&&(r.bottom=s.bottom,r.floatMinWrapBlockEnd=s.floatMinWrapBlockEnd)):r=s,n=n.parent}let o=Math.max(r.floatMinWrapBlockStart,r.floatMinWrapBlockEnd);return(e.vertical?r.right-r.left:r.bottom-r.top)<=o}getMaxBlockSizeOfPageFloats(){let e=this.getContainer().vertical;return this.floatFragments.length?Math.max.apply(null,this.floatFragments.map(t=>{let i=t.area;return e?i.width:i.height})):0}lock(){this.locked=!0}unlock(){this.locked=!1}isLocked(){return this.locked}},tr=[],Vn=class{static register(e){tr.push(e)}findByNodeContext(e){for(let t=tr.length-1;t>=0;t--){let i=tr[t];if(i.appliesToNodeContext(e))return i}throw new Error(`No PageFloatLayoutStrategy found for ${e}`)}findByFloat(e){for(let t=tr.length-1;t>=0;t--){let i=tr[t];if(i.appliesToFloat(e))return i}throw new Error(`No PageFloatLayoutStrategy found for ${e}`)}},qv=class{appliesToNodeContext(e){return Ii(e.floatReference)}appliesToFloat(e){return!0}createPageFloat(e,t,i){let n=e.floatReference;e.floatSide;let r=e.floatSide,o=e.toNodePosition(),s=!!t.generatingNodePosition;return i.resolveFloatReferenceFromColumnSpan(n,e.columnSpan,e).thenAsync(a=>{n=a,t.flowName;let h=new hp(o,n,r,e.clearSide,t.flowName,e.floatMinWrapBlock);if(h.insidePageFloatArea=s,s){let l=t.generatingNodePosition;l&&(h.parentPageFloat=t.findPageFloatByNodePosition(l))}return t.addPageFloat(h),T(h)})}createPageFloatFragment(e,t,i,n,r){let o=e[0].float;return new up(o.floatReference,t,i,e,n,r)}findPageFloatFragment(e,t){return t.findPageFloatFragment(e)}adjustPageFloatArea(e,t,i){return T(void 0)}forbid(e,t){}};Vn.register(new qv);var cp="data-vivliostyle-footnote-first-ref",dp="data-vivliostyle-footnote-referenced";function cs(e,t){return!!(e&&e.match(new RegExp(`(^|\\s)${t}($|\\s)`)))}function Pt(e){if(e.localName!=="aside")return!1;if(cs(e.getAttribute("role"),"doc-footnote"))return!0;let t=e.getAttributeNS("http://www.idpf.org/2007/ops","type")||e.getAttribute("epub:type");return cs(t,"footnote")}function Gt(e){if(e.localName!=="a")return!1;if(cs(e.getAttribute("role"),"doc-noteref"))return!0;let t=e.getAttributeNS("http://www.idpf.org/2007/ops","type")||e.getAttribute("epub:type");return cs(t,"noteref")}function $l(e,t){if(!Gt(e))return null;let i=e.getAttribute("href")||e.getAttributeNS("http://www.w3.org/1999/xlink","href");if(!i)return null;let n=Qo(i,t);return n==="#"?null:n}function pp(e,t,i){let n=$l(e,t);if(!n)return null;let r=i(n);return r&&Pt(r)?r:null}function Yv(e,t,i,n,r){if(r.value)return;let o=e.getElementsByTagName("a");for(let s=0;s<o.length;s++){let a=o.item(s),h=$l(a,t);!h||n.has(h)||n.set(h,i(a))}r.value=!0}function cu(e,t,i,n,r){if(e.localName!=="a"||!Gt(e))return!0;let o=$l(e,t);if(!o)return!0;Yv(e.ownerDocument,t,i,n,r);let s=n.get(o);return s==null||i(e)===s}function Hl(e,t){let i=t.getProp(e,"footnote-display");if(i)return i;let n=t.getProp(e,"display");return n?.value===y.inline?t.createCascadeValue(y.inline,n.priority):null}function Zv(e,t,i,n,r,o,s){if(e.namespaceURI!=="http://www.pyroxy.com/ns/shadow"||e.localName!=="include"||!e.classList.contains("-vivliostyle-footnote-content"))return t;let a=i?.owner;if(!(a instanceof Element)||!Gt(a))return t;let h=pp(a,n,r);if(!h)return t;let l=a.getAttribute(o);l?(e.setAttribute(o,l),h.setAttribute(o,l)):(e.removeAttribute(o),h.removeAttribute(o));let c=s.getStyle(h);if(!c)return t;let d={...t},p=Hl(c,s),f=s.getProp(c,"footnote-policy"),g=s.getStyleMap(c,"_pseudos"),v=g?.after;if(p&&(d["footnote-display"]=p),f&&(d["footnote-policy"]=f),v){let w=s.getMutableStyleMap(d,"_pseudos");w.after={...v}}return d}function Kv(e,t,i,n,r){var o;if(!(i?.type===st.ROOTED&&Pt(e)))return t;let s=r.getStyle(e);if(!s)return t;let a={...t},h=Hl(s,r),l=r.getProp(s,"footnote-policy"),c=r.getStyleMap(s,"_pseudos"),d=c?.["footnote-marker"],p=r.getProp(d,"content"),f=r.getProp(d,"list-style-position");if(h&&(a["footnote-display"]=h),l&&(a["footnote-policy"]=l),p&&((o=f?.evaluate)==null?void 0:o.call(f,n,"list-style-position"))===y.outside){let g=r.filterFootnoteMarkerContent(p,e);a["--viv-marker-content"]=r.createCascadeValue(g,0),a.display=r.createCascadeValue(B("list-item"),0),a["list-style-position"]=r.createCascadeValue(y.outside,0),a["list-style-type"]=r.createCascadeValue(y.none,0),a["list-style-image"]=r.createCascadeValue(y.none,0)}return a}function Jv(e,t,i){var n,r;let o=t?.type===st.ROOTED&&Pt(e)?i.getStyle(e):null;return{sourceStyle:o,footnoteDisplay:((n=Hl(o,i))==null?void 0:n.value)||null,footnotePolicy:((r=i.getProp(o,"footnote-policy"))==null?void 0:r.value)||null}}function fp(e,t){if(e instanceof j){let i=e.expr.evaluate(t);return typeof i=="string"?new K(i):typeof i=="number"?new K(String(i)):e}return e instanceof J?new J(e.values.map(i=>fp(i,t))):e}function Qv(e,t,i){let n=e?.["_footnote-marker-content"];n&&(t["--viv-marker-content"]=fp(n.value,i))}function ew(e){let t=e.getElementsByTagName("a"),i=new Set;for(let n=0;n<t.length;n++){let r=t.item(n);if(!Gt(r)||!(r instanceof HTMLAnchorElement)||!r.hash||r.href!==r.baseURI.replace(/#.*$/,"")+r.hash)continue;let o=r.hash.substring(1),s=e.getElementById(o);if(s&&Pt(s)){let a=r.baseURI.replace(/#.*$/,"")+r.hash;i.has(a)||(i.add(a),r.setAttribute(cp,"true")),s.setAttribute(dp,"true")}}}Ft("PREPROCESS_SINGLE_DOCUMENT",ew);var tw=up,iw=.1,Or=class gp extends hp{constructor(t,i,n,r,o,s){super(t,i,"block-end",null,n,o),u(this,"footnotePolicy",r),u(this,"policyAnchorNode",s)}isAllowedToPrecede(t){return!(t instanceof gp)}};function nw(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;for(;t;){if(/^(p|li|dd|dt|td|th|blockquote)$/i.test(t.localName)&&!t.querySelector("br"))return t;t=t.parentElement}return e}function mp(e){return e?-1:1}function $a(e,t){return t?e.right:e.top}function Wl(e,t){return t?e.left:e.bottom}function yp(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom,width:e.width,height:e.height}}function vp(e,t){let i=yp(e.getBoundingClientRect());return Dl(i,t),i.right<i.left||i.bottom<i.top?null:i}function Ha(e,t){let i=Array.from(e,yp);return ss(i,t),i.filter(n=>n.right>n.left&&n.bottom>n.top)}function wp(e,t){return e.length?t?Math.min(...e.map(i=>i.left)):Math.max(...e.map(i=>i.bottom)):NaN}function rw(e,t){if(!e.length)return NaN;let i=mp(t),n=e.reduce((r,o)=>$a(o,t)*i<$a(r,t)*i?o:r);return Wl(n,t)}function ow(e,t){if(!e)return NaN;if(e.nodeType===Node.ELEMENT_NODE){let o=vp(e,t);return o?Wl(o,t):NaN}let i=e.textContent||"";if(!i.length)return NaN;let n=e.ownerDocument.createRange();n.setStart(e,0),n.setEnd(e,i.length);let r=Ha(n.getClientRects(),t);return wp(r,t)}function sw(e,t){let i=e.viewNode;if(!i)return NaN;if(i.nodeType===Node.ELEMENT_NODE){let a=i;if(e.after||!e.inline){let l=vp(a,t);if(l)return e.after?Wl(l,t):$a(l,t)}let h=Ha(a.getClientRects(),t);return rw(h,t)}let n=i.textContent||"";if(!n.length)return NaN;let r=e.offsetInNode;e.after&&(r+=n.length),r=Math.max(0,Math.min(r,n.length-1));let o=i.ownerDocument.createRange();o.setStart(i,r),o.setEnd(i,r+1);let s=Ha(o.getClientRects(),t);return wp(s,t)}var du=class extends tw{constructor(e,t,i,n){super(e,"block-end",null,t,i,n)}getOrder(){return 1/0}shouldBeStashedBefore(e){return e instanceof Or?!0:this.getOrder()<e.getOrder()}},aw=class{constructor(e,t,i){u(this,"footnote",e),u(this,"vertical",i),u(this,"anchorEdge"),this.anchorEdge=ow(t,i)}allowLayout(e){if(!isNaN(this.anchorEdge)){let i=sw(e,this.vertical);if(!isNaN(i)){let n=mp(this.vertical);return i*n<this.anchorEdge*n-iw}}let t=e.toNodePosition();return!Oi(t,this.footnote.nodePosition)}},lw=class{appliesToNodeContext(e){return e.floatSide==="footnote"}appliesToFloat(e){return e instanceof Or}createPageFloat(e,t,i){var n;let r=Pe.REGION,o=t.getPageFloatLayoutContext(r);t.getPageFloatLayoutContext(Pe.PAGE).hasSameContainerAs(o)&&(r=Pe.PAGE);let s=!!t.generatingNodePosition;s&&r!==Pe.PAGE&&(r=Pe.PAGE);let a=e.toNodePosition();t.flowName;let h=e.sourceNode,l=(n=e.shadowContext)==null?void 0:n.owner;l instanceof Element&&Gt(l)&&(h=l),h=nw(h);let c=new Or(a,r,t.flowName,e.footnotePolicy,e.floatMinWrapBlock,h);if(c.insidePageFloatArea=s,s){let d=t.generatingNodePosition;d&&(c.parentPageFloat=t.findPageFloatByNodePosition(d))}return t.addPageFloat(c),T(c)}createPageFloatFragment(e,t,i,n,r){let o=e[0].float;return new du(o.floatReference,e,n,r)}findPageFloatFragment(e,t){let i=t.getPageFloatLayoutContext(e.floatReference),n=i.getContainer(e.floatReference).element,r=i.floatFragments.filter(o=>o instanceof du&&(e.floatReference!==Pe.REGION||!o.area.parentElement||o.area.parentElement===n));return r.find(o=>o.hasFloat(e))||r[0]||null}adjustPageFloatArea(e,t,i){e.isFootnote=!0,e.adjustContentRelativeSize=!1;let n=e.element;return i.layoutContext.applyFootnoteStyle(t.vertical,i.layoutContext.nodeContext&&i.layoutContext.nodeContext.direction==="rtl",n).thenAsync(r=>{var o,s;if(e.vertical=r,e.convertPercentageSizesToPx(n),i.setComputedInsets(n,e),i.setComputedWidthAndHeight(n,e),((o=i.clientLayout.getElementComputedStyle(n))==null?void 0:o.boxSizing)==="border-box"){let h=e.vertical?e.paddingLeft+e.paddingRight+e.borderLeft+e.borderRight:e.paddingTop+e.paddingBottom+e.borderTop+e.borderBottom,l=e.vertical?["max-width","min-width","width"]:["max-height","min-height","height"],c=getComputedStyle(n);for(let d of l){let p=c.getPropertyValue(d);if(p&&p!=="none"){let f=parseFloat(p);isNaN(f)||I(n,d,`${Math.max(0,f-h)}px`)}}I(n,"box-sizing","content-box")}let a=i.pageFloatLayoutContext;for(;a;){if(a.ignoreFootnoteAreaMaxHeight){I(n,"max-block-size",""),I(n,e.vertical?"max-width":"max-height","");break}a=(s=a.parent)!=null?s:null}return T(void 0)})}forbid(e,t){let i=e;if(i.footnotePolicy===y.line){let n=t.collectPageFloatAnchors()[i.getId()]||null,r=new aw(i,n,t.getContainer(i.floatReference).vertical);t.addLayoutConstraint(r,i.floatReference)}}};Vn.register(new lw);var Gl=class{calculateOffset(e){return Ln(this.getNodeContext(),e.collectElementsOffset())}breakPositionChosen(e){}getNodeContext(){return null}};function Ln(e,t){return{current:t.reduce((i,n)=>i+n.calculateOffset(e),0),minimum:t.reduce((i,n)=>i+n.calculateMinimumOffset(e),0)}}var to=class extends Gl{constructor(e,t,i,n){super(),u(this,"position",e),u(this,"breakOnEdge",t),u(this,"overflows",i),u(this,"computedBlockSize",n),u(this,"overflowIfRepetitiveElementsDropped"),u(this,"isEdgeUpdated",!1),u(this,"edge",0),this.overflowIfRepetitiveElementsDropped=i}findAcceptableBreak(e,t){return this.updateOverflows(e),t<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(as(this.breakOnEdge)?1:0)+(this.overflows&&!e?3:0)+(this.position.parent?this.position.parent.breakPenalty:0)}updateEdge(e){var t;let i=e.calculateClonedPaddingBorder(this.position);if(this.edge=bn(this.position,e.clientLayout,0,e.vertical)+i,!this.position.after&&!this.position.inline){let n=e.parseComputedLength(e.clientLayout.getElementComputedStyle(this.position.viewNode).marginBlockStart);this.edge-=(e.vertical?-1:1)*n}else if(this.position.after&&((t=this.position.shadowContext)==null?void 0:t.root.id)==="table-cell"){let n=e.element.parentElement,r=n?.closest("table, [style*='display: table;']");if(r){let o=r.style.borderCollapse==="collapse",s=0,a=0;for(let h=n;h;h=h.parentElement){let l=e.clientLayout.getElementComputedStyle(h);if((h===n||h===r&&!o)&&(s+=e.parseComputedLength(l.paddingBlockEnd)),h===r&&!o&&(s+=e.parseComputedLength(l.borderSpacing.replace(/^\S+ (\S+)$/,"$1"))),o?a=Math.max(a,e.parseComputedLength(l.borderBlockEndWidth)):(h===n||h===r)&&(a+=e.parseComputedLength(l.borderBlockEndWidth)),h===r)break}this.edge+=(e.vertical?-1:1)*(s+a)}}this.isEdgeUpdated=!0}updateOverflows(e){this.isEdgeUpdated||this.updateEdge(e);let t=this.edge,i=this.calculateOffset(e);this.overflowIfRepetitiveElementsDropped=e.isOverflown(t+(e.vertical?-1:1)*i.minimum),this.overflows=this.position.overflow=e.isOverflown(t+(e.vertical?-1:1)*i.current)}getNodeContext(){return this.position}isFirstContentOfRepetitiveElementsOwner(){let e=this.getNodeContext();if(!e||!e.parent)return!1;let{formattingContext:t}=e.parent;if(!Yi.isInstanceOfRepetitiveElementsOwnerFormattingContext(t))return!1;let i=t.getRepetitiveElements();return i?i.isFirstContentNode(e):!1}},ir=class{find(e){let t=_t("RESOLVE_LAYOUT_PROCESSOR");for(let i=0;i<t.length;i++){let n=t[i](e);if(n)return n}throw new Error(`No processor found for a formatting context: ${e.getName()}`)}},Tn=class{layout(e,t,i){return t.isFloatNodeContext(e)?t.layoutFloatOrFootnote(e):t.isBreakable(e)?t.layoutBreakableBlock(e):t.layoutUnbreakable(e)}createEdgeBreakPosition(e,t,i,n){return new to(e.copy(),t,i,n)}startNonInlineElementNode(e){return!1}afterNonInlineElementNode(e,t){return!1}clearOverflownViewNodes(e,t,i,n){var r;if(!i.viewNode||!i.viewNode.parentNode||i.shadowType===yi.ShadowType.ROOTLESS&&Pn(i))return;let o=i.viewNode;((r=o.parentElement)==null?void 0:r.localName)==="viv-ts-inner"&&(o=o.parentElement.parentElement);let s=o.parentNode;Hd(s,o),n&&s.removeChild(o)}finishBreak(e,t,i,n){let r=i||t.viewNode!=null&&t.viewNode.nodeType==1&&!t.after;return e.clearOverflownViewNodes(t,r),n&&e.layoutContext.processFragmentedBlockEdge(t),T(!0)}},jl=class{constructor(e){u(this,"parent",e),u(this,"formattingContextType","Block")}getName(){return"Block formatting context (BlockFormattingContext)"}isFirstTime(e,t){return t}getParent(){return this.parent}saveState(){}restoreState(e){}},Xl=new Tn,hw=za.isInstanceOfBlockFormattingContext;Ft("RESOLVE_FORMATTING_CONTEXT",(e,t,i,n,r,o)=>{let s=e.parent;return!s&&e.formattingContext||s&&e.formattingContext!==s.formattingContext?null:e.establishesBFC||!e.formattingContext&&Vd(i,n,r,o)?new jl(s?s.formattingContext:null):null});Ft("RESOLVE_LAYOUT_PROCESSOR",e=>e instanceof jl?Xl:null);var ql=class{constructor(){u(this,"initialBreakPositions",null),u(this,"initialStateOfFormattingContext",null),u(this,"initialPosition"),u(this,"initialFragmentLayoutConstraints")}layout(e,t){return this.prepareLayout(e,t),this.tryLayout(e,t)}tryLayout(e,t){let i=M("AbstractLayoutRetryer.tryLayout");this.saveState(e,t);let n=this.resolveLayoutMode(e);return n.doLayout(e,t).then(r=>{let o=n.accept(r,t);o=n.postLayout(r,this.initialPosition,t,o),o?i.finish(r):(this.initialPosition,this.clearNodes(this.initialPosition),this.restoreState(e,t),this.tryLayout(this.initialPosition,t).thenFinish(i))}),i.result()}prepareLayout(e,t){}clearNodes(e){let t=e.viewNode||e.parent.viewNode,i;for(;i=t.lastChild;)t.removeChild(i);let n;for(;n=t.nextSibling;)n.parentNode.removeChild(n)}saveState(e,t){this.initialPosition=e.copy(),this.initialBreakPositions=[].concat(t.breakPositions),this.initialFragmentLayoutConstraints=[].concat(t.fragmentLayoutConstraints),e.formattingContext&&(this.initialStateOfFormattingContext=e.formattingContext.saveState())}restoreState(e,t){t.breakPositions=this.initialBreakPositions,t.fragmentLayoutConstraints=this.initialFragmentLayoutConstraints,e.formattingContext&&e.formattingContext.restoreState(this.initialStateOfFormattingContext)}},uw=class{initialState(e){return{nodeContext:e,atUnforcedBreak:!1,break:!1}}startNonDisplayableNode(e){}afterNonDisplayableNode(e){}startIgnoredTextNode(e){}afterIgnoredTextNode(e){}startNonElementNode(e){}afterNonElementNode(e){}startInlineElementNode(e){}afterInlineElementNode(e){}startNonInlineElementNode(e){}afterNonInlineElementNode(e){}finish(e){}},Wa=class{constructor(e,t){u(this,"strategy",e),u(this,"layoutContext",t)}iterate(e){let t=this.strategy,i=t.initialState(e),n=M("LayoutIterator");return n.loopWithFrame(r=>{let o;for(;i.nodeContext;){i.nodeContext.viewNode?i.nodeContext.viewNode.nodeType!==1?Ee(i.nodeContext.viewNode,i.nodeContext.whitespace)?i.nodeContext.after?o=t.afterIgnoredTextNode(i):o=t.startIgnoredTextNode(i):i.nodeContext.after?o=t.afterNonElementNode(i):o=t.startNonElementNode(i):i.nodeContext.inline?i.nodeContext.after?o=t.afterInlineElementNode(i):o=t.startInlineElementNode(i):i.nodeContext.after?o=t.afterNonInlineElementNode(i):o=t.startNonInlineElementNode(i):i.nodeContext.after?o=t.afterNonDisplayableNode(i):o=t.startNonDisplayableNode(i);let s=(o&&o.isPending()?o:T(!0)).thenAsync(()=>i.break?T(null):this.layoutContext.nextInTree(i.nodeContext,i.atUnforcedBreak));if(s.isPending()){s.then(a=>{i.break?r.breakLoop():(i.nodeContext=a,r.continueLoop())});return}else if(i.break){r.breakLoop();return}else i.nodeContext=s.get()}t.finish(i),r.breakLoop()}).then(()=>{n.finish(i.nodeContext)}),n.result()}},br=class extends uw{constructor(e){super(),u(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,t){let i=!e.leadingEdge&&Ze(e.breakAtTheEdge);if(i){let n=e.nodeContext=e.leadingEdgeContexts[0]||e.nodeContext;n.viewNode.parentNode.removeChild(n.viewNode),t.pageBreakType=e.breakAtTheEdge}return i}saveEdgeAndProcessOverflow(e,t){let i=t.checkOverflowAndSaveEdgeAndBreakPosition(e.lastAfterNodeContext,null,!0,e.breakAtTheEdge);return i&&(e.nodeContext=(e.lastAfterNodeContext||e.nodeContext).modify(),e.nodeContext.overflow=!0),i}processLayoutConstraint(e,t,i){let n=e.nodeContext,r=!t.allowLayout(n);return r&&(i.checkOverflowAndSaveEdgeAndBreakPosition(e.lastAfterNodeContext,null,!1,e.breakAtTheEdge),n=e.nodeContext=n.modify(),n.overflow=!0),r}startNonElementNode(e){e.onStartEdges=!1}startNonInlineElementNode(e){return e.leadingEdgeContexts.push(e.nodeContext.copy()),e.breakAtTheEdge=nt(e.breakAtTheEdge,e.nodeContext.breakBefore),e.onStartEdges=!0,this.startNonInlineBox(e)}afterNonInlineElementNode(e){let t,i;return e.onStartEdges?(t=this.endEmptyNonInlineBox(e),i=t&&t.isPending()?t:T(!0),i=i.thenAsync(()=>(e.break||(e.leadingEdgeContexts=[],e.leadingEdge=!1,e.atUnforcedBreak=!1,e.breakAtTheEdge=null),T(!0)))):(t=this.endNonInlineBox(e),i=t&&t.isPending()?t:T(!0)),i.thenAsync(()=>(e.break||(e.onStartEdges=!1,e.lastAfterNodeContext=e.nodeContext.copy(),e.breakAtTheEdge=nt(e.breakAtTheEdge,e.nodeContext.breakAfter)),T(!0)))}},Ga=[];function cw(){Ga=[]}var fo;function go(e){if(e==="")return 0;if(fo===void 0){let i=Intl.Segmenter;fo=typeof i=="function"?new i(void 0,{granularity:"grapheme"}):null}if(fo===null)return[...e].length;let t=0;for(let i of fo.segment(e))t++;return t}var dw=["decimal","disc","square","circle","disclosure-open","disclosure-closed"],pw=new Set(dw);function fw(e){return!(e.toLowerCase()==="none"||pw.has(e))}var gw=["cyclic","numeric","alphabetic","symbolic","additive","fixed"],mw=new Set(gw),yw=["fixed","extends"],vw=new Set(yw);function io(e){return e instanceof he&&e.name.toLowerCase()!=="none"}function bp(e){return e.name}function ww(e){if(e instanceof he)return mw.has(e.name);if(e instanceof J&&e.values.length===2){let t=e.values[0],i=e.values[1];if(t instanceof he){let n=t.name;return vw.has(n)&&(n==="fixed"&&i instanceof lt||n==="extends"&&io(i))}}return!1}function bw(e){let t=dt(e,"system");return t instanceof he&&t.name==="cyclic"}function xw(e){let t=dt(e,"system");if(t instanceof he&&t.name==="fixed")return!0;if(t instanceof J&&t.values.length===2){let[i,n]=t.values;return i instanceof he&&i.name==="fixed"&&n instanceof lt}return!1}function Sw(e){let t=dt(e,"system");return t instanceof he?1:t.values[1].num}function Cw(e){let t=dt(e,"system");return t instanceof he&&t.name==="alphabetic"}function kw(e){let t=dt(e,"system");return t instanceof he&&t.name==="numeric"}function Ew(e){let t=dt(e,"system");return t instanceof he&&t.name==="additive"}function Pw(e){let t=dt(e,"system");if(t instanceof J&&t.values.length===2){let[i,n]=t.values;return i instanceof he&&i.name==="extends"&&io(n)}return!1}function Nw(e){let t=dt(e,"system");return bp(t.values[1])}function jt(e){return e instanceof K||e instanceof he}function fi(e){return e instanceof K?e.str:e.name}function xp(e){if(jt(e))return!0;if(e instanceof J&&e.values.length===2){let t=e.values[0],i=e.values[1];return jt(t)&&jt(i)}return!1}function Tw(e){if(jt(e))return{prefix:fi(e),suffix:null};{let t=e.values[0],i=e.values[1];return{prefix:fi(t),suffix:fi(i)}}}function pu(e){return e instanceof lt||e instanceof he&&e.name==="infinite"}function ds(e,t){return e instanceof lt?e.num:t?-1/0:1/0}function ja(e){if(!(e instanceof J&&e.values.length===2))return!1;let t=e.values[0],i=e.values[1];if(!(pu(t)&&pu(i)))return!1;let n=ds(t,!0),r=ds(i,!1);return!(n>r)}function Aw(e){return{lower:ds(e.values[0],!0),upper:ds(e.values[1],!1)}}function Sp(e){return e instanceof he&&e.name==="auto"||ja(e)||e instanceof Oe&&e.values.length>=1&&e.values.every(t=>ja(t))}function Iw(e){return e instanceof he?null:(ja(e)?[e]:e.values).map(t=>Aw(t))}function ps(e){if(!(e instanceof J&&e.values.length===2))return!1;let t=e.values[0],i=e.values[1];return t instanceof lt&&t.num>=0&&jt(i)||jt(t)&&i instanceof lt&&i.num>=0}function fs(e){let[t,i]=e.values;return t instanceof lt?[t.num,fi(i)]:[i.num,fi(t)]}function Cp(e){return ps(e)}function Fw(e){let[t,i]=fs(e);return{minLength:t,symbol:i}}function kp(e){return jt(e)||e instanceof J&&e.values.length>=1&&e.values.every(t=>jt(t))}function Rw(e){return jt(e)?[fi(e)]:e.values.map(t=>fi(t))}function Ep(e){if(ps(e))return!0;if(e instanceof Oe&&e.values.length>=1){let t=1/0;for(let i of e.values){if(!ps(i))return!1;let[n]=fs(i);if(n>=t)return!1;t=n}return!0}return!1}function Lw(e){if(ps(e)){let[t,i]=fs(e);return[{weight:t,symbol:i}]}else return e.values.map(t=>{let[i,n]=fs(t);return{weight:i,symbol:n}})}var Ow=["auto","bullets","numbers","words","spell-out"],Bw=new Set(Ow);function Mw(e){return e instanceof he&&Bw.has(e.name)||io(e)}function _w(e,t){switch(e){case"system":return ww(t);case"negative":return xp(t);case"prefix":case"suffix":return jt(t);case"range":return Sp(t);case"pad":return Cp(t);case"fallback":return io(t);case"symbols":return kp(t);case"additive-symbols":return Ep(t);case"speak-as":return Mw(t);default:return!0}}function dt(e,t){var i;let n=(i=e[t])==null?void 0:i.value;return n??null}function Dw(e,t){return t.some(({lower:i,upper:n})=>e>=i&&e<=n)}function Un(e){let t=e.get("decimal");return t||(t=ce.createDecimal(e),e.set("decimal",t)),t}var Mo,_o,Do,zo,Vo,Uo,$o,Ho,mo,ci,Pp,yo,Np,vo,Tp,wo,Ap,bo,Ip,xo,Fp,So,Rp,wt,la,Lp,Op,fu,gu,ha,mu,dr,ze=class Hi{constructor(t,i){ie(this,wt),u(this,"_store"),ie(this,Mo),ie(this,_o),ie(this,Do),ie(this,zo),ie(this,Vo),ie(this,Uo),ie(this,$o),ie(this,Ho),this._store=t;let n=dt(i,"negative");de(this,Mo,n&&xp(n)?Tw(n):null);let r=dt(i,"prefix");de(this,_o,r&&jt(r)?fi(r):null);let o=dt(i,"suffix");de(this,Do,o&&jt(o)?fi(o):null);let s=dt(i,"range");de(this,zo,s&&Sp(s)?Iw(s):null);let a=dt(i,"pad");de(this,Vo,a&&Cp(a)?Fw(a):null);let h=dt(i,"fallback");de(this,Uo,h&&io(h)?bp(h):null);let l=dt(i,"symbols");de(this,$o,l&&kp(l)?Rw(l):null);let c=dt(i,"additive-symbols");de(this,Ho,c&&Ep(c)?Lw(c):null)}static create(t,i){return bw(i)?new _i(t,i):xw(i)?new zw(t,i):Cw(i)?new Uw(t,i):kw(i)?new yu(t,i):Ew(i)?new $w(t,i):Pw(i)?new Hw(t,i):new Vw(t,i)}static createDecimal(t){var i;return new yu(t,le(i=Hi,ci,Pp).call(i))}static createDisc(t){var i;return new _i(t,le(i=Hi,ci,Np).call(i))}static createSquare(t){var i;return new _i(t,le(i=Hi,ci,Tp).call(i))}static createCircle(t){var i;return new _i(t,le(i=Hi,ci,Ap).call(i))}static createDisclosureOpen(t){var i;return new _i(t,le(i=Hi,ci,Ip).call(i))}static createDisclosureClosed(t){return new _i(t,le(this,ci,Fp).call(this))}static createNone(t){var i;return new _i(t,le(i=Hi,ci,Rp).call(i))}static get CHINESE_LONGHAND_NAMES(){return vu.NAMES}static createChineseLonghand(t,i){return new vu(t,i)}static createEthiopicNumeric(t){return new Gw(t)}_getNegative(){return H(this,Mo)}static _getNegativeFrom(t){return t._getNegative()}_getPrefix(){return H(this,_o)}static _getPrefixFrom(t){return t._getPrefix()}_getSuffix(){return H(this,Do)}static _getSuffixFrom(t){return t._getSuffix()}static _getAutoRangeFrom(t){return t._getAutoRange()}_getRange(){return H(this,zo)}static _getRangeFrom(t){return t._getRange()}_getPad(){return H(this,Vo)}static _getPadFrom(t){return t._getPad()}_getFallback(){var t;return(t=this._store.get(H(this,Uo)))!=null?t:null}static _getFallbackFrom(t){return t._getFallback()}_getSymbols(){return H(this,$o)}static _getSymbolsFrom(t){return t._getSymbols()}_getAdditiveSymbols(){return H(this,Ho)}static _getAdditiveSymbolsFrom(t){return t._getAdditiveSymbols()}static _useNegativeSignFrom(t,i){return t._usesNegativeSign(i)}static _generateInitialRepresentationFrom(t,i){return t._generateInitialRepresentation(i)}format(t){return le(this,wt,dr).call(this,t,new Set)}formatMarker(t){return le(this,wt,Lp).call(this)+this.format(t)+le(this,wt,Op).call(this)}};Mo=new WeakMap,_o=new WeakMap,Do=new WeakMap,zo=new WeakMap,Vo=new WeakMap,Uo=new WeakMap,$o=new WeakMap,Ho=new WeakMap,mo=new WeakMap,ci=new WeakSet,Pp=function(){var e;return(e=H(ze,mo))!=null?e:de(ze,mo,{system:new W(B("numeric"),0),symbols:new W(new J([new K("0"),new K("1"),new K("2"),new K("3"),new K("4"),new K("5"),new K("6"),new K("7"),new K("8"),new K("9")]),0)})},yo=new WeakMap,Np=function(){var e;return(e=H(ze,yo))!=null?e:de(ze,yo,{system:new W(B("cyclic"),0),symbols:new W(new K("\u2022"),0),suffix:new W(new K(" "),0)})},vo=new WeakMap,Tp=function(){var e;return(e=H(ze,vo))!=null?e:de(ze,vo,{system:new W(B("cyclic"),0),symbols:new W(new K("\u25AA"),0),suffix:new W(new K(" "),0)})},wo=new WeakMap,Ap=function(){var e;return(e=H(ze,wo))!=null?e:de(ze,wo,{system:new W(B("cyclic"),0),symbols:new W(new K("\u25E6"),0),suffix:new W(new K(" "),0)})},bo=new WeakMap,Ip=function(){var e;return(e=H(ze,bo))!=null?e:de(ze,bo,{system:new W(B("cyclic"),0),symbols:new W(new K("\u25BE"),0),suffix:new W(new K(" "),0)})},xo=new WeakMap,Fp=function(){var e;return(e=H(ze,xo))!=null?e:de(ze,xo,{system:new W(B("cyclic"),0),symbols:new W(new K("\u25B8"),0),suffix:new W(new K(" "),0)})},So=new WeakMap,Rp=function(){var e;return(e=H(ze,So))!=null?e:de(ze,So,{system:new W(B("cyclic"),0),symbols:new W(new K(""),0),suffix:new W(new K(""),0)})},wt=new WeakSet,la=function(){var e;return(e=this._getNegative())!=null?e:{prefix:"-",suffix:null}},Lp=function(){var e;return(e=this._getPrefix())!=null?e:""},Op=function(){var e;return(e=this._getSuffix())!=null?e:". "},fu=function(){var e;return(e=this._getRange())!=null?e:this._getAutoRange()},gu=function(){var e;return(e=this._getPad())!=null?e:{minLength:0,symbol:""}},ha=function(){var e;return(e=this._getFallback())!=null?e:Un(this._store)},mu=function(e,t){let{minLength:i,symbol:n}=le(this,wt,gu).call(this);if(i===0||n==="")return e;let{prefix:r,suffix:o}=le(this,wt,la).call(this),s=t?go(r)+(o?go(o):0):0,a=i-go(e)-s;if(a<=0)return e;let h=go(n),l=Math.ceil(a/h);return n.repeat(l)+e},dr=function(e,t){var i,n,r;if(t.has(this))return le(i=Un(this._store),wt,dr).call(i,e,new Set);if(t.add(this),!Dw(e,le(this,wt,fu).call(this))){let l=le(this,wt,ha).call(this);return le(n=l,wt,dr).call(n,e,t)}let o=this._usesNegativeSign(e),s=o?Math.abs(e):e,a=this._generateInitialRepresentation(s);if(a===null){let l=le(this,wt,ha).call(this);return le(r=l,wt,dr).call(r,e,t)}let h=le(this,wt,mu).call(this,a,o);if(o){let{prefix:l,suffix:c}=le(this,wt,la).call(this);h=l+h+(c??"")}return h},ie(ze,ci),ie(ze,mo,null),ie(ze,yo,null),ie(ze,vo,null),ie(ze,wo,null),ie(ze,bo,null),ie(ze,xo,null),ie(ze,So,null);var ce=ze,_i=class extends ce{constructor(e,t){super(e,t)}_getAutoRange(){return[{lower:-1/0,upper:1/0}]}_usesNegativeSign(e){return!1}_generateInitialRepresentation(e){let t=this._getSymbols();if(!t||t.length===0)return null;let i=t.length,n=((e-1)%i+i)%i;return t[n]}},Wo,zw=class extends ce{constructor(e,t){super(e,t),ie(this,Wo),de(this,Wo,Sw(t))}_getAutoRange(){return[{lower:-1/0,upper:1/0}]}_usesNegativeSign(e){return!1}_generateInitialRepresentation(e){var t;let i=this._getSymbols();if(!i||i.length===0)return null;let n=e-H(this,Wo);return(t=i[n])!=null?t:null}};Wo=new WeakMap;var Vw=class extends ce{constructor(e,t){super(e,t)}_getAutoRange(){return[{lower:1,upper:1/0}]}_usesNegativeSign(e){return e<0}_generateInitialRepresentation(e){let t=this._getSymbols();if(!t||t.length===0||e<1)return null;let i=t.length,n=t[(e-1)%i],r=Math.ceil(e/i);return n.repeat(r)}},Uw=class extends ce{constructor(e,t){super(e,t)}_getAutoRange(){return[{lower:1,upper:1/0}]}_usesNegativeSign(e){return e<0}_generateInitialRepresentation(e){let t=this._getSymbols();if(!t||t.length<2||e<1)return null;let i=t.length,n="",r=e;for(;r!==0;)r=r-1,n=t[r%i]+n,r=Math.floor(r/i);return n}},yu=class extends ce{constructor(e,t){super(e,t)}_getAutoRange(){return[{lower:-1/0,upper:1/0}]}_usesNegativeSign(e){return e<0}_generateInitialRepresentation(e){let t=this._getSymbols();if(!t||t.length<2)return null;let i=t.length;if(e===0)return t[0];let n="",r=e;for(;r!==0;)n=t[r%i]+n,r=Math.floor(r/i);return n}},$w=class extends ce{constructor(e,t){super(e,t)}_getAutoRange(){return[{lower:0,upper:1/0}]}_usesNegativeSign(e){return e<0}_generateInitialRepresentation(e){let t=this._getAdditiveSymbols();if(!t||t.length===0)return null;let i="";if(e===0){let r=t.find(o=>o.weight===0);return r?r.symbol:null}let n=e;for(let r of t){let{weight:o,symbol:s}=r;if(o===0||o>n)continue;let a=Math.floor(n/o);if(i+=s.repeat(a),n-=o*a,n===0)return i}return null}},xr,kt,Lt,Bp=class extends ce{constructor(t,i){super(t,i),ie(this,kt),ie(this,xr);let n=Nw(i),r=n.toLowerCase();r==="disc"||r==="circle"||r==="square"||r==="disclosure-open"||r==="disclosure-closed"?de(this,xr,r):de(this,xr,n)}_getNegative(){var t;return(t=super._getNegative())!=null?t:ce._getNegativeFrom(le(this,kt,Lt).call(this))}_getPrefix(){var t;return(t=super._getPrefix())!=null?t:ce._getPrefixFrom(le(this,kt,Lt).call(this))}_getSuffix(){var t;return(t=super._getSuffix())!=null?t:ce._getSuffixFrom(le(this,kt,Lt).call(this))}_getAutoRange(){return ce._getAutoRangeFrom(le(this,kt,Lt).call(this))}_getRange(){var t;return(t=super._getRange())!=null?t:ce._getRangeFrom(le(this,kt,Lt).call(this))}_getPad(){var t;return(t=super._getPad())!=null?t:ce._getPadFrom(le(this,kt,Lt).call(this))}_getFallback(){var t;return(t=super._getFallback())!=null?t:ce._getFallbackFrom(le(this,kt,Lt).call(this))}_getSymbols(){var t;return(t=super._getSymbols())!=null?t:ce._getSymbolsFrom(le(this,kt,Lt).call(this))}_getAdditiveSymbols(){var t;return(t=super._getAdditiveSymbols())!=null?t:ce._getAdditiveSymbolsFrom(le(this,kt,Lt).call(this))}_usesNegativeSign(t){return ce._useNegativeSignFrom(le(this,kt,Lt).call(this),t)}_generateInitialRepresentation(t){return super._getSymbols()||super._getAdditiveSymbols()?null:ce._generateInitialRepresentationFrom(le(this,kt,Lt).call(this),t)}};xr=new WeakMap,kt=new WeakSet,Lt=function(e=new Set){var t;if(e.has(this))return Un(this._store);e.add(this);let i=this._store.get(H(this,xr));return i?i instanceof Bp?le(t=i,kt,Lt).call(t,e):i:Un(this._store)};var Hw=Bp,Ww=["simp-chinese-informal","simp-chinese-formal","trad-chinese-informal","trad-chinese-formal","cjk-ideographic"];function nr(e){return{suffix:new W(new K("\u3001"),0),fallback:new W(B("cjk-decimal"),0),range:new W(new J([new lt(-9999),new lt(9999)]),0),negative:new W(new K(e),0)}}var ua,ca,Co,da,ko,Xa,Mp,Go,vt=class _p extends ce{constructor(t,i){var n;let{chars:r,descriptors:o}=le(n=_p,Xa,Mp).call(n).get(i);super(t,o),ie(this,Go),de(this,Go,r)}_getAutoRange(){return[{lower:-9999,upper:9999}]}_usesNegativeSign(t){return t<0}_generateInitialRepresentation(t){let i=H(this,Go);if(t===0)return i.digits[0];let n=[],r=0,o=t;for(;o>0;)n.unshift({digit:o%10,position:r}),o=Math.floor(o/10),r++;let s=i.informal&&t>=10&&t<=19,a="",h=!1;for(let l=0;l<n.length;l++){let{digit:c,position:d}=n[l],p=l===n.length-1;c===0?!p&&!h&&(h=!0):(h&&(a+=i.digits[0],h=!1),s&&d===1?a+=i.markers[d]:(a+=i.digits[c],d>0&&(a+=i.markers[d])))}return a}};ua=new WeakMap,ca=new WeakMap,Co=new WeakMap,da=new WeakMap,ko=new WeakMap,Xa=new WeakSet,Mp=function(){var e;return(e=H(vt,ko))!=null?e:de(vt,ko,new Map([["simp-chinese-informal",{chars:H(vt,ua),descriptors:nr("\u8D1F")}],["simp-chinese-formal",{chars:H(vt,ca),descriptors:nr("\u8D1F")}],["trad-chinese-informal",{chars:H(vt,Co),descriptors:nr("\u8CA0")}],["trad-chinese-formal",{chars:H(vt,da),descriptors:nr("\u8CA0")}],["cjk-ideographic",{chars:H(vt,Co),descriptors:nr("\u8CA0")}]]))},Go=new WeakMap,ie(vt,Xa),ie(vt,ua,{digits:["\u96F6","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D","\u4E03","\u516B","\u4E5D"],markers:["","\u5341","\u767E","\u5343"],informal:!0}),ie(vt,ca,{digits:["\u96F6","\u58F9","\u8D30","\u53C1","\u8086","\u4F0D","\u9646","\u67D2","\u634C","\u7396"],markers:["","\u62FE","\u4F70","\u4EDF"],informal:!1}),ie(vt,Co,{digits:["\u96F6","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D","\u4E03","\u516B","\u4E5D"],markers:["","\u5341","\u767E","\u5343"],informal:!0}),ie(vt,da,{digits:["\u96F6","\u58F9","\u8CB3","\u53C3","\u8086","\u4F0D","\u9678","\u67D2","\u634C","\u7396"],markers:["","\u62FE","\u4F70","\u4EDF"],informal:!1}),u(vt,"NAMES",new Set(Ww)),ie(vt,ko,null);var vu=vt,Eo,qa,Dp,Ya,gs,Za,Ka,hi=class Wi extends ce{constructor(t){var i;super(t,le(i=Wi,qa,Dp).call(i))}_getAutoRange(){return[{lower:1,upper:1/0}]}_usesNegativeSign(t){return!1}_generateInitialRepresentation(t){if(t<1)return null;if(t===1)return H(Wi,gs)[1];let i=[],n=t;for(;n>0;)i.push(n%100),n=Math.floor(n/100);let r=i.length,o="";for(let s=r-1;s>=0;s--){let a=i[s],h=s%2===1,l=s===r-1;if(!(a===0||l&&a===1||h&&a===1)){let c=Math.floor(a/10),d=a%10;o+=H(Wi,Ya)[c]+H(Wi,gs)[d]}h?a!==0&&(o+=H(Wi,Za)):s!==0&&(o+=H(Wi,Ka))}return o}};Eo=new WeakMap,qa=new WeakSet,Dp=function(){var e;return(e=H(hi,Eo))!=null?e:de(hi,Eo,{range:new W(new J([new lt(1),B("infinite")]),0),suffix:new W(new K("/ "),0)})},Ya=new WeakMap,gs=new WeakMap,Za=new WeakMap,Ka=new WeakMap,ie(hi,qa),ie(hi,Eo,null),ie(hi,Ya,["","\u1372","\u1373","\u1374","\u1375","\u1376","\u1377","\u1378","\u1379","\u137A"]),ie(hi,gs,["","\u1369","\u136A","\u136B","\u136C","\u136D","\u136E","\u136F","\u1370","\u1371"]),ie(hi,Za,"\u137B"),ie(hi,Ka,"\u137C");var Gw=hi,Re,jw=class{constructor(){ie(this,Re),de(this,Re,new Map),H(this,Re).set("none",ce.createNone(H(this,Re))),H(this,Re).set("decimal",ce.createDecimal(H(this,Re))),H(this,Re).set("disc",ce.createDisc(H(this,Re))),H(this,Re).set("square",ce.createSquare(H(this,Re))),H(this,Re).set("circle",ce.createCircle(H(this,Re))),H(this,Re).set("disclosure-open",ce.createDisclosureOpen(H(this,Re))),H(this,Re).set("disclosure-closed",ce.createDisclosureClosed(H(this,Re)));for(let e of ce.CHINESE_LONGHAND_NAMES)H(this,Re).set(e,ce.createChineseLonghand(H(this,Re),e));H(this,Re).set("ethiopic-numeric",ce.createEthiopicNumeric(H(this,Re)))}define(e,t){if(!fw(e))return null;let i=ce.create(H(this,Re),t);return H(this,Re).set(e,i),i}getStyle(e){var t;return(t=H(this,Re).get(e))!=null?t:null}format(e,t){var i;return((i=this.getStyle(e))!=null?i:Un(H(this,Re))).format(t)}formatMarker(e,t){var i;return((i=this.getStyle(e))!=null?i:Un(H(this,Re))).formatMarker(t)}};Re=new WeakMap;var An=class{constructor(e){u(this,"validator",e),u(this,"success",null),u(this,"failure",null),u(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(e){this.code=2*e+1}isStartAlternate(){return this.code>0&&this.code%2!=0}markAsEndAlternate(e){this.code=2*e+2}isEndAlternate(){return this.code>0&&this.code%2==0}getAlternate(){return Math.floor((this.code-1)/2)}},Di=class{constructor(e,t){u(this,"where",e),u(this,"success",t),u(this,"what",-1)}},rr=class zp{constructor(){u(this,"nodes",[]),u(this,"connections",[]),u(this,"match",[]),u(this,"nomatch",[]),u(this,"error",[]),u(this,"emptyHead",!0)}connect(t,i){for(let n=0;n<t.length;n++)this.connections[t[n]].what=i;t.splice(0,t.length)}clone(){let t=new zp;for(let i=0;i<this.nodes.length;i++){let n=this.nodes[i],r=new An(n.validator);r.code=n.code,t.nodes.push(r)}for(let i=0;i<this.connections.length;i++){let n=this.connections[i],r=new Di(n.where,n.success);r.what=n.what,t.connections.push(r)}return t.match.push(...this.match),t.nomatch.push(...this.nomatch),t.error.push(...this.error),t}addSpecialToArr(t,i,n){let r=this.nodes.length,o=new An(wu);n>=0?i?o.markAsStartAlternate(n):o.markAsEndAlternate(n):i?o.markAsStartGroup():o.markAsEndGroup(),this.nodes.push(o),this.connect(t,r);let s=new Di(r,!0),a=new Di(r,!1);t.push(this.connections.length),this.connections.push(a),t.push(this.connections.length),this.connections.push(s)}endSpecialGroup(){let t=[this.match,this.nomatch,this.error];for(let i=0;i<t.length;i++)this.addSpecialToArr(t[i],!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 i=new An(wu);i.markAsStartAlternate(t),this.nodes.push(i);let n=new Di(0,!0),r=new Di(0,!1);this.nomatch.push(this.connections.length),this.connections.push(r),this.match.push(this.connections.length),this.connections.push(n)}addPrimitive(t){let i=this.nodes.length;this.nodes.push(new An(t));let n=new Di(i,!0),r=new Di(i,!1);this.connect(this.match,i),this.emptyHead?(this.nomatch.push(this.connections.length),this.emptyHead=!1):this.error.push(this.connections.length),this.connections.push(r),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 ue}addGroup(t,i){if(t.nodes.length==0)return;let n=this.nodes.length;if(i==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]);i==4?(this.emptyHead=!0,this.connect(this.nomatch,n)):this.connect(this.match,n);let r=this.connections.length;for(let o=0;o<t.connections.length;o++){let s=t.connections[o];s.where+=n,s.what>=0&&(s.what+=n),this.connections.push(s)}for(let o=0;o<t.match.length;o++)this.match.push(t.match[o]+r);if(i==3&&this.connect(this.match,n),i==2||i==3)for(let o=0;o<t.nomatch.length;o++)this.match.push(t.nomatch[o]+r);else if(this.emptyHead){for(let o=0;o<t.nomatch.length;o++)this.nomatch.push(t.nomatch[o]+r);this.emptyHead=t.emptyHead}else for(let o=0;o<t.nomatch.length;o++)this.error.push(t.nomatch[o]+r);for(let o=0;o<t.error.length;o++)this.error.push(t.error[o]+r);t.nodes=null,t.connections=null}finish(t,i){let n=this.nodes.length;this.nodes.push(t),this.nodes.push(i),this.connect(this.match,n),this.connect(this.nomatch,n+1),this.connect(this.error,n+1);for(let r of this.connections)r.success?this.nodes[r.where].success=this.nodes[r.what]:this.nodes[r.where].failure=this.nodes[r.what];for(let r=0;r<n;r++)if(this.nodes[r].failure==null||this.nodes[r].success==null)throw new Error("Invalid validator state");return this.nodes[0]}},Xw=1,ms=2,Vp=4,Si=8,Zi=16,$n=32,On=64,ys=128,ni=256,ri=512,vs=1024,Up=2048,$p=4096,ws=8192,Yl=class extends Kt{constructor(){super()}validateForShorthand(e,t){let i=e[t].visit(this);return i?[i]:null}},ue=class Hp extends Yl{constructor(t,i,n){super(),u(this,"allowed",t),u(this,"idents",i),u(this,"units",n)}visitEmpty(t){return this.allowed&Xw?t:null}visitSlash(t){return this.allowed&Up?t:null}visitStr(t){return this.allowed&ms?t:null}visitIdent(t){return this.idents[t.name.toLowerCase()]||(this.allowed&Vp||this.allowed&On&&CSS.supports("color",t.name)?t:null)}visitNumeric(t){return t.num==0&&!(this.allowed&ri)?t.unit=="%"&&this.allowed&vs?t:null:t.num<0&&!(this.allowed&ni)?null:this.units[t.unit]?t:null}visitNum(t){return t.num==0?this.allowed&ri?t:null:t.num<=0&&!(this.allowed&ni)?null:this.allowed&Zi?t:null}visitInt(t){return t.num==0?this.allowed&ri?t:null:t.num<=0&&!(this.allowed&ni)?null:this.allowed&($n|Zi)?t:this.idents[`${t.num}`]||null}visitHexColor(t){return this.allowed&On&&/^([0-9A-F]{3,4}|([0-9A-F]{2}){3,4})$/i.test(t.hex)?t:null}visitURL(t){return this.allowed&ys?t:null}visitURange(t){return this.allowed&$p?t:null}visitSpaceList(t){return null}visitCommaList(t){return null}visitFunc(t){if(t.name.toLowerCase()==="attr"){let i=Ql(t);if(i&&Jw(i.type,this.allowed,this.units))return t}if(this.allowed&On){if(t.name==="device-cmyk"||t.name==="cmyk")return CSS.supports("color","color(srgb 0 0 0)")&&Jc(t)!==null?t:null;if(CSS.supports("color",t.toString()))return t}if(this.allowed&ws){let i=t.visit(new td);if(CSS.supports("background-image",i.toString()))return t}return t.name==="calc"&&this.allowed&(Si|Zi|$n|ni|ri|vs)?t:null}visitExpr(t){return this.allowed&2046?t:null}combine(t){let i={},n={};for(let r in this.idents)i[r]=this.idents[r];for(let r in t.idents)i[r]=t.idents[r];for(let r in this.units)n[r]=this.units[r];for(let r in t.units)n[r]=t.units[r];return new Hp(this.allowed|t.allowed,i,n)}},te=Object.create(null),qw=Zi|ni|ri,Yw=$n|ni|ri,zi=Si|ni|ri|vs;function no(e){let t=Object.create(null);for(let i of e)t[i]=Me;return t}var Ds=no(["%"]),zs=no(["em","ex","ch","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","pvw","pvh","pvi","pvb","pvmin","pvmax","cm","mm","in","px","pt","pc","q"]),Wp={...zs,...Ds},Zl=no(["deg","grad","rad","turn"]),Kl=no(["s","ms"]),Jl=no(["hz","khz"]);function Zw(e){return e.replace(/\s+/g,"").toLowerCase()}function Vs(e){return e.toLowerCase()}function Kw(e){if(e instanceof he)switch(e.name.toLowerCase()){case"string":case"raw-string":return{kind:"string"};case"url":return{kind:"url"};case"color":case"integer":case"number":case"length":case"angle":case"time":case"frequency":return{kind:"syntax",syntax:`<${e.name.toLowerCase()}>`};default:return{kind:"unit",unit:Vs(e.name)}}if(e instanceof ai&&e.name.toLowerCase()==="type"){if(e.values.length!==1)return null;let t=Zw(e.values[0].stringValue());return t?{kind:"syntax",syntax:t}:null}return null}function Ql(e){var t;if(e.name.toLowerCase()!=="attr"||e.values.length<1||e.values.length>2)return null;let i,n={kind:"string"},r=e.values[0];if(r instanceof he)i=r.name;else if(r instanceof J){let o=r.values;if(o.length<1||o.length>2||!(o[0]instanceof he)||(i=o[0].name,o.length===2&&(n=Kw(o[1]),!n)))return null}else return null;return{attributeName:i,type:n,fallback:(t=e.values[1])!=null?t:null}}function Gp(e,t){return!!e[Vs(t)]}function un(e,t){return Object.keys(t).some(i=>Gp(e,i))}function Jw(e,t,i){switch(e.kind){case"string":return!!(t&ms);case"url":return!!(t&(ys|ws));case"unit":return Gp(i,e.unit);case"syntax":switch(e.syntax){case"<string>":return!!(t&ms);case"<url>":return!!(t&(ys|ws));case"<color>":return!!(t&On);case"<integer>":return!!(t&($n|Zi|ni|ri));case"<number>":return!!(t&(Zi|$n|ni|ri));case"<length>":return un(i,zs);case"<length-percentage>":return un(i,Wp);case"<percentage>":return un(i,Ds);case"<angle>":return un(i,Zl);case"<time>":return un(i,Kl);case"<frequency>":return un(i,Jl);default:return!1}}return!1}function Ja(e){switch(e.kind){case"string":return null;case"url":return null;case"unit":return new ue(zi,te,{[Vs(e.unit)]:Me});case"syntax":switch(e.syntax){case"<color>":return new ue(On,te,te);case"<integer>":return new ue(Yw,te,te);case"<number>":return new ue(qw,te,te);case"<length>":return new ue(zi,te,zs);case"<length-percentage>":return new ue(zi,te,Wp);case"<percentage>":return new ue(zi,te,Ds);case"<angle>":return new ue(zi,te,Zl);case"<time>":return new ue(zi,te,Kl);case"<frequency>":return new ue(zi,te,Jl);default:return null}}return null}function Qw(e){switch(e.kind){case"string":case"url":case"unit":return!0;case"syntax":return e.syntax==="<string>"||e.syntax==="<url>"||!!Ja(e)}return!1}function eb(e){switch(e.kind){case"url":return new Qe("about:invalid");case"string":return new K("");default:return y.unset}}function tb(e,t,i){if(t==null)return null;switch(i.kind){case"string":return new K(t);case"url":return t?new Qe(t):new Qe("about:invalid");case"unit":{let n=Ri(e,new xt(`${t.trim()}${Vs(i.unit)}`,null),""),r=Ja(i);return n&&r?n.visit(r):null}case"syntax":{if(i.syntax==="<string>")return new K(t);if(i.syntax==="<url>")return t?new Qe(t):new Qe("about:invalid");let n=Ri(e,new xt(t,null),""),r=Ja(i);return n&&r?n.visit(r):null}}return null}var wu=new ue(0,te,te),eh=class extends Yl{constructor(e){super(),u(this,"successTerminal"),u(this,"failureTerminal"),u(this,"first"),this.successTerminal=new An(null),this.failureTerminal=new An(null),this.first=e.finish(this.successTerminal,this.failureTerminal)}validateList(e,t,i){let n=t?[]:e,r=this.first,o=i,s=null,a=null;for(;r!==this.successTerminal&&r!==this.failureTerminal;){if(o>=e.length){r=r.failure;continue}let h=e[o],l=h;if(r.isSpecial()){let c=!0;r.isStartGroup()?(s?s.push(a):s=[a],a=[]):r.isEndGroup()?s.length>0?a=s.pop():a=null:r.isEndAlternate()?a[r.getAlternate()]="taken":c=a[r.getAlternate()]==null,r=c?r.success:r.failure}else{if(o==0&&!t&&r.validator instanceof Sr&&this instanceof Sr){if(l=new J(e).visit(r.validator),l){o=e.length,r=r.success;continue}}else if(o==0&&!t&&r.validator instanceof th&&this instanceof Sr){if(l=new Oe(e).visit(r.validator),l){o=e.length,r=r.success;continue}}else l=h.visit(r.validator);if(!l){r=r.failure;continue}if(l!==h&&e===n){n=[];for(let c=0;c<o;c++)n[c]=e[c]}e!==n&&(n[o-i]=l),o++,r=r.success}}return r===this.successTerminal&&(t?n.length>0:o==e.length)?n:null}validateSingle(e){let t=this.validateList([e],!1,0);return t?t[0]: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}},Sr=class extends eh{constructor(e){super(e)}visitSpaceList(e){let t=this.validateList(e.values,!1,0);return t===e.values?e:t?new J(t):null}visitCommaList(e){let t=this.first,i=!1;for(;t;){if(t.validator instanceof th){i=!0;break}t=t.failure}if(i){let n=this.validateList(e.values,!1,0);return n===e.values?e:n?new Oe(n):null}return null}validateForShorthand(e,t){return this.validateList(e,!0,t)}},th=class extends eh{constructor(e){super(e)}visitSpaceList(e){return this.validateSingle(e)}visitCommaList(e){let t=this.validateList(e.values,!1,0);return t===e.values?e:t?new Oe(t):null}validateForShorthand(e,t){let i=this.first,n;for(;i!==this.failureTerminal;){if(n=i.validator.validateForShorthand(e,t),n)return n;i=i.failure}return null}},ib=class extends eh{constructor(e,t){super(t),u(this,"name",e)}validateSingle(e){return null}visitFunc(e){if(e.name.toLowerCase()!=this.name)return null;let t=this.validateList(e.values,!1,0);return t===e.values?e:t?new ai(e.name,t):null}},bu=class extends Yl{validateSingle(e){return null}visitFunc(e){let t=Ql(e);return t&&Qw(t.type)?e:null}},jp=class{tryParse(e,t,i){return t}success(e,t){}},Xp=class extends jp{constructor(e,t){super(),u(this,"name",t),u(this,"validator"),this.validator=e.validators[this.name]}tryParse(e,t,i){if(i.values[this.name])return t;let n=this.validator.validateForShorthand(e,t);if(n){let r=n.length,o=r>1?new J(n):n[0];return this.success(o,i),t+r}return t}success(e,t){t.values[this.name]=e}},nb=class extends Xp{constructor(e,t){super(e,t[0]),u(this,"names",t)}success(e,t){for(let i=0;i<this.names.length;i++)t.values[this.names[i]]=e}},rb=class extends jp{constructor(e,t){super(),u(this,"nodes",e),u(this,"slash",t)}tryParse(e,t,i){let n=t;if(this.slash)if(e[t]==jn){if(++t==e.length)return n}else return n;let r=this.nodes[0].tryParse(e,t,i);if(r==t)return n;t=r;for(let o=1;o<this.nodes.length&&t<e.length&&(r=this.nodes[o].tryParse(e,t,i),r!=t);o++)t=r;return t}},Us=class extends Kt{constructor(){super(...arguments),u(this,"syntax",null),u(this,"propList",null),u(this,"error",!1),u(this,"values",{}),u(this,"validatorSet",null)}setOwner(e){this.validatorSet=e}syntaxNodeForProperty(e){return new Xp(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,t){this.syntax=e,this.propList=t}finish(e,t){var i,n;if(!this.error){for(let r of this.propList)t.simpleProperty(r,(n=(i=this.values[r])!=null?i:this.validatorSet.defaultValues[r])!=null?n:y.initial,e);return!0}return!1}propagateDefaultingValue(e,t,i){for(let n of this.propList)i.simpleProperty(n,e,t)}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)}},Xn=class extends Us{constructor(){super()}validateList(e){let t=0,i=0;for(;t<e.length;){let n=this.syntax[i].tryParse(e,t,this);if(n>t){t=n,i=0;continue}if(++i==this.syntax.length){this.error=!0;break}}return t}},qp=class extends Us{constructor(){super()}validateList(e){if(e.length>this.syntax.length||e.length==0)return this.error=!0,0;for(let t=0;t<this.syntax.length;t++){let i=t;for(;i>=e.length;)i=i==1?0:i-2;if(this.syntax[t].tryParse(e,i,this)!=i+1)return this.error=!0,0}return e.length}createSyntaxNode(){return new nb(this.validatorSet,this.propList)}},ob=class extends Us{constructor(){super()}validateList(e){let t=e.length;for(let i=0;i<e.length;i++)if(e[i]===jn){t=i;break}if(t>this.syntax.length||e.length==0)return this.error=!0,0;for(let i=0;i<this.syntax.length;i++){let n=i;for(;n>=t;)n=n==1?0:n-2;let r;if(t+1<e.length)for(r=t+i+1;r>=e.length;)r=r-(r==t+2?1:2);else r=n;let o=[e[n],e[r]];if(this.syntax[i].tryParse(o,0,this)!=2)return this.error=!0,0}return e.length}},sb=class extends Xn{constructor(){super()}mergeIn(e,t){var i,n;for(let r of this.propList){let o=(n=(i=t[r])!=null?i:this.validatorSet.defaultValues[r])!=null?n:y.initial,s=e[r];s||(s=[],e[r]=s),s.push(o)}}visitCommaList(e){let t={};for(let i=0;i<e.values.length;i++)if(this.values={},e.values[i]instanceof Oe?this.error=!0:(e.values[i].visit(this),this.mergeIn(t,this.values),this.values["background-color"]&&i!=e.values.length-1&&(this.error=!0)),this.error)return null;this.values={};for(let i in t)i=="background-color"?this.values[i]=t[i].pop():this.values[i]=new Oe(t[i]);return null}},ab=class extends Xn{constructor(){super()}init(e,t){super.init(e,t),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(e){let t=super.validateList(e),i=this.values["font-variant_css2"];i&&(delete this.values["font-variant_css2"],this.values["font-variant-caps"]=i);let n=this.values["font-stretch_css3"];if(n&&(delete this.values["font-stretch_css3"],this.values["font-stretch"]=n),t+2>e.length)return this.error=!0,t;this.error=!1;let r=this.validatorSet.validators;if(!e[t].visit(r["font-size"])){let s=this.values["font-weight"],a=s instanceof ai&&s.name==="calc"?e.indexOf(s):-1;if(a>=0&&e[a].visit(r["font-size"]))delete this.values["font-weight"],t=a;else return this.error=!0,t}if(this.values["font-size"]=e[t++],e[t]===jn){if(t++,t+2>e.length)return this.error=!0,t;if(!e[t].visit(r["line-height"]))return this.error=!0,t;this.values["line-height"]=e[t++]}let o=t==e.length-1?e[t]:new J(e.slice(t,e.length));return o.visit(r["font-family"])?(this.values["font-family"]=o,e.length):(this.error=!0,t)}visitCommaList(e){if(e.values[0].visit(this),this.error)return null;let t=[this.values["font-family"]];for(let n=1;n<e.values.length;n++)t.push(e.values[n]);let i=new Oe(t);return i.visit(this.validatorSet.validators["font-family"])?this.values["font-family"]=i:this.error=!0,null}visitIdent(e){let t=this.validatorSet.systemFonts[e.name];if(t)for(let i in t)this.values[i]=t[i];else this.error=!0;return null}},lb=class extends Xn{validateList(e){if(e.length===1&&e[0]instanceof he)switch(e[0].name.toLowerCase()){case"normal":e=[this.validatorSet.defaultValues["text-autospace"],this.validatorSet.defaultValues["text-spacing-trim"]];break;case"auto":e=[y.auto,y.auto];break;case"none":e=[B("no-autospace"),B("space-all")];break}return super.validateList(e)}},hb=class extends Us{constructor(e,t=[]){super(),u(this,"name",e),this.propList=t}clone(){let e=new this.constructor(this.name,[...this.propList]);return e.validatorSet=this.validatorSet,e}validateValueText(e){let t=this.validatorSet.expandBrowserShorthand(this.name,e);if(!t)return this.error=!0,!1;this.propList=t.propList,this.values={};for(let i of t.propList){let n=t.values[i];if(!n)continue;let r=Ri(this.validatorSet.scope,new xt(n,null),"");if(!r)return this.error=!0,!1;this.values[i]=r}return this.error=!1,!0}validateList(e){let t=e.length===1?e[0].toString():new J(e).toString();return this.validateValueText(t)?e.length:0}visitCommaList(e){return this.validateValueText(e.toString()),null}},xu=["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","inset-block-start","inset-block-end","inset-inline-start","inset-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","src","template","text-decoration-skip","text-justify","text-zoom","unicode-range","utilization","wrap-flow"],Yp=class extends Xn{constructor(){super()}refreshPropList(){this.propList=this.validatorSet.getPropertiesForAll()}init(e,t){super.init(e,t)}validateList(e){return this.error=!0,0}},Su={SIMPLE:Xn,INSETS:qp,INSETS_SLASH:ob,COMMA:sb,FONT:ab,TEXT_SPACING:lb,ALL:Yp},ub=["initial-letter"],cb=class{constructor(){u(this,"validators",{}),u(this,"prefixes",{}),u(this,"defaultValues",{}),u(this,"namedValidators",{}),u(this,"systemFonts",{}),u(this,"shorthands",{}),u(this,"layoutProps",{}),u(this,"backgroundProps",{}),u(this,"scope",new ts(null)),u(this,"browserShorthandStyle",null),u(this,"browserShorthandMisses",{}),u(this,"browserPropertyNamesForAll",null),u(this,"allPropertyNames",null)}invalidateAllPropertyNames(){this.allPropertyNames=null}getBrowserPropertyNamesForAll(){if(this.browserPropertyNamesForAll)return this.browserPropertyNamesForAll;if(typeof document>"u"||typeof getComputedStyle!="function")return null;let e=document.documentElement;if(!e)return null;let t=getComputedStyle(e),i=[];for(let n=0;n<t.length;n++){let r=t.item(n);!r||Xe(r)||xu.includes(r)||i.push(r)}return this.browserPropertyNamesForAll=i,this.browserPropertyNamesForAll}getPropertiesForAll(){if(this.allPropertyNames)return this.allPropertyNames;let e=new Set;for(let n in this.validators)xu.includes(n)||e.add(n);let t=this.getBrowserPropertyNamesForAll();if(t)for(let n of t)this.shorthands[n]||e.add(n);let i=Array.from(e);return t&&(this.allPropertyNames=i),i}getBrowserShorthandStyle(){return this.browserShorthandStyle!==null?this.browserShorthandStyle:typeof document>"u"?null:(this.browserShorthandStyle=document.createElement("div").style,this.browserShorthandStyle)}expandBrowserShorthand(e,t){let i=this.getBrowserShorthandStyle();if(!i)return null;i.cssText="",i.setProperty(e,t);let n=Array.from({length:i.length},(o,s)=>i.item(s)).filter(o=>!!o);if(!n.length||n.length===1&&n[0]===e.toLowerCase())return null;let r={};for(let o of n)r[o]=i.getPropertyValue(o);return{propList:n,values:r}}getShorthand(e,t){if(Xe(e))return null;let i=this.shorthands[e];if(i)return i instanceof Yp&&!this.allPropertyNames&&i.refreshPropList(),i;if(this.browserShorthandMisses[e]||t==null)return null;let n=this.expandBrowserShorthand(e,typeof t=="string"?t:t.toString());if(!n)return(typeof t=="string"?!/\bvar\(/i.test(t):!Cu(t))&&(this.browserShorthandMisses[e]=!0),null;let r=new hb(e,n.propList);return r.setOwner(this),this.shorthands[e]=r,this.invalidateAllPropertyNames(),r}addReplacement(e,t){let i;if(t.type==3)i=new O(t.num,t.text);else if(t.type==7)i=new jc(t.text);else if(t.type==1)i=B(t.text);else throw new Error("unexpected replacement");if(e.isPrimitive()){let n=e.nodes[0].validator.idents;for(let r in n)n[r]=i;return e}throw new Error("unexpected replacement")}newGroup(e,t){let i=new rr;if(e=="||"){for(let r=0;r<t.length;r++){let o=new rr;o.startClause(r),o.addGroup(t[r],1),o.endClause(r),i.addGroup(o,r==0?1:4)}let n=new rr;return n.startSpecialGroup(),n.addGroup(i,3),n.endSpecialGroup(),n}else{let n;switch(e){case" ":n=1;break;case"|":case"||":n=4;break;default:throw new Error("unexpected op")}for(let r=0;r<t.length;r++)i.addGroup(t[r],r==0?1:n);return i}}addCounts(e,t,i){let n=new rr;for(let r=0;r<t;r++)n.addGroup(e.clone(),1);if(i==Number.POSITIVE_INFINITY)n.addGroup(e,3);else for(let r=t;r<i;r++)n.addGroup(e.clone(),2);return n}primitive(e){let t=new rr;return t.addPrimitive(e),t}newFunc(e,t){let i;switch(e){case"COMMA":i=new th(t);break;case"SPACE":i=new Sr(t);break;case"attr":i=new bu;break;default:i=new ib(e.toLowerCase(),t);break}return this.primitive(i)}initBuiltInValidators(){this.namedValidators.COLOR=this.primitive(new ue(On,te,te)),this.namedValidators.ATTR=this.primitive(new bu),this.namedValidators.IMAGE_FUNCTION=this.primitive(new ue(ws,te,te)),this.namedValidators.POS_INT=this.primitive(new ue($n,te,te)),this.namedValidators.POS_NUM=this.primitive(new ue(Zi,te,te)),this.namedValidators.POS_PERCENTAGE=this.primitive(new ue(Si,te,Ds)),this.namedValidators.NEGATIVE=this.primitive(new ue(ni,te,te)),this.namedValidators.ZERO=this.primitive(new ue(ri,te,te)),this.namedValidators.ZERO_PERCENTAGE=this.primitive(new ue(vs,te,te)),this.namedValidators.POS_LENGTH=this.primitive(new ue(Si,te,zs)),this.namedValidators.POS_ANGLE=this.primitive(new ue(Si,te,Zl)),this.namedValidators.POS_TIME=this.primitive(new ue(Si,te,Kl)),this.namedValidators.FREQUENCY=this.primitive(new ue(Si,te,Jl)),this.namedValidators.RESOLUTION=this.primitive(new ue(Si,te,{dpi:Me,dpcm:Me,dppx:Me})),this.namedValidators.URI=this.primitive(new ue(ys,te,te)),this.namedValidators.URANGE=this.primitive(new ue($p,te,te)),this.namedValidators.IDENT=this.primitive(new ue(Vp,te,te)),this.namedValidators.STRING=this.primitive(new ue(ms,te,te)),this.namedValidators.SLASH=this.primitive(new ue(Up,te,te));let e={"font-family":B("sans-serif")};this.systemFonts.caption=e,this.systemFonts.icon=e,this.systemFonts.menu=e,this.systemFonts["message-box"]=e,this.systemFonts["small-caption"]=e,this.systemFonts["status-bar"]=e}isBuiltIn(e){return!!e.match(/^[A-Z_0-9]+$/)}readNameAndPrefixes(e,t){let i=e.token();if(i.type==0)return null;let n={"":!0};if(i.type==14){do{if(e.consume(),i=e.token(),i.type!=1)throw new Error("Prefix name expected");n[i.text]=!0,e.consume(),i=e.token()}while(i.type==16);if(i.type!=15)throw new Error("']' expected");e.consume(),i=e.token()}if(i.type!=1)throw new Error("Property name expected");if(t==2?i.text=="SHORTHANDS":i.text=="DEFAULTS")return e.consume(),null;let r=i.text;if(e.consume(),t!=2){if(e.token().type!=39)throw new Error("'=' expected");this.isBuiltIn(r)||(this.prefixes[r]=n)}else if(e.token().type!=18)throw new Error("':' expected");return r}parseValidators(e){for(;;){let t=this.readNameAndPrefixes(e,1);if(!t)return;let i=[],n=[],r="",o,s=!0,a=()=>{if(i.length==0)throw new Error("No values");return i.length==1?i[0]:this.newGroup(r,i)},h=c=>{if(s)throw new Error(`'${c}': unexpected`);if(r&&r!=c)throw new Error(`mixed operators: '${c}' and '${r}'`);r=c,s=!0},l=null;for(;!l;){e.consume();let c=e.token();switch(c.type){case 1:if(s||h(" "),this.isBuiltIn(c.text)){let d=this.namedValidators[c.text];if(!d)throw new Error(`'${c.text}' unexpected`);i.push(d.clone())}else{let d={};d[c.text.toLowerCase()]=B(c.text),i.push(this.primitive(new ue(0,d,te)))}s=!1;break;case 5:{let d={};d[`${c.num}`]=new lt(c.num),i.push(this.primitive(new ue(0,d,te))),s=!1;break}case 34:h("|");break;case 25:h("||");break;case 14:s||h(" "),n.push({vals:i,op:r,b:"["}),r="",i=[],s=!0;break;case 6:s||h(" "),n.push({vals:i,op:r,b:"(",fn:c.text}),r="",i=[],s=!0;break;case 15:{o=a();let d=n.pop();if(d.b!="[")throw new Error("']' unexpected");i=d.vals,i.push(o),r=d.op,s=!1;break}case 11:{o=a();let d=n.pop();if(d.b!="(")throw new Error("')' unexpected");i=d.vals,i.push(this.newFunc(d.fn,o)),r=d.op,s=!1;break}case 18:if(s)throw new Error("':' unexpected");e.consume(),i.push(this.addReplacement(i.pop(),e.token()));break;case 22:if(s)throw new Error("'?' unexpected");i.push(this.addCounts(i.pop(),0,1));break;case 36:if(s)throw new Error("'*' unexpected");i.push(this.addCounts(i.pop(),0,Number.POSITIVE_INFINITY));break;case 23:if(s)throw new Error("'+' unexpected");i.push(this.addCounts(i.pop(),1,Number.POSITIVE_INFINITY));break;case 12:{if(e.consume(),c=e.token(),c.type!=5)throw new Error("<int> expected");let d=c.num,p=d;if(e.consume(),c=e.token(),c.type==16){if(e.consume(),c=e.token(),c.type!=5)throw new Error("<int> expected");p=c.num,e.consume(),c=e.token()}if(c.type!=13)throw new Error("'}' expected");i.push(this.addCounts(i.pop(),d,p));break}case 17:if(l=a(),n.length>0)throw new Error(`unclosed '${n.pop().b}'`);break;default:throw new Error("unexpected token")}}e.consume(),this.isBuiltIn(t)?this.namedValidators[t]=l:l.isSimple()?this.validators[t]=l.nodes[0].validator:this.validators[t]=new Sr(l)}}parseDefaults(e){for(;;){let t=this.readNameAndPrefixes(e,2);if(!t)return;let i=[];for(;;){e.consume();let n=e.token();if(n.type==17){e.consume();break}switch(n.type){case 1:i.push(B(n.text));break;case 4:i.push(new At(n.num));break;case 5:i.push(new lt(n.num));break;case 3:i.push(new O(n.num,n.text));break;default:throw new Error("unexpected token")}}this.defaultValues[t]=i.length>1?new J(i):i[0]}}parseShorthands(e){for(;;){let t=this.readNameAndPrefixes(e,3);if(!t)return;let i=e.nthToken(1),n;i.type==1&&Su[i.text]?(n=new Su[i.text],e.consume()):n=new Xn,n.setOwner(this);let r=!1,o=[],s=!1,a=[],h=[];for(;!r;)switch(e.consume(),i=e.token(),i.type){case 1:if(this.validators[i.text])o.push(n.syntaxNodeForProperty(i.text)),i.text.includes("_")||h.push(i.text);else if(this.shorthands[i.text]instanceof qp){let l=this.shorthands[i.text];o.push(l.createSyntaxNode()),h.push(...l.propList)}else throw new Error(`'${i.text}' is neither a simple property nor an inset shorthand`);break;case 19:if(o.length>0||s)throw new Error("unexpected slash");s=!0;break;case 14:a.push({slash:s,syntax:o}),o=[],s=!1;break;case 15:{let l=new rb(o,s),c=a.pop();o=c.syntax,s=c.slash,o.push(l);break}case 17:r=!0,e.consume();break;default:throw new Error("unexpected token")}n.init(o,h),this.shorthands[t]=n,this.invalidateAllPropertyNames()}}parse(e){let t=new xt(e,null);this.parseValidators(t),this.parseDefaults(t),this.parseShorthands(t),this.backgroundProps=this.makePropSet(["background"]),this.layoutProps=this.makePropSet(["margin","border","padding","columns","column-gap","column-rule","column-fill"])}makePropSet(e){var t;let i={};for(let n of e){let r=this.shorthands[n],o=r?r.propList:[n];for(let s of o)i[s]=(t=this.defaultValues[s])!=null?t:y.initial}return i}validatePropertyAndHandleShorthand(e,t,i,n){var r,o;let s=n.ruleType;if(Xe(e)||s==="font-face"){n.simpleProperty(e,t,i);return}if(s==="counter-style"){_w(e,t)?n.simpleProperty(e,t,i):n.invalidPropertyValue(e,t);return}let a="",h=e;e=e.toLowerCase();let l=e.match(/^-([a-z]+)-([-a-z0-9]+)$/);l&&(a=l[1],e=l[2]);let c=a?h:e;if(Cu(t)){this.getShorthand(c,t),n.simpleProperty(h,t,i);return}let d=this.prefixes[e];if(!d||!d[a]){if(CSS.supports(h,t.toString())){let f=(r=this.getShorthand(c,t))==null?void 0:r.clone();f?Z(t)?f.propagateDefaultingValue(t,i,n):(t.visit(f),f.finish(i,n)||n.invalidPropertyValue(h,t)):n.simpleProperty(h,t,i)}else a&&!Sc.includes(`-${a}-`)||n.unknownProperty(h,t);return}else if(ub.includes(e)&&!Object.keys(d).some(f=>Ro(f?`-${f}-`:"",e))){n.unknownProperty(h,t);return}let p=this.validators[e];if(p){let f=Z(t)||t.isExpr()?t:t.visit(p);f?n.simpleProperty(e,f,i):!a&&CSS.supports(e,t.toString())?n.simpleProperty(e,t,i):n.invalidPropertyValue(h,t)}else{let f=(o=this.getShorthand(e,t))==null?void 0:o.clone();if(!f){n.unknownProperty(h,t);return}Z(t)?f.propagateDefaultingValue(t,i,n):(t.visit(f),f.finish(i,n)||n.invalidPropertyValue(h,t))}}};function Zp(){let e=new cb;return e.initBuiltInValidators(),e.parse(kd),e}var db=class extends Kt{constructor(){super(...arguments),u(this,"varFound",!1)}visitFunc(e){return e.name==="var"?this.varFound=!0:this.varFound||this.visitValues(e.values),null}};function Cu(e){let t=new db;return e.visit(t),t.varFound}function Kp(e,t,i){return e-=i,t===0?e===0:e%t===0&&e/t>=0}var pb=class{constructor(e){u(this,"matchers",e)}matches(){return this.matchers.some(e=>e.matches())}},fb=class{constructor(e){u(this,"matchers",e)}matches(){return this.matchers.every(e=>e.matches())}},Jp=class jo{constructor(t,i,n){u(this,"elementOffset",t),u(this,"a",i),u(this,"b",n)}static registerFragmentIndex(t,i,n){let r=jo.fragmentIndices;(!r[t]||r[t].priority<=n)&&(r[t]={fragmentIndex:i,priority:n})}static clearFragmentIndices(){jo.fragmentIndices={}}matches(){let t=jo.fragmentIndices[this.elementOffset];return t!=null&&t.fragmentIndex!=null&&Kp(t.fragmentIndex,this.a,this.b)}};u(Jp,"fragmentIndices",{});var $s=Jp,Po=class{static buildViewConditionMatcher(e,t){let i=t.split("_");return i[0]=="NFS"?new $s(e,parseInt(i[1],10),parseInt(i[2],10)):(`${t}`,null)}static buildAllMatcher(e){return new fb(e)}static buildAnyMatcher(e){return new pb(e)}},Qp={"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},gb=["image-resolution","orphans","widows"];function mb(){return _t("POLYFILLED_INHERITED_PROPS").reduce((e,t)=>e.concat(t()),[].concat(gb))}var yb={"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},Qa=["margin-%","padding-%","border-%-width","border-%-style","border-%-color","%"],vb=["max-%","min-%","%"],ku=(()=>{let e=["left","right","top","bottom"],t={width:!0,height:!0,"max-width":!0,"max-height":!0,"min-width":!0,"min-height":!0};for(let i=0;i<Qa.length;i++)for(let n=0;n<e.length;n++){let r=Qa[i].replace("%",e[n]);t[r]=!0}return t})();function qn(e,t){let i={};for(let n of Qa)for(let r in e){let o=n.replace("%",r),s=n.replace("%",e[r]);i[o]=s,i[s]=o}for(let n of vb)for(let r in t){let o=n.replace("%",r),s=n.replace("%",t[r]);i[o]=s,i[s]=o}return i}var ef=qn({"block-start":"right","block-end":"left","inline-start":"top","inline-end":"bottom"},{"block-size":"width","inline-size":"height"}),tf=qn({"block-start":"top","block-end":"bottom","inline-start":"left","inline-end":"right"},{"block-size":"height","inline-size":"width"}),wb=qn({"block-start":"right","block-end":"left","inline-start":"bottom","inline-end":"top"},{"block-size":"width","inline-size":"height"}),bb=qn({"block-start":"top","block-end":"bottom","inline-start":"right","inline-end":"left"},{"block-size":"height","inline-size":"width"}),xb=qn({inside:"right",outside:"left"},{}),Sb=qn({inside:"left",outside:"right"},{}),W=class el{constructor(t,i){u(this,"value",t),u(this,"priority",i)}getBaseValue(){return this}filterValue(t){let i=this.value.visit(t);return i===this.value?this:new el(i,this.priority)}increaseSpecificity(t){return t==0?this:new el(this.value,this.priority+t)}evaluate(t,i,n,r){return i&&Xe(i)?this.value:Ss(t,this.value,i,n,r)}isEnabled(t){return!0}},tl=class il extends W{constructor(t,i,n){super(t,i),u(this,"condition",n)}getBaseValue(){return new W(this.value,this.priority)}filterValue(t){let i=this.value.visit(t);return i===this.value?this:new il(i,this.priority,this.condition)}increaseSpecificity(t){return t==0?this:new il(this.value,this.priority+t,this.condition)}isEnabled(t){try{return!!this.condition.evaluate(t)}catch(i){Y.warn(i)}return!1}};function nl(e,t,i){return(!t||i.priority>=t.priority)&&i.isEnabled(e)?i.getBaseValue():t}function Jt(e,t,i,n){if(e)if(!i)delete e[t];else{let r=e[t];(!r||i.priority>=r.priority)&&(n?i.isEnabled(n)&&(e[t]=i.getBaseValue()):e[t]=i)}}var nf={"region-id":!0,"fragment-selector-id":!0},Cr="data-viv-footnote-counter";function bs(e){let t=e.getAttribute(Cr);if(!t)return Object.create(null);let i;try{i=JSON.parse(t)}catch{return Object.create(null)}if(!i||typeof i!="object"||Array.isArray(i))return Object.create(null);let n=Object.create(null);return Object.entries(i).forEach(([r,o])=>{if(Array.isArray(o)){let s=o.filter(a=>typeof a=="number"&&isFinite(a));n[r]=s}else typeof o=="number"&&isFinite(o)&&(n[r]=[o])}),n}function rf(e,t,i){let n=bs(e);n[t]=i,e.setAttribute(Cr,JSON.stringify(n))}function Cb(e,t){var i,n;if(!Gt(e)||e.hasAttribute(cp))return null;let r=bs(e)[t];if(r)return r;let o=e.getAttribute("href")||e.getAttributeNS("http://www.w3.org/1999/xlink","href");if(!o)return null;let s=e.baseURI||((i=e.ownerDocument)==null?void 0:i.baseURI)||"",a=Qo(o,s);if(a==="#"||a.replace(/#.*$/,"")!==s.replace(/#.*$/,""))return null;let h=a.indexOf("#");if(h<0||h===a.length-1)return null;let l=(n=e.ownerDocument)==null?void 0:n.getElementById(a.substring(h+1));if(!(l instanceof Element))return null;let c=bs(l)[t];return c?(rf(e,t,c),c):null}function kb(e){let t=ve(e,"content");return!!t&&It(t.value)}function Eb(e){return!!nf[e]}function Xo(e){return e.charAt(0)==="_"&&e!=="_viewConditionalStyles"}function Xi(e){return e.charAt(0)!=="_"&&!nf[e]}function In(e){return!!Qp[e]||Xe(e)}function ve(e,t){return e[t]}function Fi(e,t,i){i?e[t]=i:delete e[t]}function ft(e,t){return e[t]}function si(e,t){let i=e[t];return i||(i={},e[t]=i),i}var of=e=>{let t=e._viewConditionalStyles;return t||(t=[],e._viewConditionalStyles=t),t};function sf(e,t){return e[t]}function af(e,t){let i=e[t];return i||(i=[],e[t]=i),i}function xs(e,t,i,n,r,o,s){var a,h;if([{id:r,styleKey:"_pseudos"},{id:o,styleKey:"_regions"}].forEach(l=>{if(l.id){let c=si(t,l.styleKey);t=c[l.id],t||(t={},c[l.id]=t)}}),s){let l=of(t);t={},l.push({styles:t,matcher:s})}for(let l in i)if(!Xo(l))if(Eb(l)){let c=sf(i,l),d=af(t,l);Array.prototype.push.apply(d,c)}else{let c=ve(i,l);if(!c.isEnabled(e))continue;let d=c.increaseSpecificity(n);Jt(t,l,d,e);let p=(a=e.style)==null?void 0:a.validatorSet,f=(h=p?.getShorthand(l,d.value))==null?void 0:h.propList;if(f)for(let g of f){let v=new W(Me,d.priority);Jt(t,g,v,e)}}}function Pb(e,t){let i={};for(let n=0;n<t.length;n++)xs(e,i,t[n],0,null,null,null);return i}function ih(e,t){if(e.length>0){e.sort((n,r)=>r.getPriority()-n.getPriority());let i=null;for(let n=e.length-1;n>=0;n--)i=e[n],i.chained=t,t=i;return i}return t}var Nb=class extends nn{constructor(e,t){super(),u(this,"props",e),u(this,"context",t),u(this,"propName","")}setPropName(e){this.propName=e}getFontSize(){let e=ve(this.props,"font-size");if(!e.value.isNumeric())return Zt.em;let t=e.value;if(!hm(t.unit))throw new Error("Unexpected state");return t.num*Zt[t.unit]}visitNumeric(e){return this.context,this.propName==="font-size"?rl(e,this.getFontSize(),this.context):e.unit==="em"||e.unit==="rem"||e.unit==="lh"||e.unit==="rlh"?nh(e,this.getFontSize(),this.context):e}visitExpr(e){return this.propName=="font-size"?Ss(this.context,e,this.propName).visit(this):e}};function nh(e,t,i){let n=e.unit,r=e.num;return n==="em"?new O(r*t,"px"):n==="rem"?new O(r*i.fontSize(),"px"):n==="rlh"?new O(r*i.rootLineHeight,"px"):e}function rl(e,t,i){e=nh(e,t,i);let n=e.unit,r=e.num;return n==="px"?e:n==="%"?new O(r/100*t,"px"):new O(r*i.queryUnitSize(n,!1),"px")}var Yn=class{apply(e){}mergeWith(e){return new Tb([this,e])}clone(){return this}},No=class extends Yn{constructor(e){super(),u(this,"conditionItem",e)}apply(e){e.pushConditionItem(this.conditionItem.fresh(e))}},Tb=class lf extends Yn{constructor(t){super(),u(this,"list",t)}apply(t){for(let i=0;i<this.list.length;i++)this.list[i].apply(t)}mergeWith(t){return this.list.push(t),this}clone(){return new lf([].concat(this.list))}},rh=class extends Yn{constructor(e,t,i,n,r){super(),u(this,"style",e),u(this,"specificity",t),u(this,"pseudoelement",i),u(this,"regionId",n),u(this,"viewConditionId",r)}apply(e){xs(e.context,e.currentStyle,this.style,this.specificity,this.pseudoelement,this.regionId,e.buildViewConditionMatcher(this.viewConditionId))}},Ne=class extends Yn{constructor(){super(),u(this,"chained",null)}apply(e){this.chained.apply(e)}getPriority(){return 0}makePrimary(e){return!1}},Ab=class extends Ne{constructor(e){super(),u(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}},Ib=class extends Ne{constructor(e){super(),u(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}},Eu=class extends Ne{constructor(e){super(),u(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}},Fb=class extends Ne{constructor(e,t){super(),u(this,"ns",e),u(this,"localName",t)}apply(e){e.currentLocalName==this.localName&&e.currentNamespace==this.ns&&this.chained.apply(e)}getPriority(){return 8}makePrimary(e){if(this.chained){let t=e.nsPrefix[this.ns];t||(t=`ns${e.nsCount++}:`,e.nsPrefix[this.ns]=t);let i=t+this.localName;e.insertInTable(e.nstags,i,this.chained)}return!0}},Rb=class extends Ne{constructor(e,t,i=!1){super(),u(this,"epubTypePatt",e),u(this,"targetLocalName",t),u(this,"useRoleAttr",i)}apply(e){let t=e.currentElement;if(t instanceof HTMLAnchorElement&&t.hash&&t.href==t.baseURI.replace(/#.*$/,"")+t.hash){let i=t.hash.substring(1),n=t.ownerDocument.getElementById(i);if(n&&(!this.targetLocalName||n.localName==this.targetLocalName)){let r=this.useRoleAttr?n.getAttribute("role"):n.getAttributeNS("http://www.idpf.org/2007/ops","type")||n.getAttribute("epub:type");r&&r.match(this.epubTypePatt)&&this.chained.apply(e)}}}},Lb=class extends Ne{constructor(e){super(),u(this,"ns",e)}apply(e){e.currentNamespace==this.ns&&this.chained.apply(e)}};function Hs(e,t,i,n){var r;if(!e)return!1;let o=((r=e.ownerDocument)==null?void 0:r.contentType)==="text/html",s=o?Br(i):i;if(t!==null){let a=e.getAttributeNodeNS(t||null,s);return!!a&&n(a)}for(let a of Array.from(e.attributes))if((o?Br(a.localName):a.localName)===s&&n(a))return!0;return!1}function Br(e){return e.replace(/[A-Z]/g,t=>t.toLowerCase())}function hf(e){return e==="i"}function or(e,t){return Array.from(e,i=>{let n=es(i);if(!hf(t))return n;let r=Br(i),o=r.toUpperCase();return r!==o&&/^[a-z]$/i.test(i)?`[${r}${o}]`:n}).join("")}function sr(e){return new RegExp(e)}function Ob(e,t,i){return hf(i)?Br(e)===Br(t):e===t}var Pu=class extends Ne{constructor(e,t){super(),u(this,"ns",e),u(this,"name",t)}apply(e){Hs(e.currentElement,this.ns,this.name,()=>!0)&&this.chained.apply(e)}},Bb=class extends Ne{constructor(e,t,i,n=null){super(),u(this,"ns",e),u(this,"name",t),u(this,"value",i),u(this,"caseSensitivity",n)}apply(e){Hs(e.currentElement,this.ns,this.name,t=>Ob(t.value,this.value,this.caseSensitivity))&&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}},Mb=class extends Ne{constructor(e,t){super(),u(this,"ns",e),u(this,"name",t)}apply(e){Hs(e.currentElement,this.ns,this.name,t=>!!yb[t.value])&&this.chained.apply(e)}getPriority(){return 0}makePrimary(e){return!1}},ar=class extends Ne{constructor(e,t,i,n=null){super(),u(this,"ns",e),u(this,"name",t),u(this,"regexp",i),u(this,"caseSensitivity",n)}apply(e){Hs(e.currentElement,this.ns,this.name,t=>!!t.value.match(this.regexp))&&this.chained.apply(e)}},_b=class extends Ne{constructor(e){super(),u(this,"langRegExp",e)}apply(e){e.lang.match(this.langRegExp)&&this.chained.apply(e)}},Nu=class extends Ne{constructor(){super()}apply(e){e.isFirst&&this.chained.apply(e)}getPriority(){return 6}},Db=class extends Ne{constructor(){super()}apply(e){e.isRoot&&this.chained.apply(e)}getPriority(){return 12}},sn=class extends Ne{constructor(e,t){super(),u(this,"a",e),u(this,"b",t)}matchANPlusB(e){return Kp(e,this.a,this.b)}},zb=class extends sn{constructor(e,t){super(e,t)}apply(e){this.matchANPlusB(e.currentSiblingOrder)&&this.chained.apply(e)}getPriority(){return 5}},ol=class extends sn{constructor(e,t){super(e,t)}apply(e){let t=e.currentSiblingTypeCounts[e.currentNamespace][e.currentLocalName];this.matchANPlusB(t)&&this.chained.apply(e)}getPriority(){return 5}},sl=class extends sn{constructor(e,t){super(e,t)}apply(e){let t=e.currentFollowingSiblingOrder;t===null&&(t=e.currentFollowingSiblingOrder=e.currentElement.parentNode.childElementCount-e.currentSiblingOrder+1),this.matchANPlusB(t)&&this.chained.apply(e)}getPriority(){return 4}},al=class extends sn{constructor(e,t){super(e,t)}apply(e){let t=e.currentFollowingSiblingTypeCounts;if(!t[e.currentNamespace]){let i=e.currentElement;do{let n=i.namespaceURI,r=i.localName,o=t[n];o||(o=t[n]={}),o[r]=(o[r]||0)+1}while(i=i.nextElementSibling)}this.matchANPlusB(t[e.currentNamespace][e.currentLocalName])&&this.chained.apply(e)}getPriority(){return 4}},Vb=class extends Ne{constructor(){super()}apply(e){let t=e.currentElement.firstChild;for(;t;){switch(t.nodeType){case Node.ELEMENT_NODE:return;case Node.TEXT_NODE:if(t.length>0)return}t=t.nextSibling}this.chained.apply(e)}getPriority(){return 4}},Ub=class extends Ne{constructor(){super()}apply(e){e.currentElement.disabled===!1&&this.chained.apply(e)}getPriority(){return 5}},$b=class extends Ne{constructor(){super()}apply(e){e.currentElement.disabled===!0&&this.chained.apply(e)}getPriority(){return 5}},Hb=class extends Ne{constructor(){super()}apply(e){let t=e.currentElement;(t.selected===!0||t.checked===!0)&&this.chained.apply(e)}getPriority(){return 5}},rt=class extends Ne{constructor(e){super(),u(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}},uf=class cf extends Yn{constructor(){super(),u(this,"applied",!1)}apply(t){this.applied=!0}clone(){let t=new cf;return t.applied=this.applied,t}},oh=class extends Ne{constructor(e){super(),u(this,"checkAppliedAction"),u(this,"firstActions",[]),this.checkAppliedAction=new uf;for(let t of e)this.firstActions.push(ih(t,this.checkAppliedAction))}apply(e){for(let t of this.firstActions)if(t.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 Ne?e.getPriority():0))}positive(){return!0}relational(){return!1}},Wb=class extends oh{positive(){return!1}},Gb=class extends oh{constructor(e){super([]),u(this,"selectorTexts",e)}apply(e){for(let t of this.selectorTexts){let i,n;/^\s*[+~]/.test(t)?(n=e.currentElement.parentNode,i=`:scope > :nth-child(${Array.from(n.children).indexOf(e.currentElement)+1}) ${t}`):(n=e.currentElement,i=`:scope ${t}`);try{if(n.querySelector(i)){this.checkAppliedAction.apply(e);break}}catch{}}this.checkAppliedAction.applied&&this.chained.apply(e),this.checkAppliedAction.applied=!1}relational(){return!0}},df=class extends sn{constructor(e,t,i){super(e,t),u(this,"checkAppliedAction"),u(this,"firstActions",[]),this.checkAppliedAction=new uf;for(let n of i)this.firstActions.push(ih(n,this.checkAppliedAction))}apply(e){for(let r of this.firstActions)if(r.apply(e),this.checkAppliedAction.applied)break;if(!this.checkAppliedAction.applied)return;this.checkAppliedAction.applied=!1;let t=e.currentElement,i=1,n=t.previousElementSibling;for(;n;)this.matchesSelector(n,e)&&i++,n=n.previousElementSibling;this.matchANPlusB(i)&&this.chained.apply(e)}matchesSelector(e,t){let i=t.currentElement,n=t.currentNamespace,r=t.currentLocalName,o=t.currentId,s=t.currentClassNames,a=t.currentSiblingOrder;t.currentElement=e,t.currentNamespace=e.namespaceURI||"",t.currentLocalName=e.localName,t.currentId=e.id,t.currentClassNames=e.classList?Array.from(e.classList):[];let h=1,l=e.previousElementSibling;for(;l;)h++,l=l.previousElementSibling;t.currentSiblingOrder=h;for(let d of this.firstActions)if(d.apply(t),this.checkAppliedAction.applied)break;let c=this.checkAppliedAction.applied;return this.checkAppliedAction.applied=!1,t.currentElement=i,t.currentNamespace=n,t.currentLocalName=r,t.currentId=o,t.currentClassNames=s,t.currentSiblingOrder=a,c}getPriority(){return 5}},jb=class extends df{constructor(e,t,i){super(e,t,i)}apply(e){for(let r of this.firstActions)if(r.apply(e),this.checkAppliedAction.applied)break;if(!this.checkAppliedAction.applied)return;this.checkAppliedAction.applied=!1;let t=e.currentElement,i=1,n=t.nextElementSibling;for(;n;)this.matchesSelector(n,e)&&i++,n=n.nextElementSibling;this.matchANPlusB(i)&&this.chained.apply(e)}getPriority(){return 4}},Ws=class{constructor(e,t,i){u(this,"condition",e),u(this,"viewConditionId",t),u(this,"viewCondition",i)}increment(e){e.increment(this.condition,this.viewCondition)}decrement(e){e.decrement(this.condition,this.viewCondition)}buildViewConditionMatcher(e){return e.buildViewConditionMatcher(this.viewConditionId)}},Xb=class pf extends Ws{constructor(t,i,n){super(t,i,n)}fresh(t){return new pf(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,i){return i==0&&this.increment(t),!1}pop(t,i){return i==0?(this.decrement(t),!0):!1}},qb=class ff extends Ws{constructor(t,i,n){super(t,i,n)}fresh(t){return new ff(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,i){return i==0?this.increment(t):i==1&&this.decrement(t),!1}pop(t,i){return i==0?(this.decrement(t),!0):(i==1&&this.increment(t),!1)}},Yb=class gf extends Ws{constructor(t,i,n){super(t,i,n),u(this,"fired",!1)}fresh(t){return new gf(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,i){return this.fired?(this.decrement(t),!0):!1}pop(t,i){return this.fired?(this.decrement(t),!0):(i==0&&(this.fired=!0,this.increment(t)),!1)}},Zb=class mf extends Ws{constructor(t,i,n){super(t,i,n),u(this,"fired",!1)}fresh(t){return new mf(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,i){return this.fired&&(i==-1?this.increment(t):i==0&&this.decrement(t)),!1}pop(t,i){if(this.fired){if(i==-1)return this.decrement(t),!0;i==0&&this.increment(t)}else i==0&&(this.fired=!0,this.increment(t));return!1}},Kb=class{constructor(e,t){u(this,"afterprop",e),u(this,"element",t)}fresh(e){return this}push(e,t){return!1}pop(e,t){return t==0?(e.processPseudoelementProps(this.afterprop,this.element),!0):!1}},Jb=class{constructor(e){u(this,"lang",e)}fresh(e){return this}push(e,t){return!1}pop(e,t){return t==0?(e.lang=this.lang,!0):!1}},Qb=class{constructor(e){u(this,"oldQuotes",e)}fresh(e){return this}push(e,t){return!1}pop(e,t){return t==0?(e.quotes=this.oldQuotes,!0):!1}},e0=class extends nn{constructor(e,t,i,n){super(),u(this,"element",e),u(this,"scope",t),u(this,"propName",i),u(this,"validatorSet",n),u(this,"hadAttrFunction",!1)}validatePropertyValue(e){var t,i;if(Z(e))return e;let n=(t=this.validatorSet)==null?void 0:t.validators[this.propName];return n?(i=e.visit(n))!=null?i:y.unset:!this.propName||CSS.supports(this.propName,e.toString())?e:y.unset}visitFunc(e){var t;if(e.name.toLowerCase()!=="attr")return super.visitFunc(e);this.hadAttrFunction=!0;let i=Ql(e);if(!i)return super.visitFunc(e);let n=((t=i.fallback)!=null?t:eb(i.type)).visit(this);return!this.element||!this.element.hasAttribute(i.attributeName)?n:tb(this.scope,this.element.getAttribute(i.attributeName),i.type)||n}};function Mr(e,t){if(It(e)){if(e instanceof K)return e.stringValue();if(e instanceof j&&t){let i=e.expr.evaluate(t);return typeof i=="string"?i:typeof i=="number"?String(i):""}if(e instanceof J)return e.values.map(i=>Mr(i,t)).join("")}return""}function sh(e){if(e instanceof j){let t=e.expr;return t instanceof we&&/^page-counters?-/.test(t.str)}return e instanceof J||e instanceof Oe?e.values.some(t=>sh(t)):!1}function ll(e,t){return sh(e)?e instanceof J?new J(e.values.map(i=>ll(i,t))):e instanceof Oe?new Oe(e.values.map(i=>ll(i,t))):e:new K(Mr(e,t))}var _r=class extends nn{constructor(e,t,i,n){super(),u(this,"cascade",e),u(this,"element",t),u(this,"counterResolver",i),u(this,"pseudoName",n)}getCounterStore(){var e,t;return(t=(e=this.cascade.context)==null?void 0:e.counterStore)!=null?t:null}getPageScope(){var e,t;return(t=(e=this.cascade.context)==null?void 0:e.style)==null?void 0:t.pageScope}hasLocalCounterResetOrSet(e){return this.hasLocalCounter(e,"counter-reset",{reset:!0})||this.hasLocalCounter(e,"counter-set",{defaultValue:0})}hasLocalCounterIncrement(e){return this.hasLocalCounter(e,"counter-increment",{})}hasLocalCounter(e,t,i){let n=this.cascade.currentStyle,r=n?.[t];if(!r)return!1;let o=r.evaluate(this.cascade.context);if(!o||Z(o))return!1;let s=qi(o,i);return Object.prototype.hasOwnProperty.call(s,e)}evaluateAndGetString(e){if(!e)return"";let t=this.cascade.quoteDepth,i=e.visit(this),n=Mr(i,this.cascade.context);return this.cascade.quoteDepth=t,n}visitIdent(e){let t=this.cascade,i=t.quotes,n=Math.floor(i.length/2)-1;switch(e.name){case"open-quote":{let r=i[2*Math.min(n,t.quoteDepth)];return t.quoteDepth++,r}case"close-quote":return t.quoteDepth>0&&t.quoteDepth--,i[2*Math.min(n,t.quoteDepth)+1];case"no-open-quote":return t.quoteDepth++,new K("");case"no-close-quote":return t.quoteDepth>0&&t.quoteDepth--,new K("")}return e}format(e,t){return this.cascade.counterStyleStore.format(t,e)}formatCounterList(e,t,i){if(!e.length)return this.format(0,i);let n=new gi;for(let r=0;r<e.length;r++)r>0&&n.append(t),n.append(this.format(e[r],i));return n.toString()}formatLastValue(e,t){let i=e.length?e[e.length-1]:0;return this.format(i,t)}buildCounterText(e,t,i,n,r,o=!1,s=!1){var a,h,l,c,d,p,f,g,v;let w=typeof r=="string",x=A=>w?this.formatCounterList(A,r,i):this.formatLastValue(A,i),m=A=>{this.pseudoName==="footnote-call"&&this.element&&rf(this.element,t,A)},S=(A,z)=>A.length===z.length&&A.every((U,X)=>U===z[X]);if(this.pseudoName==="footnote-call"&&this.element){let A=Cb(this.element,t);if(A)return x(A)}if(this.pseudoName==="footnote-marker"&&this.element){let A=bs(this.element)[t];if(A)return x(A)}let b;if(t==="pages")return x([]);if(!this.element){if(o&&n.length)return b=n,m(b),x(b);if((a=e.isPageControlledCounter)!=null&&a.call(e,t)&&s&&n.length){let A=((h=e.currentPageCounters)==null?void 0:h[t])||[];return b=[(A.length?A[A.length-1]:0)+n[n.length-1]],m(b),x(b)}if(!((l=e.isPageControlledCounter)!=null&&l.call(e,t))){let A=((c=e.currentPageCounters)==null?void 0:c[t])||[];if(A.length)return b=A,m(b),x(b)}}let C=((d=e.currentPageDocCounters)==null?void 0:d[t])||[],P=!this.element&&n.length&&!S(n,C),L=this.element||P?n:C.length?C:n;if((p=e.isPageControlledCounter)!=null&&p.call(e,t)){let A=((f=e.currentPageDocCounters)==null?void 0:f[t])||[],z=((g=e.currentPageCounters)==null?void 0:g[t])||[],U=z.length?z[z.length-1]:0,X=A.length?A[0]:0,re=L.length?L[0]:0,k=U+(re-X);return b=L.length?[k,...L.slice(1)]:z.length?z:[0],m(b),x(b)}return L.length?(b=L,m(b),x(b)):(b=((v=e.currentPageCounters)==null?void 0:v[t])||[],m(b),x(b))}visitFuncCounter(e){var t;let i=e[0].toString(),n=e.length>1?e[1].stringValue():"decimal",r=(this.cascade.counters[i]||[]).slice(),o=!this.element&&this.hasLocalCounterResetOrSet(i),s=!this.element&&this.hasLocalCounterIncrement(i),a=this.getCounterStore();if(a){let l=i==="pages"||((t=a?.isPageControlledCounter)==null?void 0:t.call(a,i)),c=this.getPageScope(),d=new we(c,()=>this.buildCounterText(a,i,n,r,void 0,o,s),l?`page-counter-${i}`:`counter-${i}`);if(l&&a!=null&&a.registerPageCounterExpr){let p=f=>this.formatLastValue(f,n);a.registerPageCounterExpr(i,p,d)}return new j(d)}let h=this.cascade.counters[i];if(h&&h.length){let l=h&&h.length&&h[h.length-1]||0;return new K(this.format(l,n))}else{let l=new j(this.counterResolver.getPageCounterVal(i,c=>this.format(c||0,n)));return new J([l])}}visitFuncCounters(e){var t;let i=e[0].toString(),n=e[1].stringValue(),r=e.length>2?e[2].stringValue():"decimal",o=(this.cascade.counters[i]||[]).slice(),s=!this.element&&this.hasLocalCounterResetOrSet(i),a=!this.element&&this.hasLocalCounterIncrement(i),h=this.getCounterStore();if(h){let p=i==="pages"||((t=h?.isPageControlledCounter)==null?void 0:t.call(h,i)),f=this.getPageScope(),g=new we(f,()=>this.buildCounterText(h,i,r,o,n,s,a),p?`page-counters-${i}`:`counters-${i}`);return p&&h!=null&&h.registerPageCounterExpr&&h.registerPageCounterExpr(i,v=>this.formatCounterList(v,n,r),g),new j(g)}let l=this.cascade.counters[i],c=new gi;if(l&&l.length)for(let p=0;p<l.length;p++)p>0&&c.append(n),c.append(this.format(l[p],r));let d=new j(this.counterResolver.getPageCountersVal(i,p=>{let f=[];if(p.length)for(let v=0;v<p.length;v++)f.push(this.format(p[v],r));let g=c.toString();return g.length&&f.push(g),f.length?f.join(n):this.format(0,r)}));return new J([d])}visitFuncTargetCounter(e){let t=e[0],i;t instanceof Qe?i=t.url:i=t.stringValue();let n=e[1].toString(),r=e.length>2?e[2].stringValue():"decimal",o=new j(this.counterResolver.getTargetCounterVal(i,n,s=>this.format(s||0,r)));return new J([o])}visitFuncTargetCounters(e){let t=e[0],i;t instanceof Qe?i=t.url:i=t.stringValue();let n=e[1].toString(),r=e[2].stringValue(),o=e.length>3?e[3].stringValue():"decimal",s=new j(this.counterResolver.getTargetCountersVal(i,n,a=>{let h=a.map(l=>this.format(l,o));return h.length?h.join(r):this.format(0,o)}));return new J([s])}visitFuncTargetText(e){let t=e[0],i;t instanceof Qe?i=t.url:i=t.stringValue();let n=e.length>1?e[1].stringValue():"content",r=new j(this.counterResolver.getTargetTextVal(i,n));return new J([r])}visitFuncString(e){let t=e.length>0?e[0].stringValue():"",i=e.length>1?e[1].stringValue():"first";return new j(this.counterResolver.getNamedStringVal(t,i))}visitFuncElement(e){let t=e.length>0?e[0].stringValue():"",i=e.length>1?e[1].stringValue():"first";return new j(this.counterResolver.getRunningElementVal(t,i))}visitFuncContent(e){var t,i,n,r,o,s,a,h;let l=e.length>0?e[0].stringValue():"text",c="";switch(l){case"text":c=this.element.textContent;break;case"before":case"after":case"marker":{let d=(t=this.element)==null?void 0:t.querySelectorAll(`[data-adapt-pseudo="${l}"]`),p=null;if(d&&this.element)for(let f=0;f<d.length;f++){let g=d[f];if(g.parentElement===this.element){p=g;break}}if(p)c=p.textContent||"";else{let f=ft(this.cascade.currentStyle,"_pseudos"),g=(n=(i=f?.[l])==null?void 0:i.content)==null?void 0:n.value;if(g)c=this.evaluateAndGetString(g);else if(l==="marker"){let v=(r=this.cascade.currentStyle["--viv-marker-content"])==null?void 0:r.value;c=Mr(v,this.cascade.context)}}}break;case"first-letter":{let d=ft(this.cascade.currentStyle,"_pseudos"),p=(s=(o=d?.before)==null?void 0:o.content)==null?void 0:s.value,f=(h=(a=d?.after)==null?void 0:a.content)==null?void 0:h.value,g=(this.evaluateAndGetString(p)||this.element.textContent||this.evaluateAndGetString(f)).match(Jo);c=g?g[0]:""}break}return new K(c)}visitFuncLeader(e){let t="";if(e[0]instanceof he)switch(e[0].stringValue()){case"dotted":t=".";break;case"solid":t="_";break;case"space":t=" ";break}else e[0]instanceof K&&(t=e[0].stringValue());return t.length==0?new K(""):new j(new we(null,()=>t,"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}};function pa(e,t,i){let n;if(e.nodeType===1)n=Array.from(e.getClientRects());else{let r=e.ownerDocument.createRange();r.selectNodeContents(e),n=t.getRangeClientRects(r)}return n.reduce((r,o)=>r+(i==="vertical-rl"||i==="vertical-lr"?o.height:o.width),0)}var t0=(e,t,i)=>{let n=t.filter(h=>h.after&&h.viewNode.nodeType===1&&h.viewNode.getAttribute("data-viv-leader"));for(let h of n){let l=function(E){S==="rtl"?g.textContent=(E.startsWith("\u200F")?"":"\u200F")+E+(E.endsWith("\u200F")?"":"\u200F"):g.textContent=E},c=function(){let E=i.clientLayout.getElementClientRect(v);return m==="vertical-rl"||m==="vertical-lr"?S==="rtl"?E.top-=k:E.bottom+=k:S==="rtl"?E.left-=k:E.right+=k,L.left>E.left||L.right<E.right||L.top>E.top||L.bottom<E.bottom},d=function(){let E,N,R=x.repeat(1e4);if(l(R),c())E=1,N=1e4;else return;for(let $=0;$<16;$++){let V="",q=Math.floor((E+N)/2);for(let Q=0;Q<q;Q++)V+=x;if(l(V),c())N=q;else{if(E==q)return;E=q}}l(x)},p=function(E){let N=0,R=v.parentElement;for(;R&&R!==f.viewNode;)N+=i.getComputedInsets(R)[E],R=R.parentElement;return N};var r=l,o=c,s=d,a=p;let f=h.parent;for(;f&&f.inline;)f=f.parent;let g=h.viewNode,v=g.parentElement,w=v.getAttribute("data-adapt-pseudo"),x=g.getAttribute("data-viv-leader-value"),{writingMode:m,direction:S,marginInlineEnd:b}=i.clientLayout.getElementComputedStyle(v);g.style.marginInlineStart="1px",l(x),v.style.display="inline-block",v.style.textIndent="0";let C=eo(f.viewNode),P=C?.style.columnFill||null;C&&(C.style.columnFill="auto");let L=i.clientLayout.getElementClientRect(f.viewNode),A=i.clientLayout.getElementClientRect(v),z=i.parseComputedLength(b),U=[],X=v.parentElement;for(;X.parentElement&&X.parentElement!==f.viewNode;)X=X.parentElement;let re=X.nextSibling;for(;re;){if(re.nodeType===1){let E=re,{display:N,float:R,position:$}=i.clientLayout.getElementComputedStyle(E);if(R!=="none"||$==="absolute"||$==="fixed"){re=re.nextSibling;continue}if(Ut(N))U.push(E);else if(uv(N))break}else if(re.nodeType===3){let E=re;E.length>0&&U.push(E)}re=re.nextSibling}let k=U.reduce((E,N)=>E+pa(N,i.clientLayout,m),0);if(w!=="after"){let E=pa(X,i.clientLayout,m),N=pa(v,i.clientLayout,m);k+=E-N}m==="vertical-rl"||m==="vertical-lr"?(S==="rtl"?L.top+=z:L.bottom-=z,L.top=Math.min(A.top,L.top),L.bottom=Math.max(A.bottom,L.bottom)):(S==="rtl"?L.left+=z:L.right-=z,L.left=Math.min(A.left,L.left),L.right=Math.max(A.right,L.right)),d();let _=i.clientLayout.getElementClientRect(v);S=="rtl"?v.style.float="left":v.style.float="right";let F=i.clientLayout.getElementClientRect(v),D=0;S=="rtl"?m=="vertical-rl"||m=="vertical-lr"?D=_.top-F.top-p("top"):D=_.left-F.left-p("left"):m=="vertical-rl"||m=="vertical-lr"?D=F.bottom-_.bottom-p("bottom"):D=F.right-_.right-p("right"),D-=k,D=Math.max(0,D-.1),v.style.float="",g.style.marginInlineStart=`${D}px`,C&&(P?C.style.columnFill=P:C.style.removeProperty("column-fill"))}};Ft("POST_LAYOUT_BLOCK",t0);var ah=1/1048576;function cn(e,t){for(let i in e)t[i]=e[i].clone()}var i0=class yf{constructor(){u(this,"nsCount",0),u(this,"nsPrefix",{}),u(this,"tags",{}),u(this,"nstags",{}),u(this,"epubtypes",{}),u(this,"classes",{}),u(this,"ids",{}),u(this,"pagetypes",{}),u(this,"order",0)}clone(){let t=new yf;t.nsCount=this.nsCount;for(let i in this.nsPrefix)t.nsPrefix[i]=this.nsPrefix[i];return cn(this.tags,t.tags),cn(this.nstags,t.nstags),cn(this.epubtypes,t.epubtypes),cn(this.classes,t.classes),cn(this.ids,t.ids),cn(this.pagetypes,t.pagetypes),t.order=this.order,t}insertInTable(t,i,n){let r=t[i];r&&(n=r.mergeWith(n)),t[i]=n}createInstance(t,i,n,r,o,s){return new n0(this,t,i,n,r,o,s)}nextOrder(){return this.order+=ah}},vf=class wf{constructor(t,i,n,r,o,s,a){u(this,"context",i),u(this,"counterListener",n),u(this,"counterResolver",r),u(this,"counterStyleStore",s),u(this,"cmykStore",a),u(this,"code"),u(this,"stack",[[],[]]),u(this,"conditions",Object.create(null)),u(this,"currentElement",null),u(this,"currentElementOffset",null),u(this,"currentStyle",null),u(this,"currentClassNames",null),u(this,"currentLocalName",""),u(this,"currentNamespace",""),u(this,"currentId",""),u(this,"currentXmlId",""),u(this,"currentNSTag",""),u(this,"currentEpubTypes",null),u(this,"currentPageType",null),u(this,"previousPageType",null),u(this,"firstPageType",null),u(this,"pageTypePageIndices",Object.create(null)),u(this,"isFirst",!0),u(this,"isRoot",!0),u(this,"counters",Object.create(null)),u(this,"lastCounterChanges",[]),u(this,"lastCounterChangeTypes",Object.create(null)),u(this,"counterScoping",[Object.create(null)]),u(this,"quotes"),u(this,"quoteDepth",0),u(this,"lang",""),u(this,"siblingOrderStack",[0]),u(this,"currentSiblingOrder",0),u(this,"siblingTypeCountsStack",[{}]),u(this,"currentSiblingTypeCounts"),u(this,"currentFollowingSiblingOrder",null),u(this,"followingSiblingOrderStack"),u(this,"followingSiblingTypeCountsStack",[{}]),u(this,"currentFollowingSiblingTypeCounts"),u(this,"viewConditions",Object.create(null)),u(this,"dependentConditions",[]),u(this,"elementStack"),this.code=t,this.quotes=[new K("\u201C"),new K("\u201D"),new K("\u2018"),new K("\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,i){this.conditions[t]=(this.conditions[t]||0)+1,i&&(this.viewConditions[t]?this.viewConditions[t].push(i):this.viewConditions[t]=[i])}decrement(t,i){this.conditions[t]--,this.viewConditions[t]&&(this.viewConditions[t]=this.viewConditions[t].filter(n=>n!==i),this.viewConditions[t].length===0&&delete this.viewConditions[t])}buildViewConditionMatcher(t){let i=null;t&&(this.currentElementOffset,i=Po.buildViewConditionMatcher(this.currentElementOffset,t));let n=this.dependentConditions.map(r=>{let o=this.viewConditions[r];return o&&o.length>0?o.length===1?o[0]:Po.buildAnyMatcher([].concat(o)):null}).filter(r=>r);return n.length<=0?i:i===null?n.length===1?n[0]:Po.buildAllMatcher(n):Po.buildAllMatcher([i].concat(n))}applyAction(t,i){let n=t[i];n&&n.apply(this)}pushRule(t,i,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=fa,this.currentPageType=i,this.applyActions()}defineCounter(t,i){let n=this.counterScoping[this.counterScoping.length-1];n||(n=Object.create(null),this.counterScoping[this.counterScoping.length-1]=n),this.counters[t]?(n[t]&&this.counters[t].pop(),this.counters[t].push(i)):this.counters[t]=[i],n[t]=!0}pushCounters(t){var i,n,r,o,s,a,h,l,c,d;let p=new Set,f=Object.create(null),g=y.inline,v=t.display;if(v&&(g=v.evaluate(this.context)),g===y.none){(i=this.currentElement)==null||i.setAttribute("data-viv-display-none","true"),this.lastCounterChanges=[],this.lastCounterChangeTypes=Object.create(null),this.counterScoping.push(null);return}else if((n=this.currentElement)!=null&&n.closest("[data-viv-display-none]")){this.lastCounterChanges=[],this.lastCounterChangeTypes=Object.create(null),this.counterScoping.push(null);return}let w=y.inline,x=t.float;x&&(w=x.evaluate(this.context));let m=null,S=null,b=null,C=t["counter-reset"];if(C){let A=C.evaluate(this.context);A&&(m=qi(A,{reset:!0}))}let P=t["counter-set"];if(P){let A=P.evaluate(this.context);A&&(b=qi(A,{defaultValue:0}))}let L=t["counter-increment"];if(L){let A=L.evaluate(this.context);A&&(S=qi(A))}if((this.currentLocalName=="ol"||this.currentLocalName=="ul")&&this.currentNamespace=="http://www.w3.org/1999/xhtml"&&(m||(m=Object.create(null)),m["list-item"]=((o=(r=this.currentElement)==null?void 0:r.start)!=null?o:1)-1),ur(g)&&(S||(S=Object.create(null)),S["list-item"]=(s=S["list-item"])!=null?s:1,/^\s*[-+]?\d/.test((h=(a=this.currentElement)==null?void 0:a.getAttribute("value"))!=null?h:"")&&(b||(b=Object.create(null)),b["list-item"]=this.currentElement.value)),((c=(l=this.currentElement)==null?void 0:l.parentNode)==null?void 0:c.nodeType)===Node.DOCUMENT_NODE&&(m||(m=Object.create(null)),m.footnote===void 0&&(m.footnote=0)),w===y.footnote&&!this.currentStyle["--viv-semantic-footnote-content"]&&(S||(S=Object.create(null)),S.footnote===void 0)){let A=(d=this.currentStyle["counter-increment"])==null?void 0:d.value;(!A||!(A===y.footnote||A instanceof J&&A.values.includes(y.footnote)))&&(S.footnote=1)}if(m)for(let A in m)p.add(A),f[A]="reset";if(S)for(let A in S)p.add(A),f[A]||(f[A]="increment");if(b)for(let A in b)p.add(A),f[A]="set";if(this.lastCounterChanges=Array.from(p),this.lastCounterChangeTypes=f,m)for(let A in m)this.defineCounter(A,m[A]);if(S)for(let A in S){this.counters[A]||this.defineCounter(A,0);let z=this.counters[A];z[z.length-1]+=S[A]}if(b)for(let A in b)if(!this.counters[A])this.defineCounter(A,b[A]);else{let z=this.counters[A];z[z.length-1]=b[A]}if(ur(g)){let A=this.counters["list-item"],z=A[A.length-1];t["ua-list-item-count"]=new W(new At(z),0);let U=si(t,"_pseudos");U.marker||(U.marker={})}this.counterScoping.push(null)}popCounters(){let t=this.counterScoping.pop();if(t)for(let i in t){let n=this.counters[i];n&&(n.length==1?delete this.counters[i]:n.pop())}}setNamedStrings(t){let i=t["string-set"];if(!i)return;i=i.filterValue(new _r(this,this.currentElement,this.counterResolver));let n=i.value instanceof Oe?i.value.values:[i.value];for(let r of n)if(r instanceof J){let o=r.values[0].stringValue(),s=r.values.slice(1);if(s.some(a=>sh(a)))this.counterResolver.setNamedString(o,ll(new J(s),this.context),this.currentElementOffset);else{let a=s.map(h=>Mr(h,this.context)).join("");this.counterResolver.setNamedString(o,a,this.currentElementOffset)}}delete t["string-set"]}setRunningElement(t){let i=t.position;if(i?.value instanceof ai&&i.value.name==="running"){let n=i.value.values[0].stringValue();this.counterResolver.setRunningElement(n,this.currentElementOffset)}}processPseudoelementProps(t,i,n){this.pushCounters(t);let r=t.content;r&&(t.content=r.filterValue(new _r(this,i,this.counterResolver,n))),this.popCounters()}pushElement(t,i,n,r){var o,s,a;let h=this.currentPageType;this.currentPageType=null,this.currentElement=i,this.currentElementOffset=r,this.currentStyle=n,this.currentNamespace=i.namespaceURI,this.currentLocalName=i.localName;let l=this.code.nsPrefix[this.currentNamespace];l?this.currentNSTag=l+this.currentLocalName:this.currentNSTag="",this.currentId=i.getAttribute("id"),this.currentXmlId=i.getAttributeNS("http://www.w3.org/XML/1998/namespace","id");let c=i.getAttribute("class");c?this.currentClassNames=c.split(/\s+/):this.currentClassNames=fa;let d=i.getAttributeNS("http://www.idpf.org/2007/ops","type");d?this.currentEpubTypes=d.split(/\s+/):this.currentEpubTypes=fa;let p=Sa(i);p&&(this.stack[this.stack.length-1].push(new Jb(this.lang)),this.lang=p.toLowerCase());let f=this.isRoot,g=this.siblingOrderStack;this.currentSiblingOrder=++g[g.length-1],g.push(0);let v=this.siblingTypeCountsStack,w=this.currentSiblingTypeCounts=v[v.length-1],x=w[this.currentNamespace];x||(x=w[this.currentNamespace]={}),x[this.currentLocalName]=(x[this.currentLocalName]||0)+1,v.push({});let m=this.followingSiblingOrderStack;m[m.length-1]!==null?this.currentFollowingSiblingOrder=--m[m.length-1]:this.currentFollowingSiblingOrder=null,m.push(null);let S=this.followingSiblingTypeCountsStack,b=this.currentFollowingSiblingTypeCounts=S[S.length-1];b&&b[this.currentNamespace]&&b[this.currentNamespace][this.currentLocalName]--,S.push({}),this.applyActions(),this.currentPageType=h,this.applyVarFilter([this.currentStyle],t,i),this.applyCalcFilter(this.currentStyle,this.context),this.applyCmykFilter(this.currentStyle,this.currentElement),this.applyAttrFilter(i,t);let C=n.quotes,P=null;if(C){let z=C.evaluate(this.context);z&&(P=new Qb(this.quotes),z===y.none?this.quotes=[new K(""),new K("")]:z===y.auto||z===y.initial?this.quotes=[new K("\u201C"),new K("\u201D"),new K("\u2018"),new K("\u2019")]:z instanceof J&&(this.quotes=z.values))}this.pushCounters(this.currentStyle);let L=this.currentId||this.currentXmlId||i.getAttribute("name")||"";if(f||L){let z=Object.create(null);Object.keys(this.counters).forEach(U=>{z[U]=Array.from(this.counters[U])}),this.counterListener.countersOfId(L,z)}let A=ft(this.currentStyle,"_pseudos");if(A){let z=!0;for(let U of r0){U||(z=!1);let X=A[U];if(X){let re=(o=ve(this.currentStyle,"float"))==null?void 0:o.value,k=i instanceof Element&&Gt(i),_=i instanceof Element&&Pt(i),F=!!ve(this.currentStyle,"--viv-semantic-footnote-content"),D=re===y.footnote,E=(U==="before"||U==="after")&&(D||_||F)&&!!X.content,N=kb(X),R=U==="footnote-call"&&k&&N,$=U==="footnote-marker"&&(_||F)&&N;if((U==="before"||U==="after")&&!(E||It((s=X.content)==null?void 0:s.value)||this.hasNonTrivialViewConditionalPseudoContent(X))||U==="marker"&&!ur((a=ve(this.currentStyle,"display"))==null?void 0:a.value)||(U==="footnote-call"||U==="footnote-marker")&&re!==y.footnote&&!R&&!$||(U==="footnote-call"||U==="footnote-marker")&&F&&!N)delete A[U];else if(z){if(this.processPseudoelementProps(X,i,U),U==="marker")this.processMarkerPseudoelementProps(X,i,t),delete A[U];else if(U==="footnote-marker"){if(this.resolvePseudoelementInheritedPropertyValue(X,"list-style-position",t,i)===y.outside){this.processMarkerPseudoelementProps(X,i,t);let V=X.content;V&&(this.currentStyle["_footnote-marker-content"]=V),this.currentStyle.display=new W(B("list-item"),0),this.currentStyle["list-style-position"]=new W(y.outside,0),this.currentStyle["list-style-type"]=new W(y.none,0),this.currentStyle["list-style-image"]=new W(y.none,0),delete A[U]}}else if(U==="first-letter"&&X["initial-letter"]){let V=X["initial-letter"].evaluate(this.context);V!==y.normal&&!Z(V)&&(this.currentStyle["--viv-initialLetter"]=new W(V,0)),delete X["initial-letter"]}}else this.stack[this.stack.length-2].push(new Kb(X,i))}}}this.setNamedStrings(this.currentStyle),this.setRunningElement(this.currentStyle),P&&this.stack[this.stack.length-2].push(P)}hasNonTrivialViewConditionalPseudoContent(t){let i=t._viewConditionalStyles;return!i||i.length<=0?!1:i.some(n=>{var r;return It((r=n.styles.content)==null?void 0:r.value)})}processMarkerPseudoelementProps(t,i,n){var r,o,s,a,h;let l=ur((r=this.currentStyle.display)==null?void 0:r.value);if(!It((o=t.content)==null?void 0:o.value)&&l){let d=this.getInheritedPropertyValue("list-style-type",n,i),p=this.getInheritedPropertyValue("list-style-image",n,i);if(p instanceof Qe)t.content=new W(new J([p,new K(" ")]),0);else if(d instanceof K)t.content=new W(d,0);else if(d instanceof he&&d!==y.none){let f=(a=(s=this.currentStyle["ua-list-item-count"])==null?void 0:s.value)==null?void 0:a.num;if(f!=null){let g=d.name.toLowerCase();g==="disc"||g==="circle"||g==="square"||g==="disclosure-open"||g==="disclosure-closed"||(t.content=new W(new K(this.counterStyleStore.formatMarker(d.name,f)),0))}}}let c=t.content;if(c){let d=c.value;if(It(d)){let p=this.resolveMarkerContentVal(d);this.currentStyle["--viv-marker-content"]=new W(p,0)}}for(let d of wf.markerAllowedProps){let p=t[d];if(p){let f=p.evaluate(this.context,d);f&&!Z(f)&&(this.currentStyle[`--viv-marker-${d}`]=new W(f,0))}}if(!Ut((h=ve(this.currentStyle,"display"))==null?void 0:h.value)){let d=this.getInheritedPropertyValue("list-style-position",n,i);d&&d!==y.outside&&!Z(d)&&(this.currentStyle["list-style-position"]=new W(d,0))}}resolveMarkerContentVal(t){if(t instanceof j){let i=t.expr.evaluate(this.context);return typeof i=="string"?new K(i):typeof i=="number"?new K(String(i)):t}if(t instanceof J){let i=t.values.map(n=>this.resolveMarkerContentVal(n));return new J(i)}return t}getInheritedPropertyValue(t,i,n){var r;for(let s=n;s;s=s.parentElement){let a=(s===this.currentElement?this.currentStyle:i.getStyle(s,!1))[t];if(a){let h=a.evaluate(this.context,t);if(h===y.inherit||h===y.unset||h===y.revert)continue;if(h===y.initial)break;return h}}let o=i.validatorSet;return(r=o?.defaultValues[t])!=null?r:null}resolvePseudoelementInheritedPropertyValue(t,i,n,r){var o;let s=t[i];if(s){let a=s.evaluate(this.context,i);if(a!==y.inherit&&a!==y.unset&&a!==y.revert){if(a===y.initial){let h=n.validatorSet;return(o=h?.defaultValues[i])!=null?o:null}return a}}return this.getInheritedPropertyValue(i,n,r)}applyAttrFilterInner(t,i,n){let r=t.scope,o=t.validatorSet;for(let s in n)if(Xi(s)&&!Xe(s)){let a=n[s],h=new e0(i,r,s,o),l=a.filterValue(h);if(!h.hadAttrFunction){n[s]=l;continue}let c=h.validatePropertyValue(l.value);n[s]=c===l.value?l:new W(c,l.priority)}}applyAttrFilter(t,i){let n=this.currentStyle,r=ft(n,"_pseudos");for(let o in r)this.applyAttrFilterInner(i,t,r[o]);this.applyAttrFilterInner(i,t,n)}applyVarFilter(t,i,n){let r=t[0],o=t.map(d=>({...d})),s=32,a={},h=ft(r,"_pseudos"),l=Object.keys(r).filter(Xi),c=d=>{var p,f,g;let v=ve(r,d),w=v.value,x=Xe(d)?o:t,m=new f0(x,i,n,Xe(d)?d:null);Xe(d)&&m.getFallbackCycleMembers(w,x,n)&&(w=y.initial);for(let S=0;;S++){if(S>=s){w=Xe(d)?y.initial:y.unset;break}let b=w.visit(m);if(m.error){w=Xe(d)?y.initial:y.unset,m.error=!1;break}if(b===w)break;w=b}if(w!==v.value){let S=i.validatorSet,b=(p=S?.getShorthand(d,w))==null?void 0:p.clone();if(b)if(Z(w)){for(let C of b.propList){let P=new W(w,v.priority),L=ve(r,C);Fi(a,C,nl(this.context,L,P))}delete r[d]}else{let C=Ri(i.scope,new xt(w.toString(),null),"");if(C&&(C.visit(b),!b.error)){for(let P of b.propList){let L=new W((g=(f=b.values[P])!=null?f:S.defaultValues[P])!=null?g:y.initial,v.priority),A=ve(r,P);Fi(a,P,nl(this.context,A,L))}delete r[d]}}else r[d]=new W(w,v.priority)}if(a[d]){let S=ve(r,d);S&&S.value!==Me&&Jt(a,d,S,this.context)}};for(let d in r)if(Xo(d)){if(d==="_pseudos")continue;let p=ft(r,d);for(let f in p)this.applyVarFilter([p[f],...t],i,n)}for(let d of l)Xe(d)&&c(d);for(let d of l)Xe(d)||c(d);if(h)for(let d in h)this.applyVarFilter([h[d],...t],i,n);for(let d in a)r[d]=a[d]}applyCalcFilter(t,i){let n=new Tf(i);for(let r in t)if(Xo(r)){let o=ft(t,r);for(let s in o)this.applyCalcFilter(o[s],i)}else if(Xi(r)&&!Xe(r)){let o=ve(t,r),s=o.value.visit(n);s!==o.value&&(t[r]=new W(s,o.priority))}}applyCmykFilter(t,i){let n=new td(this.cmykStore);if(this.applyCmykFilterInternal(t,n,""),i){let r=n.getConversions();r&&i.setAttribute("data-viv-device-cmyk",JSON.stringify(r))}}applyCmykFilterInternal(t,i,n){for(let r in t)if(Xo(r)){let o=ft(t,r);for(let s in o)this.applyCmykFilterInternal(o[s],i,`::${s}:`)}else if(Xi(r)&&!Xe(r)){let o=ve(t,r),s=o.value.toString();i.reset();let a=o.value.visit(i);a!==o.value&&(i.hadDeviceCmyk()&&i.recordConversion(n+r,s),t[r]=new W(a,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 i=1;i>=-1;--i){let n=this.stack[this.stack.length-i-2];for(t=0;t<n.length;)n[t].push(this,i)?n.splice(t,1):t++}this.isFirst=!0,this.isRoot=!1}pop(){for(let t=1;t>=-1;--t){let i=this.stack[this.stack.length-t-2],n=0;for(;n<i.length;)i[n].pop(this,t)?i.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()}};u(vf,"markerAllowedProps",["color","font-family","font-size","font-style","font-weight","font-variant","hyphens","line-height","tab-size","text-combine-upright","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-orientation","text-shadow","text-transform","unicode-bidi","direction","white-space"]);var n0=vf,fa=[],r0=["before","footnote-call","footnote-marker","marker","inner","first-letter","first-line","","after"],hl=null;function o0(e){hl=e}var Dr=class extends on{constructor(e,t,i,n,r,o,s){super(e,t,s),u(this,"condition",i),u(this,"regionId",r),u(this,"validatorSet",o),u(this,"chain",null),u(this,"specificity",0),u(this,"elementStyle",null),u(this,"conditionCount",0),u(this,"pseudoelement",null),u(this,"selectorFunctionContainsPseudoelement",!1),u(this,"footnoteContent",!1),u(this,"cascade"),u(this,"state"),u(this,"viewConditionId",null),u(this,"insideSelectorRule"),u(this,"invalid",!1),this.cascade=n?n.cascade:hl?hl.clone():new i0,this.state=0}insertNonPrimary(e){this.cascade.insertInTable(this.cascade.tags,"*",e)}processChain(e){let t=ih(this.chain,e);t!==e&&t.makePrimary(this.cascade)||this.insertNonPrimary(t)}invalidContinuationAfterPseudoelement(e){return this.pseudoelement?(this.invalidSelector(`::${this.pseudoelement} followed by ${e}`),!0):this.selectorFunctionContainsPseudoelement?(this.invalidSelector(`Selector containing pseudo-element followed by ${e}`),!0):!1}isInsideSelectorRule(e){return this.state!=0?(this.reportAndSkip(e),!0):!1}tagSelector(e,t){!t&&!e||this.invalidContinuationAfterPseudoelement(t||"*")||(t&&(this.specificity+=1),t&&e?this.chain.push(new Fb(e,t.toLowerCase())):t?this.chain.push(new Eu(t.toLowerCase())):this.chain.push(new Lb(e)))}invalidSelector(e){Y.warn(e),this.chain.push(new rt("")),this.setInvalid()}setInvalid(){this.invalid=!0;for(let e=this;e instanceof Hn;e=e.parent)e.parent.invalid=!0}classSelector(e){this.invalidContinuationAfterPseudoelement(`.${e}`)||(this.specificity+=256,this.chain.push(new Ab(e)))}pseudoclassSelector(e,t){if(!this.invalidContinuationAfterPseudoelement(`:${e}`)){switch(e.toLowerCase()){case"enabled":this.chain.push(new Ub);break;case"disabled":this.chain.push(new $b);break;case"checked":this.chain.push(new Hb);break;case"root":case"scope":this.chain.push(new Db);break;case"link":this.chain.push(new Eu("a")),this.chain.push(new Pu("","href"));break;case"href-epub-type":case"href-role-type":if(t&&t.length>=1&&typeof t[0]=="string"){let i=t[0],n=new RegExp(`(^|\\s)${es(i)}($|\\s)`),r=t[1];this.chain.push(new Rb(n,r,e==="href-role-type"))}else this.chain.push(new rt(""));break;case"footnote-content":this.footnoteContent=!0;break;case"visited":case"active":case"hover":case"focus":this.chain.push(new rt(""));break;case"lang":if(t&&t.length==1&&typeof t[0]=="string"){let i=t[0];this.chain.push(new _b(new RegExp(`^${es(i.toLowerCase())}($|-)`)))}else this.chain.push(new rt(""));break;case"nth-child":case"nth-last-child":case"nth-of-type":case"nth-last-of-type":{let i=s0[e.toLowerCase()];t&&t.length==2?this.chain.push(new i(t[0],t[1])):this.chain.push(new rt(""));break}case"first-child":this.chain.push(new Nu);break;case"last-child":this.chain.push(new sl(0,1));break;case"first-of-type":this.chain.push(new ol(0,1));break;case"last-of-type":this.chain.push(new al(0,1));break;case"only-child":this.chain.push(new Nu),this.chain.push(new sl(0,1));break;case"only-of-type":this.chain.push(new ol(0,1)),this.chain.push(new al(0,1));break;case"empty":this.chain.push(new Vb);break;case"before":case"after":case"first-line":case"first-letter":this.pseudoelementSelector(e,t);return;default:this.invalidSelector(`Unknown pseudo-class :${e}`);return}this.specificity+=256}}pseudoelementSelector(e,t){if(!this.invalidContinuationAfterPseudoelement(`::${e}`)){switch(e){case"before":case"after":case"first-line":case"first-letter":case"footnote-call":case"footnote-marker":case"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(t&&t.length==1&&typeof t[0]=="number"){let i=Math.round(t[0]);if(i>0&&i==t[0]){if(!this.pseudoelement)this.pseudoelement=`first-${i}-lines`;else{this.invalidSelector(`Double pseudo-element ::${this.pseudoelement}::${e}`);return}break}}this.chain.push(new rt(""));break;case"nth-fragment":t&&t.length==2?this.viewConditionId=`NFS_${t[0]}_${t[1]}`:this.chain.push(new rt(""));break;default:this.invalidSelector(`Unknown pseudo-element ::${e}`);return}this.specificity+=1}}idSelector(e){this.invalidContinuationAfterPseudoelement(`#${e}`)||(this.specificity+=65536,this.chain.push(new Ib(e)))}attributeSelector(e,t,i,n,r){if(this.invalidContinuationAfterPseudoelement(`[${t}]`))return;this.specificity+=256,n=n||"";let o;switch(i){case 0:o=new Pu(e,t);break;case 39:o=new Bb(e,t,n,r??null);break;case 45:!n||n.match(/\s/)?o=new rt(""):o=new ar(e,t,sr(`(^|\\s)${or(n,r??null)}($|\\s)`),r??null);break;case 44:o=new ar(e,t,sr(`^${or(n,r??null)}($|-)`),r??null);break;case 43:n?o=new ar(e,t,sr(`^${or(n,r??null)}`),r??null):o=new rt("");break;case 42:n?o=new ar(e,t,sr(`${or(n,r??null)}$`),r??null):o=new rt("");break;case 46:n?o=new ar(e,t,sr(or(n,r??null)),r??null):o=new rt("");break;case 50:if(n=="supported")o=new Mb(e,t);else{this.invalidSelector(`Unsupported :: attr selector op: ${n}`);return}break;default:this.invalidSelector(`Unsupported attr selector: ${i}`);return}this.chain.push(o)}descendantSelector(){if(this.invalidContinuationAfterPseudoelement("descendant selector"))return;let e=`d${To++}`;this.processChain(new No(new Xb(e,this.viewConditionId,null))),this.chain=[new rt(e)],this.viewConditionId=null}childSelector(){if(this.invalidContinuationAfterPseudoelement("child selector"))return;let e=`c${To++}`;this.processChain(new No(new qb(e,this.viewConditionId,null))),this.chain=[new rt(e)],this.viewConditionId=null}adjacentSiblingSelector(){if(this.invalidContinuationAfterPseudoelement("adjacent sibling selector"))return;let e=`a${To++}`;this.processChain(new No(new Yb(e,this.viewConditionId,null))),this.chain=[new rt(e)],this.viewConditionId=null}followingSiblingSelector(){if(this.invalidContinuationAfterPseudoelement("following sibling selector"))return;let e=`f${To++}`;this.processChain(new No(new Zb(e,this.viewConditionId,null))),this.chain=[new rt(e)],this.viewConditionId=null}nextSelector(){this.finishChain(),this.pseudoelement=null,this.selectorFunctionContainsPseudoelement=!1,this.footnoteContent=!1,this.specificity=0,this.chain=[]}startSelectorRule(){this.isInsideSelectorRule("E_CSS_UNEXPECTED_SELECTOR")||(this.state=1,this.elementStyle={},this.pseudoelement=null,this.selectorFunctionContainsPseudoelement=!1,this.specificity=0,this.footnoteContent=!1,this.chain=[],this.invalid=!1)}error(e,t){super.error(e,t),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.selectorFunctionContainsPseudoelement=!1,this.viewConditionId=null,this.footnoteContent=!1,this.specificity=0)}makeApplyRuleAction(e){let t=this.regionId;return this.footnoteContent&&(t?t="xxx-bogus-xxx":t="footnote"),new rh(this.elementStyle,e,this.pseudoelement,t,this.viewConditionId)}special(e,t){let i;this.condition?i=new tl(t,0,this.condition):i=new W(t,0),af(this.elementStyle,e).push(i)}property(e,t,i){this.validatorSet.validatePropertyAndHandleShorthand(e,t,i,this)}invalidPropertyValue(e,t){this.report(`E_INVALID_PROPERTY_VALUE ${e}: ${t.toString()}`)}unknownProperty(e,t){this.report(`E_INVALID_PROPERTY ${e}: ${t.toString()}`)}simpleProperty(e,t,i){e=="display"&&(t===y.oeb_page_head||t===y.oeb_page_foot)&&(this.simpleProperty("flow-options",new J([y.exclusive,y._static]),i),this.simpleProperty("flow-into",t,i),t=y.block),_t("SIMPLE_PROPERTY").forEach(o=>{let s=o({name:e,value:t,important:i});e=s.name,t=s.value,i=s.important});let n=(i?this.getImportantSpecificity():this.getBaseSpecificity())+this.cascade.nextOrder(),r=this.condition?new tl(t,n,this.condition):new W(t,n);Jt(this.elementStyle,e,r)}finish(){return this.cascade}startFuncWithSelector(e,t){let i;switch(e){case"is":i=new Hn(this);break;case"not":i=new a0(this);break;case"where":i=new l0(this);break;case"has":i=new h0(this);break;case"nth-child":t&&t.length>=2&&(i=new xf(this,t[0],t[1]));break;case"nth-last-child":t&&t.length>=2&&(i=new u0(this,t[0],t[1]));break}i&&(i.startSelectorRule(),this.owner.pushHandler(i))}},s0={"nth-child":zb,"nth-of-type":ol,"nth-last-child":sl,"nth-last-of-type":al},To=0,Hn=class bf extends Dr{constructor(t){super(t.scope,t.owner,t.condition,t,t.regionId,t.validatorSet,!1),u(this,"parent",t),u(this,"parentChain"),u(this,"chains",[]),u(this,"maxSpecificity",0),u(this,"selectorTexts",[]),u(this,"containsPseudoelementSelector",!1),this.parentChain=t.chain}nextSelector(){this.containsPseudoelementSelector||(this.containsPseudoelementSelector=!!this.pseudoelement),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(){var t;this.containsPseudoelementSelector||(this.containsPseudoelementSelector=!!this.pseudoelement),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 Gb(this.selectorTexts):this.positive()?new oh(this.chains):new Wb(this.chains)),this.increasingSpecificity()&&(this.parent.specificity+=this.maxSpecificity),(t=this.parent).selectorFunctionContainsPseudoelement||(t.selectorFunctionContainsPseudoelement=this.containsPseudoelementSelector)):this.parentChain.push(new rt("")),this.owner.popHandler()}startRuleBody(){this.reportAndSkip("E_CSS_UNEXPECTED_RULE_BODY")}error(t,i){super.error(t,i),this.chain=null,this.pseudoelement=null,this.viewConditionId=null,this.footnoteContent=!1,this.specificity=0;let n=!1;for(let r=this;r instanceof bf;r=r.parent)if(r.forgiving()){n=!0;break}n||this.owner.popHandler()}pushSelectorText(t){this.chain&&this.relational()&&this.selectorTexts.push(t)}positive(){return!0}increasingSpecificity(){return!0}forgiving(){return!0}relational(){return!1}},a0=class extends Hn{positive(){return!1}forgiving(){return!1}},l0=class extends Hn{increasingSpecificity(){return!1}},h0=class extends Hn{relational(){return!0}},xf=class extends Hn{constructor(e,t,i){super(e),u(this,"a",t),u(this,"b",i)}endFuncWithSelector(){this.chain&&this.chains.push(this.chain),this.chains.length>0?(this.maxSpecificity=Math.max(this.maxSpecificity,this.specificity),this.parentChain.push(new df(this.a,this.b,this.chains)),this.parent.specificity+=256+this.maxSpecificity):this.parentChain.push(new rt("")),this.owner.popHandler()}forgiving(){return!0}},u0=class extends xf{endFuncWithSelector(){this.chain&&this.chains.push(this.chain),this.chains.length>0?(this.maxSpecificity=Math.max(this.maxSpecificity,this.specificity),this.parentChain.push(new jb(this.a,this.b,this.chains)),this.parent.specificity+=256+this.maxSpecificity):this.parentChain.push(new rt("")),this.owner.popHandler()}},c0=class extends on{constructor(e,t){super(e,t,!1)}property(e,t,i){if(this.scope.values[e])this.error(`E_CSS_NAME_REDEFINED ${e}`,this.getCurrentToken());else{let n=e.match(/height|^(top|bottom)$/)?"vh":"vw",r=new Xr(this.scope,100,n);this.scope.defineName(e,t.toExpr(this.scope,r))}}},qo=class extends on{constructor(e,t,i,n,r,o){super(e,t,!1),u(this,"condition",i),u(this,"elementStyle",n),u(this,"validatorSet",r),u(this,"ruleType",o),u(this,"order"),this.order=0}property(e,t,i){i?Y.warn("E_IMPORTANT_NOT_ALLOWED"):this.validatorSet.validatePropertyAndHandleShorthand(e,t,i,this)}invalidPropertyValue(e,t){Y.warn("E_INVALID_PROPERTY_VALUE",`${e}:`,t.toString())}unknownProperty(e,t){Y.warn("E_INVALID_PROPERTY",`${e}:`,t.toString())}simpleProperty(e,t,i){let n=i?this.getImportantSpecificity():this.getBaseSpecificity();n+=this.order,this.order+=ah;let r=this.condition?new tl(t,n,this.condition):new W(t,n);Jt(this.elementStyle,e,r)}},d0=class extends Bd{constructor(e,t){super(e),u(this,"validatorSet",t),u(this,"elementStyle",{}),u(this,"order",0)}property(e,t,i){this.validatorSet.validatePropertyAndHandleShorthand(e,t,i,this)}invalidPropertyValue(e,t){Y.warn("E_INVALID_PROPERTY_VALUE",`${e}:`,t.toString())}unknownProperty(e,t){Y.warn("E_INVALID_PROPERTY",`${e}:`,t.toString())}simpleProperty(e,t,i){let n=i?Od:Ld;n+=this.order,this.order+=ah;let r=new W(t,n);Jt(this.elementStyle,e,r)}};function Sf(e,t){let i=of(e);i&&i.forEach(n=>{n.matcher.matches()&&t(n.styles)})}function ul(e,t,i){Sf(i,n=>{kr(e,n,t)})}function p0(e,t,i,n){let r=new d0(e,t),o=new xt(n,r);try{rv(o,r,i)}catch(s){Y.warn(s,"Style attribute parse error:")}return r.elementStyle}function Cf(e,t,i){let n=e["writing-mode"];if(n){let r=n.evaluate(t,"writing-mode");if(r&&r!==y.inherit&&r!==y.revert&&r!==y.unset)return r===y.vertical_rl}return i}function kf(e,t,i){let n=e.direction;if(n){let r=n.evaluate(t,"direction");if(r&&r!==y.inherit&&r!==y.revert&&r!==y.unset)return r===y.rtl}return i}function cl(e,t,i,n,r){let o={};for(let s in e)Xi(s)&&(o[s]=ve(e,s));return ul(o,t,e),Ef(e,i,n,(s,a)=>{kr(o,a,t),ul(o,t,a)}),o}function Ef(e,t,i,n){let r=ft(e,"_regions");if((t||i)&&r){if(i){let o=["footnote"];t?t=t.concat(o):t=o}for(let o of t){let s=r[o];s&&n(o,s)}}}function kr(e,t,i){for(let n in t)if(Xi(n)){let r=ve(t,n),o=e[n];e[n]=nl(i,o,r)}}var Pf=(e,t,i,n,r,o)=>{var s,a;let h=i?n?wb:ef:n?bb:tf,l=r?xb:Sb;for(let c in e){let d=e[c];if(!d)continue;let p=(s=h[c])!=null?s:h[l[c]],f=(a=l[c])!=null?a:l[h[c]],g=p??f,v;if(g){let w=e[g];if(w&&w.priority>d.priority||p&&f&&p!==f&&(g=f,w=e[g],w&&w.priority>d.priority))continue;v=ku[p]?p:ku[f]?f:c}else v=c,c.startsWith("text-align")&&(d.value===y.inside||d.value===y.outside)&&(d=new W(r===(d.value===y.inside)?y.right:y.left,d.priority));t[v]=o(c,d)}},f0=class Nf extends nn{constructor(t,i,n,r=null){super(),u(this,"elementStyles",t),u(this,"styler",i),u(this,"element",n),u(this,"currentCustomPropertyName",r),u(this,"resolvingCustomProperties",[]),u(this,"varResolutionState",{cycleMembers:new Set}),r&&this.resolvingCustomProperties.push(r)}getRawCustomPropertyLookup(t,i,n){var r,o;let s=n??this.styler.root;if(i!=null&&i.length){for(let a=0;a<i.length;a++){let h=(r=i[a][t])==null?void 0:r.value;if(h){if(h===y.initial)return{found:!0,value:null,elementStyles:i.slice(a),element:n};if(!(h===y.inherit||h===y.unset||h===y.revert))return{found:!0,value:h,elementStyles:i.slice(a),element:n}}}n&&(s=n.parentElement)}for(;s;s=s.parentElement){let a=this.styler.getStyle(s,!1),h=(o=a?.[t])==null?void 0:o.value;if(h){if(h===y.initial)return{found:!0,value:null,elementStyles:a?[a]:[],element:s};if(!(h===y.inherit||h===y.unset||h===y.revert))return{found:!0,value:h,elementStyles:a?[a]:[],element:s}}}return{found:!1,value:null,elementStyles:[],element:null}}collectReferencedCustomProperties(t){let i=new Set;class n extends Kt{visitFunc(o){let s=o.values[0]instanceof he&&o.values[0].name;return o.name==="var"&&s&&Xe(s)&&i.add(s),super.visitFunc(o)}}return t.visit(new n),Array.from(i)}findReferencedCycleStart(t,i,n,r=new Set){for(let o of this.collectReferencedCustomProperties(t)){if(this.resolvingCustomProperties.includes(o))return o;if(r.has(o))continue;r.add(o);let s=this.getRawCustomPropertyLookup(o,i,n),a=s.value&&this.findReferencedCycleStart(s.value,s.elementStyles,s.element,r);if(a)return a}return null}getFallbackCycleMembers(t,i,n){let r=null,o=this;class s extends Kt{visitFunc(l){if(l.name==="var")for(let c of l.values.slice(1)){let d=o.findReferencedCycleStart(c,i,n);if(d)return r=d,null}return super.visitFunc(l)}}if(t.visit(new s),!r)return null;let a=this.resolvingCustomProperties.indexOf(r);return new Set(this.resolvingCustomProperties.slice(a))}resolveCustomProperty(t,i,n,r){if(!i)return{found:!1,value:null,continueLookup:!1};if(i===y.initial)return{found:!0,value:null,continueLookup:!1};if(i===y.inherit||i===y.unset||i===y.revert)return{found:!0,value:null,continueLookup:!0};let o=this.getFallbackCycleMembers(i,n,r);return o?(o.forEach(s=>this.varResolutionState.cycleMembers.add(s)),{found:!0,value:null,continueLookup:!1}):{found:!0,value:this.resolveReferencedCustomProperty(t,i,n,r),continueLookup:!1}}resolveReferencedCustomProperty(t,i,n,r){let o=this.resolvingCustomProperties.indexOf(t);if(o>=0)return this.resolvingCustomProperties.slice(o).forEach(d=>this.varResolutionState.cycleMembers.add(d)),null;let s=new Set(this.varResolutionState.cycleMembers);this.varResolutionState.cycleMembers=new Set;let a=new Nf(n,this.styler,r,t);a.resolvingCustomProperties=this.resolvingCustomProperties,a.resolvingCustomProperties.push(t),a.varResolutionState=this.varResolutionState;let h=i,l=32;for(let d=0;;d++){if(d>=l){h=null;break}let p=h.visit(a);if(a.error){h=null;break}if(p===h)break;h=p}let c=this.varResolutionState.cycleMembers;return this.varResolutionState.cycleMembers=new Set([...s,...c]),this.resolvingCustomProperties.pop(),c.has(t)?null:h}getVarValue(t){var i,n,r,o;let s=(i=this.element)!=null?i:this.styler.root;if((n=this.elementStyles)!=null&&n.length){for(let a=0;a<this.elementStyles.length;a++){let h=this.elementStyles[a],l=this.resolveCustomProperty(t,(r=h[t])==null?void 0:r.value,this.elementStyles.slice(a),this.element);if(l.found){if(l.value)return l.value;if(!l.continueLookup)return null}}this.element&&(s=this.element.parentElement)}for(;s;s=s.parentElement){let a=this.styler.getStyle(s,!1),h=this.resolveCustomProperty(t,(o=a?.[t])==null?void 0:o.value,a?[a]:[],s);if(h.found){if(h.value)return h.value;if(!h.continueLookup)return null}}return null}visitFunc(t){if(t.name!=="var")return super.visitFunc(t);let i=t.values[0]instanceof he&&t.values[0].name;return!i||!Xe(i)?(this.error=!0,Me):this.getVarValue(i)||(this.currentCustomPropertyName&&this.varResolutionState.cycleMembers.has(this.currentCustomPropertyName)?(this.error=!0,Me):t.values.length<2?(this.error=!0,Me):t.values.length===2?t.values[1]:new Oe(t.values.slice(1)))}visitSpaceList(t){let i=this.visitValues(t.values);if(this.error)return Me;if(i===t.values)return t;let n=[];for(let r of i)r instanceof J?n.push(...r.values):n.push(r);return new J(n)}visitCommaList(t){let i=this.visitValues(t.values);if(this.error)return Me;if(i===t.values)return t;let n=[];for(let r of i)r instanceof Oe?n.push(...r.values):n.push(r);return new Oe(n)}},Tf=class extends nn{constructor(e,t,i,n){super(),u(this,"context",e),u(this,"resolveViewportUnit",t),u(this,"percentRef",i),u(this,"vertical",n)}visitFunc(e){let t=super.visitFunc(e);if(e.name!=="calc")return t;let i=t.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(i))return t;let n=Ri(this.context.rootScope,new xt(i,null),"");if(n instanceof j)try{let r=n.expr.evaluate(this.context);typeof r=="number"&&!isNaN(r)&&(/\d(px|in|pt|pc|cm|mm|q|rem|rlh)\W/i.test(i)?t=new O(r,"px"):/\d[a-z]/i.test(i)||(t=new At(r)))}catch(r){Y.warn(r)}return t}visitNumeric(e){return this.resolveViewportUnit&&Ac(e.unit)||this.context.rootFontSize!=null&&cm(e.unit)?new O(e.num*this.context.queryUnitSize(e.unit,!1,this.vertical),"px"):typeof this.percentRef=="number"&&e.unit==="%"?new O(e.num*this.percentRef/100,"px"):e}};function Ss(e,t,i,n,r){try{if(t instanceof j)return t.expr instanceof we&&(t.expr.str.startsWith("named-string-")||t.expr.str.startsWith("running-element-"))?t:av(e,t.expr,i);if(t instanceof O||t instanceof ai||t instanceof J||t instanceof Oe)return t.visit(new Tf(e,!0,n,r))}catch(o){return Y.warn(o),Me}return t}var Tu={first:!1,forceEnd:!1,allowEnd:!1,last:!1};function Au(e){let t=e instanceof ot?e:typeof e=="string"?B(e):y.none;if(t===y.none)return Tu;let i=t instanceof J?t.values:[t],n=Object.create(Tu);for(let r of i)if(r instanceof he)switch(r.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 Iu(e){return!e.first&&!e.last&&!e.forceEnd&&!e.allowEnd}var g0={trimStart:!1,spaceFirst:!1,trimEnd:!1,allowEnd:!1,trimAdjacent:!1},Fu={trimStart:!1,spaceFirst:!1,trimEnd:!1,allowEnd:!0,trimAdjacent:!0},Ru={trimStart:!0,spaceFirst:!1,trimEnd:!0,allowEnd:!1,trimAdjacent:!0};function Lu(e){let t=e instanceof ot?e:typeof e=="string"?B(e):y.normal;if(t===y.normal)return Fu;if(t===y.auto)return Ru;let i=t instanceof J?t.values:[t],n=Object.create(Fu);for(let r of i)if(r instanceof he)switch(r.name){case"trim-both":case"trim-auto":return Ru;case"space-all":return g0;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 ga={ideographAlpha:!1,ideographNumeric:!1},m0={ideographAlpha:!0,ideographNumeric:!0};function Ou(e){let t=e instanceof ot?e:typeof e=="string"?B(e):y.normal;if(t===y.normal||t===y.auto)return m0;if(t===y.none)return ga;let i=t instanceof J?t.values:[t],n=Object.create(ga);for(let r of i)if(r instanceof he)switch(r.name){case"no-autospace":return ga;case"ideograph-alpha":n.ideographAlpha=!0;break;case"ideograph-numeric":n.ideographNumeric=!0;break}return n}function Bu(e,t){return!e.ideographAlpha&&!e.ideographNumeric&&!t.trimStart&&!t.spaceFirst&&!t.trimEnd&&!t.allowEnd&&!t.trimAdjacent}function Mu(e){return e?(e=e.toLowerCase(),/^zh\b.*-(hant|tw|hk)\b/.test(e)?"zh-hant":/^zh\b/.test(e)?"zh-hans":/^ja\b/.test(e)?"ja":/^ko\b/.test(e)?"ko":e):null}var y0=/^[‘’“”〰﹙﹚﹛﹜﹝﹞〚〛]\p{M}*$/u,v0=/^[‘“﹙﹛﹝〚]\p{M}*$/u;function w0(e,t){return Gr==="chromium"&&t&&y0.test(e)}function b0(e){return v0.test(e)?"viv-ts-open":"viv-ts-close"}var x0=class{getPolyfilledInheritedProps(){return["hanging-punctuation","text-autospace","text-spacing-trim"]}preprocessSingleDocument(e){e.body&&this.preprocessForTextSpacing(e.body)}preprocessForTextSpacing(e){var t;let i=e.ownerDocument.createNodeIterator(e,NodeFilter.SHOW_TEXT);for(let n=i.nextNode();n;n=i.nextNode()){if(n.parentElement.namespaceURI!=="http://www.w3.org/1999/xhtml"||((t=n.parentElement.dataset)==null?void 0:t.mathTypeset)==="true")continue;let r=n.textContent.replace(/(?![()\[\]{}])[\p{Ps}\p{Pe}\p{Pf}\p{Pi}、。,.:;、。\u3000\u3030]\p{M}*(?=\P{M})|.(?=(?![()\[\]{}])[\p{Ps}\p{Pe}\p{Pf}\p{Pi}、。,.:;、。\u3000\u3030])|(?!\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(r.length>1){let o=r.length-1;for(let s=0;s<o;s++)n.parentNode.insertBefore(document.createTextNode(r[s]),n);n.textContent=r[o]}}}processGeneratedContent(e,t,i,n,r,o){r=Mu(r);let s=Ou(t),a=Lu(i),h=Au(n);if(Iu(h)&&Bu(s,a))return;this.preprocessForTextSpacing(e);let l=e.style.whiteSpace;(o?e.offsetHeight:e.offsetWidth)===0&&(e.style.whiteSpace="pre");let c=e.ownerDocument.createNodeIterator(e,NodeFilter.SHOW_TEXT),d=null,p=null;for(let f=c.nextNode();f;f=p){p=c.nextNode();let g=!d,v=!d||/\n$/.test(d.textContent),w=!p||/^\n/.test(p.textContent),x=!p;this.processTextSpacing(f,g||v,g,v,w,x,d,p,s,a,h,r,o),d=f}e.style.whiteSpace=l}postLayoutBlock(e,t){var i,n,r,o,s,a,h,l;let c=!e||e.fragmentIndex===1&&f(),d=c||g();function p(m){var S;if(m?.nodeType!==1)return!1;let b=m;if(b.hasAttribute(zn))return!0;let{position:C,float:P}=(S=b.style)!=null?S:{};return C==="absolute"||C==="fixed"||P&&P!=="none"}function f(){let m=t[0];for(let S=m;;S=S.parent)if(!S||!S.inline){if(S?.fragmentIndex!==1)return!1;break}if(!m.inline)return!0;for(let S=m.viewNode.previousSibling;S;S=S.previousSibling)if(!Ee(S,m.whitespace)&&!p(S))return!1;return!0}function g(){var m,S;let b=t[0],C;for(;b&&b.inline&&(C=(m=b.viewNode)==null?void 0:m.previousSibling,!(C&&(C.nodeType===Node.TEXT_NODE&&/^[ \t\r\n\f]*$/.test(C.textContent)&&b.whitespace!==bt.PRESERVE&&(C=C.previousSibling),C)));)b=b.parent;for(;C;){if(C.nodeType===Node.ELEMENT_NODE){if(C.localName==="br")return!0;let P=(S=C.style)==null?void 0:S.display;if(P&&P!=="inline")return!/^(inline|ruby)\b/.test(P)}else if(C.nodeType===Node.TEXT_NODE){if(b.whitespace===bt.PRESERVE){if(/\n$/.test(C.textContent))return!0}else if(b.whitespace===bt.NEWLINE&&/\n[ \t\r\n\f]*$/.test(C.textContent))return!0}C=C.lastChild}return!1}let v=-1;for(let m=0;m<t.length;m++){let S=t[m];if(!S.after&&S.inline&&!S.display&&S.parent&&S.viewNode.parentNode&&S.viewNode.nodeType===Node.TEXT_NODE&&!Ee(S.viewNode,S.whitespace)){let b=function(E){var N,R,$;if(((N=E.viewNode)==null?void 0:N.nodeType)===Node.ELEMENT_NODE)return E.viewNode.localName==="br";if(((R=E.viewNode)==null?void 0:R.nodeType)===Node.TEXT_NODE){let V=E.viewNode;if(E.whitespace===bt.PRESERVE){if(/\n$/.test(V.textContent))return!0}else if(E.whitespace===bt.NEWLINE&&/\n[ \t\r\n\f]*$/.test(V.textContent))return!0;if((($=V.previousElementSibling)==null?void 0:$.localName)==="br")return Ee(V,E.whitespace)}return!1},C=function(E){var N,R,$;if(((N=E.viewNode)==null?void 0:N.nodeType)===Node.ELEMENT_NODE)return E.viewNode.localName==="br";if(((R=E.viewNode)==null?void 0:R.nodeType)===Node.TEXT_NODE){let V=E.viewNode;if(E.whitespace===bt.PRESERVE){if(/^\n/.test(V.textContent))return!0}else if(E.whitespace===bt.NEWLINE&&/^[ \t\r\n\f]*\n/.test(V.textContent))return!0;if((($=V.nextElementSibling)==null?void 0:$.localName)==="br")return Ee(V,E.whitespace)}return!1};var w=b,x=C;v<0&&(v=m);let P=Mu((o=(n=(i=S.lang)!=null?i:S.parent.lang)!=null?n:e?.lang)!=null?o:(r=e?.parent)==null?void 0:r.lang),L=Ou(S.inheritedProps["text-autospace"]),A=Lu(S.inheritedProps["text-spacing-trim"]),z=Au(S.inheritedProps["hanging-punctuation"]);if(Iu(z)&&Bu(L,A)||/\b(flex|grid)\b/.test(S.parent.display))continue;let U=null,X=null,re=m===v,k=m===v&&c,_=m===v&&d,F=!1,D=!1;for(let E=m-1;E>=0;E--){let N=t[E];if(b(N)){_=!0;break}if(!N.display&&N.viewNode.nodeType===Node.TEXT_NODE&&N.viewNode.textContent.length>0){U=N.viewNode;break}if(((s=N.viewNode)==null?void 0:s.nodeType)===Node.ELEMENT_NODE&&Yt(N.viewNode)==="footnote-call"){if(N.viewNode.contains(S.viewNode))continue;let R=wv(N.viewNode);if(R){U=R;break}}if(N.display&&!/^(inline|ruby)\b/.test(N.display)||((a=N.viewNode)==null?void 0:a.nodeType)===Node.ELEMENT_NODE&&(N.viewNode.localName==="br"||ji[N.viewNode.localName]))break;E===0&&(re=!0,c&&(k=!0,_=!0))}for(let E=m+1;E<t.length;E++){let N=t[E];if(C(N)){F=!0;break}if(N.viewNode!==S.viewNode&&!N.display&&N.viewNode.nodeType===Node.TEXT_NODE&&N.viewNode.textContent.length>0){X=N.viewNode;break}if(N.display&&!/^(inline|ruby)\b/.test(N.display)||((h=N.viewNode)==null?void 0:h.nodeType)===Node.ELEMENT_NODE&&(N.viewNode.localName==="br"||ji[N.viewNode.localName])){E===t.length-1&&p(N.viewNode)&&(D=!0);break}if(E===t.length-1){F=!0,D=!0;for(let R=N.viewNode.nextSibling;R;R=R.nextSibling)if(!p(R)){D=!1;break}}}if(((l=S.parent)==null?void 0:l.display)==="inline-block"){if(!k){let E=S.parent.viewNode.firstChild;for(;Ee(E,S.whitespace);)E=E.nextSibling;S.viewNode===E&&(k=!0)}if(!D){let E=S.parent.viewNode.lastChild;for(;Ee(E,S.whitespace);)E=E.previousSibling;S.viewNode===E&&(D=!0)}}if(this.processTextSpacing(S.viewNode,re,k,_,F,D,U,X,L,A,z,P,S.vertical)>0)break}}}processTextSpacing(e,t,i,n,r,o,s,a,h,l,c,d,p){let f=e.textContent,g=e.ownerDocument,v=0,w,x,m;function S(){if(t)return!0;if(!s)return!1;w||(w=g.createRange(),w.selectNode(e));let E=w.getClientRects()[0];if(!E)return!1;x||(x=g.createRange(),x.selectNode(s));let N=x.getClientRects(),R=N[N.length-1];return R?(v||(v=Rr(R,p)),p?E.top<R.top+R.height-E.width||E.left+E.width<R.left+E.width/10||E.left>R.left+R.width-E.width/10:E.left<R.left+R.width-E.height||E.top>R.top+R.height-E.height/10||E.top+E.height<R.top+E.height/10):!1}function b(){if(!a)return!1;w||(w=g.createRange(),w.selectNode(e));let E=w.getClientRects()[0];if(!E)return!1;v||(v=Rr(E,p)),m||(m=g.createRange(),m.selectNode(a));let N=m.getClientRects()[0];return N?p?E.top+E.height>N.top+E.width||E.left>N.left+N.width-E.width/10||E.left+E.width<N.left+E.width/10:E.left+E.width>N.left+E.height||E.top+E.height<N.top+E.height/10||E.top>N.top+N.height-E.height/10:!1}let C=!1,P=!1,L=!1,A=!1,z=!1,U,X=w0(f,p);if(i&&c.first&&/^[\p{Ps}\p{Pf}\p{Pi}'"\u3000]\p{M}*$/u.test(f)?(U="viv-ts-open",C=!0,L=!0):o&&c.last&&/^[\p{Pe}\p{Pf}\p{Pi}'"]\p{M}*$/u.test(f)?(U="viv-ts-close",C=!0,A=!0):(c.forceEnd||c.allowEnd)&&/^[、。,.、。]\p{M}*$/u.test(f)?(U="viv-ts-close",C=!0,z=!0):(l.trimStart||l.spaceFirst||l.trimAdjacent)&&/^[‘“〝([{⦅〈〈《「『【〔〖〘〚]\p{M}*$/u.test(f)?(U="viv-ts-open",C=!0):(l.trimEnd||l.allowEnd||l.trimAdjacent)&&(/^[’”〞〟)]}⦆〉〉》」』】〕〗〙〛]\p{M}*$/u.test(f)||d==="zh-hans"&&/^[:;]\p{M}*$/u.test(f)||d!=="zh-hant"&&/^[、。,.]\p{M}*$/u.test(f))?(U="viv-ts-close",C=!0):X&&(U=b0(f),C=!0,P=!0),C){let E=function(q){let Q=parseFloat(g.defaultView.getComputedStyle(q).fontSize)*.7;return(p?q.offsetHeight:q.offsetWidth)>Q},N=function(){return p?R.offsetLeft:R.offsetTop};var re=E,k=N;if(e.parentElement.localName==="viv-ts-inner")return 0;let R=g.createElement(U),$=g.createElement("viv-ts-inner");if(R.appendChild($),e.parentNode.insertBefore(R,e),$.appendChild(e),X&&g.defaultView.getComputedStyle($.parentElement).textOrientation==="mixed"&&($.style.textOrientation="sideways"),P)return 0;let V=E($);if(V||L||A||z){if(U==="viv-ts-open"){if(L)R.className="viv-hang-first";else if(i||n)l.trimStart?R.className="viv-ts-trim":R.className="viv-ts-space";else if(!(l.trimStart||l.spaceFirst)&&S())R.className="viv-ts-space";else if(l.trimAdjacent&&s&&/[\p{Ps}\p{Pi}\p{Pe}\p{Pf}\u00B7\u2027\u30FB\u3000:;、。,.]\p{M}*$/u.test(s.textContent)&&(!/[\p{Pe}\p{Pf}]\p{M}*$/u.test(s.textContent)||s.parentElement.localName==="viv-ts-inner"&&E(s.parentElement)))R.className="viv-ts-trim";else if((l.trimStart||l.spaceFirst)&&S()){let q=N();R.className="viv-ts-auto",q===N()&&!S()&&(R.className="viv-ts-trim")}}else if(U==="viv-ts-close"){if(A)R.className=V?"viv-hang-last":"viv-hang-last viv-hang-hw";else if(o||r){let q=N();z?(R.className=V?c.allowEnd&&l.allowEnd?"viv-ts-auto":"viv-hang-end":"viv-hang-end viv-hang-hw",c.allowEnd&&q===N()&&(l.trimEnd?R.className="viv-ts-trim":l.allowEnd?(R.className="viv-hang-end",q===N()&&(R.className="")):R.className="viv-ts-space")):l.trimEnd?R.className="viv-ts-trim":l.allowEnd?(R.className="viv-ts-auto",q===N()&&(R.className="")):R.className="viv-ts-space"}else if(a&&/^[\p{Pe}\p{Pf}\u00B7\u2027\u30FB\u3000:;、。,.]/u.test(a.textContent))V&&l.trimAdjacent&&(R.className="viv-ts-trim");else if(z){let q=b(),Q=q&&c.allowEnd;Q||(R.className=V?"viv-hang-end":"viv-hang-end viv-hang-hw"),V?Q&&l.trimEnd?R.className="viv-ts-auto":!Q&&!b()?R.className="":!q&&c.allowEnd&&(l.trimEnd?(R.className="viv-ts-auto",b()||(R.className="viv-hang-end")):(R.className="viv-ts-space",b()||(l.allowEnd?(R.className="viv-ts-auto",b()||(R.className="viv-hang-end")):R.className="viv-hang-end"))):!q&&!b()&&(R.className="")}else if(l.trimEnd||l.allowEnd)if(b())l.allowEnd?R.className="viv-ts-space":R.className="viv-ts-auto";else{let q=N();R.className="viv-ts-auto",q===N()&&(R.className="")}}}}let _=!1;function F(E){var N;let R=(N=E?.ownerDocument.defaultView)==null?void 0:N.getComputedStyle(E);return!!R&&(R.textOrientation==="upright"||R.textCombineUpright==="all"||R["-webkit-text-combine"]==="horizontal")}function D(E,N){if(E.nodeType===Node.ELEMENT_NODE){let V=g.defaultView.getComputedStyle(E);if(parseFloat(V.marginInlineEnd)||parseFloat(V.borderInlineEndWidth)||parseFloat(V.paddingInlineEnd))return!0}let R=E.parentElement;if(R&&!R.contains(N))return D(R,N);if(N.nodeType===Node.ELEMENT_NODE){let V=g.defaultView.getComputedStyle(N);if(parseFloat(V.marginInlineStart)||parseFloat(V.borderInlineStartWidth)||parseFloat(V.paddingInlineStart))return!0}let $=N.parentElement;return $&&!$.contains(E)?D(E,$):!1}return(h.ideographAlpha||h.ideographNumeric)&&(s&&/^(?!\p{P})[\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF]/u.test(f)&&(h.ideographAlpha&&/(?![\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF\uFF01-\uFF60])\p{L}\p{M}*$/u.test(s.textContent)||h.ideographNumeric&&/(?![\uFF01-\uFF60])\p{Nd}\p{M}*$/u.test(s.textContent))&&!(p&&F(s.parentElement))&&!D(s,e)&&(e.parentNode.insertBefore(g.createElement("viv-ts-thin-sp"),e),_=!0),a&&/(?!\p{P})[\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF]\p{M}*$/u.test(f)&&(h.ideographAlpha&&/^(?![\p{sc=Han}\u3041-\u30FF\u31C0-\u31FF\uFF01-\uFF60])\p{L}/u.test(a.textContent)||h.ideographNumeric&&/^(?![\uFF01-\uFF60])\p{Nd}/u.test(a.textContent))&&!(p&&F(a.parentElement))&&!D(e,a)&&(e.parentNode.insertBefore(g.createElement("viv-ts-thin-sp"),e.nextSibling),_=!0)),v}registerHooks(){Ft("POLYFILLED_INHERITED_PROPS",this.getPolyfilledInheritedProps.bind(this)),Ft("PREPROCESS_SINGLE_DOCUMENT",this.preprocessSingleDocument.bind(this)),Ft("POST_LAYOUT_BLOCK",this.postLayoutBlock.bind(this),!0)}},lh=new x0;lh.registerHooks();function S0(e){lh.preprocessForTextSpacing(e)}function C0(e,t,i,n,r,o){lh.processGeneratedContent(e,t,i,n,r,o)}var pr=new DOMParser().parseFromString('<root xmlns="http://www.pyroxy.com/ns/shadow"/>',"text/xml"),k0=["footnote-marker","marker","first-5-lines","first-4-lines","first-3-lines","first-2-lines","first-line","first-letter","before","footnote-call","","after"],hh="data-adapt-pseudo";function Yt(e){return e.getAttribute(hh)||""}function Er(e,t){e.setAttribute(hh,t)}var ma=class{constructor(e,t,i,n,r){u(this,"element",e),u(this,"style",t),u(this,"styler",i),u(this,"context",n),u(this,"exprContentListener",r),u(this,"contentProcessed",{})}getStyle(e,t){let i=Yt(e);this.styler&&i&&i.match(/after$/)&&(this.style=this.styler.getStyle(this.element,!0),this.styler=null);let n=ft(this.style,"_pseudos"),r=n?.[i]||{};if(i.match(/^first-/)&&!r["x-first-pseudo"]){let o=1,s;i=="first-letter"?o=0:(s=i.match(/^first-([0-9]+)-lines$/))!=null&&(o=s[1]-0),r["x-first-pseudo"]=new W(new lt(o),0)}return r}processContent(e,t,i){let n=Yt(e);if(!this.contentProcessed[n]){this.contentProcessed[n]=!0;let r=t.content;It(r)&&(r.visit(new Lr(e,this.context,r,this.exprContentListener)),S0(e))}}},lC=ls.isInstanceOfAfterIfContinuesLayoutConstraint,E0=$s.registerFragmentIndex,hC=$s.clearFragmentIndices,P0=class{constructor(e,t){u(this,"sourceNode",e),u(this,"styler",t)}createElement(e,t){let i=t.viewNode.ownerDocument.createElement("div"),n=new uh(e,i,t),r=n.getColumn().pageBreakType;return n.getColumn().pageBreakType=null,n.layout(this.createNodePositionForPseudoElement(),!0).thenAsync(()=>{this.styler.contentProcessed["after-if-continues"]=!1,n.getColumn().pageBreakType=r;let o=i.firstChild;return I(o,"display","block"),T(o)})}createNodePositionForPseudoElement(){let e=pr.createElementNS("http://www.w3.org/1999/xhtml","div");Er(e,"after-if-continues");let t=this.createShadowContext(e),i={steps:[{node:e,shadowType:t.type,shadowContext:t,nodeShadow:null,shadowSibling:null}],offsetInNode:0,after:!1,preprocessedTextContent:null};return new Bi(i)}createShadowContext(e){return new Bo(this.sourceNode,e,null,null,null,yi.ShadowType.ROOTED,this.styler)}},N0=class Af{constructor(t,i,n){u(this,"nodeContext",t),u(this,"afterIfContinues",i),u(this,"pseudoElementHeight",n),u(this,"flagmentLayoutConstraintType","AfterIfContinue")}allowLayout(t,i,n){return!(i&&!t||t&&t.overflow)}nextCandidate(t){return!1}postLayout(t,i,n,r){}finishBreak(t,i){return this.getRepetitiveElements().affectTo(t)?this.afterIfContinues.createElement(i,this.nodeContext).thenAsync(n=>(this.nodeContext.viewNode.appendChild(n),T(!0))):T(!0)}getRepetitiveElements(){return new T0(this.nodeContext,this.pseudoElementHeight)}equalsTo(t){return t instanceof Af?this.afterIfContinues==t.afterIfContinues:!1}getPriorityOfFinishBreak(){return 9}},T0=class{constructor(e,t){u(this,"nodeContext",e),u(this,"pseudoElementHeight",t)}calculateOffset(e){return this.affectTo(e)?this.pseudoElementHeight:0}calculateMinimumOffset(e){return this.calculateOffset(e)}affectTo(e){if(!e)return!1;let t=e.shadowContext?e.shadowContext.owner:e.sourceNode;if(t===this.nodeContext.sourceNode)return!!e.after;for(let i=t.parentNode;i;i=i.parentNode)if(i===this.nodeContext.sourceNode)return!0;return!1}};function If(e,t){if(!e||!e.afterIfContinues||e.after||t.isFloatNodeContext(e))return T(e);let i=e.afterIfContinues;return i.createElement(t,e).thenAsync(n=>{let r=I0(e,t,n);return t.fragmentLayoutConstraints.push(new N0(e,i,r)),T(e)})}function Ff(e,t){return e.thenAsync(i=>If(i,t))}function A0(e,t){let i=M("processAfterIfContinuesOfAncestors"),n=e;return i.loop(()=>{if(n!==null){let r=If(n,t);return n=n.parent,r.thenReturn(!0)}else return T(!1)}).then(()=>{i.finish(!0)}),i.result()}function I0(e,t,i){let n=e.viewNode;n.appendChild(i);let r=_a(i,t,e.vertical);return n.removeChild(i),r}var F0=class{constructor(e){u(this,"constraints",e)}allowLayout(e){return this.constraints.every(t=>t.allowLayout(e))}},fr=class extends Gl{constructor(e,t){super(),u(this,"checkPoints",e),u(this,"penalty",t),u(this,"alreadyEvaluated",!1),u(this,"breakNodeContext",null)}findAcceptableBreak(e,t){return t<this.getMinBreakPenalty()?null:(this.alreadyEvaluated||(this.breakNodeContext=e.findBoxBreakPosition(this,t>0),this.alreadyEvaluated=!!this.breakNodeContext||t>0||!!e.pseudoParent),this.breakNodeContext)}getMinBreakPenalty(){return this.penalty}getNodeContext(){return this.alreadyEvaluated?this.breakNodeContext:this.checkPoints[this.checkPoints.length-1]}},Cs=class extends lp{constructor(e,t,i,n,r){super(e),u(this,"layoutContext",t),u(this,"clientLayout",i),u(this,"layoutConstraint",n),u(this,"pageFloatLayoutContext",r),u(this,"last"),u(this,"viewDocument"),u(this,"flowRootFormattingContext",null),u(this,"isNonFirstColumn",!1),u(this,"isFloat",!1),u(this,"isFootnote",!1),u(this,"startEdge",0),u(this,"endEdge",0),u(this,"beforeEdge",0),u(this,"afterEdge",0),u(this,"footnoteEdge",0),u(this,"box",null),u(this,"chunkPositions",null),u(this,"bands",null),u(this,"overflown",!1),u(this,"breakPositions",null),u(this,"pageBreakType",null),u(this,"forceNonfitting",!0),u(this,"leftFloatEdge",0),u(this,"rightFloatEdge",0),u(this,"bottommostFloatTop",0),u(this,"stopAtOverflow",!0),u(this,"lastAfterPosition",null),u(this,"fragmentLayoutConstraints",[]),u(this,"pseudoParent",null),u(this,"nodeContextOverflowingDueToRepetitiveElements",null),u(this,"blockDistanceToBlockEndFloats",NaN),u(this,"lastLineStride",0),u(this,"breakAtTheEdgeBeforeFloat",null),u(this,"lineFootnoteOverflowEdge",null),pv(this),this.last=e.lastChild,this.viewDocument=e.ownerDocument,r.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}almostEquals(e,t,i=this.clientLayout.pixelRatio===0?.5:1.5/(this.clientLayout.pixelRatio||1)){return Math.abs(e-t)<i}getFloatLayoutUnit(){return this.clientLayout.pixelRatio===0?0:1/(this.clientLayout.pixelRatio||1)}getFloatLayoutTolerance(e){return e||1}isOverflown(e){let t=1.5/(this.clientLayout.pixelRatio||1);return this.almostEquals(e,this.footnoteEdge,t)?!1:this.vertical?e<this.footnoteEdge:e>this.footnoteEdge}getExclusions(){let e=this.pageFloatLayoutContext.getFloatFragmentExclusions();return this.exclusions.concat(e)}openAllViews(e){let t=M("openAllViews"),i=e.steps;this.layoutContext.setViewRoot(this.element,this.isFootnote);let n=i.length-1,r=null;return t.loop(()=>{for(;n>=0;){let o=r,s=i[n];if(r=us(s,o),n===i.length-1&&!r.formattingContext&&(r.formattingContext=this.flowRootFormattingContext),n==0&&(r.offsetInNode=this.calculateOffsetInNodeForNodeContext(e),r.after=e.after,r.preprocessedTextContent=e.preprocessedTextContent,r.after))break;let a=this.layoutContext.setCurrent(r,n==0&&r.offsetInNode==0);if(n--,a.isPending())return a}return T(!1)}).then(()=>{t.finish(r)}),t.result()}calculateOffsetInNodeForNodeContext(e){return e.preprocessedTextContent?Iv(e.preprocessedTextContent,e.offsetInNode):e.offsetInNode}maybePeelOff(e,t){var i,n;if(e.firstPseudo&&e.inline&&!e.after&&e.firstPseudo.count==0&&e.viewNode.nodeType!=1){let r=e.viewNode.textContent,o=r.match(Jo),s=o?o[0].length:0;if(!o&&((i=e.sourceNode)==null?void 0:i.nodeType)===3&&((n=e.sourceNode.nextSibling)==null?void 0:n.nodeType)===3&&r===e.sourceNode.textContent){let a=r+e.sourceNode.nextSibling.textContent,h=a.match(Jo);if(h){let l=h[0];s=l.length,e.sourceNode.textContent=l,e.viewNode.textContent=l,e.sourceNode.nextSibling.textContent=a.substr(s)}}return this.layoutContext.peelOff(e,s)}return T(e)}buildViewToNextBlockEdge(e,t){let i=!1,n=M("buildViewToNextBlockEdge");return n.loopWithFrame(r=>{var o;if(e.viewNode&&!Pn(e)&&((o=e.viewNode.parentElement)==null?void 0:o.namespaceURI)==="http://www.w3.org/1999/xhtml"&&(t.push(e.copy()),t.length>1e3)){let s=e.viewNode.nodeType===1?e.viewNode:e.viewNode.parentElement,a=this.clientLayout.getElementClientRect(s);if(Rr(a,this.vertical)>=2){r.breakLoop();return}}this.maybePeelOff(e,0).then(s=>{let a=s;a!==e&&(e=a,Pn(e)||t.push(e.copy())),this.nextInTree(e).then(h=>{if(e=h,!e){r.breakLoop();return}(i||!this.layoutConstraint.allowLayout(e))&&(i=!0,e=e.modify(),e.overflow=!0),this.isFloatNodeContext(e)&&(Ii(e.floatReference)||e.floatSide==="footnote")?this.layoutFloatOrFootnote(e).then(l=>{if(e=l,this.pageFloatLayoutContext.isInvalidated()&&(e=null),!e){r.breakLoop();return}if(e.pluginProps.lineFootnoteOverflow){r.breakLoop();return}r.continueLoop()}):e.inline?r.continueLoop():r.breakLoop()})})}).then(()=>{n.finish(e)}),n.result()}nextInTree(e,t){let i=this.layoutContext.nextInTree(e,t);return Ff(i,this)}buildDeepElementView(e){if(!e.viewNode)return T(e);let t=[],i=e.sourceNode,n=M("buildDeepElementView");return n.loopWithFrame(r=>{e.viewNode&&e.inline&&!Pn(e)?t.push(e.copy()):(t.length>0&&this.postLayoutBlock(e,t),t=[]),this.maybePeelOff(e,0).then(o=>{let s=o;if(s!==e){let a=s;for(;a&&a.sourceNode!=i;)a=a.parent;if(a==null){e=s,r.breakLoop();return}Pn(s)||t.push(s.copy())}this.nextInTree(s).then(a=>{if(e=a,!e||e.sourceNode==i){r.breakLoop();return}if(!this.layoutConstraint.allowLayout(e)&&(e=e.modify(),e.overflow=!0,this.stopAtOverflow)){r.breakLoop();return}if(this.isFloatNodeContext(e)&&(Ii(e.floatReference)||e.floatSide==="footnote")){this.layoutFloatOrFootnote(e).then(h=>{if(e=h,this.pageFloatLayoutContext.isInvalidated()&&(e=null),!e){r.breakLoop();return}r.continueLoop()});return}r.continueLoop()})})}).then(()=>{t.length>0&&this.postLayoutBlock(e,t),n.finish(e)}),n.result()}createFloat(e,t,i,n){let r=this.viewDocument.createElement("div");return this.vertical?(n>=this.height&&(n-=.1),n<1&&(n=0),I(r,"height",`${i}px`),I(r,"width",`${n}px`)):(i>=this.width&&(i-=.1),i<1&&(i=0),I(r,"width",`${i}px`),I(r,"height",`${n}px`)),I(r,"float",t),I(r,"clear",t),this.element.insertBefore(r,e),r}killFloats(){let e=this.element.firstChild;for(;e;){let t=e.nextSibling;if(e.nodeType==1){let i=e,n=i.style.cssFloat;if(n=="left"||n=="right"||n==="none")this.element.removeChild(i);else break}e=t}}createFloats(){let e=this.element.firstChild,t=this.bands,i=this.vertical?this.getTopEdge():this.getLeftEdge(),n=this.vertical?this.getBottomEdge():this.getRightEdge(),r=this.vertical?-this.getRightEdge():this.getTopEdge(),o=this.vertical?-this.getLeftEdge():this.getBottomEdge(),s=null,a=1.5/(this.clientLayout.pixelRatio||1);for(let p of t){let f=Math.abs(p.x1-i)<a&&Math.abs(p.x2-n)<a?a:void 0;this.almostEquals(p.x1,i,f)?p.x1=i:this.almostEquals(p.x1,n,f)&&(p.x1=n),this.almostEquals(p.x2,n,f)?p.x2=n:this.almostEquals(p.x2,i,f)&&(p.x2=i),this.almostEquals(p.y1,r,f)?p.y1=r:this.almostEquals(p.y1,o,f)&&(p.y1=o),this.almostEquals(p.y2,o,f)?p.y2=o:this.almostEquals(p.y2,r,f)&&(p.y2=r)}let h=this.getFloatLayoutUnit(),l=Gr==="webkit"?Math.floor:Math.round,c=t.map(p=>h>0?(l(p.y2/h)-l(p.y1/h))*h:p.y2-p.y1),d=.01;for(let p=0;p<t.length;p++){let f=p<t.length-1?t[p+1].x1:i,g=p<t.length-1?t[p+1].x2:n,v=f-t[p].x1,w=t[p].x2-g,x=0,m=0;v>d?x=1:v<-d&&(x=-1),w>d?m=1:w<-d&&(m=-1);let S=x!==0&&m!==0?x===m?x:0:x||m;if(h>0&&S!==0){let b=S*h;c[p]+b>=0&&(p>=t.length-1||c[p+1]-b>=0)&&(c[p]+=b,p<t.length-1&&(c[p+1]-=b))}}for(let p=0;p<t.length;p++){let f=t[p];f.left=this.createFloat(e,"left",f.x1-i,c[p]),f.right=this.createFloat(e,"right",n-f.x2,c[p]),f.x1<n&&f.x2>i?s=f:s||I(f.right,"float","none")}if(s){let p=t[t.length-1],f=1.5/(this.clientLayout.pixelRatio||1);if(s!==p&&(p.y2>=o||this.almostEquals(p.y2,o,f))&&(this.footnoteEdge=this.vertical?-s.y2:s.y2,s.x1===i&&s.x2===n))for(let g=t.indexOf(s);g<t.length;g++){let v=t[g];this.element.removeChild(v.left),this.element.removeChild(v.right),v.left=null,v.right=null}}this.adjustColumnBlockSizeForBlockEndFloats()}adjustColumnBlockSizeForBlockEndFloats(){var e;if(this.element.hasAttribute("data-vivliostyle-in-column-balancing")||(e=this.element.parentElement)!=null&&e.hasAttribute("data-vivliostyle-in-column-balancing"))return;let t=this.vertical?this.width:this.height,i=this.getBoxDir()*(this.footnoteEdge-this.beforeEdge),n=1.5/(this.clientLayout.pixelRatio||1);if(i>0&&i<t&&!this.almostEquals(i,t,n)){let r=this.vertical?"width":"height";if(I(this.element,r,`${i}px`),this.vertical){let o=this.left+(t-i);I(this.element,"left",`${o}px`)}this.element.setAttribute("data-vivliostyle-column-block-size-adjusted","true")}}calculateEdge(e,t,i,n){let r;if(e&&En(e.viewNode))return NaN;if(e&&e.after&&!e.inline&&(r=bn(e,this.clientLayout,0,this.vertical),!isNaN(r)))return r;e=t[i];let o=n-e.boxOffset;for(;;){if(r=bn(e,this.clientLayout,o,this.vertical),!isNaN(r))return r;if(o>0){o--;continue}if(i--,i<0)return this.beforeEdge;e=t[i],e.viewNode.nodeType!=1&&(o=e.viewNode.textContent.length)}}parseComputedLength(e){let t=e.match(/^(-?[0-9]*(\.[0-9]*)?)px$/);return t?this.clientLayout.adjustLengthValue(parseFloat(t[0])):0}getComputedMargin(e){let t=this.clientLayout.getElementComputedStyle(e),i=new ta(0,0,0,0);return t&&(i.left=this.parseComputedLength(t.marginLeft),i.top=this.parseComputedLength(t.marginTop),i.right=this.parseComputedLength(t.marginRight),i.bottom=this.parseComputedLength(t.marginBottom)),i}getComputedPaddingBorder(e){let t=this.clientLayout.getElementComputedStyle(e),i=new ta(0,0,0,0);return t&&(i.left=this.parseComputedLength(t.borderLeftWidth)+this.parseComputedLength(t.paddingLeft),i.top=this.parseComputedLength(t.borderTopWidth)+this.parseComputedLength(t.paddingTop),i.right=this.parseComputedLength(t.borderRightWidth)+this.parseComputedLength(t.paddingRight),i.bottom=this.parseComputedLength(t.borderBottomWidth)+this.parseComputedLength(t.paddingBottom)),i}getComputedInsets(e){let t=this.clientLayout.getElementComputedStyle(e),i=new ta(0,0,0,0);if(t){if(t.boxSizing=="border-box")return this.getComputedMargin(e);i.left=this.parseComputedLength(t.marginLeft)+this.parseComputedLength(t.borderLeftWidth)+this.parseComputedLength(t.paddingLeft),i.top=this.parseComputedLength(t.marginTop)+this.parseComputedLength(t.borderTopWidth)+this.parseComputedLength(t.paddingTop),i.right=this.parseComputedLength(t.marginRight)+this.parseComputedLength(t.borderRightWidth)+this.parseComputedLength(t.paddingRight),i.bottom=this.parseComputedLength(t.marginBottom)+this.parseComputedLength(t.borderBottomWidth)+this.parseComputedLength(t.paddingBottom)}return i}setComputedInsets(e,t){let i=this.clientLayout.getElementComputedStyle(e);i&&(t.marginLeft=this.parseComputedLength(i.marginLeft),t.borderLeft=this.parseComputedLength(i.borderLeftWidth),t.paddingLeft=this.parseComputedLength(i.paddingLeft),t.marginTop=this.parseComputedLength(i.marginTop),t.borderTop=this.parseComputedLength(i.borderTopWidth),t.paddingTop=this.parseComputedLength(i.paddingTop),t.marginRight=this.parseComputedLength(i.marginRight),t.borderRight=this.parseComputedLength(i.borderRightWidth),t.paddingRight=this.parseComputedLength(i.paddingRight),t.marginBottom=this.parseComputedLength(i.marginBottom),t.borderBottom=this.parseComputedLength(i.borderBottomWidth),t.paddingBottom=this.parseComputedLength(i.paddingBottom))}setComputedWidthAndHeight(e,t){let i=this.clientLayout.getElementComputedStyle(e);i&&(t.width=this.parseComputedLength(i.width),t.height=this.parseComputedLength(i.height))}layoutUnbreakable(e){return this.buildDeepElementView(e)}layoutFloat(e){let t=M("layoutFloat"),i=e.viewNode,n=aa(e.floatSide,e.vertical,e.direction,this.layoutContext.page.side);return I(i,"float","none"),I(i,"display","inline-block"),I(i,"vertical-align","top"),this.buildDeepElementView(e).then(r=>{let o=Bt(this.clientLayout,i,this.vertical),s=this.getComputedMargin(i),a=new Mt(o.left-s.left,o.top-s.top,o.right+s.right,o.bottom+s.bottom),h=this.rtl?this.endEdge:this.startEdge,l=this.rtl?this.startEdge:this.endEdge,c=e.parent;for(;c&&c.inline;)c=c.parent;if(c){let b=c.viewNode.ownerDocument.createElement("div");b.style.left="0px",b.style.top="0px",this.vertical?(b.style.bottom="0px",b.style.width="1px"):(b.style.right="0px",b.style.height="1px"),c.viewNode.appendChild(b);let C=Bt(this.clientLayout,b,this.vertical);h=Math.max(this.rtl?this.getEndEdge(C):this.getStartEdge(C),h),l=Math.min(this.rtl?this.getStartEdge(C):this.getEndEdge(C),l),c.viewNode.removeChild(b);let P=this.vertical?a.y2-a.y1:a.x2-a.x1;n=="left"?l=Math.max(l,h+P):h=Math.min(h,l-P),c!==e.parent&&!e.firstPseudo&&(c.viewNode.appendChild(i),i.setAttribute("data-vivliostyle-float-box-moved","true"))}let d=new Mt(h,this.getBoxDir()*this.beforeEdge,l,this.getBoxDir()*this.afterEdge),p=a;this.vertical&&(p=ns(a));let f=this.getBoxDir();if(p.y1<this.bottommostFloatTop*f){let b=p.y2-p.y1;p.y1=this.bottommostFloatTop*f,p.y2=p.y1+b}if(e.clearSide){let b=/^(top|bottom|inside|outside|(block|inline)-(start|end))$/.test(e.clearSide)?aa(e.clearSide,e.vertical,e.direction,this.layoutContext.page.side):e.clearSide==="same"?n:e.clearSide,C=this.beforeEdge;b!=="right"&&(C=f*Math.max(C*f,this.leftFloatEdge*f)),b!=="left"&&(C=f*Math.max(C*f,this.rightFloatEdge*f));let P=C*f;if(p.y1<P){let L=p.y2-p.y1;p.y1=P,p.y2=p.y1+L}}d.y2+=this.getFloatLayoutUnit(),zm(d,this.bands,p,n),this.vertical&&(a=od(p));let g=this.getComputedInsets(i);I(i,"width",`${a.x2-a.x1-g.left-g.right}px`),I(i,"height",`${a.y2-a.y1-g.top-g.bottom}px`),I(i,"position","absolute"),e.display,I(i,"display",e.display);let v,w=null;if(c&&(c.containingBlockForAbsolute?w=c:w=c.getContainingBlockForAbsolute()),w){let b=w.viewNode.ownerDocument.createElement("div");b.style.position="absolute",w.vertical?b.style.right="0":b.style.left="0",b.style.top="0",w.viewNode.appendChild(b),v=Bt(this.clientLayout,b,this.vertical),w.viewNode.removeChild(b)}else v={left:this.getLeftEdge()-this.paddingLeft,right:this.getRightEdge()+this.paddingRight,top:this.getTopEdge()-this.paddingTop};if(w?w.vertical:this.vertical){let b=Math.max(0,v.right-a.x2);I(i,"right",`${b}px`)}else{let b=Math.max(0,a.x1-v.left);I(i,"left",`${b}px`)}let x=Math.max(0,a.y1-v.top);I(i,"top",`${x}px`),e.clearSpacer&&(e.clearSpacer.parentNode.removeChild(e.clearSpacer),e.clearSpacer=null);let m=this.vertical?a.x1:a.y2,S=this.vertical?a.x2:a.y1;!this.isOverflown(m)||this.breakPositions.length==0?(this.killFloats(),d=new Mt(this.getLeftEdge(),this.getTopEdge(),this.getRightEdge(),this.getBottomEdge()),this.vertical&&(d=ns(d)),Vm(d,this.bands,p,null,n),this.createFloats(),n=="left"?this.leftFloatEdge=m:this.rightFloatEdge=m,this.bottommostFloatTop=S,this.updateMaxReachedAfterEdge(m),t.finish(r)):(e=e.modify(),e.overflow=!0,t.finish(e))}),t.result()}setupFloatArea(e,t,i,n,r,o){let s=this.pageFloatLayoutContext,a=s.getContainer(t),h=e.element;a.element.parentNode.appendChild(h),e.isFloat=!0,e.originX=a.originX,e.originY=a.originY,e.vertical=a.vertical,e.rtl=a.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=(a.exclusions||[]).concat(),e.forceNonfitting=!s.hasFloatFragments(),e.innerShape=null;let l=a.getPaddingRect();return e.setHorizontalPosition(l.x1-a.originX,l.x2-l.x1),e.setVerticalPosition(l.y1-a.originY,l.y2-l.y1),r.adjustPageFloatArea(e,a,this).thenAsync(()=>{e.init();let c=!!s.setFloatAreaDimensions(e,t,i,n,!0,e.isFootnote||!s.hasFloatFragments(),o);if(c){if(e.isFootnote){let d=getComputedStyle(e.element);if(e.vertical){let p=parseFloat(d.maxWidth);!isNaN(p)&&e.width>p&&(e.width=p,I(e.element,"width",`${p}px`))}else{let p=parseFloat(d.maxHeight);!isNaN(p)&&e.height>p&&(e.height=p,I(e.element,"height",`${p}px`))}}e.killFloats(),e.init()}else a.element.parentNode.removeChild(h);return T(c)})}createPageFloatArea(e,t,i,n,r){let o=this.element.ownerDocument.createElement("div");I(o,"position","absolute");let s=this.pageFloatLayoutContext.getPageFloatLayoutContext(e.floatReference),a=new Sn(null,Pe.COLUMN,null,this.pageFloatLayoutContext.flowName,e.nodePosition,null,null);a.setOuterContext(this.pageFloatLayoutContext);let h=s.getContainer(),l=new O0(t,o,this.layoutContext.clone(),this.clientLayout,this.layoutConstraint,a,h);return a.setContainer(l),this.setupFloatArea(l,e.floatReference,t,i,n,r).thenAsync(c=>T(c?l:null))}layoutSinglePageFloatFragment(e,t,i,n,r,o,s){let a=this.pageFloatLayoutContext;e=(s?s.continuations:[]).concat(e);let h=e[0].float,l=a.getPageFloatPlacementCondition(h,t,i),c={floatArea:null,pageFloatFragment:null,newPosition:null},d=M("layoutSinglePageFloatFragment");return this.createPageFloatArea(h,t,o,r,l).then(p=>{if(c.floatArea=p,!p){d.finish(c);return}let f=!1,g=0;d.loopWithFrame(v=>{if(g>=e.length){v.breakLoop();return}let w=e[g],x=new Bi(w.nodePosition),m=p.getRootViewNodeCount();p.layout(x,!0).then(S=>{if(c.newPosition=S,!S||n){if(S&&p.isFootnote&&p.breakPositions&&!(p.breakPositions.some(b=>b instanceof fr)&&p.hasNonPseudoTextContentAfter(m))){f=!0,v.breakLoop();return}g++,v.continueLoop()}else f=!0,v.breakLoop()})}).then(()=>{if(!f&&p.isFootnote&&p.computedBlockSize<=0&&c.newPosition){let v=a.getPageFloatLayoutContext(h.floatReference);if(v.footnoteMaxBlockSize==null){if(v.initFootnoteRetryFromEmptyFragment(h,p)){p.element.parentNode&&p.element.parentNode.removeChild(p.element),this.layoutSinglePageFloatFragment(e,t,i,n,r,o,s).then(w=>{d.finish(w)});return}f=!0}}if(!f){p.isFootnote&&p.applyCompactFootnoteDisplay();let v=a.setFloatAreaDimensions(p,h.floatReference,t,o,!1,n,l);if(!v)f=!0;else{let w=r.createPageFloatFragment(e,v,i,p,!!c.newPosition);a.addPageFloatFragment(w,!0),c.pageFloatFragment=w}}d.finish(c)})}),d.result()}layoutPageFloatInner(e,t,i,n){let r=this.pageFloatLayoutContext,o=e.float,s=o instanceof Or,a=s&&o.footnotePolicy===y.line&&!!n&&!n.hasFloat(o),h=new Set;for(let d=r;d;d=d.effectiveParent)for(let p of d.floatFragments)p.continuations.some(f=>f.float.insidePageFloatArea)&&h.add(p);a||r.stashEndFloatFragments(o);function l(d,p){p?r.removePageFloatFragment(p,!0):d&&d.element.parentNode.removeChild(d.element);let f=[];for(let g=r;g;g=g.effectiveParent)for(let v of g.floatFragments)!h.has(v)&&v.continuations.some(w=>w.float.insidePageFloatArea)&&f.push(v);for(let g of f)r.removePageFloatFragment(g,!0);r.restoreStashedFragments(o.floatReference),r.deferPageFloat(e)}let c=M("layoutPageFloatInner");return this.layoutSinglePageFloatFragment([e],o.floatSide,o.clearSide,s||!r.hasFloatFragments(),t,i,a?null:n).then(d=>{let p=d.floatArea,f=d.pageFloatFragment,g=d.newPosition;f?this.layoutStashedPageFloats(o.floatReference,[n]).then(v=>{if(v){let w=f;if(a&&n){let b=n.area,C=b.getRootViewNodeCount();if(b.appendContentFrom(f.area),r.removePageFloatFragment(f,!0),!r.setFloatAreaDimensions(b,o.floatReference,n.floatSide,i,!1,!0,r.getPageFloatPlacementCondition(o,o.floatSide,o.clearSide))){b.removeContentAfter(C),l(p,f),c.finish(!1);return}n.addContinuations(f.continuations),w=n}let x=!!r.generatingNodePosition,m=!x&&o instanceof Or&&o.footnotePolicy===y.line,S=m&&r.hasInvalidatedForLineFootnote(o);if(r.addPageFloatFragment(w,x||S),m&&!S&&r.markInvalidatedForLineFootnote(o),r.discardStashedFragments(o.floatReference),g){let b=new uu(o,g.primary);r.deferPageFloat(b)}c.finish(!0)}else l(p,f),c.finish(!1)}):(l(p,f),c.finish(!1))}),c.result()}layoutStashedPageFloats(e,t){let i=this.pageFloatLayoutContext,n=i.getStashedFloatFragments(e),r=[],o=[],s=!1,a=M("layoutStashedPageFloats"),h=0;return a.loopWithFrame(l=>{if(h>=n.length){l.breakLoop();return}let c=n[h];if(t.includes(c)){h++,l.continueLoop();return}let d=new Vn().findByFloat(c.continuations[0].float);this.layoutSinglePageFloatFragment(c.continuations,c.floatSide,c.clearSide,!1,d,null).then(p=>{let f=p.floatArea;f&&r.push(f);let g=p.pageFloatFragment;g?(o.push(g),h++,l.continueLoop()):(s=!0,l.breakLoop())})}).then(()=>{s?(o.forEach(l=>{i.removePageFloatFragment(l,!0)}),r.forEach(l=>{let c=l.element;c&&c.parentNode&&c.parentNode.removeChild(c)})):n.forEach(l=>{let c=l.area.element;c&&c.parentNode&&c.parentNode.removeChild(c)}),a.finish(!s)}),a.result()}findFootnoteCallElement(e){let t=e.previousSibling;for(;t;){if(t.nodeType===Node.ELEMENT_NODE&&Yt(t)==="footnote-call")return t;t=t.previousSibling}return null}setFloatAnchorViewNode(e){let t=e.viewNode.parentNode,i=t.ownerDocument.createElement("span");if(i.setAttribute(zn,"1"),e.floatSide==="footnote"){let r=this.findFootnoteCallElement(e.viewNode);r?i=r:t.insertBefore(i,e.viewNode)}else t.appendChild(i);t.removeChild(e.viewNode);let n=e.modify();return n.after=!0,n.viewNode=i,e.floatSide==="footnote"&&(n.display="inline"),n}resolveFloatReferenceFromColumnSpan(e,t,i){let n=M("resolveFloatReferenceFromColumnSpan"),r=this.pageFloatLayoutContext,o=r.getPageFloatLayoutContext(Pe.REGION);return r.getContainer().width<o.getContainer().width&&e===Pe.COLUMN?t===y.auto?this.buildDeepElementView(i.copy()).then(s=>{let a=s.viewNode,h=Vl(this.clientLayout,a,["min-content inline size"])["min-content inline size"],l=this.getComputedMargin(a);this.vertical?h+=l.top+l.bottom:h+=l.left+l.right,h>this.width?n.finish(Pe.REGION):n.finish(e)}):t===y.all?n.finish(Pe.REGION):n.finish(e):n.finish(e),n.result()}layoutPageFloat(e){let t=this.pageFloatLayoutContext,i=new Vn().findByNodeContext(e),n,r=t.findPageFloatByNodePosition(e.toNodePosition());return r?n=T(r):n=i.createPageFloat(e,t,this),n.thenAsync(o=>{let s=hs(e,0),a=this.setFloatAnchorViewNode(e);t.markPageFloatAnchorSeen(o);let h=i.findPageFloatFragment(o,t),l=new uu(o,s);if(h&&h.hasFloat(o))return t.registerPageFloatAnchor(o,a.viewNode),T(a);if(t.isForbidden(o)||t.hasPrecedingFloatsDeferredToNext(o))return t.deferPageFloat(l),t.registerPageFloatAnchor(o,a.viewNode),T(a);if(this.nodeContextOverflowingDueToRepetitiveElements)return T(null);{let c=p=>{if(!p||p.nodeType!==1)return NaN;let f=Bt(this.clientLayout,p,this.vertical);return f.right>=f.left&&f.bottom>=f.top?this.vertical?f.left:f.bottom:NaN},d=bn(a,this.clientLayout,0,this.vertical);if(e.floatSide==="footnote"){let p=o;if(p.footnotePolicy===y.line||isNaN(d)){let f=a;for(;f;){if((f.shadowContext?f.shadowContext.owner:f.sourceNode)===p.policyAnchorNode){let g=c(f.viewNode);isNaN(g)||(d=g);break}f=f.parent}}}return isNaN(d)&&e.floatSide==="footnote"&&(d=c(a.viewNode)),!(e.floatSide==="footnote"&&o.footnotePolicy===y.line)&&this.isOverflown(d)?T(a):(e.floatSide==="footnote"&&t.registerPageFloatAnchor(o,a.viewNode),this.layoutPageFloatInner(l,i,d,h).thenAsync(p=>{if(!p)return t.registerPageFloatAnchor(o,a.viewNode),T(a);if(e.floatSide==="footnote"){if(o.footnotePolicy===y.line&&t.hasInvalidatedForLineFootnote(o)){if(t.isInvalidated())return T(null);let f=i.findPageFloatFragment(o,t);if(f!=null&&f.hasFloat(o)&&f.continues)return this.registerLineFootnoteOverflowEdge(d),T(a)}return T(a)}return t.generatingNodePosition?T(a):T(null)}))}})}processLineStyling(e,t,i){let n=M("processLineStyling"),r=i.concat([]);i.splice(0,i.length);let o=0,s=e.firstPseudo;return s?.count===0&&(s=s.outer),n.loopWithFrame(a=>{if(!s){a.breakLoop();return}let h=this.findLinePositions(r),l=s.count-o;if(h.length<=l){a.breakLoop();return}let c=this.findAcceptableBreakInside(r,h[l-1],!0);if(c==null){a.breakLoop();return}this.finishBreak(c,!1,!1).then(()=>{o+=l,this.layoutContext.peelOff(c,0).then(d=>{e=d,s=e.firstPseudo,r=[],this.buildViewToNextBlockEdge(e,r).then(p=>{t=p,a.continueLoop()})})})}).then(()=>{Array.prototype.push.apply(i,r),n.finish(t)}),n.result()}registerLineFootnoteOverflowEdge(e){if(!isFinite(e))return;let t=this.getBoxDir();(this.lineFootnoteOverflowEdge==null||t*e<t*this.lineFootnoteOverflowEdge)&&(this.lineFootnoteOverflowEdge=e)}findLineFootnoteOverflowBreak(e){if(this.lineFootnoteOverflowEdge==null||e.length===0)return null;let t=this.findLinePositions(e),i=this.getBoxDir(),n=1.5/(this.clientLayout.pixelRatio||1),r=t.find(o=>i*(o-this.lineFootnoteOverflowEdge)>=-n);return r==null?null:this.findAcceptableBreakInside(e,r,!0)}isLoneImage(e){return e.length!=2&&this.breakPositions.length>0?!1:e[0].sourceNode==e[1].sourceNode&&ji[e[0].sourceNode.localName]}getTrailingMarginEdgeAdjustment(e){let t=0,i=0;for(let n=e.length-1;n>=0;n--){let r=e[n];if(!r||!r.after||!r.viewNode||r.viewNode.nodeType!=1)break;let o=this.getComputedMargin(r.viewNode),s=this.vertical?-o.left:o.bottom;s>0?t=Math.max(t,s):i=Math.min(i,s)}return t+i}layoutBreakableBlock(e){let t=M("layoutBreakableBlock"),i=[];return this.lineFootnoteOverflowEdge=null,this.buildViewToNextBlockEdge(e,i).then(n=>{let r=i.length-1;if(r<0){t.finish(n);return}this.postLayoutBlock(n,i);let o=this.suppressOpenAncestorBlockEndInset(n??e),s=this.calculateEdge(n,i,r,i[r].boxOffset);o();let a=!1;if(!n||!En(n.viewNode)){let l=Ln(n,this.collectElementsOffset());a=this.isOverflown(s+(this.vertical?-1:1)*l.minimum),this.isOverflown(s+(this.vertical?-1:1)*l.current)&&!this.nodeContextOverflowingDueToRepetitiveElements&&(this.nodeContextOverflowingDueToRepetitiveElements=n)}n==null&&(s+=this.getTrailingMarginEdgeAdjustment(i)),this.updateMaxReachedAfterEdge(s);let h;e.firstPseudo?h=this.processLineStyling(e,n,i):h=T(n),h.then(l=>{let c=this.findLineFootnoteOverflowBreak(i);if(c){let d=c.modify();d.overflow=!0,d.pluginProps.lineFootnoteOverflow=1,this.breakPositions=[],this.saveEdgeBreakPosition(d,null,!0),this.lineFootnoteOverflowEdge=null,t.finish(d);return}this.lineFootnoteOverflowEdge=null,i.length>0&&(this.saveBoxBreakPosition(i),a&&!this.isLoneImage(i)&&l&&(l=l.modify(),l.overflow=!0)),t.finish(l)})}),t.result()}postLayoutBlock(e,t){_t("POST_LAYOUT_BLOCK").forEach(i=>{i(e,t,this)})}findEndOfLine(e,t,i){let n=this.vertical?e-1:e+1,r=0,o=t[0].boxOffset,s=r,a=t.length-1,h=t[a].boxOffset,l;for(;o<h;){l=o+Math.ceil((h-o)/2),s=r;let c=a;for(;s<c;){let p=s+Math.ceil((c-s)/2);t[p].boxOffset>l?c=p-1:s=p}let d=this.calculateEdge(null,t,s,l);if(this.vertical?d<=n:d>=n){for(h=l-1;t[s].boxOffset==l;)s--;a=s}else i&&this.updateMaxReachedAfterEdge(d),o=l,r=s}return{nodeContext:t[s],index:o,checkPointIndex:s}}findAcceptableBreakInside(e,t,i){var n,r,o;let s=this.findEndOfLine(t,e,!0),a=s.nodeContext;if(s.checkPointIndex===0&&s.index===a.boxOffset)return null;let h=a.viewNode;if(h.nodeType!=1&&((n=h.parentElement)==null?void 0:n.localName)!=="viv-ts-inner"){let l=h;a=this.resolveTextNodeBreaker(a).breakTextNode(l,a,s.index,e,s.checkPointIndex,i)}else{let l=su(a);if(l){if(((r=this.breakPositions)==null?void 0:r[0])instanceof fr&&l!=null&&l.viewNode.contains(this.breakPositions[0].checkPoints[0].viewNode))return null;for(a=l;!a.after&&a.inline&&a.parent;){let c=(o=a.viewNode)==null?void 0:o.previousSibling;for(;c&&(Ee(c,a.parent.whitespace)||Ot(c));)c=c.previousSibling;if(c)break;a=a.parent}}}return this.clearOverflownViewNodes(a,!1),a}resolveTextNodeBreaker(e){return _t("RESOLVE_TEXT_NODE_BREAKER").reduce((t,i)=>i(e)||t,ks.instance)}getRangeBoxes(e,t){let i=[],n=e.ownerDocument.createRange(),r=!1,o=e,s=null,a=!1,h=!0;for(;h;){let l=!0;do{let c=null;o==t&&(t.nodeType===1?h=!(!t.firstChild||r):h=!1);let d=o.nodeType===1?o:null;d?r?r=!1:zl(d)?l=!a:!d.firstChild||ji[d.localName]||/^r(uby|[bt]c?)$/.test(d.localName)||vv(this.clientLayout.getElementComputedStyle(d).display)?(l=!a,l?(d.localName==="ruby"&&o.firstChild&&(o=o.firstChild),n.setStartBefore(o),a=!0,s=o):/^r(uby|tc?)$/.test(d.localName)||(s=o),o.contains(t)&&(h=!1)):c=o.firstChild:(a||(o.parentNode==null?h=!1:(n.setStartBefore(o),a=!0)),s=o),c||(c=o.nextSibling,c||(r=!0,c=o.parentNode)),o=c}while(l&&h);if(a){n.setEndAfter(s);let c=this.clientLayout.getRangeClientRects(n);ss(c,this.vertical);for(let d=0;d<c.length;d++)i.push(c[d]);a=!1}}return i}findLinePositions(e){let t=[],i=this.getRangeBoxes(e[0].viewNode,e[e.length-1].viewNode);i.sort(this.vertical?zv:Dv);let n=0,r=0,o=0,s=0,a=0,h=this.getBoxDir();for(;;){if(a<i.length){let l=i[a],c=1;if(s>0){let d=Math.max(this.getBoxSize(l),1);h*this.getBeforeEdge(l)<h*n?c=h*(this.getAfterEdge(l)-n)/d:h*this.getAfterEdge(l)>h*r?c=h*(r-this.getBeforeEdge(l))/d:c=1}if(s==0||c>=.6||c>=.2&&this.getStartEdge(l)>=o-1){o=this.getEndEdge(l),this.vertical?(n=s==0?l.right:Math.max(n,l.right),r=s==0?l.left:Math.min(r,l.left)):(n=s==0?l.top:Math.min(n,l.top),r=s==0?l.bottom:Math.max(r,l.bottom)),s++,a++;continue}}if(s>0&&(t.push(r),s=0),a>=i.length)break}return t.sort(kc),this.vertical&&t.reverse(),t}calculateClonedPaddingBorder(e){let t=0;for(let i=e;i;i=i.parent)if(!i.inline&&Nn(i.viewNode)){let n=this.getComputedPaddingBorder(i.viewNode);t+=i.vertical?-n.left:n.bottom,i.display==="table"&&(t+=(i.vertical?-1:1)*i.blockBorderSpacing)}return t}getOffsetByRepetitiveElements(e){let t;return e?t=e.calculateOffset(this):t=Ln(null,this.collectElementsOffset()),t.current}findBoxBreakPosition(e,t){let i=this.element.parentNode,n=this.element.nextSibling;i.removeChild(this.element),i.insertBefore(this.element,n);let r=e.checkPoints,o=r[0];for(;o.parent&&o.inline;)o=o.parent;let s,a;t&&!this.isFootnote?(s=1,a=1):(s=Math.max((o.inheritedProps.widows||2)-0,1),a=Math.max((o.inheritedProps.orphans||2)-0,1));let h=this.calculateClonedPaddingBorder(o),l=this.findLinePositions(r),c=this.footnoteEdge-h,d=this.getBoxDir(),p=this.getOffsetByRepetitiveElements(e);c-=d*p;let f=this.findFirstOverflowingEdgeAndCheckPoint(r);isNaN(f.edge)&&(f.edge=d*(1/0));let g=mi(l.length,m=>{let S=l[m];return this.vertical?S<c||S<=f.edge:S>c||S>=f.edge}),v=g<=0;v&&(g=mi(l.length,m=>this.vertical?l[m]<c:l[m]>c));let w=r[r.length-1].viewNode;if(w?.parentElement.localName==="viv-ts-inner"&&(w=w.parentElement.parentElement),(g===l.length&&w.nextSibling||g>=l.length-1&&w.parentElement.querySelector(".MJXc-display"))&&(s=0,a=1),g=Math.min(l.length-s,g),g<a)return null;c=l[g-1];let x;if(v?x=f.checkPoint:x=this.findAcceptableBreakInside(e.checkPoints,c,t),x){let m=this.getAfterEdgeOfBlockContainer(x);if(!isNaN(m)&&d*(c-m)>0&&(c=m),this.computedBlockSize=d*(c-this.beforeEdge)+p,l.length>=2){let S=Math.max(1,Math.min(g-1,l.length-1));this.lastLineStride=Math.abs(l[S]-l[S-1])}}return x}getAfterEdgeOfBlockContainer(e){let t=e;do t=t.parent;while(t&&t.inline);return t?(t=t.copy().modify(),t.after=!0,bn(t,this.clientLayout,0,this.vertical)):NaN}findFirstOverflowingEdgeAndCheckPoint(e){let t=e.findIndex(n=>n.overflow);if(t<0)return{edge:NaN,checkPoint:null};let i=e[t];return{edge:this.calculateEdge(null,e,t,i.boxOffset),checkPoint:i}}findEdgeBreakPosition(e){return this.computedBlockSize=e.computedBlockSize+this.getOffsetByRepetitiveElements(e),e.position}finishBreak(e,t,i){e.formattingContext;let n=new ir().find(e.formattingContext).finishBreak(this,e,t,i);return n||(n=Xl.finishBreak(this,e,t,i)),n}findAcceptableBreakPosition(){let e=null,t=null,i=0,n=0;do{i=n,n=Number.MAX_VALUE;for(let r=this.breakPositions.length-1;r>=0&&!t;--r){e=this.breakPositions[r],t=e.findAcceptableBreak(this,i);let o=e.getMinBreakPenalty();o>i&&(n=Math.min(n,o))}}while(n>i&&!t&&this.forceNonfitting);return{breakPosition:t?e:null,nodeContext:t}}doFinishBreak(e,t,i,n){if(this.pageFloatLayoutContext.isInvalidated()||this.pageBreakType||!t)return T(e);let r=M("doFinishBreak"),o=!1;if(!e){if(this.forceNonfitting&&!this.isFootnote)return Y.warn("Could not find any page breaks?!!"),this.skipTailEdges(t).then(s=>{s?(s=s.modify(),s.overflow=!1,this.finishBreak(s,o,!0).then(()=>{r.finish(s)})):r.finish(s)}),r.result();e=i,o=!0,this.computedBlockSize=n}return this.finishBreak(e,o,!0).then(()=>{r.finish(e)}),r.result()}isBreakable(e){for(let t=e;t;t=t.parent)if(Ot(t.viewNode))return!1;return e.after?!0:e.sourceNode.namespaceURI==="http://www.w3.org/2000/svg"?!1:!e.flexContainer}isZeroLength(e){let t=e.trim();return t===""||/^0+(?:\.0+)?(?:[a-z%]*)$/i.test(t)}hasNonZeroBlockStartInset(e){return this.vertical?!(this.isZeroLength(e.paddingRight)&&this.isZeroLength(e.borderRightWidth)):!(this.isZeroLength(e.paddingTop)&&this.isZeroLength(e.borderTopWidth))}hasNonZeroBlockEndInset(e){return this.vertical?!(this.isZeroLength(e.paddingLeft)&&this.isZeroLength(e.borderLeftWidth)):!(this.isZeroLength(e.paddingBottom)&&this.isZeroLength(e.borderBottomWidth))}suppressOpenAncestorBlockEndInset(e){if(!os(this))return()=>{};let t=[];for(let i=e?.parent;i;i=i.parent){if(i.after||i.inline)continue;let n=i.viewNode;if(!n||n.nodeType!==1||Nn(n))continue;let r=this.clientLayout.getElementComputedStyle(n);if(r&&!this.hasNonZeroBlockEndInset(r))continue;let o=n.getAttribute("data-viv-box-break");Ct(n,"block-end"),t.push({element:n,original:o})}return()=>{for(let{element:i,original:n}of t)n===null?i.removeAttribute("data-viv-box-break"):i.setAttribute("data-viv-box-break",n)}}checkOverflowAndSaveEdge(e,t){if(!e)return!1;for(let s=e;s;s=s.parent)if(Ot(s.viewNode))return!1;if(En(e.viewNode))return!1;let i=this.suppressOpenAncestorBlockEndInset(e),n=bn(e,this.clientLayout,0,this.vertical);i();let r=Ln(e,this.collectElementsOffset()),o=this.isOverflown(n+(this.vertical?-1:1)*r.minimum);if(this.isOverflown(n+(this.vertical?-1:1)*r.current)&&!this.nodeContextOverflowingDueToRepetitiveElements)this.nodeContextOverflowingDueToRepetitiveElements=e;else if(t){let s=n+this.getTrailingMarginEdgeAdjustment(t),a=this.footnoteEdge-this.getBoxDir()*r.current;n=this.vertical?Math.min(n,Math.max(s,a)):Math.max(n,Math.min(s,a))}return this.updateMaxReachedAfterEdge(n),o}checkOverflowAndSaveEdgeAndBreakPosition(e,t,i,n){if(!e||En(e.viewNode))return!1;let r=this.checkOverflowAndSaveEdge(e,t);return(i||!r)&&this.saveEdgeBreakPosition(e,n,r),r}applyClearance(e){if(!e.viewNode.parentNode||e.floatReference!==Pe.INLINE||e.floatSide)return!1;let t=e.clearSide==="same"?e.floatSide:e.clearSide,i=/^(page|column|region)$/.test(t),n=this.getComputedMargin(e.viewNode),r=e.viewNode.ownerDocument.createElement("div");this.vertical?(r.style.bottom="0px",r.style.width="1px",r.style.marginRight=`${n.right}px`):(r.style.right="0px",r.style.height="1px",r.style.marginTop=`${n.top}px`);let o=()=>i?this.clientLayout.getElementClientRect(r):Bt(this.clientLayout,r,this.vertical);e.viewNode.parentNode.insertBefore(r,e.viewNode);let s=o(),a=this.getBeforeEdge(s),h=this.getBoxDir(),l=/^(top|bottom|inside|outside|(block|inline)-(start|end))$/.test(t)?aa(t,e.vertical,e.direction,this.layoutContext.page.side):t,c=l==="left"||l==="right"?e.direction==="rtl"==(l==="left")?"inline-end":"inline-start":l,d=this.pageFloatLayoutContext.getPageFloatClearEdge(c,this),p=d;switch(l){case"left":d=h*Math.max(d*h,this.leftFloatEdge*h);break;case"right":d=h*Math.max(d*h,this.rightFloatEdge*h);break;default:d=h*Math.max(d*h,Math.max(this.rightFloatEdge*h,this.leftFloatEdge*h))}let f=this.getFloatLayoutUnit(),g=this.leftFloatEdge*h>this.beforeEdge*h||this.rightFloatEdge*h>this.beforeEdge*h;if(f>0&&g){let w=d*h>p*h;d=h*(Math.ceil(d*h/f)+(w?1:0))*f}let v=this.getFloatLayoutTolerance(f);if(a*h+v>d*h)return e.viewNode.parentNode.removeChild(r),!1;{let w=Math.max(1,(d-a)*h);this.vertical?r.style.width=`${w}px`:r.style.height=`${w}px`,s=o();let x=this.getAfterEdge(s);if(!e.floatSide)if(this.vertical){let m=x-n.right-d;m>0==n.right>=0&&(m+=n.right),r.style.marginLeft=`${m}px`}else{let m=d-(x+n.top);m>0==n.top>=0&&(m+=n.top),r.style.marginBottom=`${m}px`}return e.clearSpacer=r,!0}}isBFC(e){return!!(hw(e)||Yi.isInstanceOfRepetitiveElementsOwnerFormattingContext(e))}hasFixedPositionAncestor(e){for(let t=e;t;t=t.parent)if(ou(t.viewNode))return!0;return!1}skipEdges(e,t,i){var n;let r=e.after?(n=e.parent)==null?void 0:n.formattingContext:e.formattingContext;if(r&&!this.isBFC(r))return T(e);let o=M("skipEdges"),s=this,a=!i&&t&&e&&e.after,h=i,l=null,c=[],d=[],p=!1;function f(C){var P,L;if(!(!t||s.isNonFirstColumn||i||!au(h))){for(let A=C;A;A=A.parent)if(A.breakBefore==="column"&&(A.breakBefore=null),((P=A.viewNode)==null?void 0:P.nodeType)===1){let z=A.viewNode;((L=z.style)==null?void 0:L.breakBefore)==="column"&&(z.style.breakBefore="")}}}function g(C){var P,L;if(!(!t||!s.isNonFirstColumn||i||h!=="column")){for(let A=C;A;A=A.parent)if(A.breakBefore==="column"&&(A.breakBefore=null),((P=A.viewNode)==null?void 0:P.nodeType)===1){let z=A.viewNode;((L=z.style)==null?void 0:L.breakBefore)==="column"&&(z.style.breakBefore="")}h=null}}function v(C){var P,L;if(!(i||!au(h))){for(let A=C;A;A=A.parent)if(A.breakAfter==="column"&&(A.breakAfter=null),((P=A.viewNode)==null?void 0:P.nodeType)===1){let z=A.viewNode;((L=z.style)==null?void 0:L.breakAfter)==="column"&&(z.style.breakAfter="")}}}function w(C){h=nt(h,C)}function x(){return i?!0:Ze(h)?t?s.isNonFirstColumn&&h!=="column"&&h!=="region":!m()&&!S():!1}function m(){var C;if(!l||!e||e.floatSide)return!1;for(let P=l;P!=null&&P.parent;P=P.parent){if(P.parent.viewNode&&Ot(P.parent.viewNode))continue;let L=P.after?P.viewNode:(C=P.viewNode)==null?void 0:C.previousSibling;for(;L&&(Ee(L,P.parent.whitespace)||Ot(L));)L=L.previousSibling;if(L)return!1}return!0}function S(){var C,P;if(l||!(e!=null&&e.viewNode)||e.shadowContext||e.after||e.floatSide||!((C=e.parent)!=null&&C.viewNode)||Ot(e.parent.viewNode))return!1;let L=!1;for(let A=e;A!=null&&A.parent&&!A.after;A=A.parent){if(A!==e&&Ot(A.viewNode))return!1;let z=(P=A.viewNode)==null?void 0:P.previousSibling;for(;z&&(Ee(z,A.parent.whitespace)||Ot(z));)Ot(z)&&(L=!0),z=z.previousSibling;if(z)return!1}return L}let b=()=>{e=c[0]||e,e.viewNode.parentNode.removeChild(e.viewNode),this.pageBreakType=h};return o.loopWithFrame(C=>{for(var P;e;){e.formattingContext;let L=new ir().find(e.formattingContext);do{if(!e.viewNode)break;if(e.inline&&e.viewNode.nodeType!=1){if(Ee(e.viewNode,e.whitespace)||this.hasFixedPositionAncestor(e))break;if(!e.after){w(e.breakBefore),f(e),g(e),x()?b():this.checkOverflowAndSaveEdgeAndBreakPosition(l,null,!0,h)?(e=(this.stopAtOverflow&&l||e).modify(),e.overflow=!0):(!l&&!t&&c.length===0&&this.saveEdgeBreakPosition(e,h,!1),e=e.modify(),e.breakBefore=h),C.breakLoop();return}}if(!e.after){if(e.floatSide&&(this.breakAtTheEdgeBeforeFloat=as(h)?h:null),L&&L.startNonInlineElementNode(e))break;if(e.clearSide&&this.applyClearance(e)&&t&&this.breakPositions.length===0&&this.saveEdgeBreakPosition(e.copy(),h,!1),!e.inline&&!e.repeatOnBreak&&(l?su(l):this.breakPositions[this.breakPositions.length-1]instanceof fr||!t&&c.length===0)&&this.saveEdgeBreakPosition(e.copy(),h,!1),!this.isBFC(e.formattingContext)||Yi.isInstanceOfRepetitiveElementsOwnerFormattingContext(e.formattingContext)||this.isFloatNodeContext(e)||e.flexContainer||!e.nodeShadow&&!e.sourceNode.firstElementChild&&Ee(e.sourceNode.firstChild,e.whitespace)){c.push(e.copy()),w(e.breakBefore),f(e),g(e),x()?b():(this.checkOverflowAndSaveEdgeAndBreakPosition(l,null,!0,h)||!this.layoutConstraint.allowLayout(e))&&(e=(this.stopAtOverflow&&l||e).modify(),e.overflow=!0),C.breakLoop();return}}if(e.viewNode.nodeType!=1)break;let z=e.viewNode,U=z.style;if(e.after){$d(z,this),e.floatSide&&(h=h??this.breakAtTheEdgeBeforeFloat,this.breakAtTheEdgeBeforeFloat=null);let X=e.sourceNode;if(X.localName==="svg"||X.localName==="math"||X.getAttribute("data-math-typeset")==="true"){p=!1,l=e.copy(),d.push(l),h=null,w(e.breakAfter),v(e),this.checkOverflowAndSaveEdgeAndBreakPosition(l,null,!this.stopAtOverflow,h);break}if(e.inline||L&&L.afterNonInlineElementNode(e,this.stopAtOverflow))break;if(p){if(ou(e.viewNode))break;if(x()){b(),C.breakLoop();return}c=[],t=!1,a=!1,h=null}p=!1,Wd(e.viewNode)||(l=e.copy(),d.push(l)),w(e.breakAfter),v(e),U&&!Ot(e.viewNode)&&this.hasNonZeroBlockEndInset(U)&&(d=l?[l]:[])}else{if(c.push(e.copy()),w(e.breakBefore),f(e),g(e),l&&Ze(h)&&fv(l.viewNode,e.viewNode),(e.pageType!=((P=e.parent)==null?void 0:P.pageType)||!Ze(h))&&!this.layoutConstraint.allowLayout(e)&&(this.checkOverflowAndSaveEdgeAndBreakPosition(l,null,!this.stopAtOverflow,h),e=e.modify(),e.overflow=!0,this.stopAtOverflow)){C.breakLoop();return}let X=e.viewNode.localName;if(ji[X]){x()?b():this.checkOverflowAndSaveEdgeAndBreakPosition(l,null,!0,h)&&(e=(this.stopAtOverflow&&l||e).modify(),e.overflow=!0),C.breakLoop();return}U&&this.hasNonZeroBlockStartInset(U)&&(a=!1,d=[]),p=!0}}while(!1);let A=this.nextInTree(e,a);if(A.isPending()){A.then(z=>{e=z,C.continueLoop()});return}else e=A.get()}this.checkOverflowAndSaveEdgeAndBreakPosition(l,d,!this.stopAtOverflow,h)?l&&this.stopAtOverflow&&(e=l.modify(),e.overflow=!0):Ze(h)&&(this.pageBreakType=h),C.breakLoop()}).then(()=>{l&&(this.lastAfterPosition=l.toNodePosition()),o.finish(e)}),o.result()}skipTailEdges(e){let t=e.copy(),i=M("skipEdges"),n=null,r=!1;return i.loopWithFrame(o=>{for(;e;){do{if(!e.viewNode)break;if(e.inline&&e.viewNode.nodeType!=1){if(Ee(e.viewNode,e.whitespace))break;if(!e.after){Ze(n)&&(this.pageBreakType=n),o.breakLoop();return}}if(!e.after&&(this.isFloatNodeContext(e)||e.flexContainer)){n=nt(n,e.breakBefore),Ze(n)&&(this.pageBreakType=n),o.breakLoop();return}if(e.viewNode.nodeType!=1)break;let a=e.viewNode.style;if(e.after){if(r){if(Ze(n)){this.pageBreakType=n,o.breakLoop();return}n=null}r=!1,n=nt(n,e.breakAfter)}else{n=nt(n,e.breakBefore);let h=e.viewNode.localName;if(ji[h]){Ze(n)&&(this.pageBreakType=n),o.breakLoop();return}if(a&&this.hasNonZeroBlockStartInset(a)){o.breakLoop();return}}r=!0}while(!1);let s=this.layoutContext.nextInTree(e);if(s.isPending()){s.then(a=>{e=a,o.continueLoop()});return}else e=s.get()}t=null,o.breakLoop()}).then(()=>{i.finish(t)}),i.result()}layoutFloatOrFootnote(e){if(Ii(e.floatReference)||e.floatSide==="footnote"){let t=this.pageFloatLayoutContext.generatingNodePosition;if(t&&e.sourceNode===t.steps[0].node){let i=e.modify();return i.floatSide=null,i.floatReference=Pe.INLINE,i.clearSide=null,this.isBreakable(i)?this.layoutBreakableBlock(i):this.layoutUnbreakable(i)}return this.layoutPageFloat(e)}else return this.layoutFloat(e)}layoutNext(e,t,i){let n=M("layoutNext");return this.skipEdges(e,t,i||null).then(r=>{if(e=r,!e||this.pageBreakType||this.stopByOverflow(e))n.finish(e);else{let o=e.formattingContext;new ir().find(o).layout(e,this,t).thenFinish(n)}}),n.result()}clearOverflownViewNodes(e,t){if(e)for(let i=e.parent;e;e=i,i=i?i.parent:null){let n=(i||e).formattingContext;new ir().find(n).clearOverflownViewNodes(this,i,e,t),t=!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 t=this.clientLayout.getElementClientRect(e);this.element.removeChild(e);let i=this.originX+this.left+this.getInsetLeft(),n=this.originY+this.top+this.getInsetTop();this.box=new Mt(i,n,i+this.width,n+this.height),this.startEdge=t?this.vertical?this.rtl?t.bottom:t.top:this.rtl?t.right:t.left:0,this.endEdge=t?this.vertical?this.rtl?t.top:t.bottom:this.rtl?t.left:t.right:0,this.beforeEdge=t?this.vertical?t.right:t.top:0,this.afterEdge=t?this.vertical?t.left:t.bottom:0,this.leftFloatEdge=this.beforeEdge,this.rightFloatEdge=this.beforeEdge,this.bottommostFloatTop=this.beforeEdge,this.footnoteEdge=this.afterEdge,this.bands=Mm(this.box,[this.getInnerShape()],this.getExclusions(),8,this.snapHeight,this.vertical),this.createFloats()}init(){this.chunkPositions=[],I(this.element,"width",`${this.width}px`),I(this.element,"height",`${this.height}px`),this.initGeom(),this.computedBlockSize=0,this.overflown=!1,this.pageBreakType=null,this.lastAfterPosition=null,this.lastLineStride=0}saveEdgeBreakPosition(e,t,i){e.formattingContext;let n=e.copy(),r=new ir().find(e.formattingContext),o=this.calculateClonedPaddingBorder(n),s=r.createEdgeBreakPosition(n,t,i,this.computedBlockSize+o);this.breakPositions.push(s)}saveBoxBreakPosition(e){let t=e[0].breakPenalty;if(t){let n=e[0];for(;n.parent&&n.inline;)n=n.parent;t=n.breakPenalty}let i=new fr(e,t);this.breakPositions.push(i)}updateMaxReachedAfterEdge(e){if(!isNaN(e)){let t=this.getBoxDir()*(e-this.beforeEdge);this.computedBlockSize=Math.max(t,this.computedBlockSize)}}layout(e,t,i){if(this.chunkPositions.push(e),e.primary.after&&(this.lastAfterPosition=e.primary),this.stopAtOverflow&&this.overflown)return T(e);if(this.isFullWithPageFloats())return e.primary.after&&e.primary.steps.length===1?T(null):T(e);_l(this);let n=M("layout");return this.openAllViews(e.primary).then(r=>{let o=null;if(r.viewNode)o=r.copy();else{let a=h=>{h.nodeContext.viewNode&&(o=h.nodeContext,this.layoutContext.removeEventListener("nextInTree",a))};this.layoutContext.addEventListener("nextInTree",a)}let s=new R0(t,i);s.layout(r,this).then(a=>{this.doFinishBreak(a,s.context.overflownNodeContext,o,s.initialComputedBlockSize).then(h=>{let l=null;this.pseudoParent?l=T(null):l=this.doFinishBreakOfFragmentLayoutConstraints(h),l.then(()=>{if(os(this)&&(yv(this),_s(this)),this.element.hasAttribute("data-vivliostyle-column-block-size-adjusted")&&(this.vertical?(I(this.element,"width",`${this.width}px`),I(this.element,"left",`${this.left}px`)):I(this.element,"height",`${this.height}px`),this.element.removeAttribute("data-vivliostyle-column-block-size-adjusted")),this.pageFloatLayoutContext.isInvalidated()){n.finish(null);return}if(!h)n.finish(null);else{this.overflown=!0;let c=new Bi(h.toNodePosition());n.finish(c)}})})})}),n.result()}isFullWithPageFloats(){return this.pageFloatLayoutContext.isColumnFullWithPageFloats(this)}getMaxBlockSizeOfPageFloats(){return this.pageFloatLayoutContext.getMaxBlockSizeOfPageFloats()}doFinishBreakOfFragmentLayoutConstraints(e){let t=M("doFinishBreakOfFragmentLayoutConstraints"),i=[].concat(this.fragmentLayoutConstraints);i.sort((r,o)=>r.getPriorityOfFinishBreak()-o.getPriorityOfFinishBreak());let n=0;return t.loop(()=>n<i.length?i[n++].finishBreak(e,this).thenReturn(!0):T(!1)).then(()=>{t.finish(!0)}),t.result()}doLayout(e,t,i){let n=M("doLayout"),r=null;return this.breakPositions=[],this.nodeContextOverflowingDueToRepetitiveElements=null,n.loopWithFrame(o=>{for(;e;){let s=!0;if(this.layoutNext(e,t,i||null).then(a=>{if(t=!1,i=null,this.nodeContextOverflowingDueToRepetitiveElements&&this.stopAtOverflow?(this.pageBreakType=null,e=this.nodeContextOverflowingDueToRepetitiveElements,e.overflow=!0):e=a,this.pageFloatLayoutContext.isInvalidated())o.breakLoop();else if(this.pageBreakType)o.breakLoop();else if(e&&this.stopByOverflow(e)){r=e;let h=this.findAcceptableBreakPosition();e=h.nodeContext,h.breakPosition&&h.breakPosition.breakPositionChosen(this),o.breakLoop()}else s?s=!1:o.continueLoop()}),s){s=!1;return}}this.computedBlockSize+=this.getOffsetByRepetitiveElements(),o.breakLoop()}).then(()=>{n.finish({nodeContext:e,overflownNodeContext:r})}),n.result()}redoLayout(){let e=this.chunkPositions,t=this.element.lastChild;for(;t!=this.last;){let s=t.previousSibling;this.element===t.parentNode&&this.layoutContext.isPseudoelement(t)||this.element.removeChild(t),t=s}this.killFloats(),this.init();let i=M("redoLayout"),n=0,r=null,o=!0;return i.loopWithFrame(s=>{if(n<e.length){let a=e[n++];this.layout(a,o).then(h=>{o=!1,h?(r=h,s.breakLoop()):s.continueLoop()});return}s.breakLoop()}).then(()=>{i.finish(r)}),i.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 t=this;t;t=t.pseudoParent)t.fragmentLayoutConstraints.forEach(i=>{if(Yi.isInstanceOfRepetitiveElementsOwnerLayoutConstraint(i)){let n=i.getRepetitiveElements();e.push(n)}if(ls.isInstanceOfAfterIfContinuesLayoutConstraint(i)){let n=i.getRepetitiveElements();e.push(n)}Li.isInstanceOfTableRowLayoutConstraint(i)&&i.getElementsOffsetsForTableCell(this).forEach(n=>{e.push(n)})});return e}},uh=class{constructor(e,t,i){u(this,"startNodeContexts",[]),u(this,"column"),u(this,"flowRootSourceNode"),this.flowRootSourceNode=i.sourceNode,this.column=Object.create(e),this.column.element=t,this.column.layoutContext=e.layoutContext.clone(),this.column.stopAtOverflow=!1,this.column.flowRootFormattingContext=i.formattingContext,this.column.pseudoParent=e;let n=this.column.calculateClonedPaddingBorder(i);this.column.footnoteEdge=this.column.footnoteEdge-n;let r=this;this.column.openAllViews=function(o){return Cs.prototype.openAllViews.call(this,o).thenAsync(s=>(r.startNodeContexts.push(s.copy()),T(s)))}}layout(e,t){return this.column.layout(e,t)}findAcceptableBreakPosition(e){let t=this.column.findAcceptableBreakPosition();if(e){let i=this.startNodeContexts[0].copy(),n=new to(i,null,i.overflow,0);if(n.findAcceptableBreak(this.column,0),!t.nodeContext)return{breakPosition:n,nodeContext:i}}return t}finishBreak(e,t,i){return this.column.finishBreak(e,t,i)}doFinishBreakOfFragmentLayoutConstraints(e){this.column.doFinishBreakOfFragmentLayoutConstraints(e)}isStartNodeContext(e){let t=this.startNodeContexts[0];return t.viewNode===e.viewNode&&t.after===e.after&&t.offsetInNode===e.offsetInNode}isLastAfterNodeContext(e){return Oi(e.toNodePosition(),this.column.lastAfterPosition)||this.isEffectivelyLastAfterNodeContext(e)}isEffectivelyLastAfterNodeContext(e){var t;let i=this.flowRootSourceNode,n=e.sourceNode;if(!i||!n||!e.after||i!==n&&!((t=i.contains)!=null&&t.call(i,n)))return!1;if(n.nodeType===Node.TEXT_NODE){let r=n;if(e.offsetInNode<r.length){let o=r.data.slice(e.offsetInNode);if(!tp(o,e.whitespace))return!1}}for(let r=n;r&&r!==i;r=r.parentNode)for(let o=r.nextSibling;o;o=o.nextSibling)if(!Ee(o,e.whitespace))return!1;return!0}getColumnElement(){return this.column.element}getColumn(){return this.column}},ks=class{breakTextNode(e,t,i,n,r,o){if(t.after)t.offsetInNode=e.length;else{let s=i-t.boxOffset,a=e.data;a.charCodeAt(s)==173?s=this.breakAfterSoftHyphen(e,a,s,t):s=this.breakAfterOtherCharacter(e,a,s,t),s>0&&(t=this.updateNodeContext(t,s,e))}return t}breakAfterSoftHyphen(e,t,i,n){let r=/[\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(t.slice(0,i))?"\u200D":"";if(e.replaceData(i,t.length-i,n.breakWord?"":r+_u(n)),r){let o=n.preprocessedTextContent[0][1];n.preprocessedTextContent[0][1]=o.slice(0,i+1)+r+o.slice(i+1)}return i+1}breakAfterOtherCharacter(e,t,i,n){let r=t.charAt(i);i++;let o=t.charAt(i);return e.replaceData(i,t.length-i,!n.breakWord&&Ih(r)&&Ih(o)?_u(n):""),i}updateNodeContext(e,t,i){return e=e.modify(),e.offsetInNode+=t,e.breakBefore=null,e}};u(ks,"instance");ks.instance=new ks;function _u(e){return e.hyphenateCharacter||e.parent&&e.parent.hyphenateCharacter||"-"}var R0=class extends ql{constructor(e,t){super(),u(this,"leadingEdge",e),u(this,"breakAfter"),u(this,"initialPageBreakType",null),u(this,"initialComputedBlockSize",0),u(this,"initialOverflown",!1),u(this,"initialLastLineStride",0),u(this,"context",{overflownNodeContext:null}),this.breakAfter=t||null}resolveLayoutMode(e){return new L0(this.leadingEdge,this.breakAfter,this.context)}prepareLayout(e,t){t.fragmentLayoutConstraints=[],t.pseudoParent||cw()}clearNodes(e){super.clearNodes(e);let t=e;for(;t;){let i=t.viewNode;i&&Hd(i.parentNode,i),t=t.parent}}saveState(e,t){super.saveState(e,t),this.initialPageBreakType=t.pageBreakType,this.initialComputedBlockSize=t.computedBlockSize,this.initialOverflown=t.overflown,this.initialLastLineStride=t.lastLineStride}restoreState(e,t){super.restoreState(e,t),t.pageBreakType=this.initialPageBreakType,t.computedBlockSize=this.initialComputedBlockSize,t.overflown=this.initialOverflown,t.lastLineStride=this.initialLastLineStride}},L0=class{constructor(e,t,i){u(this,"leadingEdge",e),u(this,"breakAfter",t),u(this,"context",i)}doLayout(e,t){let i=M("DefaultLayoutMode.doLayout");return A0(e,t).then(()=>{t.doLayout(e,this.leadingEdge,this.breakAfter).then(n=>{this.context.overflownNodeContext=n.overflownNodeContext,i.finish(n.nodeContext)})}),i.result()}accept(e,t){return t.pageFloatLayoutContext.isInvalidated()||t.pageBreakType||t.fragmentLayoutConstraints.length<=0?!0:t.fragmentLayoutConstraints.every(i=>i.allowLayout(e,this.context.overflownNodeContext,t))}postLayout(e,t,i,n){return n||(n=!i.fragmentLayoutConstraints.some(r=>r.nextCandidate(e))),i.fragmentLayoutConstraints.forEach(r=>{r.postLayout(n,e,t,i)}),n}},O0=class extends Cs{constructor(e,t,i,n,r,o,s){super(t,i,n,r,o),u(this,"floatSide",e),u(this,"parentContainer",s),u(this,"rootViewNodes",[]),u(this,"floatMargins",[]),u(this,"adjustContentRelativeSize",!0),u(this,"parentElement"),this.parentElement=s.element}openAllViews(e){return super.openAllViews(e).thenAsync(t=>(t&&this.fixFloatSizeAndPosition(t),T(t)))}convertPercentageSizesToPx(e){let t=this.parentContainer.getPaddingRect(),i=t.x2-t.x1,n=t.y2-t.y1;function r(o,s){o.forEach(a=>{let h=ki(e,a);if(h&&h.charAt(h.length-1)==="%"){let l=parseFloat(h),c=s*l/100;I(e,a,`${c}px`)}})}r(["width","max-width","min-width"],i),r(["height","max-height","min-height"],n),r(["margin-top","margin-right","margin-bottom","margin-left","padding-top","padding-right","padding-bottom","padding-left"],this.vertical?n:i),["margin-top","margin-right","margin-bottom","margin-left"].forEach(o=>{ki(e,o)==="auto"&&I(e,o,"0")})}fixFloatSizeAndPosition(e){for(;e.parent;)e=e.parent;e.viewNode.nodeType;let t=e.viewNode;if(this.rootViewNodes.push(t),this.adjustContentRelativeSize&&this.convertPercentageSizesToPx(t),this.floatMargins.push(this.getComputedMargin(t)),this.adjustContentRelativeSize){let i=this.floatSide;if(this.parentContainer.vertical){if(i==="block-end"||i==="left"){let n=ki(t,"height");n!==""&&n!=="auto"&&I(t,"margin-top","auto")}}else if(i==="block-end"||i==="bottom"){let n=ki(t,"width");n!==""&&n!=="auto"&&I(t,"margin-left","auto")}}}getRootViewNodeCount(){return this.rootViewNodes.length}hasNonPseudoTextContentAfter(e){let t=i=>{var n;return i.nodeType===Node.TEXT_NODE?!!((n=i.textContent)!=null&&n.trim()):i.nodeType!==Node.ELEMENT_NODE||Yt(i)?!1:Array.from(i.childNodes).some(t)};return this.rootViewNodes.slice(e).some(t)}appendContentFrom(e){e.rootViewNodes.forEach(t=>{this.element.appendChild(t)}),this.rootViewNodes.push(...e.rootViewNodes),this.floatMargins.push(...e.floatMargins),e.rootViewNodes.splice(0),e.floatMargins.splice(0),e.element.parentNode&&e.element.parentNode.removeChild(e.element),this.applyCompactFootnoteDisplay(),this.updateComputedBlockSizeForFootnoteArea(!0)}removeContentAfter(e){let t=this.rootViewNodes.splice(e);this.floatMargins.splice(e),t.forEach(i=>{i.parentNode&&i.parentNode.removeChild(i)}),this.applyCompactFootnoteDisplay(),this.updateComputedBlockSizeForFootnoteArea(!0)}getContentInlineSize(){return Math.max.apply(null,this.rootViewNodes.map((e,t)=>{let i=Bt(this.clientLayout,e,this.vertical),n=this.floatMargins[t];return this.vertical?n.top+i.height+n.bottom:n.left+i.width+n.right}))}getContentBlockMarginAfter(){return this.rootViewNodes.length===0?0:Math.max.apply(null,this.rootViewNodes.map((e,t)=>{let i=this.floatMargins[t];return this.vertical?i.left:i.bottom}))}applyCompactFootnoteDisplay(){let e=this.layoutContext,t=e?.styler,i=e?.xmldoc,n=this.rootViewNodes.filter(h=>{var l,c,d,p;let f=(l=h.ownerDocument.defaultView)==null?void 0:l.getComputedStyle(h);if((f?.getPropertyValue("--viv-footnote-display").trim()||"")==="compact")return!(f?.display==="list-item"&&f.getPropertyValue("list-style-position").trim()==="outside");let g=h.getAttribute(Ht);if(!g||!t||!i)return!1;let v=i.getNodeByOffset(parseInt(g,10));if(!v||v.nodeType!==Node.ELEMENT_NODE)return!1;let w=t.getStyle(v,!1),x=(d=(c=ve(w,"footnote-display"))==null?void 0:c.value)==null?void 0:d.toString(),m=!!((p=ve(w,"--viv-marker-content"))!=null&&p.value);return x==="compact"&&!m});if(n.length===0){this.updateInlineFootnoteSeparators(),this.updateComputedBlockSizeForFootnoteArea(!0);return}let r=this.element.getBoundingClientRect(),o=this.vertical?r.height:r.width;n.forEach(h=>{I(h,"display","inline"),h.style.setProperty("--viv-footnote-white-space","nowrap")});let s=1.5/(this.clientLayout.pixelRatio||1),a=h=>{let l=h.cloneNode(!0);I(l,"display","inline-block"),I(l,"position","absolute"),I(l,"visibility","hidden"),I(l,"white-space","nowrap"),I(l,"max-width","none"),I(l,"left","0"),I(l,"top","0"),this.element.appendChild(l);let c=l.getBoundingClientRect();return this.element.removeChild(l),this.vertical?c.height:c.width};n.forEach(h=>{a(h)>o+s&&(I(h,"display","block"),h.style.removeProperty("--viv-footnote-white-space"))}),this.updateInlineFootnoteSeparators(),this.updateComputedBlockSizeForFootnoteArea(!0)}updateComputedBlockSizeForFootnoteArea(e=!1){if(this.rootViewNodes.length===0){this.computedBlockSize=0;return}let t=this.getBoxDir(),i=this.beforeEdge;if(e){let n=Bt(this.clientLayout,this.element,this.vertical),r=this.vertical?this.borderRight+this.paddingRight:this.borderTop+this.paddingTop;i=this.getBeforeEdge(n)+t*r}this.computedBlockSize=Math.max(0,...this.rootViewNodes.map(n=>{let r=Bt(this.clientLayout,n,this.vertical),o=this.getComputedMargin(n),s=this.vertical?o.left:o.bottom;return t*(this.getAfterEdge(r)-i)+Math.max(0,s)}))}getFootnoteAfterPseudo(e){return Array.from(e.children).find(t=>Yt(t)==="after")}hasAuthorFootnoteAfterPseudo(e){let t=this.getFootnoteAfterPseudo(e);if(t&&!t.hasAttribute("data-vivliostyle-default-footnote-separator"))return!0;let i=Array.from(e.children).find(r=>r instanceof Element&&Pt(r)),n=i?this.getFootnoteAfterPseudo(i):null;return!!n&&!n.hasAttribute("data-vivliostyle-default-footnote-separator")}createDefaultFootnoteAfterPseudo(e){let t=e.ownerDocument.createElement("span");Er(t,"after"),t.setAttribute("data-vivliostyle-default-footnote-separator","1"),t.style.whiteSpace="normal",t.textContent=" ",e.appendChild(t)}getFootnoteBreakOpportunity(e){let t=e.nextElementSibling;return t!=null&&t.hasAttribute("data-vivliostyle-footnote-break")?t:null}createFootnoteBreakOpportunity(e){let t=e.ownerDocument.createElement("wbr");t.setAttribute("data-vivliostyle-footnote-break","1"),e.insertAdjacentElement("afterend",t)}updateInlineFootnoteSeparators(){this.rootViewNodes.forEach((e,t)=>{var i,n;let r=e,o=(i=r.ownerDocument.defaultView)==null?void 0:i.getComputedStyle(r).display,s=this.rootViewNodes[t+1],a=(n=s?.ownerDocument.defaultView)==null?void 0:n.getComputedStyle(s).display,h=this.getFootnoteAfterPseudo(r),l=this.hasAuthorFootnoteAfterPseudo(r),c=!!(h!=null&&h.hasAttribute("data-vivliostyle-default-footnote-separator")),d=this.getFootnoteBreakOpportunity(r);if(o==="inline"&&a==="inline"){let p=!h&&!l;p&&this.createDefaultFootnoteAfterPseudo(r),!p&&!d?this.createFootnoteBreakOpportunity(r):p&&d?.remove()}else c&&h.remove(),d?.remove()})}},tn=class{constructor(e,t){u(this,"parent",e),u(this,"rootSourceNode",t),u(this,"formattingContextType","RepetitiveElementsOwner"),u(this,"isRoot",!1),u(this,"repetitiveElements",null)}getName(){return"Repetitive elements owner formatting context (RepetitiveElementsOwnerFormattingContext)"}isFirstTime(e,t){return t}getParent(){return this.parent}getRepetitiveElements(){return this.repetitiveElements}getRootViewNode(e){let t=this.getRootNodeContext(e);return t?t.viewNode:null}getRootNodeContext(e){do if(!e.belongsTo(this)&&e.sourceNode===this.rootSourceNode)return e;while(e=e.parent);return null}initializeRepetitiveElements(e){this.repetitiveElements||Ga.some(t=>t.root===this.rootSourceNode?(this.repetitiveElements=t.elements,!0):!1)||(this.repetitiveElements=new B0(e,this.rootSourceNode),Ga.push({root:this.rootSourceNode,elements:this.repetitiveElements}))}saveState(){}restoreState(e){}},B0=class{constructor(e,t){u(this,"vertical",e),u(this,"ownerSourceNode",t),u(this,"headerSourceNode",null),u(this,"footerSourceNode",null),u(this,"headerViewNode",null),u(this,"footerViewNode",null),u(this,"headerNodePosition",null),u(this,"footerNodePosition",null),u(this,"headerHeight",0),u(this,"footerHeight",0),u(this,"isSkipHeader",!1),u(this,"isSkipFooter",!1),u(this,"enableSkippingFooter",!0),u(this,"enableSkippingHeader",!0),u(this,"doneInitialLayout",!1),u(this,"firstContentSourceNode",null),u(this,"lastContentSourceNode",null),u(this,"affectedNodeCache",[]),u(this,"afterLastContentNodeCache",[]),u(this,"allowInsert",!1),u(this,"allowInsertRepeatitiveElements")}setHeaderNodeContext(e){this.headerNodePosition||(this.headerNodePosition=hs(e,0),this.headerSourceNode=e.sourceNode,this.headerViewNode=e.viewNode)}setFooterNodeContext(e){this.footerNodePosition||(this.footerNodePosition=hs(e,0),this.footerSourceNode=e.sourceNode,this.footerViewNode=e.viewNode)}updateHeight(e){this.headerViewNode&&(this.headerHeight=_a(this.headerViewNode,e,this.vertical),this.headerViewNode=null),this.footerViewNode&&(this.footerHeight=_a(this.footerViewNode,e,this.vertical),this.footerViewNode=null)}prepareLayoutFragment(){this.isSkipHeader=this.isSkipFooter=!1,this.enableSkippingFooter=!0,this.enableSkippingHeader=!0}appendHeaderToFragment(e,t,i){return!this.headerNodePosition||this.isSkipHeader?T(!0):this.appendElementToFragment(this.headerNodePosition,e,t,i)}appendFooterToFragment(e,t,i){return!this.footerNodePosition||this.isSkipFooter?T(!0):this.appendElementToFragment(this.footerNodePosition,e,t,i)}appendElementToFragment(e,t,i,n){let r=t.viewNode.ownerDocument,o=t.viewNode,s=r.createElement("div");o.appendChild(s);let a=new uh(n,s,t),h=a.getColumn().pageBreakType;return a.getColumn().pageBreakType=null,this.allowInsertRepeatitiveElements=!0,a.layout(new Bi(e),!0).thenAsync(()=>(this.allowInsertRepeatitiveElements=!1,o.removeChild(s),this.moveChildren(s,o,i),a.getColumn().pageBreakType=h,T(!0)))}moveChildren(e,t,i){if(t)for(;e.firstChild;){let n=e.firstChild;e.removeChild(n),n.setAttribute(zn,"1"),i?t.insertBefore(n,i):t.appendChild(n)}}calculateOffset(e){let t=0;return e&&!this.affectTo(e)||((!this.isSkipFooter||e&&this.isAfterLastContent(e))&&(t+=this.footerHeight),this.isSkipHeader||(t+=this.headerHeight)),t}calculateMinimumOffset(e){let t=0;return e&&!this.affectTo(e)||(!this.enableSkippingFooter&&e&&this.isAfterLastContent(e)&&(t+=this.footerHeight),this.enableSkippingHeader||(t+=this.headerHeight)),t}isAfterLastContent(e){return this.findResultFromCache(e,this.afterLastContentNodeCache,t=>this.isAfterNodeContextOf(this.lastContentSourceNode,e,!1))}affectTo(e){return this.findResultFromCache(e,this.affectedNodeCache,t=>this.isAfterNodeContextOf(this.ownerSourceNode,e,!0))}findResultFromCache(e,t,i){let n=t.filter(r=>r.nodeContext.sourceNode===e.sourceNode&&r.nodeContext.after===e.after);if(n.length>0)return n[0].result;{let r=i(e);return t.push({nodeContext:e,result:r}),r}}isAfterNodeContextOf(e,t,i){let n=[];for(let r=e;r;r=r.parentNode){if(t.sourceNode===r)return t.after;n.push(r)}for(let r=t.sourceNode;r;r=r.parentNode){let o=n.indexOf(r);if(o>=0)return i?o===0:!1;for(let s=r;s;s=s.previousElementSibling)if(n.includes(s))return!0}return t.after}isFirstContentNode(e){return e&&this.firstContentSourceNode===e.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(e){return this.headerSourceNode===e}isFooterSourceNode(e){return this.footerSourceNode===e}},Rf=class{constructor(e){u(this,"formattingContext",e)}accept(e,t){return!!e}postLayout(e,t,i,n){let r=this.formattingContext.getRepetitiveElements();return r&&(i.clientLayout,r.doneInitialLayout||(r.updateHeight(i),r.doneInitialLayout=!0)),n}},Lf=class{constructor(e){u(this,"formattingContext",e)}accept(e,t){return!0}postLayout(e,t,i,n){return n}},M0=class extends Rf{constructor(e,t){super(e),u(this,"processor",t)}doLayout(e,t){return this.processor.doInitialLayout(e,t)}accept(e,t){return!1}},_0=class extends Lf{constructor(e,t){super(e),u(this,"processor",t)}doLayout(e,t){return!e.belongsTo(this.formattingContext)&&!e.after&&t.fragmentLayoutConstraints.unshift(new ch(e)),this.processor.doLayout(e,t)}},ch=class Of{constructor(t){u(this,"flagmentLayoutConstraintType","RepetitiveElementsOwner"),u(this,"nodeContext");let i=di(t.formattingContext);this.nodeContext=i.getRootNodeContext(t)}allowLayout(t,i,n){let r=this.getRepetitiveElements();return!r||En(this.nodeContext.viewNode)||!r.isEnableToUpdateState()?!0:i&&!t||t&&t.overflow?!Mf(t,i,r):!0}nextCandidate(t){let i=this.getRepetitiveElements();return i&&i.isEnableToUpdateState()?(i.updateState(),!0):!1}postLayout(t,i,n,r){let o=this.getRepetitiveElements();o&&t&&r.stopAtOverflow&&(i==null||o.isAfterLastContent(i))&&o.preventSkippingFooter()}finishBreak(t,i){let n=di(this.nodeContext.formattingContext),r=this.getRepetitiveElements();if(!r)return T(!0);let o=this.nodeContext;return $0(n,o,i).thenAsync(()=>H0(n,o,i).thenAsync(()=>(r.prepareLayoutFragment(),T(!0))))}getRepetitiveElements(){return di(this.nodeContext.formattingContext).getRepetitiveElements()}equalsTo(t){return t instanceof Of?di(this.nodeContext.formattingContext)===di(t.nodeContext.formattingContext):!1}getPriorityOfFinishBreak(){return 10}},D0=class extends ql{constructor(e,t){super(),u(this,"formattingContext",e),u(this,"processor",t)}resolveLayoutMode(e){let t=this.formattingContext.getRepetitiveElements();return!e.belongsTo(this.formattingContext)&&!t.doneInitialLayout?new M0(this.formattingContext,this.processor):(!e.belongsTo(this.formattingContext)&&!e.after&&t&&t.preventSkippingHeader(),new _0(this.formattingContext,this.processor))}},z0=class extends br{constructor(e,t){super(),u(this,"formattingContext",e),u(this,"column",t)}startNonInlineElementNode(e){let t=this.formattingContext,i=e.nodeContext,n=t.getRepetitiveElements();if(i.parent&&t.rootSourceNode===i.parent.sourceNode){switch(i.repeatOnBreak){case"header":if(n.isHeaderRegistered())i.repeatOnBreak="none";else return n.setHeaderNodeContext(i),T(!0);break;case"footer":if(n.isFooterRegistered())i.repeatOnBreak="none";else return n.setFooterNodeContext(i),T(!0);break}n.firstContentSourceNode||(n.firstContentSourceNode=i.sourceNode)}return br.prototype.startNonInlineElementNode.call(this,e)}afterNonInlineElementNode(e){let t=this.formattingContext,i=e.nodeContext;return i.sourceNode===t.rootSourceNode&&(t.getRepetitiveElements().lastContentSourceNode=e.lastAfterNodeContext&&e.lastAfterNodeContext.sourceNode,e.break=!0),i.repeatOnBreak==="header"||i.repeatOnBreak==="footer"?T(!0):br.prototype.afterNonInlineElementNode.call(this,e)}},V0=class extends Tn{layout(e,t,i){if(t.isFloatNodeContext(e))return t.layoutFloatOrFootnote(e);let n=di(e.formattingContext);return n.getRootViewNode(e)?(i&&Bf(e.parent,t),e.belongsTo(n)?Tn.prototype.layout.call(this,e,t,i):new D0(n,this).layout(e,t)):t.buildDeepElementView(e)}startNonInlineElementNode(e){let t=W0(e).getRepetitiveElements();return t&&!t.allowInsertRepeatitiveElements&&(t.isHeaderSourceNode(e.sourceNode)||t.isFooterSourceNode(e.sourceNode))&&e.viewNode.parentNode.removeChild(e.viewNode),!1}doInitialLayout(e,t){let i=di(e.formattingContext),n=M("BlockLayoutProcessor.doInitialLayout");return this.layoutEntireBlock(e,t).thenFinish(n),n.result()}layoutEntireBlock(e,t){let i=di(e.formattingContext),n=new z0(i,t);return new Wa(n,t.layoutContext).iterate(e)}doLayout(e,t){let i=di(e.formattingContext),n=M("doLayout"),r=t.layoutContext.nextInTree(e,!1);return Ff(r,t).then(o=>{let s=o;n.loopWithFrame(a=>{for(;s;){let h=!0;if(t.layoutNext(s,!1).then(l=>{s=l,t.pageFloatLayoutContext.isInvalidated()||t.pageBreakType||s&&t.stopByOverflow(s)||s&&s.after&&s.sourceNode==i.rootSourceNode?a.breakLoop():h?h=!1:a.continueLoop()}),h){h=!1;return}}a.breakLoop()}).then(()=>{n.finish(s)})}),n.result()}finishBreak(e,t,i,n){return Tn.prototype.finishBreak.call(this,e,t,i,n)}clearOverflownViewNodes(e,t,i,n){Tn.prototype.clearOverflownViewNodes(e,t,i,n)}};function U0(e,t){for(let i=e;i;i=i.parent){let n=i.formattingContext;n&&n instanceof tn&&!i.belongsTo(n)&&t(n,i)}}function Bf(e,t){e&&U0(e.after?e.parent:e,(i,n)=>{Li.isInstanceOfTableFormattingContext(i)||t.fragmentLayoutConstraints.push(new ch(n))})}function $0(e,t,i){let n=e.getRepetitiveElements();if(n){let r=e.getRootNodeContext(t);if(r.viewNode){let o=r.viewNode.firstChild;return n.appendHeaderToFragment(r,o,i)}}return T(!0)}function H0(e,t,i){let n=e.getRepetitiveElements();if(n&&!n.isSkipFooter){let r=e.getRootNodeContext(t);if(r.viewNode)return n.appendFooterToFragment(r,null,i)}return T(!0)}function Mf(e,t,i){let n=i.ownerSourceNode,r=e||t;return!r||n.contains(r.sourceNode)}function W0(e){let t=e.formattingContext;return!t||!(t instanceof tn)?null:t}function di(e){return e instanceof tn,e}var G0=new V0;Ft("RESOLVE_LAYOUT_PROCESSOR",e=>e instanceof tn&&!Li.isInstanceOfTableFormattingContext(e)?G0:null);var _f=class{constructor(e,t){u(this,"rowIndex",e),u(this,"sourceNode",t),u(this,"cells",[]),u(this,"breakBefore",null),u(this,"breakAfter",null)}addCell(e){this.cells.push(e)}getMinimumHeight(){return Math.min.apply(null,this.cells.map(e=>e.height))}},j0=class{constructor(e,t,i){u(this,"rowIndex",e),u(this,"columnIndex",t),u(this,"viewElement"),u(this,"colSpan"),u(this,"rowSpan"),u(this,"height",0),u(this,"anchorSlot",null),this.viewElement=i,this.colSpan=i.colSpan||1,this.rowSpan=i.rowSpan||1}setHeight(e){this.height=e}setAnchorSlot(e){this.anchorSlot=e}},X0=class{constructor(e,t,i){u(this,"rowIndex",e),u(this,"columnIndex",t),u(this,"cell",i)}},q0=class{constructor(e,t,i){u(this,"column",e),u(this,"cellNodeContext",i),u(this,"pseudoColumn"),u(this,"empty",!1),this.pseudoColumn=new uh(e,t,i)}findAcceptableBreakPosition(){let e=this.cellNodeContext.viewNode,{verticalAlign:t,alignContent:i}=e.style;t!=="top"&&t!=="baseline"&&I(e,"vertical-align","top"),i&&i!=="normal"&&I(e,"align-content","normal");let n=this.pseudoColumn.findAcceptableBreakPosition(!0);return I(e,"vertical-align",t),i&&i!=="normal"&&I(e,"align-content",i),n}},Y0=class{constructor(e,t){u(this,"viewNode",e),u(this,"side",t)}},Z0=class extends to{constructor(e,t,i,n){super(e,t,i,n),u(this,"formattingContext"),u(this,"acceptableCellBreakPositions",null),u(this,"rowIndex",null),this.formattingContext=e.formattingContext}findAcceptableBreak(e,t){let i=super.findAcceptableBreak(e,t);return t<this.getMinBreakPenalty()?null:this.getAcceptableCellBreakPositions().every(n=>!!n.nodeContext)?this.hasUnfinishedCells()?null:i:null}hasUnfinishedCells(){let e=this.getRowIndex(),t=this.formattingContext.getCellsFallingOnRow(e);for(let i of t){if(i.rowIndex+i.rowSpan-1>e)continue;let n=this.formattingContext.getCellFragmentOfCell(i);if(n){let r=n.findAcceptableBreakPosition();if(r.nodeContext&&!n.pseudoColumn.isLastAfterNodeContext(r.nodeContext))return!0}}return!1}getMinBreakPenalty(){let e=super.getMinBreakPenalty();this.getAcceptableCellBreakPositions().forEach(i=>{e+=i.breakPosition.getMinBreakPenalty()});let t=this.getCellFragments();return e+=Math.max(0,...t.map(i=>i.cellNodeContext.breakPenalty)),e}getAcceptableCellBreakPositions(){if(!this.acceptableCellBreakPositions){let e=this.formattingContext,t=this.getCellFragments();this.acceptableCellBreakPositions=t.map(i=>i.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)}},K0=class extends Gl{constructor(e,t,i){super(),u(this,"rowIndex",e),u(this,"beforeNodeContext",t),u(this,"formattingContext",i),u(this,"acceptableCellBreakPositions",null)}findAcceptableBreak(e,t){if(this!==e.breakPositions[0]&&t<this.getMinBreakPenalty())return null;let i=this.getCellFragments(),n=this.getAcceptableCellBreakPositions(),r=n.every(o=>!!o.nodeContext)&&n.some((o,s)=>{let a=i[s].pseudoColumn,h=o.nodeContext;return!a.isStartNodeContext(h)&&!a.isLastAfterNodeContext(h)});return this.beforeNodeContext.overflow=n.some(o=>o.nodeContext&&o.nodeContext.overflow),r?this.beforeNodeContext:null}getMinBreakPenalty(){let e=this.formattingContext.getRowByIndex(this.rowIndex),t=this.beforeNodeContext.breakPenalty,i=this.getAcceptableCellBreakPositions(),n=this.getCellFragments();t+=Math.max(0,...n.map(o=>o.cellNodeContext.breakPenalty));let r=i.some((o,s)=>o.breakPosition instanceof fr&&n[s].cellNodeContext.sourceNode.rowSpan>1);return i.forEach((o,s)=>{let a=o.breakPosition.getMinBreakPenalty();r&&o.breakPosition instanceof to&&o.breakPosition.overflows&&a>=3&&(n[s].column.checkOverflowAndSaveEdge(o.nodeContext,null)||(a-=3)),t+=a}),t}getAcceptableCellBreakPositions(){if(!this.acceptableCellBreakPositions){let e=this.getCellFragments();this.acceptableCellBreakPositions=e.map(t=>t.findAcceptableBreakPosition())}return this.acceptableCellBreakPositions}getCellFragments(){return this.formattingContext.getCellsFallingOnRow(this.rowIndex).map(this.formattingContext.getCellFragmentOfCell,this.formattingContext)}},Bn=class extends tn{constructor(e,t){super(e,t),u(this,"tableSourceNode",t),u(this,"formattingContextType","Table"),u(this,"vertical",!1),u(this,"columnCount",-1),u(this,"tableWidth",0),u(this,"captions",[]),u(this,"colGroups",null),u(this,"colWidths",null),u(this,"inlineBorderSpacing",0),u(this,"rows",[]),u(this,"slots",[]),u(this,"cellFragments",[]),u(this,"lastRowViewNode",null),u(this,"cellBreakPositions",[]),u(this,"repetitiveElements",null)}getName(){return"Table formatting context (Table.TableFormattingContext)"}isFirstTime(e,t){var i;if(!t)return t;switch(e.display){case"table-row":{let n=this.findRowIndexBySourceNode(e.sourceNode);return this.cellBreakPositions.every(r=>this.isPreviousFragmentRowSpanningCellBreakPosition(r,n))&&e.fragmentIndex<=1}case"table-cell":return e.fragmentIndex>1||((i=e.parent)==null?void 0:i.display)==="table-row"&&e.parent.fragmentIndex>1?!1:!this.cellBreakPositions.some(n=>n.cellNodePosition.steps[0].node===e.sourceNode);default:return t}}getParent(){return this.parent}finishFragment(){this.cellFragments=[]}addRow(e,t){this.rows[e]=t}getRowSlots(e){let t=this.slots[e];return t||(t=this.slots[e]=[]),t}addCell(e,t){let i=this.rows[e];i||(this.addRow(e,new _f(e,null)),i=this.rows[e]),i.addCell(t);let n=e+t.rowSpan,r=this.getRowSlots(e),o=0;for(;r[o];)o++;for(;e<n;e++){r=this.getRowSlots(e);for(let s=o;s<o+t.colSpan;s++){let a=r[s]=new X0(e,s,t);t.anchorSlot||t.setAnchorSlot(a)}}}getRowByIndex(e){return this.rows[e]}findRowIndexBySourceNode(e){return this.rows.findIndex(t=>e===t.sourceNode)}isPreviousFragmentRowSpanningCellBreakPosition(e,t){let i=e.cell;return t>=0&&i.rowIndex<t&&i.rowIndex+i.rowSpan>t}addCellFragment(e,t,i){let n=this.cellFragments[e];n||(n=this.cellFragments[e]=[]),n[t]=i}getCellsFallingOnRow(e){return this.getRowSlots(e).reduce((t,i)=>i.cell!==t[t.length-1]?t.concat(i.cell):t,[])}getRowSpanningCellsOverflowingTheRow(e){return this.getCellsFallingOnRow(e).filter(t=>t.rowIndex+t.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((t,i)=>t+i.colSpan,0)))),this.columnCount}updateCellSizes(e){this.rows.forEach(t=>{t.cells.forEach(i=>{let n=Bt(e,i.viewElement,this.vertical);i.viewElement=null,i.setHeight(this.vertical?n.width:n.height)})})}findCellFromColumn(e){if(!e)return null;let t=null,i=0,n=0;e:for(i=0;i<this.cellFragments.length;i++)if(this.cellFragments[i]){for(n=0;n<this.cellFragments[i].length;n++)if(this.cellFragments[i][n]&&e===this.cellFragments[i][n].pseudoColumn.getColumn()){t=this.rows[i].cells[n];break e}}if(!t)return null;for(;i<this.slots.length;i++)for(;n<this.slots[i].length;n++){let r=this.slots[i][n];if(r.cell===t)return{rowIndex:r.rowIndex,columnIndex:r.columnIndex}}return null}collectElementsOffsetOfUpperCells(e){let t=[];return this.slots.reduce((i,n,r)=>{if(r>=e.rowIndex)return i;let o=n[e.columnIndex]&&this.getCellFragmentOfCell(n[e.columnIndex].cell);return!o||t.includes(o)||(this.collectElementsOffsetFromColumn(o.pseudoColumn.getColumn(),i),t.push(o)),i},[])}collectElementsOffsetOfHighestColumn(){let e=[];return this.rows.forEach(t=>{t.cells.forEach((i,n)=>{e[n]||(e[n]={collected:[],elements:[]});let r=e[n],o=this.getCellFragmentOfCell(i);!o||r.collected.includes(o)||(this.collectElementsOffsetFromColumn(o.pseudoColumn.getColumn(),r.elements),r.collected.push(o))})}),[new J0(e.map(t=>t.elements))]}collectElementsOffsetFromColumn(e,t){e.fragmentLayoutConstraints.forEach(i=>{if(Yi.isInstanceOfRepetitiveElementsOwnerLayoutConstraint(i)){let n=i.getRepetitiveElements();t.push(n)}Li.isInstanceOfTableRowLayoutConstraint(i)&&i.getElementsOffsetsForTableCell(null).forEach(n=>{t.push(n)})})}saveState(){return[].concat(this.cellBreakPositions)}restoreState(e){this.cellBreakPositions=[].concat(e)}},J0=class{constructor(e){u(this,"repeatitiveElementsInColumns",e)}calculateOffset(e){return this.calculateMaxOffsetOfColumn(e,t=>t.current)}calculateMinimumOffset(e){return this.calculateMaxOffsetOfColumn(e,t=>t.minimum)}calculateMaxOffsetOfColumn(e,t){let i=0;return this.repeatitiveElementsInColumns.forEach(n=>{let r=Ln(e,n);i=Math.max(i,t(r))}),i}};function $t(e){return e instanceof Bn,e}function Q0(e){return e==="table-row-group"||e==="table-header-group"||e==="table-footer-group"}function ex(e){return e==="table"||e==="inline-table"}function Du(e){return Q0(e)||ex(e)}function Df(e,t,i){let n=e.nodeContext,r=n.display,o=n.parent?n.parent.display:null,s=!1;if(o==="inline-table"&&!(n.formattingContext instanceof Bn)){for(let a=n.parent;a;a=a.parent)if(a.formattingContext instanceof Bn){s=a.formattingContext===t;break}}return s||r==="table-row"&&!Du(o)||r==="table-cell"&&o!=="table-row"&&!Du(o)||n.formattingContext instanceof Bn&&n.formattingContext!==t?i.buildDeepElementView(n).thenAsync(a=>(e.nodeContext=a,T(!0))):null}function zf(e,t){let i=t.nodeContext;return!(i!=null&&i.floatSide)||!(Ii(i.floatReference)||i.floatSide==="footnote")?null:e.layoutFloatOrFootnote(i).thenAsync(n=>(n&&(t.nodeContext=n),T(!0)))}var tx=class extends br{constructor(e,t){super(),u(this,"formattingContext",e),u(this,"column",t),u(this,"rowIndex",-1),u(this,"columnIndex",0),u(this,"inRow",!1),u(this,"checkPoints",[]),u(this,"inHeaderOrFooter",!1)}startNonInlineElementNode(e){let t=this.formattingContext,i=Df(e,t,this.column);if(i)return i;this.postLayoutBlockContents(e);let n=zf(this.column,e);if(n)return n;let r=e.nodeContext,o=r.display,s=t.getRepetitiveElements();switch(o){case"table":t.inlineBorderSpacing=r.inlineBorderSpacing;break;case"table-caption":{let a=new Y0(r.viewNode,r.captionSide);t.captions.push(a);break}case"table-header-group":return s.isHeaderRegistered()||(this.inHeaderOrFooter=!0,s.setHeaderNodeContext(r)),T(!0);case"table-footer-group":return s.isFooterRegistered()||(this.inHeaderOrFooter=!0,s.setFooterNodeContext(r)),T(!0);case"table-row":this.inHeaderOrFooter||(this.inRow=!0,this.rowIndex++,r.sourceNode,this.columnIndex=0,t.addRow(this.rowIndex,new _f(this.rowIndex,r.sourceNode)),r.breakBefore&&(t.rows[this.rowIndex].breakBefore=r.breakBefore),s.firstContentSourceNode||(s.firstContentSourceNode=r.sourceNode));break}return super.startNonInlineElementNode(e)}afterNonInlineElementNode(e){let t=this.formattingContext,i=e.nodeContext,n=i.display,r=this.column.clientLayout;if(this.postLayoutBlockContents(e),i.sourceNode===t.tableSourceNode){let o=r.getElementComputedStyle(t.getRootViewNode(i));t.tableWidth=parseFloat(o[t.vertical?"height":"width"]),t.getRepetitiveElements().lastContentSourceNode=e.lastAfterNodeContext&&e.lastAfterNodeContext.sourceNode,e.break=!0}else switch(n){case"table-header-group":case"table-footer-group":if(this.inHeaderOrFooter)return this.inHeaderOrFooter=!1,T(!0);break;case"table-row":if(!this.inHeaderOrFooter){t.lastRowViewNode=i.viewNode,this.inRow=!1;let o=t.rows[this.rowIndex];o&&i.breakAfter&&(o.breakAfter=nt(o.breakAfter,i.breakAfter))}break;case"table-cell":if(!this.inHeaderOrFooter){this.inRow||(this.rowIndex++,this.columnIndex=0,this.inRow=!0);let o=i.viewNode;t.addCell(this.rowIndex,new j0(this.rowIndex,this.columnIndex,o)),this.columnIndex++,Hf(o);let s=t.rows[this.rowIndex];s&&(i.breakBefore&&(s.breakBefore=nt(s.breakBefore,i.breakBefore)),i.breakAfter&&(s.breakAfter=nt(s.breakAfter,i.breakAfter)))}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 t=e.nodeContext;t&&t.viewNode&&!Pn(t)&&this.checkPoints.push(t.clone())}postLayoutBlockContents(e){this.checkPoints.length>0&&this.column.postLayoutBlock(e.nodeContext,this.checkPoints),this.checkPoints=[]}},Vf=class Uf extends br{constructor(t,i){super(!0),u(this,"formattingContext",t),u(this,"column",i),u(this,"inRow",!1),u(this,"currentRowIndex",-1),u(this,"currentColumnIndex",0),u(this,"originalStopAtOverflow"),u(this,"inHeader"),u(this,"inFooter"),u(this,"didExtractRowSpanningCellBreakPositions",!1),this.originalStopAtOverflow=i.stopAtOverflow,i.stopAtOverflow=!1}startNonInlineElementNode(t){return zf(this.column,t)||super.startNonInlineElementNode(t)}resetColumn(){this.column.stopAtOverflow=this.originalStopAtOverflow}getColSpanningCellWidth(t){let i=this.formattingContext.colWidths,n=0;for(let r=0;r<t.colSpan;r++)n+=i[t.anchorSlot.columnIndex+r];return n+=this.formattingContext.inlineBorderSpacing*(t.colSpan-1),n}layoutCell(t,i,n){let r=t.rowIndex,o=t.columnIndex,s=t.colSpan,a=i.viewNode;s>1&&(I(a,"box-sizing","border-box"),I(a,this.formattingContext.vertical?"height":"width",`${this.getColSpanningCellWidth(t)}px`));let h=a.ownerDocument.createElement("div");a.appendChild(h);let l=new q0(this.column,h,i);return this.formattingContext.addCellFragment(r,o,l),n.primary.steps.length===1&&n.primary.after&&(l.empty=!0),l.pseudoColumn.layout(n,!0).thenAsync(()=>(Hf(a),T(!0)))}findBrokenCellAtSlot(t,i){let n=this.formattingContext.cellBreakPositions;for(let r=0;r<n.length;r++){let o=n[r];if(o.cell.anchorSlot.columnIndex===t&&o.cellNodePosition.steps[0].node===i)return{position:o,index:r}}return null}extractRowSpanningCellBreakPositions(){if(this.didExtractRowSpanningCellBreakPositions)return[];let t=this.formattingContext.cellBreakPositions;if(t.length===0)return[];let i=[];return t.forEach(n=>{let r=n.cell,o=r.rowIndex;if(o<this.currentRowIndex&&o+r.rowSpan>this.currentRowIndex){let s=i[o];s||(s=i[o]=[]),s.push(n)}}),this.didExtractRowSpanningCellBreakPositions=i.length>0,i}layoutRowSpanningCellsFromPreviousFragment(t){let i=this.formattingContext,n=this.extractRowSpanningCellBreakPositions(),r=n.reduce(d=>d+1,0);if(r===0)return T(!0);let o=this.column.layoutContext,s=t.nodeContext;s.viewNode.parentNode.removeChild(s.viewNode);let a=M("layoutRowSpanningCellsFromPreviousFragment"),h=T(!0),l=0,c=[];return n.forEach(d=>{h=h.thenAsync(()=>{let p=us(d[0].cellNodePosition.steps[1],s.parent);return o.setCurrent(p,!1).thenAsync(()=>{let f=T(!0),g=0;function v(w){for(;g<w;){if(!c.includes(g)){let x=p.viewNode.ownerDocument.createElement("td");I(x,"padding","0"),p.viewNode.appendChild(x)}g++}}return d.forEach(w=>{f=f.thenAsync(()=>{let x=w.cell;v(x.anchorSlot.columnIndex);let m=w.cellNodePosition,S=us(m.steps[0],p);return S.offsetInNode=m.offsetInNode,S.after=m.after,S.fragmentIndex=m.steps[0].fragmentIndex+1,o.setCurrent(S,!1).thenAsync(()=>{let b=w.breakChunkPosition;for(let C=0;C<x.colSpan;C++)c.push(g+C);return g+=x.colSpan,this.layoutCell(x,S,b).thenAsync(()=>(S.viewNode.rowSpan=x.rowIndex+x.rowSpan-this.currentRowIndex+r-l,T(!0)))})})}),f.thenAsync(()=>(v(i.getColumnCount()),l++,T(!0)))})})}),h.then(()=>{o.setCurrent(s,!0,t.atUnforcedBreak).then(()=>{a.finish(!0)})}),a.result()}startTableRow(t){if(this.inHeader||this.inFooter)return T(!0);let i=t.nodeContext,n=this.formattingContext;return this.currentRowIndex<0?(i.sourceNode,this.currentRowIndex=n.findRowIndexBySourceNode(i.sourceNode)):this.currentRowIndex++,this.currentColumnIndex=0,this.inRow=!0,this.layoutRowSpanningCellsFromPreviousFragment(t).thenAsync(()=>{var r;this.registerCellFragmentIndex();let o=t.breakAtTheEdge;if(this.currentRowIndex>0){let a=n.rows[this.currentRowIndex-1];a!=null&&a.breakAfter&&(o=nt(o,a.breakAfter))}let s=n.rows[this.currentRowIndex];return s!=null&&s.breakBefore&&(o=nt(o,s.breakBefore)),!t.leadingEdge&&Ze(o)?(this.column.checkOverflowAndSaveEdgeAndBreakPosition(t.lastAfterNodeContext,null,!0,o),(r=i.viewNode)!=null&&r.parentNode&&i.viewNode.parentNode.removeChild(i.viewNode),t.lastAfterNodeContext&&this.column.layoutContext.processFragmentedBlockEdge(t.lastAfterNodeContext),this.column.pageBreakType=o,this.resetColumn(),t.break=!0,T(!0)):(this.column.checkOverflowAndSaveEdgeAndBreakPosition(t.lastAfterNodeContext,null,!0,o)&&n.getRowSpanningCellsOverflowingTheRow(this.currentRowIndex-1).length===0&&(this.resetColumn(),i.overflow=!0,t.break=!0),T(!0))})}registerCellFragmentIndex(){this.formattingContext.getRowByIndex(this.currentRowIndex).cells.forEach(t=>{let i=this.formattingContext.cellBreakPositions.find(n=>n.cell===t);if(i){let n=i.cellNodePosition.steps[0],r=this.column.layoutContext.xmldoc.getElementOffset(n.node);E0(r,n.fragmentIndex+1,1)}})}startTableCell(t){if(this.inHeader||this.inFooter)return T(!0);let i=t.nodeContext;this.inRow||(this.currentRowIndex<0?this.currentRowIndex=0:this.currentRowIndex++,this.currentColumnIndex=0,this.inRow=!0);let n=this.formattingContext.getRowByIndex(this.currentRowIndex).cells[this.currentColumnIndex];if(!n)return t.break=!0,T(!0);let r=i.copy().modify();r.after=!0,t.nodeContext=r;let o=M("startTableCell"),s,a=this.findBrokenCellAtSlot(n.anchorSlot.columnIndex,i.sourceNode);if(a){let h=a.position;this.formattingContext.cellBreakPositions.splice(a.index,1),i.fragmentIndex=h.cellNodePosition.steps[0].fragmentIndex+1,s=T(h.breakChunkPosition)}else s=this.column.nextInTree(i,t.atUnforcedBreak).thenAsync(h=>{h.viewNode&&i.viewNode.removeChild(h.viewNode);let l=hs(h,0);return T(new Bi(l))});return s.then(h=>{this.layoutCell(n,i,h).then(()=>{this.afterNonInlineElementNode(t),this.currentColumnIndex++,o.finish(!0)})}),o.result()}startNonInlineBox(t){let i=Df(t,$t(this.formattingContext),this.column);if(i)return i;let n=t.nodeContext,r=this.formattingContext.getRepetitiveElements(),o=n.display;return o==="table-header-group"&&r&&r.isHeaderSourceNode(n.sourceNode)?(this.inHeader=!0,T(!0)):o==="table-footer-group"&&r&&r.isFooterSourceNode(n.sourceNode)?(this.inFooter=!0,T(!0)):o==="table-row"?this.startTableRow(t):o==="table-cell"?this.startTableCell(t):T(!0)}endNonInlineBox(t){let i=t.nodeContext;if(i.display==="table-row"&&(this.inRow=!1,!this.inHeader&&!this.inFooter)){let n=i.copy().modify();n.after=!1;let r=new K0(this.currentRowIndex,n,this.formattingContext);this.column.breakPositions.push(r)}return T(!0)}afterNonInlineElementNode(t){let i=t.nodeContext,n=this.formattingContext.getRepetitiveElements(),r=i.display;if(r==="table-header-group"?n&&!n.allowInsertRepeatitiveElements&&n.isHeaderSourceNode(i.sourceNode)?(this.inHeader=!1,i.viewNode.parentNode.removeChild(i.viewNode)):I(i.viewNode,"display","table-row-group"):r==="table-footer-group"&&(n&&!n.allowInsertRepeatitiveElements&&n.isFooterSourceNode(i.sourceNode)?(this.inFooter=!1,i.viewNode.parentNode.removeChild(i.viewNode)):I(i.viewNode,"display","table-row-group")),r&&Uf.ignoreList[r])i.viewNode.parentNode.removeChild(i.viewNode);else if(i.sourceNode===this.formattingContext.tableSourceNode)i.overflow=this.column.checkOverflowAndSaveEdge(i,null),this.resetColumn(),t.break=!0;else if(r==="table-row"&&!this.inHeader&&!this.inFooter){let o=super.afterNonInlineElementNode(t);return(o&&o.isPending()?o:T(!0)).thenAsync(()=>{if(!t.break){let s=this.column.checkOverflowAndSaveEdge(i,null),a=this.formattingContext.getRepetitiveElements(),h=this.column.nodeContextOverflowingDueToRepetitiveElements===i,l=!s&&h&&!!(a!=null&&a.isFooterRegistered());(s||h)&&!l&&this.formattingContext.getRowSpanningCellsOverflowingTheRow(this.currentRowIndex).length===0&&(this.resetColumn(),i.overflow=!0,t.break=!0)}return T(!0)})}else return super.afterNonInlineElementNode(t);return T(!0)}};u(Vf,"ignoreList",{"table-caption":!0,"table-column-group":!0,"table-column":!0});var ix=Vf,zr=[];function nx(e){let t=zr.findIndex(n=>n.root===e),i=zr[t];return i?i.tableLayoutOption:null}function rx(e){let t=zr.findIndex(i=>i.root===e);t>=0&&zr.splice(t,1)}var $f=class{layoutEntireTable(e,t){let i=$t(e.formattingContext),n=new tx(i,t);return new Wa(n,t.layoutContext).iterate(e)}getColumnWidths(e,t,i,n){let r=e.ownerDocument,o=r.createElement("tr"),s=[];for(let h=0;h<t;h++){let l=r.createElement("td");o.appendChild(l),s.push(l)}e.parentNode.insertBefore(o,e.nextSibling);let a=s.map(h=>{let l=Bt(n,h,i),c=i?l.height:l.width;return Math.ceil(c)});return e.parentNode.removeChild(o),a}getColGroupElements(e){let t=[],i=e.firstElementChild;for(;i;)i.localName==="colgroup"&&t.push(i),i=i.nextElementSibling;return t}normalizeAndGetColElements(e){let t=[];return e.forEach(i=>{let n=i.span;i.removeAttribute("span");let r=i.firstElementChild;for(;r;){if(r.localName==="col"){let o=r.span;for(r.removeAttribute("span"),n-=o;o-- >1;){let s=r.cloneNode(!0);i.insertBefore(s,r),t.push(s)}t.push(r)}r=r.nextElementSibling}for(;n-- >0;)r=i.ownerDocument.createElement("col"),i.appendChild(r),t.push(r)}),t}addMissingColElements(e,t,i,n){if(e.length<i){let r=n.ownerDocument.createElement("colgroup");t.push(r);for(let o=e.length;o<i;o++){let s=n.ownerDocument.createElement("col");r.appendChild(s),e.push(s)}}}normalizeColGroups(e,t,i){let n=e.vertical,r=e.lastRowViewNode;if(!r)return;e.lastRowViewNode=null;let o=r.ownerDocument.createDocumentFragment(),s=e.getColumnCount();if(!(s>0)){e.colGroups=o;return}let a=e.colWidths=this.getColumnWidths(r,s,n,i.clientLayout),h=this.getColGroupElements(t),l=this.normalizeAndGetColElements(h);this.addMissingColElements(l,h,s,t),l.forEach((c,d)=>{I(c,n?"height":"width",`${a[d]}px`)}),h.forEach(c=>{o.appendChild(c.cloneNode(!0))}),e.colGroups=o}doInitialLayout(e,t){let i=$t(e.formattingContext);i.vertical=e.vertical,i.initializeRepetitiveElements(e.vertical),e.sourceNode;let n=nx(e.sourceNode);rx(e.sourceNode);let r=M("TableLayoutProcessor.doInitialLayout"),o=e.copy();return this.layoutEntireTable(e,t).then(s=>{var a;let h=s.viewNode,l=i.rows[0];if(l&&Ze(l.breakBefore)&&this.hasInFlowContentBefore(h,t)){(a=h.parentNode)==null||a.removeChild(h),t.pageBreakType=l.breakBefore,r.finish(o);return}let c=Bt(t.clientLayout,h,t.vertical),d=t.vertical?c.left:c.bottom;if(d+=(t.vertical?-1:1)*Ln(e,t.collectElementsOffset()).current,!t.isOverflown(d)&&(!n||!n.calculateBreakPositionsInside)&&!this.hasForcedBreakInRows(i)){t.breakPositions.push(new lx(o)),r.finish(s);return}this.normalizeColGroups(i,h,t),i.updateCellSizes(t.clientLayout),r.finish(null)}),r.result()}hasForcedBreakInRows(e){for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(i&&(t>0&&Ze(i.breakBefore)||t<e.rows.length-1&&Ze(i.breakAfter)))return!0}return!1}hasInFlowContentBefore(e,t){let i=e;for(;i&&i!==t.element;){let n=i.previousSibling;for(;n;){if(n.nodeType===1&&!Ot(n)||n.nodeType===3&&!Ee(n))return!0;n=n.previousSibling}i=i.parentNode}return!1}addCaptions(e,t,i){let n=e.captions;n.forEach((r,o)=>{r&&(t.insertBefore(r.viewNode,i),r.side==="top"&&(n[o]=null))})}addColGroups(e,t,i){e.colGroups&&this.getColGroupElements(t).length===0&&(t.insertBefore(e.colGroups.cloneNode(!0),i),I(t,"table-layout","fixed"),I(t,e.vertical?"height":"width",`${e.tableWidth}px`))}removeColGroups(e,t){if(e.colGroups&&t){let i=this.getColGroupElements(t);i&&i.forEach(n=>{t.removeChild(n)})}}doLayout(e,t){let i=$t(e.formattingContext),n=i.getRootViewNode(e),r=n.firstChild;this.addCaptions(i,n,r),this.addColGroups(i,n,r);let o=new ix(i,t),s=new Wa(o,t.layoutContext),a=M("TableFormattingContext.doLayout");return s.iterate(e).thenFinish(a),a.result()}layout(e,t,i){let n=$t(e.formattingContext);if(n.getRootViewNode(e)){if(i){let r=n.getRepetitiveElements();r&&e.sourceNode!==n.tableSourceNode&&!e.after&&!r.isFooterRegistered()&&r.preventSkippingHeader(),Bf(e.parent,t)}return new sx(n,this).layout(e,t)}else return t.buildDeepElementView(e)}createEdgeBreakPosition(e,t,i,n){return new Z0(e,t,i,n)}startNonInlineElementNode(e){return!1}afterNonInlineElementNode(e,t){return ya(e),!1}finishBreak(e,t,i,n){let r=$t(t.formattingContext);if(t.display==="table-row"){t.sourceNode;let o=r.findRowIndexBySourceNode(t.sourceNode),s;if(t.after?s=r.getRowSpanningCellsOverflowingTheRow(o):s=r.getCellsFallingOnRow(o),r.cellBreakPositions=r.cellBreakPositions.filter(a=>!s.includes(a.cell)),s.length){let a=M("TableLayoutProcessor.finishBreak"),h=0;return a.loopWithFrame(l=>{if(h===s.length){l.breakLoop();return}let c=s[h++],d=r.getCellFragmentOfCell(c),p=d.findAcceptableBreakPosition().nodeContext,f=d.cellNodeContext,g=f.toNodePosition(),v=new Bi(p.toNodePosition());r.cellBreakPositions.push({cellNodePosition:g,breakChunkPosition:v,cell:c});let w=f.viewNode;d.column.layoutContext.processFragmentedBlockEdge(d.cellNodeContext),o<c.rowIndex+c.rowSpan-1&&(w.rowSpan=o-c.rowIndex+1),d.empty?l.continueLoop():d.pseudoColumn.finishBreak(p,!1,!0).then(()=>{ox(d,r,p),l.continueLoop()})}).then(()=>{e.clearOverflownViewNodes(t,!1),e.layoutContext.processFragmentedBlockEdge(t),ya(t),r.finishFragment(),a.finish(!0)}),a.result()}}return ya(t),r.finishFragment(),Xl.finishBreak(e,t,i,n)}clearOverflownViewNodes(e,t,i,n){Tn.prototype.clearOverflownViewNodes(e,t,i,n)}};function ox(e,t,i){let n=t.getRepetitiveElements();if(!n||!(n.isHeaderRegistered()||n.isFooterRegistered()))return;let r=t.vertical,o=e.column,s=e.pseudoColumn.getColumnElement(),a=e.cellNodeContext.viewNode,h=Bt(o.clientLayout,a,r),l=o.getComputedPaddingBorder(a);if(r){let c=h.right-o.footnoteEdge-n.calculateOffset(i)-l.right;I(s,"max-width",`${c}px`)}else{let c=o.footnoteEdge-n.calculateOffset(i)-h.top-l.top;I(s,"max-height",`${c}px`)}}function Hf(e){let t=e.matches("td, th")?e:e.closest("td, th");if(!t||t.style.verticalAlign!=="baseline")return;let i=t.querySelector(".-vivliostyle-table-cell-container");if(!i)return;let n=i.children;if(n.length!==0){for(let r=0;r<n.length;r++){let o=n[r].style.position;if(o!=="absolute"&&o!=="fixed")return}I(i,"display","contents")}}function ya(e){let t=e.display==="table-row"?e.viewNode.parentElement:e.display==="table"?e.viewNode.querySelector("tbody"):null;if(!t)return;let i;try{i=t.querySelectorAll(":scope>tr:has(>:empty):not(:has(>:not([rowspan]:not([rowspan='1']),:empty)))")}catch{return}if(i.length===0)return;let n=Array.from(i).reduce((d,p)=>{let f=p.getBoundingClientRect(),g=e.vertical?f.width:f.height;return d+g},0),r=i[i.length-1],o=Array.from(t.children).indexOf(r),s=Array.from(r.children).reduce((d,p)=>{let f=p.rowSpan;return f>1&&o+f<t.childElementCount?Math.max(d,f):d},0),a=s?t.children[o+s-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 h=a.getBoundingClientRect(),l=e.vertical?h.width:h.height,c=n+l;I(a,e.vertical?"width":"height",`${c}px`)}var sx=class extends ql{constructor(e,t){super(),u(this,"tableFormattingContext",e),u(this,"processor",t)}resolveLayoutMode(e){let t=this.tableFormattingContext.getRepetitiveElements();return!t||!t.doneInitialLayout?new ax(this.tableFormattingContext,this.processor):(e.sourceNode===this.tableFormattingContext.tableSourceNode&&!e.after&&t&&t.preventSkippingHeader(),new ux(this.tableFormattingContext,this.processor))}clearNodes(e){super.clearNodes(e);let t=this.tableFormattingContext.getRootViewNode(e);this.processor.removeColGroups(this.tableFormattingContext,t)}restoreState(e,t){super.restoreState(e,t),this.tableFormattingContext.finishFragment()}},ax=class extends Rf{constructor(e,t){super(e),u(this,"processor",t)}doLayout(e,t){return this.processor.doInitialLayout(e,t)}},lx=class extends to{constructor(e){super(e,null,e.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(e){e.fragmentLayoutConstraints.push(new hx(this.position.sourceNode))}},hx=class Wf{constructor(t){u(this,"tableRootNode",t),u(this,"flagmentLayoutConstraintType","EntireTable")}allowLayout(t,i,n){return t.overflow,!1}nextCandidate(t){return!0}postLayout(t,i,n,r){i.sourceNode,zr.push({root:i.sourceNode,tableLayoutOption:{calculateBreakPositionsInside:!0}})}finishBreak(t,i){return T(!0)}equalsTo(t){return t instanceof Wf&&t.tableRootNode===this.tableRootNode}getPriorityOfFinishBreak(){return 0}},ux=class extends Lf{constructor(e,t){super(e),u(this,"processor",t)}doLayout(e,t){let i=this.formattingContext.getRepetitiveElements();if(i&&!i.isAfterLastContent(e)){let n=new cx(e);t.fragmentLayoutConstraints.some(r=>n.equalsTo(r))||t.fragmentLayoutConstraints.unshift(n)}return this.processor.doLayout(e,t)}},cx=class Gf extends ch{constructor(t){super(t),u(this,"flagmentLayoutConstraintType","TableRow"),u(this,"cellFragmentLayoutConstraints",[])}allowLayout(t,i,n){let r=this.getRepetitiveElements();return!r||n.pseudoParent||En(this.nodeContext.viewNode)||!r.isEnableToUpdateState()?!0:i&&!t||t&&t.overflow?!Mf(t,i,r):!0}nextCandidate(t){let i=$t(this.nodeContext.formattingContext);return this.collectCellFragmentLayoutConstraints(t,i).some(n=>n.constraints.some(r=>r.nextCandidate(t)))?!0:super.nextCandidate(t)}postLayout(t,i,n,r){let o=$t(this.nodeContext.formattingContext);if(this.cellFragmentLayoutConstraints=this.collectCellFragmentLayoutConstraints(i,o),this.cellFragmentLayoutConstraints.forEach(s=>{s.constraints.forEach(a=>{a.postLayout(t,s.breakPosition,n,r)})}),!t){let s=o.getRootViewNode(this.nodeContext);new $f().removeColGroups(o,s),this.removeDummyRowNodes(n)}super.postLayout(t,i,n,r)}finishBreak(t,i){let n=$t(this.nodeContext.formattingContext),r=M("finishBreak"),o=this.cellFragmentLayoutConstraints.reduce((a,h)=>a.concat(h.constraints.map(l=>({constraint:l,breakPosition:h.breakPosition}))),[]),s=0;return r.loop(()=>{if(s<o.length){let a=o[s++];return a.constraint.finishBreak(a.breakPosition,i).thenReturn(!0)}else return T(!1)}).then(()=>{r.finish(!0)}),r.result().thenAsync(()=>super.finishBreak(t,i))}removeDummyRowNodes(t){if(!(!t||t.display!=="table-row"||!t.viewNode))for(;t.viewNode.previousElementSibling;){let i=t.viewNode.previousElementSibling;i.parentNode&&i.parentNode.removeChild(i)}}collectCellFragmentLayoutConstraints(t,i){return this.getCellFragemnts(t,i).map(n=>({constraints:n.fragment.pseudoColumn.getColumn().fragmentLayoutConstraints,breakPosition:n.breakPosition}))}getCellFragemnts(t,i){let n=Number.MAX_VALUE;t&&t.display==="table-row"&&(t.sourceNode,n=i.findRowIndexBySourceNode(t.sourceNode)+1),n=Math.min(i.cellFragments.length,n);let r=[];for(let o=0;o<n;o++)i.cellFragments[o]&&i.cellFragments[o].forEach(s=>{s&&r.push({fragment:s,breakPosition:s.findAcceptableBreakPosition().nodeContext})});return r}getElementsOffsetsForTableCell(t){let i=$t(this.nodeContext.formattingContext),n=i.findCellFromColumn(t);return n?i.collectElementsOffsetOfUpperCells(n):i.collectElementsOffsetOfHighestColumn()}equalsTo(t){return t instanceof Gf?$t(this.nodeContext.formattingContext)===$t(t.nodeContext.formattingContext):!1}},dx=new $f;function px(e,t,i,n,r,o){if(!t)return null;if(i===y.table){let s=e.parent;return new Bn(s?s.formattingContext:null,e.sourceNode)}return null}function fx(e){return e instanceof Bn?dx:null}Ft("RESOLVE_FORMATTING_CONTEXT",px);Ft("RESOLVE_LAYOUT_PROCESSOR",fx);function zu(e){return e.reduce((t,i)=>t+i,0)/e.length}function gx(e){let t=zu(e);return zu(e.map(i=>{let n=i-t;return n*n}))}var mx=class{constructor(e,t){u(this,"layoutResult",e),u(this,"penalty",t)}};function Vr(e){return e.vertical?e.width:e.height}function Ur(e,t){e.vertical?e.width=t:e.height=t}var jf=class{constructor(e,t,i){u(this,"layoutContainer",e),u(this,"columnGenerator",t),u(this,"regionPageFloatLayoutContext",i),u(this,"originalContainerBlockSize"),this.originalContainerBlockSize=Vr(e)}balanceColumns(e){let t=M("ColumnBalancer#balanceColumns");this.layoutContainer.element.setAttribute("data-vivliostyle-in-column-balancing","true"),this.preBalance(e),this.savePageFloatLayoutContexts(e),this.layoutContainer.clear();let i=[this.createTrialResult(e)];return t.loopWithFrame(n=>{if(!this.hasNextCandidate(i)){n.breakLoop();return}this.updateCondition(i),this.columnGenerator().then(r=>{if(this.savePageFloatLayoutContexts(r),this.layoutContainer.clear(),!r){n.breakLoop();return}i.push(this.createTrialResult(r)),n.continueLoop()})}).then(()=>{let n=i.reduce((r,o)=>o.penalty<r.penalty?o:r,i[0]);this.layoutContainer.element.removeAttribute("data-vivliostyle-in-column-balancing"),this.restoreContents(n.layoutResult),this.tightenColumnBlockSizes(n.layoutResult.columns),this.postBalance(),t.finish(n.layoutResult)}),t.result()}createTrialResult(e){let t=this.calculatePenalty(e);return new mx(e,t)}preBalance(e){}postBalance(){Ur(this.layoutContainer,this.originalContainerBlockSize)}tightenColumnBlockSizes(e){if(e.length<=1)return;let t=Math.max.apply(null,e.map(i=>i.computedBlockSize));if(!(t<=0))for(let i of e)if(i.vertical){let n=parseFloat(i.element.style.width),r=parseFloat(i.element.style.left);if(isFinite(n)&&isFinite(r)&&n>t){let o=r+n-t;I(i.element,"width",`${t}px`),I(i.element,"left",`${o}px`),i.width=t,i.left=o}}else{let n=parseFloat(i.element.style.height);isFinite(n)&&n>t&&(I(i.element,"height",`${t}px`),i.height=t)}}savePageFloatLayoutContexts(e){let t=this.regionPageFloatLayoutContext.detachChildren();e&&(e.columnPageFloatLayoutContexts=t)}restoreContents(e){let t=this.layoutContainer.element;e.columns.forEach(i=>{t.appendChild(i.element)}),e.columnPageFloatLayoutContexts,this.regionPageFloatLayoutContext.attachChildren(e.columnPageFloatLayoutContexts)}},dl=1;function Xf(e){let t=e[e.length-1];if(t.penalty===0)return!1;let i=e[e.length-2];if(i&&t.penalty>=i.penalty)return!1;let n=t.layoutResult.columns,r=Math.max.apply(null,n.map(s=>s.computedBlockSize)),o=Math.max.apply(null,n.map(s=>s.getMaxBlockSizeOfPageFloats()));return r>o+dl}function qf(e,t){let i=e[e.length-1].layoutResult.columns,n=Math.max.apply(null,i.map(r=>isNaN(r.blockDistanceToBlockEndFloats)?r.computedBlockSize:r.computedBlockSize-r.blockDistanceToBlockEndFloats+dl))-dl;n<Vr(t)?Ur(t,n):Ur(t,Vr(t)-1)}var yx=class extends jf{constructor(e,t,i,n){super(i,e,t),u(this,"columnCount",n),u(this,"originalPosition",null),u(this,"foundUpperBound",!1)}preBalance(e){let t=e.columns.reduce((i,n)=>i+n.computedBlockSize,0);Ur(this.layoutContainer,t/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 t=e.columns;return Vu(t)?1/0:Math.max.apply(null,t.map(i=>i.computedBlockSize))}hasNextCandidate(e){if(e.length===1)return!0;if(this.foundUpperBound)return Xf(e);{let t=e[e.length-1];return this.checkPosition(t.layoutResult.position)&&!Vu(t.layoutResult.columns)?(this.foundUpperBound=!0,!0):Vr(this.layoutContainer)<this.originalContainerBlockSize}}updateCondition(e){if(this.foundUpperBound)qf(e,this.layoutContainer);else{let t=Math.min(this.originalContainerBlockSize,Vr(this.layoutContainer)+this.originalContainerBlockSize*.1);Ur(this.layoutContainer,t)}}};function Vu(e){if(e.length<=1)return!1;let t=e[e.length-1].computedBlockSize,i=e.slice(0,e.length-1),n=Math.max(...e.map(o=>o.lastLineStride||0)),r=n>0?n/2:6;return i.every(o=>t>o.computedBlockSize+r)}var vx=class extends jf{constructor(e,t,i){super(i,e,t)}calculatePenalty(e){if(e.columns.every(i=>i.computedBlockSize===0))return 1/0;let t=e.columns.filter(i=>!i.pageBreakType).map(i=>i.computedBlockSize);return gx(t)}hasNextCandidate(e){return Xf(e)}updateCondition(e){qf(e,this.layoutContainer)}};function wx(e,t,i,n,r,o,s){if(t===y.auto)return null;{let a=s.positions.length===0,h=o[o.length-1],l=!!(h&&h.pageBreakType);return a||l?new yx(i,n,r,e):t===y.balance_all?new vx(i,n,r):(y.balance,null)}}var va=class{constructor(e,t,i){u(this,"endStuckFixed"),u(this,"endFixed"),u(this,"endSlipped"),this.endStuckFixed=e,this.endFixed=t,this.endSlipped=i}},bx=class{constructor(){u(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(e){if(this.map.length==0)this.map.push(new va(e,e,e));else{let t=this.map[this.map.length-1],i=t.endSlipped+e-t.endFixed;t.endFixed==t.endStuckFixed?(t.endFixed=e,t.endStuckFixed=e,t.endSlipped=i):this.map.push(new va(e,e,i))}}addSlippedRange(e){this.map.length==0?this.map.push(new va(e,0,0)):this.map[this.map.length-1].endFixed=e}slippedByFixed(e){let t=mi(this.map.length,n=>e<=this.map[n].endFixed),i=this.map[t];return i.endSlipped-Math.max(0,i.endStuckFixed-e)}fixedBySlipped(e){let t=mi(this.map.length,n=>e<=this.map[n].endSlipped),i=this.map[t];return i.endStuckFixed-(i.endSlipped-e)}};function xx(e){let t={};return Object.keys(e).forEach(i=>{t[i]=Array.from(e[i])}),t}var Sx=class pl{constructor(t,i,n,r,o,s,a,h){if(u(this,"context",t),u(this,"style",i),u(this,"offset",n),u(this,"isRoot",r),u(this,"flowChunk",o),u(this,"atBlockStart",s),u(this,"atFlowStart",a),u(this,"isParentBoxDisplayed",h),u(this,"flowName"),u(this,"isBlockValue",null),u(this,"hasBoxValue",null),u(this,"styleValues",{}),u(this,"beforeBox",null),u(this,"afterBox",null),u(this,"breakBefore",null),this.flowName=o.flowName,this.hasBox()){let l=i._pseudos;if(l&&l.before){let c=new pl(t,l.before,n,!1,o,this.isBlock(),a,!0),d=c.styleValue("content");It(d)&&(this.beforeBox=c,this.breakBefore=c.breakBefore)}}this.breakBefore=nt(this.getBreakValue("before"),this.breakBefore),this.atFlowStart&&Ze(this.breakBefore)&&(o.breakBefore=nt(o.breakBefore,this.breakBefore))}buildAfterPseudoElementBox(t,i,n){if(this.hasBox()){let r=this.style._pseudos;if(r&&r.after){let o=new pl(this.context,r.after,t,!1,this.flowChunk,i,n,!0),s=o.styleValue("content");It(s)&&(this.afterBox=o)}}}styleValue(t,i){if(!(t in this.styleValues)){let n=this.style[t];this.styleValues[t]=n?n.evaluate(this.context,t):i||null}return this.styleValues[t]}displayValue(){return this.styleValue("display",y.inline)}isBlock(){if(this.isBlockValue===null){let t=this.displayValue(),i=this.styleValue("position"),n=this.styleValue("float");this.isBlockValue=Vd(t,i,n,this.isRoot)}return this.isBlockValue}hasBox(){return this.hasBoxValue===null&&(this.hasBoxValue=this.isParentBoxDisplayed&&this.displayValue()!==y.none&&!vr(this.styleValue("position"))),this.hasBoxValue}getBreakValue(t){let i=null;if(this.isBlock()){let n=this.styleValue(`break-${t}`);n&&(i=n.toString())}return i}},Cx=class{constructor(e){u(this,"context",e),u(this,"stack",[]),u(this,"atBlockStart",!0),u(this,"atFlowStart",!0),u(this,"atStartStack",[])}empty(){return this.stack.length===0}lastBox(){return this.stack[this.stack.length-1]}lastFlowName(){let e=this.lastBox();return e?e.flowChunk.flowName:null}isCurrentBoxDisplayed(){return this.stack.every(e=>e.displayValue()!==y.none)}push(e,t,i,n){let r=this.lastBox();n&&r&&n.flowName!==r.flowName&&this.atStartStack.push({atBlockStart:this.atBlockStart,atFlowStart:this.atFlowStart});let o=n||r.flowChunk,s=this.atFlowStart||!!n,a=this.isCurrentBoxDisplayed(),h=new Sx(this.context,e,t,i,o,s||this.atBlockStart,s,a);return this.stack.push(h),this.atBlockStart=h.hasBox()?!h.beforeBox&&h.isBlock():this.atBlockStart,this.atFlowStart=h.hasBox()?!h.beforeBox&&s:this.atFlowStart,h}encounteredTextNode(e){let t=this.lastBox();if((e.nodeType===Node.TEXT_NODE||e.nodeType===Node.CDATA_SECTION_NODE)&&(this.atBlockStart||this.atFlowStart)&&t.hasBox()){let i=t.styleValue("white-space",y.normal).toString(),n=ep(i);n&&!Ee(e,n)&&(this.atBlockStart=!1,this.atFlowStart=!1)}}pop(e){let t=this.stack.pop();if(t.buildAfterPseudoElementBox(e,this.atBlockStart,this.atFlowStart),this.atFlowStart&&t.afterBox){let n=t.afterBox.getBreakValue("before");t.flowChunk.breakBefore=nt(t.flowChunk.breakBefore,n)}let i=this.lastBox();if(i)if(i.flowName===t.flowName)t.hasBox()&&(this.atBlockStart=this.atFlowStart=!1);else{let n=this.atStartStack.pop();this.atBlockStart=n.atBlockStart,this.atFlowStart=n.atFlowStart}return t}nearestBlockStartOffset(e){if(!e.atBlockStart)return e.offset;let t=this.stack.length-1,i=this.stack[t];for(i===e&&(t--,i=this.stack[t]);t>=0;){if(i.flowName!==e.flowName)return e.offset;if(!i.atBlockStart||i.isRoot)return i.offset;e=i,i=this.stack[--t]}throw new Error("No block start offset found!")}},Uu=class{constructor(e,t,i,n,r,o,s,a,h,l){u(this,"xmldoc",e),u(this,"scope",i),u(this,"context",n),u(this,"primaryFlows",r),u(this,"validatorSet",o),u(this,"counterListener",s),u(this,"root"),u(this,"cascadeHolder"),u(this,"last"),u(this,"rootStyle",{}),u(this,"styleMap",{}),u(this,"counterSnapshots",[]),u(this,"flows",{}),u(this,"flowChunks",[]),u(this,"flowListener",null),u(this,"flowToReach",null),u(this,"idToReach",null),u(this,"cascade"),u(this,"offsetMap"),u(this,"primary",!0),u(this,"primaryStack",[]),u(this,"rootBackgroundAssigned",!1),u(this,"rootLayoutAssigned",!1),u(this,"lastOffset"),u(this,"breakBeforeValues",{}),u(this,"boxStack"),u(this,"bodyReached",!0),this.root=e.root,this.cascadeHolder=t,this.last=this.root,this.cascade=t.createInstance(n,s,a,e.lang,h,l),this.offsetMap=new bx;let c=e.getElementOffset(this.root);this.lastOffset=c,this.boxStack=new Cx(n),this.offsetMap.addStuckRange(c);let d=this.getAttrStyle(this.root);this.cascade.pushElement(this,this.root,d,c),this.recordCounterSnapshot(c,this.cascade.counters,this.cascade.lastCounterChanges,this.cascade.lastCounterChangeTypes),this.postprocessTopStyle(d,!1),this.root.namespaceURI==="http://www.w3.org/1999/xhtml"&&(this.bodyReached=!1),this.primaryStack.push(!0),this.styleMap={},this.styleMap[`e${c}`]=d,this.lastOffset++,this.replayFlowElementsFromOffset(-1)}hasProp(e,t,i){let n=e[i];return n&&n.evaluate(this.context)!==t[i]}transferPropsToRoot(e,t){for(let i in t){let n=e[i];if(n)this.rootStyle[i]=n,delete e[i];else{let r=t[i];r&&(this.rootStyle[i]=new W(r,Rd))}}}postprocessTopStyle(e,t){var i;if(t)for(let n of["writing-mode","direction"])e[n]&&!(t&&this.rootStyle[n])&&(this.rootStyle[n]=e[n]);else for(let n in e)In(n)&&(this.rootStyle[n]=e[n]);if(!this.rootBackgroundAssigned){let n=this.hasProp(e,this.validatorSet.backgroundProps,"background-color")?e["background-color"].evaluate(this.context):null,r=this.hasProp(e,this.validatorSet.backgroundProps,"background-image")?e["background-image"].evaluate(this.context):null;(n&&!Z(n)||r&&!Z(r))&&(this.transferPropsToRoot(e,this.validatorSet.backgroundProps),this.rootBackgroundAssigned=!0)}if(!this.rootLayoutAssigned){for(let n=0;n<$u.length;n++)if(this.hasProp(e,this.validatorSet.layoutProps,$u[n])){this.transferPropsToRoot(e,this.validatorSet.layoutProps),this.rootLayoutAssigned=!0;break}}if(!t){let n=e["font-size"],r=!0;if(n&&!Z(n.value)){let a=n.evaluate(this.context);if(a instanceof O){let h=a.num;switch(a.unit){case"em":case"rem":h*=this.context.initialFontSize;break;case"%":h*=this.context.initialFontSize/100;break;case"lh":case"rlh":h*=this.context.initialFontSize*Zt.lh/Zt.em;break;default:{let l=Zt[a.unit];l&&(h*=l),r=!1}}this.context.rootFontSize=h,this.context.isRelativeRootFontSize=r}}let o=(i=this.context.rootFontSize)!=null?i:this.context.initialFontSize,s=e["line-height"];if(s&&!Z(s.value)){let a=s.evaluate(this.context);if(a instanceof At)this.context.rootLineHeight=a.num*o;else if(a instanceof O){let h=a.num;switch(a.unit){case"em":case"rem":h*=o;break;case"%":h*=o/100;break;case"lh":case"rlh":h*=this.context.initialFontSize*this.context.pref.lineHeight;break;default:{let l=Zt[a.unit];l&&(h*=l)}}this.context.rootLineHeight=h}}else this.context.rootLineHeight=this.context.fontSize()*this.context.pref.lineHeight}}getTopContainerStyle(){let e=0;for(;!this.bodyReached&&(e+=5e3,this.styleUntil(e,0)!=Number.POSITIVE_INFINITY););return this.rootStyle}getAttrStyle(e){if(e.style instanceof CSSStyleDeclaration){let t=e.getAttribute("style");if(t)return p0(this.scope,this.validatorSet,this.xmldoc.url,t)}return{}}recordCounterSnapshot(e,t,i=[],n){let r={offset:e,counters:xx(t),changes:Array.from(i||[]),changeTypes:n?{...n}:void 0},o=this.counterSnapshots[this.counterSnapshots.length-1];if(o&&o.offset===e){this.counterSnapshots[this.counterSnapshots.length-1]=r;return}this.counterSnapshots.push(r)}getCounterSnapshotAtOffset(e){if(!this.counterSnapshots.length)return null;let t=mi(this.counterSnapshots.length,n=>e<this.counterSnapshots[n].offset),i=t===0?0:t-1;return this.counterSnapshots[i]||null}getLastCounterSnapshot(){return this.counterSnapshots.length?this.counterSnapshots[this.counterSnapshots.length-1]:null}getReachedOffset(){return this.lastOffset}replayFlowElementsFromOffset(e){if(e>=this.lastOffset)return;let t=this.context,i=this.xmldoc.getElementOffset(this.root);if(e<i){let o=this.getStyle(this.root,!1);if(!this.cascade.firstPageType){let l=o.page,c=l&&!Z(l.value)&&l.value.toString();c&&c.toLowerCase()!=="auto"&&(this.cascade.firstPageType=c)}let s=ve(o,"flow-into"),a=s?s.evaluate(t,"flow-into").toString():"body",h=this.encounteredFlowElement(a,o,this.root,i);this.boxStack.empty()&&this.boxStack.push(o,i,!0,h)}let n=this.xmldoc.getNodeByOffset(e),r=this.xmldoc.getNodeOffset(n,0,!1);if(!(r>=this.lastOffset))for(;;){if(n.nodeType!=1)r+=n.textContent.length;else{let s=n,a=this.getStyle(s,!1),h=a["flow-into"];if(h){let l=h.evaluate(t,"flow-into").toString();this.encounteredFlowElement(l,a,s,r)}r++}if(r>=this.lastOffset)break;let o=n.firstChild;if(o==null){for(;o=n.nextSibling,!o;)if(n=n.parentNode,n===this.root)return}n=o}}resetFlowChunkStream(e){this.flowListener=e;for(let t=0;t<this.flowChunks.length;t++)this.flowListener.encounteredFlowChunk(this.flowChunks[t],this.flows[this.flowChunks[t].flowName])}styleUntilFlowIsReached(e){this.flowToReach=e;let t=0;for(;!(this.flowToReach==null||(t+=5e3,this.styleUntil(t,0)==Number.POSITIVE_INFINITY)););}styleUntilIdIsReached(e){if(!e)return;this.idToReach=e;let t=0;for(;!(!this.idToReach||(t+=5e3,this.styleUntil(t,0)===Number.POSITIVE_INFINITY)););this.idToReach=null}encounteredFlowElement(e,t,i,n){let r=0,o=Number.POSITIVE_INFINITY,s=!1,a=!1,h=!1,l=t["flow-options"];if(l){let v=$m(l.evaluate(this.context,"flow-options"));s=!!v.exclusive,a=!!v.static,h=!!v.last}let c=t["flow-linger"];c&&(o=Zh(c.evaluate(this.context,"flow-linger"),Number.POSITIVE_INFINITY));let d=t["flow-priority"];d&&(r=Zh(d.evaluate(this.context,"flow-priority"),0));let p=this.breakBeforeValues[n]||null,f=this.flows[e];if(!f){let v=this.boxStack.lastFlowName();f=this.flows[e]=new Mv(e,v)}let g=new _v(e,i,n,r,o,s,a,h,p);return this.flowChunks.push(g),this.flowToReach==e&&(this.flowToReach=null),this.flowListener&&this.flowListener.encounteredFlowChunk(g,f),g}registerForcedBreakOffset(e,t,i){if(Ze(e)){let r=this.flows[i].forcedBreakOffsets;(r.length===0||r[r.length-1]<t)&&r.push(t)}let n=this.breakBeforeValues[t];this.breakBeforeValues[t]=nt(n,e)}styleUntil(e,t){let i=-1,n;if(e<=this.lastOffset&&(n=this.offsetMap.slippedByFixed(e),i=n+t,i<this.offsetMap.getMaxSlipped()))return this.offsetMap.fixedBySlipped(i);if(this.last==null)return Number.POSITIVE_INFINITY;let r=this.context;for(;this.last;){let o=this.last.firstChild;if(o==null)for(;this.last;){if(this.last.nodeType==1){this.cascade.popElement(this.last),this.primary=this.primaryStack.pop();let s=this.boxStack.pop(this.lastOffset),a=null;if(s.afterBox){let h=s.afterBox.getBreakValue("before");this.registerForcedBreakOffset(h,s.afterBox.atBlockStart?this.boxStack.nearestBlockStartOffset(s):s.afterBox.offset,s.flowName),a=s.afterBox.getBreakValue("after")}a=nt(a,s.getBreakValue("after")),this.registerForcedBreakOffset(a,this.lastOffset,s.flowName)}if(o=this.last.nextSibling,o)break;if(this.last=this.last.parentNode,!this.last||this.last===this.root)return this.last=null,e<this.lastOffset&&(i<0&&(n=this.offsetMap.slippedByFixed(e),i=n+t),i<=this.offsetMap.getMaxSlipped())?this.offsetMap.fixedBySlipped(i):Number.POSITIVE_INFINITY}if(this.last=o,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 s=this.last,a=this.getAttrStyle(s);this.primaryStack.push(this.primary),this.cascade.pushElement(this,s,a,this.lastOffset),this.cascade.lastCounterChanges.length>0&&this.recordCounterSnapshot(this.lastOffset,this.cascade.counters,this.cascade.lastCounterChanges,this.cascade.lastCounterChangeTypes);let h=s.getAttribute("id")||s.getAttributeNS("http://www.w3.org/XML/1998/namespace","id");h&&h===this.idToReach&&(this.idToReach=null),!this.bodyReached&&s.localName=="body"&&s.parentNode==this.root&&(this.postprocessTopStyle(a,!0),this.bodyReached=!0);let l,c=a["flow-into"];if(c){let p=c.evaluate(r,"flow-into").toString(),f=this.encounteredFlowElement(p,a,s,this.lastOffset);this.primary=!!this.primaryFlows[p],l=this.boxStack.push(a,this.lastOffset,s===this.root,f)}else l=this.boxStack.push(a,this.lastOffset,s===this.root),s===this.xmldoc.body&&(l.breakBefore=nt(l.flowChunk.breakBefore,l.breakBefore));let d=this.boxStack.nearestBlockStartOffset(l);if(d===0||s===this.xmldoc.body){let p=a.page,f=p&&!Z(p.value)&&p.value.toString();!this.cascade.firstPageType&&f&&f.toLowerCase()!=="auto"&&(this.cascade.firstPageType=f)}if(this.registerForcedBreakOffset(l.breakBefore,d,l.flowName),l.beforeBox){let p=l.beforeBox.getBreakValue("after");this.registerForcedBreakOffset(p,l.beforeBox.atBlockStart?d:l.offset,l.flowName)}if(this.primary&&l.displayValue()===y.none&&(this.primary=!1),this.styleMap[`e${this.lastOffset}`]=a,this.lastOffset++,this.primary?this.offsetMap.addStuckRange(this.lastOffset):this.offsetMap.addSlippedRange(this.lastOffset),this.bodyReached&&d===0)continue;if(e<this.lastOffset&&(i<0&&(n=this.offsetMap.slippedByFixed(e),i=n+t),i<=this.offsetMap.getMaxSlipped()))return this.offsetMap.fixedBySlipped(i)}}return Number.POSITIVE_INFINITY}getStyle(e,t){let i=this.xmldoc.getElementOffset(e),n=`e${i}`;return t&&(i=this.xmldoc.getNodeOffset(e,0,!0)),this.lastOffset<=i&&this.styleUntil(i,0),this.styleMap[n]}processContent(e,t,i){}},$u=["column-count","column-width","column-fill"],uC=`OTTO${new Date().valueOf()}`;function dh(e){return Object.keys(e).filter(t=>!["src","font-family","font-display"].includes(t)).sort()}function kx(e){let t=new gi;for(let i of dh(e))t.append(`${i}:${e[i].toString()};`);return t.toString()}function Ex(e,t){let i={};for(let n in e)i[n]=ve(e,n).evaluate(t,n);return i}var Yf=class{constructor(e){u(this,"properties",e),u(this,"fontTraitKey"),u(this,"src"),u(this,"blobURLs",[]),u(this,"blobs",[]),u(this,"family"),this.fontTraitKey=kx(this.properties),this.src=this.properties.src?this.properties.src.toString():null;let t=this.properties["font-family"];this.family=t?t.stringValue():null}traitsEqual(e){return this.fontTraitKey==e.fontTraitKey}makeAtRule(e,t){let i=new gi;i.append(`@font-face {
1874
1874
  font-family: `),i.append(this.family),i.append(`;
1875
1875
  `);for(let n of dh(this.properties))i.append(n),i.append(": "),this.properties[n].appendTo(i,!0),i.append(`;
1876
1876
  `);if(t){i.append('src: url("');let n=Ky(t);i.append(n),this.blobURLs.push(n),this.blobs.push(t),i.append('")')}else i.append("src: "),i.append(e);return i.append(`;
1877
1877
  }
1878
- `),i.toString()}},Px=class{constructor(e){u(this,"deobfuscator",e),u(this,"familyMap",{})}registerFamily(e,t){let i=e.family,n=this.familyMap[i],o=t.family;if(n){if(n!=o)throw new Error(`E_FONT_FAMILY_INCONSISTENT ${e.family}`)}else this.familyMap[i]=o}filterFontFamily(e){if(e instanceof _e){let t=e.values,i=[];for(let n of t){let o=this.familyMap[n.stringValue()];o&&i.push(B(o)),i.push(n)}return new _e(i)}else{let t=this.familyMap[e.stringValue()];return t?new _e([B(t),e]):e}}},Nx=class{constructor(e,t,i){u(this,"head",e),u(this,"body",t),u(this,"srcURLMap",{}),u(this,"familyPrefix"),u(this,"familyCounter",0),this.familyPrefix=i||"Fnt_"}getViewFontFamily(e,t){let i=e.family,n=t.familyMap[i];return n||(n=this.familyPrefix+ ++this.familyCounter,t.familyMap[i]=n,n)}initFont(e,t,i){let n=M("initFont"),o=e.src,r={};for(let l of dh(e.properties))r[l]=e.properties[l];let s=this.getViewFontFamily(e,i);r["font-family"]=B(s);let a=new Yf(r),h=this.head.ownerDocument.createElement("style");return h.textContent=a.makeAtRule(o,t),this.head.appendChild(h),Y.debug("Load font:",o),n.finish(a),n.result()}loadFont(e,t){let i=e.src,n=e.family+";"+i+";"+e.fontTraitKey,o=this.srcURLMap[n];return o?o.piggyback(r=>{t.registerFamily(e,r),Y.debug("Found already-loaded font:",i)}):(o=new Qo(()=>{let r=M("loadFont"),s=i.replace(/^url\("([^"]+)"\).*$/,"$1"),a=t.deobfuscator?t.deobfuscator(s):null;return a?Os(s,"blob").then(h=>{if(!h.responseBlob){r.finish(null);return}a(h.responseBlob).then(l=>{this.initFont(e,l,t).thenFinish(r)})}):this.initFont(e,null,t).thenFinish(r),r.result()},`loadFont ${i}`),this.srcURLMap[n]=o,o.start()),o}findOrLoadFonts(e,t){let i=[];for(let n of e){if(!n.src||!n.family){Y.warn("E_FONT_FACE_INVALID");continue}i.push(this.loadFont(n,t))}return Dn(i).thenAsync(()=>this.waitFontLoading())}waitFontLoading(){let e=this.head.ownerDocument.fonts,t=0;if(e.forEach(n=>{n.status==="unloaded"&&(t++,n.load().catch(o=>{}))}),t===0)return T(!0);let i=M("waitFontLoading");return i.loop(()=>i.sleep(20).thenAsync(()=>e.status==="loading"?T(!0):T(!1))).thenFinish(i),i.result()}},vi=!0;function Tx(e){vi=e}var Ki=[];function Hu(e,t){return e===t||(e.src||t.src?e.src===t.src:e.textContent===t.textContent)}function Zf(e){let t=Array.from(e.querySelectorAll("body > :not(script):not(link):not(style) ~ script"));return Array.from(e.querySelectorAll("head > script, body > script")).filter(i=>!t.includes(i))}function ph(e,t,i){if(!vi||!(i!=null&&i.inHead)&&!(i!=null&&i.atEnd)&&Zf(e.ownerDocument).includes(e))return T(!1);let n=e.textContent,o=e.src,r=e.type==="module",s=o&&o.includes("/MathJax.js");if(s){if(t.document.head.querySelector("script[src*='/MathJax.js']"))return T(!0);t.MathJax||(t.MathJax={MathML:{extensions:["content-mathml.js"]},showProcessingMessages:!1,messageStyle:"none",skipStartupTypeset:!0,CommonHTML:{linebreaks:{automatic:!0}},"fast-preview":{disabled:!0},AuthorInit:function(){t.MathJax.Hub.processSectionDelay=0}})}let a=(r||o)&&e.async&&!s,h=(r&&!a||o&&e.defer)&&!s,l=!(i!=null&&i.atEnd)&&(i?.forceDefer||h||a);if(Kf(t)||(t.onload=null),l)return Ki.some(d=>Hu(d,e))||Ki.push(e),T(!0);for(let d of t.document.head.getElementsByTagName("script"))d.hasAttribute("data-vivliostyle-scripting")&&Hu(d,e)&&t.document.head.removeChild(d);let c=t.document.createElement("script");c.textContent=n,o&&(c.src=o),c.async=a,c.defer=h,c.setAttribute("data-vivliostyle-scripting","true");for(let d of e.attributes)["src","async","defer"].includes(d.name)||c.setAttribute(d.name,d.value);if(Y.debug("script:",o),o){let d=Et(c);return t.document.head.appendChild(c),Dn([d])}else return t.document.head.appendChild(c),T(!0)}function Ax(e,t){var i;let n={},o=s=>{var a;let h=(a=s["font-family"])==null?void 0:a.value;if(h)if(h.values)for(let c of h.values)n[c.stringValue()]=!0;else n[h.stringValue()]=!0;let l=s._marginBoxes;if(l)for(let c of Object.values(l))o(c)},r=s=>{if(s instanceof oh)o(s.style);else if(s instanceof Yn||Array.isArray(s))for(let a of Object.values(s))r(a)};for(let s of Object.values(t.cascade.code))for(let a of Object.values(s??{}))r(a);for(let s of e.querySelectorAll("[style]"))(i=s.style)!=null&&i.fontFamily&&(n[s.style.fontFamily]=!0);return Object.keys(n).join(",")}function Ix(e,t,i){var n;let o=(n=t.document.querySelector("[data-vivliostyle-textcontent]"))!=null?n:t.document.createElement("div");return o.style.position="fixed",o.style.fontSize="0",o.setAttribute("data-vivliostyle-textcontent","true"),o.setAttribute("aria-hidden","true"),o.style.fontFamily=Ax(e,i),o.textContent=e.documentElement.textContent,t.document.body.appendChild(o),o}function Fx(e,t,i){if(!vi)return T(!1);let n=Zf(e);if(n.length===0)return T(!1);let o=n.some(c=>!(c.async||c.defer||c.type==="module")),r=o?Ix(e,t,i):null,s=t.document.fonts,a=t.$,h=!1,l=M("loadScripts");return l.loop(()=>{if(n.length===0)return o?l.sleep(20).thenAsync(()=>{var d,p;return s.status==="loading"||t.document.documentElement.classList.contains("wf-loading")||(d=t.FontJSON)!=null&&d.Font&&(p=t.ret)!=null&&p.readyState&&t.ret.readyState<4?T(!0):T(!1)}):T(!1);let c=n.shift();return ph(c,t,{inHead:!0,forceDefer:h}).thenAsync(()=>(!h&&t.$!==a&&(Ki.push(c),h=!0),n.length===0&&o&&(Y.debug("dispatchEvent: DOMContentLoaded (document)"),t.document.dispatchEvent(new Event("DOMContentLoaded"))),T(!0)))}).then(()=>{r&&r.remove(),l.finish(!0)}),l.result()}function Rx(e){if(!vi)return T(!1);let t=M("loadScripts");return t.loop(()=>Ki.length===0?T(!1):ph(Ki.shift(),e,{atEnd:!0}).thenReturn(Ki.length>0)).then(()=>{Y.debug("dispatchEvent: DOMContentLoaded (window)"),e.dispatchEvent(new Event("DOMContentLoaded")),Y.debug("dispatchEvent: load (window)"),e.dispatchEvent(new Event("load")),t.finish(!0)}),t.result()}function Kf(e){return vi?Ki.length>0||!!e.document.head.querySelector("script[data-vivliostyle-scripting]"):!1}var Lx=e=>String(e).replace(/[\u0000-\u001F"\\\u2028\u2029]/g,Pl),Ox=e=>`"${Lx(e)}"`,wa=(e,t,i)=>Ox(i.transformURL(xi(String(e)),t)),Bx=(e,t,i)=>e.replace(/[uU][rR][lL]\(\s*"((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^"\r\n])+)"/gm,(n,o)=>`url(${wa(o,t,i)}`).replace(/[uU][rR][lL]\(\s*'((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^'\r\n])+)'/gm,(n,o)=>`url(${wa(o,t,i)}`).replace(/[uU][rR][lL]\(\s*((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^"'\r\n\)\s])+)/gm,(n,o)=>`url(${wa(o,t,i)}`),Mx={},_x=new Set(["base","body","head","html","link","meta","script","style","title"]);function Dx(e){if(e instanceof K)return e;if(e instanceof J){let t=[];for(let i of e.values)if(i instanceof K)t.push(i.str);else return null;if(t.length>0)return new K(t.join(""))}return null}function zx(e){return e instanceof Qe?e:e instanceof J&&e.values[0]instanceof Qe&&e.values.slice(1).every(t=>t instanceof K&&t.str.trim()==="")?e.values[0]:null}function Vx(e){if(jo!=="webkit")return!1;let t=e["--viv-marker-content"];if(!t)return!1;let i=zx(t);if(i)return e["list-style-type"]=y.none,e["list-style-image"]=i,delete e["--viv-marker-content"],!0;let n=Dx(t);return n?(e["list-style-type"]=n,e["list-style-image"]=y.none,!0):!1}function Ux(e){e.addEventListener("load",()=>{e.contentWindow.navigator.epubReadingSystem={name:"adapt",version:"0.1",layoutStyle:"paginated",hasFeature:function(t,i){return t==="mouse-events"}}},!1)}var fl=class mo extends Nl{constructor(t,i,n,o,r,s,a,h,l,c,d,p,f,g,v,w=new Map,x={value:!1}){super(),u(this,"flowName",t),u(this,"context",i),u(this,"viewport",n),u(this,"styler",o),u(this,"regionIds",r),u(this,"xmldoc",s),u(this,"docFaces",a),u(this,"footnoteStyle",h),u(this,"stylerProducer",l),u(this,"page",c),u(this,"customRenderer",d),u(this,"fallbackMap",p),u(this,"documentURLTransformer",f),u(this,"pageProps",g),u(this,"cascadedPageStyle",v),u(this,"semanticFootnoteFirstRefOffsets",w),u(this,"semanticFootnoteFirstRefOffsetsInitialized",x),u(this,"document"),u(this,"exprContentListener"),u(this,"computedStyleParentFontSizeOverride",null),u(this,"computedStyleParentLineHeightOverride",null),u(this,"nodeContext",null),u(this,"viewRoot",null),u(this,"isFootnote",!1),u(this,"sourceNode",null),u(this,"offsetInNode",0),u(this,"viewNode",null),this.document=n.document,this.exprContentListener=o.counterListener.getExprContentListener()}clone(){return new mo(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,this.pageProps,this.cascadedPageStyle,this.semanticFootnoteFirstRefOffsets,this.semanticFootnoteFirstRefOffsetsInitialized)}getExplicitPageType(t){let i=t?.page;if(!i||Z(i.value))return null;let n=i.evaluate(this.context,"page").toString();return!n||n.toLowerCase()==="auto"?null:n}isNormalFlowElement(t){var i,n,o;let r=this.styler.getStyle(t,!1),s=(i=r?.display)==null?void 0:i.evaluate(this.styler.context,"display");if((s&&!Z(s)?s:y.inline)===y.none)return!1;let a=(n=r?.position)==null?void 0:n.evaluate(this.styler.context,"position"),h=a&&!Z(a)?a:y.static;if(wo(h)||Ro(h))return!1;let l=(o=r?.float)==null?void 0:o.evaluate(this.styler.context,"float");return(l&&!Z(l)?l:y.none)===y.none}getFirstInFlowChildElement(t){var i;let n=t.firstChild;for(;n;){if(n.nodeType===Node.TEXT_NODE){if(!Ee(n))return null;n=n.nextSibling;continue}if(n.nodeType!==Node.ELEMENT_NODE){n=n.nextSibling;continue}let o=n;if(this.isNormalFlowElement(o)){let r=this.styler.getStyle(o,!1),s=(i=r?.display)==null?void 0:i.evaluate(this.styler.context,"display"),a=s&&!Z(s)?s:y.inline;return Ut(a)?null:o}n=n.nextSibling}return null}getEffectiveStartPageType(t,i){let n=i,o=t;for(;o;){let r=this.getFirstInFlowChildElement(o);if(!r)return n;let s=this.getExplicitPageType(this.styler.getStyle(r,!1));s&&(n=s),o=r}return n}syncTextNodePageTypeBoundary(t){if(t.sourceNode.nodeType!==Node.TEXT_NODE||Ee(t.sourceNode)||t.fragmentIndex!==1)return;let i=t.pageType;this.styler.cascade.currentPageType!==i&&(en(t.breakBefore)||(t.breakBefore=nt(t.breakBefore,"page")),i!==this.styler.cascade.previousPageType&&(this.styler.cascade.previousPageType=this.styler.cascade.currentPageType),this.styler.cascade.currentPageType=i)}syncSemanticFootnoteCounterToTarget(t){if(t.localName!=="a"||!Gt(t)||!cu(t,this.xmldoc.url,o=>this.xmldoc.getElementOffset(o),this.semanticFootnoteFirstRefOffsets,this.semanticFootnoteFirstRefOffsetsInitialized))return;let i=t.getAttribute(ko);if(!i)return;let n=pp(t,this.xmldoc.url,o=>this.xmldoc.getElement(o));n&&n.setAttribute(ko,i)}createPseudoelementShadow(t,i,n,o,r,s,a,h){var l,c;let d=this.getPseudoMap(n,this.regionIds,this.isFootnote,this.nodeContext,s);if(!d)return h;let p=[],f=fo.createElementNS("http://www.pyroxy.com/ns/shadow","root"),g=f,v=Gt(t)&&!!d["footnote-call"]&&It((l=d["footnote-call"].content)==null?void 0:l.value);for(let m of k0){let S;if(m){if(!d[m])continue;let b=Pt(t),C=t.namespaceURI==="http://www.pyroxy.com/ns/shadow"&&t.localName==="include"&&t.classList.contains("-vivliostyle-footnote-content");if(m=="footnote-call"&&!Gt(t)||m=="footnote-marker"&&!(b||C||i&&this.isFootnote)&&!((c=this.nodeContext)!=null&&c.pluginProps.nestedFootnoteDetached))continue;if(m.match(/^first-/)){let P=o.display;if(!P||P===y.inline)continue;let L=t.firstElementChild;if(L&&Ee(L.previousSibling)){let A=r.getStyle(L,!1);if(A){let z=ve(A,"display");if(z!=null&&z.value&&z.value!==y.inline)continue}}}if(m==="before"||m==="after"||m==="footnote-call"||m==="footnote-marker"){let P=d[m].content,L=(m==="before"||m==="after")&&(o.float===y.footnote||b||C)&&!!P;if(!P||!It(P.value)&&!L)continue}p.push(m),S=fo.createElementNS("http://www.w3.org/1999/xhtml","span"),Po(S,m)}else{if(v)continue;S=fo.createElementNS("http://www.pyroxy.com/ns/shadow","content")}g.appendChild(S),m.match(/^first-/)&&(g=S)}if(!p.length)return h;let w=new ma(t,n,r,s,this.exprContentListener),x=new Br(t,f,null,a,h,st.ROOTLESS,w);return h||x}getPseudoMap(t,i,n,o,r){let s=ft(t,"_pseudos");if(!s)return null;let a={};for(let h in s){let l=a[h]={};Eo(l,s[h],r),ul(l,r,s[h]),Ef(s[h],i,n,(c,d)=>{Eo(l,d,r),Sf(d,p=>{Eo(l,p,r)})})}return a}createRefShadow(t,i,n,o,r){let s=M("createRefShadow");return this.xmldoc.store.load(t).then(a=>{let h=a;if(h){let l=h.getElement(t);if(l){let c=this.stylerProducer.getStylerForDoc(h);r=new Br(n,l,h,o,r,i,c)}}s.finish(r)}),s.result()}createShadows(t,i,n,o,r,s,a){let h=M("createShadows"),l=null,c=o.template,d;if(c instanceof Qe||c===y.footnote)if(c!==y.footnote||cu(t,this.xmldoc.url,p=>this.xmldoc.getElementOffset(p),this.semanticFootnoteFirstRefOffsets,this.semanticFootnoteFirstRefOffsetsInitialized)){let p=c instanceof Qe?c.url:Ae("user-agent.xml#footnote",Ni);d=this.createRefShadow(p,st.ROOTLESS,t,a,l)}else d=T(l);else d=T(l);return d.then(p=>{let f=null;if(t.namespaceURI=="http://www.pyroxy.com/ns/shadow"&&t.localName=="include"){let v=t.getAttribute("href"),w=null;v?w=a?a.xmldoc:this.xmldoc:a&&(a.owner.namespaceURI=="http://www.w3.org/1999/xhtml"?v=a.owner.getAttribute("href"):v=a.owner.getAttributeNS("http://www.w3.org/1999/xlink","href"),w=a.parentShadow?a.parentShadow.xmldoc:this.xmldoc),v&&(v=Qr(v,w.url),f=this.createRefShadow(v,st.ROOTED,t,a,p))}f==null&&(f=T(p));let g=null;f.then(v=>{if(o.display===y.table_cell){let w=Ae("user-agent.xml#table-cell",Ni);g=this.createRefShadow(w,st.ROOTLESS,t,a,v)}else g=T(v);g.then(w=>{w=this.createPseudoelementShadow(t,i,n,o,r,s,a,w),h.finish(w)})})}),h.result()}setViewRoot(t,i){this.viewRoot=t,this.isFootnote=i}computeStyle(t,i,n,o){var r;let s=this.context,a=cl(n,s,this.regionIds,this.isFootnote,this.nodeContext),h=!((r=this.nodeContext)!=null&&r.parent);h&&(!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 l=t;t=Cf(a,s,t);let c=!h&&t!==l;i=kf(a,s,i);let d=(x,m)=>{let S;c&&(t?/^(min-|max-)?(height|inline-size)$/.test(x)&&(S=s.pageAreaHeight):/^(min-|max-)?(width|inline-size)$/.test(x)&&(S=s.pageAreaWidth));let b=m.evaluate(s,x,S,t);return x=="font-family"&&(b=this.docFaces.filterFontFamily(b)),b},p=!!new Je(s.style.pageScope,"left-page").evaluate(s);if(Pf(a,o,t,i,p,d),c){let x=o[t?"height":"width"];(!x||x===y.auto)&&(o[t?"height":"width"]=y.max_content)}if(wo(o.position))return o.position=y.fixed,o.visibility=y.hidden,t;let f=o.position,g=o.float,v=o.display||(this.sourceNode&&this.sourceNode.namespaceURI==="http://www.w3.org/1999/xhtml"?y.inline:void 0),w=zd(v,f,g,this.sourceNode===this.xmldoc.root);return["display","position","float"].forEach(x=>{w[x]&&(o[x]=w[x])}),t}inheritFromSourceParent(t){var i,n;let o=this.nodeContext.sourceNode,r=[],s=null,a=o instanceof Element&&o.namespaceURI==="http://www.pyroxy.com/ns/shadow"&&o.localName==="include"&&o.classList.contains("-vivliostyle-footnote-content"),h=this.isFootnote&&(!((i=this.nodeContext)!=null&&i.parent)||a),l=this.nodeContext.shadowContext;if(o instanceof Element&&o.namespaceURI==="http://www.pyroxy.com/ns/shadow"&&o.localName==="include"&&o.classList.contains("-vivliostyle-footnote-content")){let w=l?.owner;if(w instanceof Element&&Gt(w)){let x=w.getAttribute("href")||w.getAttributeNS("http://www.w3.org/1999/xlink","href");if(x){let m=Qr(x,this.xmldoc.url),S=this.xmldoc.getElement(m);S&&Pt(S)&&((n=S.parentNode)==null?void 0:n.nodeType)===1&&(o=S.parentNode,l=null)}}}let c=-1;for(;o&&o.nodeType==1;){let w=l&&l.root==o,x=!!w&&l.type==st.ROOTED&&Pt(o);if(!w||l.type==st.ROOTLESS||x){let m=(l?l.styler:this.styler).getStyle(o,!1);r.push(m),s=s||Sa(o)}w&&!x?(o=l.owner,l=l.parentShadow):(o=o.parentNode,c++)}let d=new Set;if(r.length>0){let w=r[0],x=cl(w,this.context,this.regionIds,this.isFootnote,this.nodeContext);for(let m in x){if(!In(m))continue;let S=x[m].evaluate(this.context,m);S&&S!==y.inherit&&S!==y.unset&&S!==y.revert&&S!==Be&&d.add(m)}}let p=c===0,f=this.context.queryUnitSize("em",p),g={"font-size":new W(new O(f,"px"),0)};p&&(g["line-height"]=new W(new At(this.context.pref.lineHeight),0));let v=new Nb(g,this.context);for(let w=r.length-1;w>=0;--w){let x=r[w],m=[];for(let C in x)In(C)&&m.push(C);m.sort(_h);let S,b;for(let C of m){if(w>0&&h&&C.startsWith("--viv-marker-")||w>0&&d.has(C))continue;v.setPropName(C);let P=ve(x,C),L=P;if(P.value===y.initial)delete g[C];else if(!Z(P.value)){if(C==="font-size"&&w===r.length-1&&this.context.isRelativeRootFontSize&&this.context.rootFontSize)L=new W(new O(this.context.rootFontSize,"px"),P.priority);else if(C==="line-height"&&w===r.length-1&&this.context.rootLineHeight&&P.value instanceof O&&(P.value.unit==="lh"||P.value.unit==="rlh"))L=new W(new O(this.context.rootLineHeight,"px"),P.priority);else if(w===0&&P.value instanceof O&&P.value.unit==="lh"){let A=this.getLineHeightUnitSize(C,S,b);A!=null&&(L=new W(new O(P.value.num*A,"px"),P.priority))}else Xe(C)||(L=P.filterValue(v));C==="font-size"?S=L.value:C==="line-height"&&(b=L.value),g[C]=L}}}for(let w in t)In(w)||(g[w]=t[w]);return{lang:s,elementStyle:g}}resolveURL(t){return t=Ae(t,this.xmldoc.url),this.fallbackMap[t]||t}inheritLangAttribute(){this.nodeContext.lang=Sa(this.nodeContext.sourceNode)||this.nodeContext.parent&&this.nodeContext.parent.lang||this.nodeContext.lang}transferPolyfilledInheritedProps(t){let i=mb().filter(n=>t[n]);if(i.length){let n=this.nodeContext.inheritedProps;if(this.nodeContext.parent){n=this.nodeContext.inheritedProps={};for(let o in this.nodeContext.parent.inheritedProps)n[o]=this.nodeContext.parent.inheritedProps[o]}i.forEach(o=>{let r=t[o];if(r){if(Z(r))r===y.initial&&(n[o]=void 0);else if(r instanceof lt)n[o]=r.num;else if(r instanceof he)n[o]=r.name;else if(r instanceof O){let s=r;switch(s.unit){case"dpi":case"dpcm":case"dppx":n[o]=s.num*Zt[s.unit];break;default:n[o]=r}}else n[o]=r;["widows","orphans"].includes(o)||delete t[o]}})}}resolveFormattingContext(t,i,n,o,r,s){let a=_t("RESOLVE_FORMATTING_CONTEXT");for(let h=0;h<a.length;h++){let l=a[h](t,i,n,o,r,s);if(l){t.formattingContext=l;return}}}createElementView(t,i){var n,o;let r=!0,s=M("createElementView"),a=this.sourceNode,h=this.nodeContext.shadowContext?this.nodeContext.shadowContext.styler:this.styler,l=h.getStyle(a,!1);if(this.syncSemanticFootnoteCounterToTarget(a),!this.nodeContext.shadowContext){let P=this.xmldoc.getElementOffset(a);$s.registerFragmentIndex(P,this.nodeContext.fragmentIndex,0)}let c={},d={getStyle:P=>this.styler.getStyle(P,!1),getProp:(P,L)=>P?ve(P,L):null,getStyleMap:(P,L)=>ft(P,L),getMutableStyleMap:(P,L)=>si(P,L),createCascadeValue:(P,L)=>new W(P,L),filterFootnoteMarkerContent:(P,L)=>P.filterValue(new Do(this.styler.cascade,L,this.styler.cascade.counterResolver,"footnote-marker")).value};if(!this.nodeContext.parent){let P=this.inheritFromSourceParent(l);l=P.elementStyle,this.nodeContext.lang=P.lang}let p=l.position,f=l.float,g=l["float-reference"],v=f&&!Z(f.value)&&f.value!==y.none&&g&&!Z(g.value)?jv(g.value.toString()):null,w=!!this.nodeContext.shadowContext&&this.nodeContext.shadowContext.type===st.ROOTED&&Pt(a);if(this.nodeContext.parent&&(wo(p?.value)||v&&Ii(v)||w)){let P=this.inheritFromSourceParent(l);l=P.elementStyle,this.nodeContext.lang=P.lang}l=Zv(a,l,this.nodeContext.shadowContext,this.xmldoc.url,P=>this.xmldoc.getElement(P),ko,d),l=Kv(a,l,this.nodeContext.shadowContext,this.context,d),this.nodeContext.vertical=this.computeStyle(this.nodeContext.vertical,this.nodeContext.direction==="rtl",l,c),v&&Ii(v)&&c.display===y.block&&(c.display=y.flow_root),h.processContent(a,c,this.nodeContext),this.transferPolyfilledInheritedProps(c),this.inheritLangAttribute(),c.direction&&(this.nodeContext.direction=c.direction.toString());let x=c["flow-into"];if(x&&x.toString()!=this.flowName)return s.finish(!1),s.result();if(vi&&a.localName==="script"&&a.namespaceURI==="http://www.w3.org/1999/xhtml")return ph(a,this.viewport.window).thenFinish(s),s.result();let m=c.display;if(Pt(a)&&!w&&a.hasAttribute(dp)&&(m=c.display=y.none),Z(m)&&(m===y.initial||m===y.unset?m=y.inline:m===y.inherit?m=((n=this.nodeContext.parent)==null?void 0:n.display)&&B((o=this.nodeContext.parent)==null?void 0:o.display):m=null),m===y.none)return s.finish(!1),s.result();let S=this.nodeContext.parent==null,b=c[this.nodeContext.vertical?"width":"height"],C=(m===y.grid||m===y.inline_grid)&&!!b&&!(b===y.auto||Z(b));return this.nodeContext.flexContainer=m===y.flex||C,this.createShadows(a,S,l,c,h,this.context,this.nodeContext.shadowContext).then(P=>{var L,A;this.nodeContext.nodeShadow=P;let z=c.position,U=c.float,X=c.clear,oe=this.nodeContext.vertical?y.vertical_rl:y.horizontal_tb,k=this.nodeContext.parent?this.nodeContext.parent.vertical?y.vertical_rl:y.horizontal_tb:oe,_=hv(a),F=c["column-count"],D=c["column-width"],E=F&&F!==y.auto&&!Z(F)||D&&D!==y.auto&&!Z(D);this.nodeContext.establishesBFC=cv(m,z,U,c.overflow,oe,k,E||_),this.nodeContext.containingBlockForAbsolute=dv(z),this.nodeContext.isInsideBFC()&&U!==y.footnote&&!(v&&Ii(v))&&(U=null,X=null);let N=null,R=!1,$=this.isFootnote&&(!((L=this.nodeContext)!=null&&L.parent)||this.nodeContext.pluginProps.nestedFootnoteDetached||w),V=Jv(a,this.nodeContext.shadowContext,d);Qv(V.sourceStyle,c,this.context),N=V.footnoteDisplay;let q=U instanceof J||U===y.left||U===y.right||U===y.top||U===y.bottom||U===y.inline_start||U===y.inline_end||U===y.block_start||U===y.block_end||U===y.snap_block||U===y.snap_inline||U===y.inside||U===y.outside||U===y.footnote;if(U&&(delete c.float,U===y.footnote))if(N=c["footnote-display"]||N,R=!!c["--viv-marker-content"],$){q=!1;let G=N?.toString();G&&(c["--viv-footnote-display"]=B(G)),m=R?B("list-item"):G==="inline"||G==="compact"?y.inline:y.block,c.display=m}else c.display=y.inline;if($&&Pt(a)){R=R||!!c["--viv-marker-content"];let G=N?.toString();G&&(c["--viv-footnote-display"]=B(G)),R&&(m=c.display=B("list-item")),!R&&(G==="inline"||G==="compact")&&(m=c.display=y.inline)}X&&(X===y.inherit&&this.nodeContext.parent&&this.nodeContext.parent.clearSide&&(X=B(this.nodeContext.parent.clearSide)),(X===y.left||X===y.right||X===y.top||X===y.bottom||X===y.inline_start||X===y.inline_end||X===y.block_start||X===y.block_end||X===y.inside||X===y.outside||X===y.both||X===y.all||X===y.same||X===y.column||X===y.region||X===y.page)&&(delete c.clear,(q||c.display&&c.display!=y.inline)&&(this.nodeContext.clearSide=X.toString())));let Q=uo(m)&&!!(c["ua-list-item-count"]||c["--viv-marker-content"]),ee=c["break-inside"];(q||ee&&!Z(ee)&&ee!==y.auto)&&this.nodeContext.breakPenalty++,m&&m!==y.inline&&Ut(m)&&this.nodeContext.breakPenalty++,this.nodeContext.inline=!q&&!m||Ut(m)||Ud(m),this.nodeContext.display=m?m.toString():"inline",this.nodeContext.floatSide=q?U.toString():null,this.nodeContext.floatReference=v||Pe.INLINE;let pe=c["float-min-wrap-block"];this.nodeContext.floatMinWrapBlock=pe&&!Z(pe)?pe:null;let re=this.isInsideNonRootMultiColumn(),se=c["column-span"];if(this.nodeContext.columnSpan=!re&&se&&!Z(se)?se:null,!this.nodeContext.inline){let G=c["break-after"];G&&!Z(G)&&!(re&&G===y.column)&&(this.nodeContext.breakAfter=G.toString(),Da[this.nodeContext.breakAfter]&&(c["break-after"]=y.column));let Dt=c["break-before"];Dt&&!Z(Dt)&&!(re&&Dt===y.column)&&(this.nodeContext.breakBefore=Dt.toString(),Da[this.nodeContext.breakBefore]&&(this.isAtStartOfPage()?delete c["break-before"]:c["break-before"]=y.column),this.nodeContext.fragmentIndex!==1&&(this.nodeContext.breakBefore=null));let qt=c.page,an=qt&&!Z(qt)?qt.toString():null,zt=an;!zt&&!this.nodeContext.parent&&(this.nodeContext.shadowContext||m===y.table_header_group||m===y.table_footer_group)&&(zt=this.styler.cascade.currentPageType),!zt||zt.toLowerCase()==="auto"?zt=this.nodeContext.pageType:this.nodeContext.pageType=zt;let Kn=an!=null&&an.toLowerCase()!=="auto",wi=Kn?this.nodeContext.fragmentIndex===1?this.getEffectiveStartPageType(a,zt):(A=this.styler.cascade.currentPageType)!=null?A:zt:zt;this.styler.cascade.currentPageType!==wi&&!(!Kn&&c.position===y.fixed)&&(this.nodeContext.fragmentIndex===1&&!en(this.nodeContext.breakBefore)&&(this.nodeContext.breakBefore="page"),wi!==this.styler.cascade.previousPageType&&(this.styler.cascade.previousPageType=this.styler.cascade.currentPageType),this.styler.cascade.currentPageType=wi)}this.nodeContext.captionSide=c["caption-side"]&&c["caption-side"].toString()||"top";let De=c["border-collapse"];if(!De||De===B("separate")){let G=c["border-spacing"],Dt,qt;G&&(G instanceof J?(Dt=G.values[0],qt=G.values[1]):Dt=qt=G,Dt.isNumeric()&&(this.nodeContext.inlineBorderSpacing=ut(Dt,this.context)),qt.isNumeric()&&(this.nodeContext.blockBorderSpacing=ut(qt,this.context)))}let Te=c["footnote-policy"]||V.footnotePolicy;Te&&!Z(Te)&&(c["--viv-footnote-policy"]=Te),this.nodeContext.footnotePolicy=Te&&!Z(Te)?Te:null;let fe=c["x-first-pseudo"];if(fe){let G=this.nodeContext.parent?this.nodeContext.parent.firstPseudo:null;this.nodeContext.firstPseudo=new Uv(G,fe.num)}this.nodeContext.inline||this.processAfterIfcontinues(a,l,h,this.context);let Ce=c["white-space"];if(Ce){let G=ep(Ce.toString());G!==null&&(this.nodeContext.whitespace=G)}let ge=c["hyphenate-character"];ge&&ge instanceof K&&(this.nodeContext.hyphenateCharacter=ge.str);let Ie=c["word-break"],Oe=c["line-break"],Fe=c["overflow-wrap"];(Ie===y.break_all||Oe===y.anywhere||Fe===y.break_word||Fe===y.anywhere)&&(this.nodeContext.breakWord=!0),this.resolveFormattingContext(this.nodeContext,t,m,z,U,S),this.nodeContext.parent&&this.nodeContext.parent.formattingContext&&(t=this.nodeContext.parent.formattingContext.isFirstTime(this.nodeContext,t)),this.nodeContext.inline||(this.nodeContext.repeatOnBreak=this.processRepeatOnBreak(c),this.findAndProcessRepeatingElements(a,h));let He=!1,gt=null,Zn=[],Rt=a.namespaceURI,me=a.localName,sr=me;Rt=="http://www.w3.org/1999/xhtml"?(_x.has(me)?me="div":me=="vide_"?me="video":me=="audi_"?me="audio":me=="object"&&(He=!!this.customRenderer),a.hasAttribute(hh)&&a.hasAttribute("src")&&c.content instanceof Qe&&(me="img")):Rt=="http://www.idpf.org/2007/ops"?(me="span",Rt="http://www.w3.org/1999/xhtml"):Rt=="http://www.pyroxy.com/ns/shadow"?(Rt="http://www.w3.org/1999/xhtml",me=this.nodeContext.inline?"span":"div"):He=!!this.customRenderer,Q?t?(me="li",c["--viv-marker-content"]&&(Vx(c)||(c["list-style-type"]=y.none,c["list-style-image"]=y.none))):(m=Ut(m)?y.inline:y.block,c.display=m,me="div"):me=="body"||me=="li"?me="div":me=="q"&&(me="span"),c.behavior&&c.behavior.toString()!="none"&&this.customRenderer&&(He=!0),a.dataset&&a.getAttribute("data-math-typeset")==="true"&&(He=!0);let Xs;if(He){let G=this.nodeContext.parent?this.nodeContext.parent.viewNode:null;Xs=this.customRenderer(a,G,c)}else Xs=T(null);Xs.then(G=>{var Dt,qt,an,zt,Kn;if(G)He&&(r=G.getAttribute("data-adapt-process-children")=="true");else if(c.display===y.none){s.finish(!1);return}else G=this.createElement(Rt,me);if(!S&&E&&c["column-fill"]===y.auto){let We=this.nodeContext.vertical?c.width:c.height;(!We||We===y.auto||Z(We))&&(G.setAttribute("data-viv-saved-column-fill","auto"),c["column-fill"]=y.balance)}me!=sr&&(G.setAttribute("data-vivliostyle-original-tag",sr),(sr==="html"||sr==="body")&&(G.role="presentation")),me=="a"&&G.addEventListener("click",this.page.hrefHandler,!1),gt&&(this.applyPseudoelementStyle(this.nodeContext,"inner",gt),G.appendChild(gt)),G.localName=="iframe"&&G.namespaceURI=="http://www.w3.org/1999/xhtml"&&Ux(G);let wi=this.nodeContext.inheritedProps["image-resolution"],qs=[],Ys=c.width,Zs=c.height,Cg=a.getAttribute("width"),kg=a.getAttribute("height"),Ks=Ys===y.auto||!Ys&&!Cg,Js=Zs===y.auto||!Zs&&!kg,xh=a.attributes,Eg=xh.length,Jn=null,Sh=null;m===y.table_cell&&((an=(qt=(Dt=this.nodeContext.parent)==null?void 0:Dt.viewNode)==null?void 0:qt.lastElementChild)==null?void 0:an.localName)==="a"&&G.appendChild(this.nodeContext.parent.viewNode.lastElementChild);for(let We=0;We<Eg;We++){let St=xh[We],ht=St.namespaceURI,ae=St.localName,ke=St.nodeValue;if(ht){if(ht=="http://www.w3.org/2000/xmlns/")continue;ht=="http://www.w3.org/1999/xlink"&&ae=="href"&&(ke=this.documentURLTransformer.transformURL(this.resolveURL(ke),this.xmldoc.url))}else{if(!vi&&ae.match(/^on/)||ae=="style")continue;if(ae==="media"&&me==="source"&&Rt==="http://www.w3.org/1999/xhtml"&&((zt=a.parentElement)==null?void 0:zt.localName)==="picture")try{let Ge=this.context.rootScope,mt=new Bs(Ge),lr=new xt(ke,mt),Ch=Dd(lr,mt,"");if(Ch){if(Ch.toExpr().evaluate(this.context))continue;ke="not all"}}catch{}if((ae=="id"||ae=="name")&&t){let Ge=this.documentURLTransformer.transformFragment(ke,this.xmldoc.url);G.setAttribute(ae,ke),G.setAttribute("data-vivliostyle-id",Ge);let mt=G.ownerDocument.createElement("a");mt.setAttribute(ae,Ge),mt.setAttribute(zn,"1"),mt.style.position="absolute",G.appendChild(mt),this.page.registerElementWithId(G,Ge);continue}if(ae=="src"||ae=="href"||ae=="poster")ke=this.resolveURL(ke),ae==="href"?ke=this.documentURLTransformer.transformURL(ke,this.xmldoc.url):ke=Fo(ke),ae==="src"&&(ke=xc(ke));else if(ae=="srcset")ke=ke.split(",").map(Ge=>{let mt=Ge.trim().split(/\s+/),lr=Fo(this.resolveURL(mt[0]));return mt.length>1?`${lr} ${mt.slice(1).join(" ")}`:lr}).join(",");else if(ae==="data"&&He&&me==="object"&&G.hasAttribute("data"))continue;if(ae==="poster"&&me==="video"&&Rt==="http://www.w3.org/1999/xhtml"){let Ge=new Image,mt=Et(Ge,ke);Ks&&Js?(Zn.push(mt),qs.push({image:Ge,element:G,fetcher:mt})):this.page.fetchers.push(mt)}}if(Rt=="http://www.w3.org/2000/svg"&&/^[A-Z\-]+$/.test(ae)&&(ae=ae.toLowerCase()),this.isSVGUrlAttribute(ae)&&(ke=Bx(ke,this.xmldoc.url,this.documentURLTransformer)),ht){let Ge=Mx[ht];Ge&&(ae=`${Ge}:${ae}`)}if(ae=="src"&&!ht&&(me=="img"||me=="input")&&Rt=="http://www.w3.org/1999/xhtml")Jn=ke;else if(ae=="alt"&&!ht&&me=="img"&&Rt=="http://www.w3.org/1999/xhtml")Sh=ke;else if(ae=="href"&&me=="image"&&Rt=="http://www.w3.org/2000/svg"&&(ht=="http://www.w3.org/1999/xlink"||!ht))ht||G.setAttribute(ae,ke),this.page.fetchers.push(Et(G,ke));else if(ht)G.setAttributeNS(ht,ae,ke);else try{G.setAttribute(ae,ke)}catch(Ge){Y.warn(Ge)}}if(Jn){let We=me==="input"?new Image:G,St=Et(We,Jn,Sh);We!==G&&(G.src=Jn);let ht=()=>{var ae,ke;if(c.position===y.fixed)return!0;for(let Ge=(ae=this.nodeContext.parent)==null?void 0:ae.viewNode;Ge&&Ge!==this.viewRoot;Ge=Ge.parentElement)if(((ke=Ge.style)==null?void 0:ke.position)==="fixed")return!0;return!1};!Ks&&!Js&&!(()=>{let ae=this.nodeContext.vertical?Ys:Zs;return ae instanceof O&&ae.unit==="%"})()&&!ht()?this.page.fetchers.push(St):(Ks&&Js&&wi&&wi!==1&&qs.push({image:We,element:G,fetcher:St}),Zn.push(St))}else!Jn&&me==="img"&&Rt==="http://www.w3.org/1999/xhtml"&&(G.srcset||((Kn=a.parentElement)==null?void 0:Kn.localName)==="picture")&&this.page.fetchers.push(Et(G));delete c.content;let ar=c["--viv-marker-content"];if(ar){let We=ar instanceof J?ar.values:[ar];for(let St of We)St instanceof Qe&&St.url&&Zn.push(Et(new Image,St.url))}if(G.localName==="object"&&G.namespaceURI==="http://www.w3.org/1999/xhtml"&&G.hasAttribute("data")&&this.page.fetchers.push(Et(G)),G.localName==="embed"&&G.namespaceURI==="http://www.w3.org/1999/xhtml"&&G.hasAttribute("src")&&this.page.fetchers.push(Et(G)),G.localName==="iframe"&&G.namespaceURI==="http://www.w3.org/1999/xhtml"&&G.hasAttribute("src")){let We=G;We.loading==="lazy"&&(We.loading="eager"),this.page.fetchers.push(Et(G))}if(this.preprocessElementStyle(c),this.applyComputedStyles(G,c),this.nodeContext.inline)t||(Ct(G,"inline-start"),Nn(G)&&Ct(G,"clone"));else if(t){if(!Ro(c.position)){let We=c["margin-break"],St=this.getBreakTypeAt(this.nodeContext),ht=St!==null,ae=St==="auto";(We===y.discard&&ht||We!==y.keep&&ae&&!this.nodeContext.floatSide)&&sa(G,"block-start")}}else{let We=this.nodeContext.vertical?"width":"height";ki(G,We)&&I(G,We,this.nodeContext.display==="table-row"?"0.01px":""),Ct(G,"block-start"),Nn(G)&&Ct(G,"clone"),sa(G,"block-start")}Q&&c["ua-list-item-count"]&&G.setAttribute("value",c["ua-list-item-count"].stringValue()),this.viewNode=G,Zn.length?Dn(Zn).then(()=>{wi>0&&this.modifyElemDimensionWithImageResolution(qs,wi,c,this.nodeContext.vertical),s.finish(r)}):s.timeSlice().then(()=>{s.finish(r)})})}),s.result()}isAtStartOfPage(){var t,i;for(let n=this.nodeContext;n!=null&&n.parent&&!n.after;n=n.parent){let o=n===this.nodeContext&&!n.viewNode?(t=n.parent.viewNode)==null?void 0:t.lastChild:(i=n.viewNode)==null?void 0:i.previousSibling;for(;o&&(Ee(o,n.parent.whitespace)||Ot(o));)o=o.previousSibling;if(o)return!1}return!0}isInsideNonRootMultiColumn(){var t;let i=(t=this.nodeContext.parent)==null?void 0:t.viewNode;return!!(i&&tr(i))}getBreakTypeAt(t){var i,n,o,r,s;if(this.isInsideTable(t))return null;for(let h=t;h&&!h.after;h=h.parent){if(Ze(h.breakBefore))return h.breakBefore;if(h.fragmentIndex===1&&!h.parent)return h.sourceNode===h.sourceNode.ownerDocument.documentElement?"page":null;if((i=h.parent)!=null&&i.floatSide)return null;let l=(n=h.parent)==null?void 0:n.viewNode;if(l){let c=this.viewport.window.getComputedStyle(l),d=parseFloat(c.paddingBlockStart),p=parseFloat(c.borderBlockStartWidth);if(d||p)return null;let f=l?.firstChild;for(;f&&(Ee(f,h.parent.whitespace)||!h.floatSide&&Ot(f));)f=f.nextSibling;if(f&&f!==h.viewNode)return null}}let a=(s=(r=(o=this.context)==null?void 0:o.currentLayoutPosition)==null?void 0:r.flowPositions[this.flowName])==null?void 0:s.startBreakType;return Ze(a)?a:"auto"}isInsideTable(t){for(let i=t;i&&!i.after;i=i.parent)if(i.display&&i.display.startsWith("table"))return!0;return!1}processAfterIfcontinues(t,i,n,o){let r=this.getPseudoMap(i,this.regionIds,this.isFootnote,this.nodeContext,o);if(r&&r["after-if-continues"]&&r["after-if-continues"].content){let s=new ma(t,i,n,o,this.exprContentListener);this.nodeContext.afterIfContinues=new P0(t,s)}}isSVGUrlAttribute(t){return mo.SVG_URL_ATTRIBUTES.includes(t.toLowerCase())}modifyElemDimensionWithImageResolution(t,i,n,o){t.forEach(r=>{if(r.fetcher.get().get()==="load"){let s=r.image,a=s.width/i,h=s.height/i,l=r.element;if(a>0&&h>0){if(n["box-sizing"]===y.border_box&&(n["border-left-style"]!==y.none&&(a+=ut(n["border-left-width"],this.context)),n["border-right-style"]!==y.none&&(a+=ut(n["border-right-width"],this.context)),n["border-top-style"]!==y.none&&(h+=ut(n["border-top-width"],this.context)),n["border-bottom-style"]!==y.none&&(h+=ut(n["border-bottom-width"],this.context))),i>1){let c=n["max-width"]||y.none,d=n["max-height"]||y.none;if(c===y.none&&d===y.none)I(l,"max-width",`${a}px`);else if(c!==y.none&&d===y.none)I(l,"width",`${a}px`);else if(c===y.none&&d!==y.none)I(l,"height",`${h}px`);else{c.isNumeric(),d.isNumeric();let p=c,f=d;p.unit!=="%"?I(l,"max-width",`${Math.min(a,ut(p,this.context))}px`):f.unit!=="%"?I(l,"max-height",`${Math.min(h,ut(f,this.context))}px`):o?I(l,"height",`${h}px`):I(l,"width",`${a}px`)}}else if(i<1){let c=n["min-width"]||Le,d=n["min-height"]||Le;c.isNumeric(),c.isNumeric();let p=c,f=d;p.num===0&&f.num===0?I(l,"min-width",`${a}px`):p.num!==0&&f.num===0?I(l,"width",`${a}px`):p.num===0&&f.num!==0?I(l,"height",`${h}px`):p.unit!=="%"?I(l,"min-width",`${Math.max(a,ut(p,this.context))}px`):f.unit!=="%"?I(l,"min-height",`${Math.max(h,ut(f,this.context))}px`):o?I(l,"height",`${h}px`):I(l,"width",`${a}px`)}}}})}preprocessElementStyle(t){_t("PREPROCESS_ELEMENT_STYLE").forEach(i=>{i(this.nodeContext,t)})}findAndProcessRepeatingElements(t,i){for(let n=t.firstChild;n;n=n.nextSibling){if(n.nodeType!==1)continue;let o={},r=i.getStyle(n,!1);if(this.computeStyle(this.nodeContext.vertical,this.nodeContext.direction==="rtl",r,o),!this.processRepeatOnBreak(o))continue;if(this.nodeContext.formattingContext instanceof tn&&!this.nodeContext.belongsTo(this.nodeContext.formattingContext))return;let s=this.nodeContext.parent,a=s&&s.formattingContext;this.nodeContext.formattingContext=new tn(a,this.nodeContext.sourceNode),this.nodeContext.formattingContext.initializeRepetitiveElements(this.nodeContext.vertical);return}}processRepeatOnBreak(t){let i=t["repeat-on-break"];return i!==y.none&&((i===y.auto||Z(i))&&(t.display===y.table_header_group?i=y.header:t.display===y.table_footer_group?i=y.footer:i=y.none),i&&i!==y.none)?i.toString():null}createTextNodeView(){let t=M("createTextNodeView");return this.preprocessTextContent().then(()=>{let i=this.offsetInNode||0,n=hu(this.nodeContext.preprocessedTextContent).substr(i);this.viewNode=document.createTextNode(n),t.finish(!0)}),t.result()}preprocessTextContent(){if(this.nodeContext.preprocessedTextContent!=null)return T(!0);let t,i=t=this.sourceNode.textContent,n=M("preprocessTextContent"),o=_t("PREPROCESS_TEXT_CONTENT"),r=0;return n.loop(()=>r>=o.length?T(!1):o[r++](this.nodeContext,i).thenAsync(s=>(i=s,T(!0)))).then(()=>{this.nodeContext.preprocessedTextContent=Av(t,i),n.finish(!0)}),n.result()}createNodeView(t,i){let n=M("createNodeView"),o,r=!0;return this.sourceNode.nodeType==1?o=this.createElementView(t,i):this.sourceNode.nodeType==8?(this.viewNode=null,o=T(!0)):o=this.createTextNodeView(),o.then(s=>{var a;if(r=s,this.nodeContext.viewNode=this.viewNode,this.viewNode){let h=(d,p)=>d?.nodeType===1&&Yt(d)===p,l=this.nodeContext.parent,c=l?h(this.viewNode,"after")&&h(l.viewNode,"first-letter")&&(a=l.viewNode)!=null&&a.hasChildNodes()?l.parent.viewNode:l.viewNode:this.viewRoot;this.nodeContext.pluginProps.nestedFootnoteDetached&&(c=this.viewRoot),c&&(this.nodeContext.inline&&!(this.viewNode.nodeType===3&&Ee(this.viewNode))&&!c.hasChildNodes()&&Zd(c).includes("block-start")&&Ct(c,"text-start"),c.appendChild(this.viewNode),mv(this.viewNode))}n.finish(r)}),n.result()}setCurrent(t,i,n){return this.nodeContext=t,t?(this.sourceNode=t.sourceNode,this.offsetInNode=t.offsetInNode):(this.sourceNode=null,this.offsetInNode=-1),this.viewNode=null,this.nodeContext?this.createNodeView(i,!!n):T(!0)}processShadowContent(t){if(t.shadowContext==null||t.sourceNode.localName!="content"||t.sourceNode.namespaceURI!="http://www.pyroxy.com/ns/shadow")return t;let i=t.boxOffset,n=t.shadowContext,o=t.parent,r,s,a=n.subShadow||n.parentShadow;n.subShadow?(r=n.subShadow.root,s=n.subShadow.type,s==st.ROOTLESS&&(r=r.firstChild)):(r=n.owner.firstChild,s=st.ROOTLESS);let h=t.sourceNode.nextSibling;if(h?(t.sourceNode=h,t.resetView()):t.shadowSibling?t=t.shadowSibling:r?t=null:(t=t.parent.modify(),t.after=!0),r){let l=new xn(r,o,i);return l.shadowContext=a,l.shadowType=s,l.shadowSibling=t,this.processShadowContent(l)}return t.boxOffset=i,t}nextPositionInTree(t){let i=t.boxOffset+1;if(t.after){if(!t.parent)return null;if(t.shadowType!=st.ROOTED){let n=t.sourceNode.nextSibling;if(n)return t=t.modify(),t.boxOffset=i,t.sourceNode=n,t.resetView(),this.processShadowContent(t)}return t.shadowSibling?(t=t.shadowSibling.modify(),t.boxOffset=i,t):(t=t.parent.modify(),t.boxOffset=i,t.after=!0,t)}else{if(t.nodeShadow){let o=t.nodeShadow.root;if(t.nodeShadow.type==st.ROOTLESS&&(o=o.firstChild),o){let r=new xn(o,t,i);return r.shadowContext=t.nodeShadow,r.shadowType=t.nodeShadow.type,this.processShadowContent(r)}}let n=t.sourceNode.firstChild;if(n)return this.processShadowContent(new xn(n,t,i));if(t.sourceNode.nodeType!=1){let o=hu(t.preprocessedTextContent);i+=o.length-1-t.offsetInNode}return t=t.modify(),t.boxOffset=i,t.after=!0,t}}findImmediateFootnoteCallSibling(t){let i=this.xmldoc.getElementOffset(t.sourceNode),n=t.viewNode;if(!n)return null;let o=n.previousSibling;for(;o;){if(o.nodeType===Node.TEXT_NODE){if(o.textContent.trim().length===0){o=o.previousSibling;continue}return null}if(o.nodeType===Node.ELEMENT_NODE){let r=o;return Yt(r)==="footnote-call"&&r.getAttribute(mo.FOOTNOTE_CALL_OWNER_ATTR)===i.toString()?r:null}return null}return null}isSemanticFootnoteElement(t){let i=t.sourceNode;return i instanceof Element&&Pt(i)}insertFootnoteCall(t){var i,n;let o=M("insertFootnoteCall"),r=fo.createElementNS("http://www.w3.org/1999/xhtml","span");Po(r,"footnote-call");let s=this.xmldoc.getElementOffset(t.sourceNode);r.setAttribute(mo.FOOTNOTE_CALL_OWNER_ATTR,s.toString());let a=new xn(r,t.parent,t.boxOffset);a.inline=!0;let h=new ma(t.sourceNode,this.styler.getStyle(t.sourceNode,!1),this.styler,this.context,this.exprContentListener);return a.shadowContext=new Br(t.sourceNode,r,null,((i=t.parent)==null?void 0:i.shadowContext)||null,null,st.ROOTLESS,h),a.shadowSibling=t,t.boxOffset++,(n=t.viewNode)!=null&&n.parentNode&&t.viewNode.parentNode.removeChild(t.viewNode),this.setCurrent(a,!0,!1).then(l=>{if(l&&r.hasChildNodes())o.finish(a);else{let c=a.modify();c.after=!0,a.viewNode||(c.inline=!0),o.finish(c)}}),o.result()}nextInTree(t,i){let n=this.nextPositionInTree(t);if(!n||n.after)return T(n);this.syncTextNodePageTypeBoundary(n);let o=M("nextInTree");return this.setCurrent(n,!0,i).then(r=>{if((!n.viewNode||!r)&&(n=n.modify(),n.after=!0,n.viewNode||(n.inline=!0)),n.floatSide==="footnote"&&!(this.isFootnote&&!n.parent)&&!n.after&&!n.pluginProps.footnoteCallProcessed&&!n.shadowContext&&!this.isSemanticFootnoteElement(n)){let s=this.findImmediateFootnoteCallSibling(n);s!=null&&s.parentNode&&s.parentNode.removeChild(s),this.isFootnote&&n.parent&&(n.pluginProps.nestedFootnoteDetached=1),n.pluginProps.footnoteCallProcessed=1,this.insertFootnoteCall(n).then(a=>{this.dispatchEvent({type:"nextInTree",nodeContext:a}),o.finish(a)});return}this.dispatchEvent({type:"nextInTree",nodeContext:n}),o.finish(n)}),o.result()}addImageFetchers(t){No(t,this.page)}applyComputedStyles(t,i){var n,o,r;let s=i["background-image"];s&&this.addImageFetchers(s);let a=i["border-image-source"];a&&this.addImageFetchers(a);let h=i["list-style-image"];h&&this.addImageFetchers(h);let l=i["mask-image"];l&&this.addImageFetchers(l);let c=i["clip-path"];c&&this.addImageFetchers(c);let d=i.filter;d&&this.addImageFetchers(d);let p=i["shape-outside"];p&&this.addImageFetchers(p);let f=i["--viv-marker-content"];f&&this.addImageFetchers(f);let g=i.position===y.relative,v=((n=this.nodeContext)==null?void 0:n.parent)===null&&((o=this.sourceNode)==null?void 0:o.parentElement)===null&&!!((r=this.viewRoot)!=null&&r.parentElement),w=Object.keys(i);w.sort(_h);let x,m;for(let S of w){if(Hx[S])continue;let b=i[S];if(!(!b||b===Be&&!Xe(S))){if(b=b.visit(new jm(this.xmldoc.url,this.documentURLTransformer)),b instanceof O)if(b.unit==="em"){let C=this.getEmUnitSize(S,x);C!=null&&(b=new O(b.num*C,"px"))}else if(b.unit==="lh"){let C=this.getLineHeightUnitSize(S,x,m);C!=null&&(b=new O(b.num*C,"px"))}else Ic(b.unit)&&(b=qc(b,this.context));if((S==="font-size"||S==="line-height")&&(S==="font-size"?x=b:m=b,this.viewport.layoutUnitAdj&&b instanceof O&&b.unit!=="%"&&b.unit!=="em"&&b.unit!=="lh"&&(b=new fn(`calc(${b.toString()} - var(--viv-layoutUnitAdj))`))),Rv[S]||g&&Lv[S]){this.page.delayedItems.push(new Ul(t,S,b));continue}v&&this.page.pageAreaElement&&In(S)?(I(this.page.pageAreaElement.parentElement.parentElement,S,b.toString()),S!=="writing-mode"&&S!=="direction"&&I(this.viewport.layoutBox,S,b.toString())):I(t,S,b.toString())}}}parsePlusLayoutUnitAdj(t){if(t.endsWith("px")){let i=parseFloat(t);if(!isNaN(i))return Math.round((i+this.viewport.layoutUnitAdj)*this.viewport.layoutUnitPerPixel)/this.viewport.layoutUnitPerPixel}return null}getFootnoteAreaInheritedMetrics(){var t,i;let n=(i=(t=this.page.pageAreaElement)==null?void 0:t.parentElement)==null?void 0:i.parentElement,o=n?this.viewport.window.getComputedStyle(n):null,r=o&&this.parsePlusLayoutUnitAdj(o.fontSize)||this.context.rootFontSize||this.context.initialFontSize,s=o&&this.parsePlusLayoutUnitAdj(o.lineHeight)||this.context.rootLineHeight||r*this.context.pref.lineHeight;return{fontSize:r,lineHeight:s}}getComputedFontMetrics(t,i){var n,o,r;let s=this.viewport.window.getComputedStyle(t),a=(n=this.parsePlusLayoutUnitAdj(s.fontSize))!=null?n:i.fontSize,h=(r=(o=this.parsePlusLayoutUnitAdj(s.lineHeight))!=null?o:i.lineHeight)!=null?r:a!=null?a*this.context.pref.lineHeight:null;return{fontSize:a,lineHeight:h}}getParentViewStyle(){var t,i,n;return((n=(i=(t=this.nodeContext)==null?void 0:t.parent)==null?void 0:i.viewNode)==null?void 0:n.nodeType)===1?this.viewport.window.getComputedStyle(this.nodeContext.parent.viewNode):null}getParentComputedMetrics(t){var i,n;return{fontSize:(i=this.computedStyleParentFontSizeOverride)!=null?i:t?this.parsePlusLayoutUnitAdj(t.fontSize):this.context.rootFontSize,lineHeight:(n=this.computedStyleParentLineHeightOverride)!=null?n:t?this.parsePlusLayoutUnitAdj(t.lineHeight):this.context.rootLineHeight}}getLineHeightUnitSize(t,i,n){var o,r,s;let a=this.getParentViewStyle(),h=this.getParentComputedMetrics(a),l=h.lineHeight;if(t==="line-height"||t==="font-size")return l;let c=null;if(n)if(n instanceof At||n instanceof O&&(n.unit==="em"||n.unit==="%"))c=n instanceof O&&n.unit==="%"?n.num/100:n.num;else{if(n instanceof O&&n.unit!=="lh"){let d=this.context.queryUnitSize(n.unit,!1);if(d!=null)return n.num*d}return null}if(c==null)for(let d=(r=(o=this.nodeContext)==null?void 0:o.parent)==null?void 0:r.viewNode;d&&d.nodeType===1;d=d.parentNode){let p=(s=d?.style)==null?void 0:s.lineHeight;if(p){/^[0-9.]+$/.test(p)&&(c=parseFloat(p));break}}if(c!=null){if(i&&!(i instanceof O))return null;let d=h.fontSize;if(i instanceof O){let p=ol(i,d,this.context).num;return typeof p!="number"||isNaN(p)?null:c*p}else return d==null?null:c*d}return l}getEmUnitSize(t,i){let n=this.getParentViewStyle(),o=this.getParentComputedMetrics(n).fontSize;if(t==="font-size"||i==null)return o;if(i instanceof O){let r=ol(i,o,this.context).num;if(typeof r=="number"&&!isNaN(r))return r}return null}applyPseudoelementStyle(t,i,n){if(t.after)return;let o=this.sourceNode,r=(t.shadowContext?t.shadowContext.styler:this.styler).getStyle(o,!1),s=ft(r,"_pseudos");if(!s||(r=s[i],!r))return;let a={};t.vertical=this.computeStyle(t.vertical,t.direction==="rtl",r,a);let h=a.content;It(h)&&(h.visit(new Oo(n,this.context,h,this.exprContentListener)),delete a.content),this.applyComputedStyles(n,a)}peelOff(t,i){let n=M("peelOff"),o=t.firstPseudo,r=t.offsetInNode,s=t.after;if(i>0){let d=t.viewNode.textContent;t.viewNode.textContent=d.substr(0,i),r+=i}else if(!s&&t.viewNode&&r==0){let d=t.viewNode.parentNode;d&&d.removeChild(t.viewNode)}let a=t.boxOffset+i,h=[];for(;t&&t.firstPseudo===o;)h.push(t),t=t.parent;let l=h.pop(),c=l.shadowSibling;return n.loop(()=>{for(;h.length>0;){l=h.pop(),t=new xn(l.sourceNode,t,a),h.length==0&&(t.offsetInNode=r,t.after=s),t.shadowType=l.shadowType,t.shadowContext=l.shadowContext,t.nodeShadow=l.nodeShadow,t.shadowSibling=l.shadowSibling?l.shadowSibling:c,c=null;let d=this.setCurrent(t,!1);if(d.isPending())return d}return T(!1)}).then(()=>{n.finish(t)}),n.result()}createElement(t,i){return t=="http://www.w3.org/1999/xhtml"?this.document.createElement(i):this.document.createElementNS(t,i)}applyFootnoteStyle(t,i,n){var o;let r={},s=[],a=this.footnoteStyle;if(this.cascadedPageStyle){let p=ft(this.cascadedPageStyle,Ns);p&&p.area&&(a=p.area)}let h=ft(a,"_pseudos");t=this.computeStyle(t,i,a,r);let l=this.getFootnoteAreaInheritedMetrics();!r["font-size"]&&l.fontSize!=null&&(r["font-size"]=new O(l.fontSize,"px")),delete r.content;let c=this.computedStyleParentFontSizeOverride,d=this.computedStyleParentLineHeightOverride;this.computedStyleParentFontSizeOverride=l.fontSize,this.computedStyleParentLineHeightOverride=l.lineHeight;try{this.applyComputedStyles(n,r);let p=this.getComputedFontMetrics(n,l);if(this.computedStyleParentFontSizeOverride=p.fontSize,this.computedStyleParentLineHeightOverride=p.lineHeight,h&&h.before){let f=h.before,g=!!ve(f,"display"),v={},w=this.createElement("http://www.w3.org/1999/xhtml","span");Po(w,"before"),n.appendChild(w),this.computeStyle(t,i,f,v),g||(v.display=y.block);let x=ve(f,"content");if(x){let S=((o=this.sourceNode)==null?void 0:o.nodeType)===1?this.sourceNode:this.xmldoc.root;v.content=x.filterValue(new Do(this.styler.cascade,S,this.styler.cascade.counterResolver,"before")).evaluate(this.context,"content")}let m=v.content;if(It(m)){m.visit(new Oo(w,this.context,m,this.exprContentListener));let S=w.querySelectorAll("img[src]");for(let C=0;C<S.length;C++){let P=S[C],L=P.getAttribute("src");if(!L)continue;let A=Et(P,L);s.push(A),this.page.fetchers.push(A)}let b=w.getAttribute("src");if(b){let C=w.querySelector("img");C||(C=this.document.createElement("img"),C.setAttribute("src",b),w.appendChild(C));let P=Et(C,b);s.push(P),this.page.fetchers.push(P)}}delete v.content,this.applyComputedStyles(w,v)}}finally{this.computedStyleParentFontSizeOverride=c,this.computedStyleParentLineHeightOverride=d}return s.length?Dn(s).thenReturn(t):T(t)}processFragmentedBlockEdge(t){var i,n,o;let r=!t.inline&&t.after?t.parent:t,s=!1;if(t.inline&&t.after&&!t.shadowContext&&((i=t.sourceNode.nextSibling)==null?void 0:i.nodeType)===1){let h=t.sourceNode.nextSibling,l=(n=ve(this.styler.getStyle(h,!1),"display"))==null?void 0:n.value.toString();s=l&&!Ut(l)||h.getAttribute("data-math-typeset")==="true"&&/^\s*(\$\$|\\\[)/.test(h.textContent)}let a=0;for(let h=r;h;h=h.parent){if(((o=h.viewNode)==null?void 0:o.nodeType)!==1)continue;let l=h.viewNode;if(l.style)if(h.inline){if(Ct(l,"inline-end"),Nn(l)){let c=h.vertical?l.offsetWidth:l.offsetHeight;Ct(l,"clone"),(h.vertical?l.offsetWidth:l.offsetHeight)>c&&this.fixClonedBoxDecorationOverflow(l)}}else{let c=this.nodeContext.vertical?"width":"height";if(ki(l,c)&&I(l,c,""),Ct(l,"block-end"),!a++&&h!==r){let{textAlign:d}=this.viewport.window.getComputedStyle(l);if(d==="justify"&&!s){let p=this.createChildAnonymousBlockIfNeeded(l);p?p!==l?Kd(p,["block-start","text-start","block-end","text-end","justify"]):(Ct(l,"text-end"),Ct(l,"justify")):Ct(l,"text-end")}else Ct(l,"text-end")}Nn(l)&&Ct(l,"clone"),sa(l,"block-end")}}}fixClonedBoxDecorationOverflow(t){let i=this.viewport.window.getComputedStyle(t),n=parseFloat(i.paddingInlineEnd),o=parseFloat(i.borderInlineEndWidth),r=-(n+o);isNaN(r)||(t.style.marginInlineEnd=`${r}px`)}createChildAnonymousBlockIfNeeded(t){let i=r=>{let{display:s,position:a,float:h}=this.viewport.window.getComputedStyle(r);if(r.localName==="ruby"||ji[r.localName])return!1;if(r.localName==="br")return!0;if((s==="inline"||s==="contents")&&r.hasChildNodes()){let l=r.lastElementChild;if(l&&(!l.nextSibling||l.nextSibling===r.lastChild&&Ee(l.nextSibling))){let c=i(l);if(c||c===null)return c}for(let c=l?.previousElementSibling;c;c=c.previousElementSibling){let d=i(c);if(d||d===null)return null}return!1}if(s==="none"||a==="absolute"||a==="fixed"||h&&h!=="none"||r.hasAttribute(zn)){let l=r.previousElementSibling;return l&&(l.nextSibling===r||l.nextSibling===r.previousSibling&&Ee(l.nextSibling))?i(l):!1}return!(!s||Ut(s))},n=null;for(let r=t.lastElementChild;r;r=r.previousElementSibling){let s=i(r);if(s){n=r;break}if(s===null)return null}if(!n)return t;if(n===t.lastElementChild&&(!n.nextSibling||n.nextSibling===t.lastChild&&Ee(n.nextSibling)))return null;let o=t.ownerDocument.createElement("span");o.className="viv-anonymous-block";for(let r=n.nextSibling,s=null;r;r=s)s=r.nextSibling,o.appendChild(r);return t.appendChild(o),o}convertLengthToPx(t,i,n){let o=t.num,r=t.unit;if(um(r)){let s=i;for(;s&&s.nodeType!==1;)s=s.parentNode;let a=parseFloat(n.getElementComputedStyle(s)["font-size"]);return this.context,nh(t,a,this.context).num}else{let s=this.context.queryUnitSize(r,!1);return s?o*s:t}}isSameNodePositionStep(t,i){if(t.shadowContext){if(!i.shadowContext)return!1;let n=t.node.nodeType===1?t.node:t.node.parentElement,o=i.node.nodeType===1?i.node:i.node.parentElement;return t.shadowContext.owner===i.shadowContext.owner&&Yt(n)===Yt(o)}else return t.node===i.node}isSameNodePosition(t,i){return t.offsetInNode===i.offsetInNode&&t.after==i.after&&t.steps.length===i.steps.length&&t.steps.every((n,o)=>{let r=i.steps[o];return this.isSameNodePositionStep(n,r)})}isPseudoelement(t){return!!Yt(t)}};u(fl,"SVG_URL_ATTRIBUTES",["color-profile","clip-path","cursor","filter","marker","marker-start","marker-end","marker-mid","fill","stroke","mask"]),u(fl,"FOOTNOTE_CALL_OWNER_ATTR","data-viv-footnote-call-owner");var $x=fl,Hx={"float-min-wrap-block":!0,"float-reference":!0,"flow-into":!0,"flow-linger":!0,"flow-options":!0,"flow-priority":!0,"footnote-display":!0,"footnote-policy":!0,"margin-break":!0,page:!0},Wx=class{constructor(e){u(this,"layoutBox"),u(this,"window"),u(this,"pixelRatio"),u(this,"scaleRatio"),u(this,"layoutUnitPerPixel"),this.layoutBox=e.layoutBox,this.window=e.window,this.pixelRatio=e.pixelRatio,this.scaleRatio=e.scaleRatio,this.layoutUnitPerPixel=e.layoutUnitPerPixel}subtractOffsets(e,t){let i=t.left,n=t.top;return{left:e.left-i,top:e.top-n,right:e.right-i,bottom:e.bottom-n,width:e.width,height:e.height}}getRangeClientRects(e){let t=e.getClientRects(),i=this.layoutBox.getBoundingClientRect();return Array.from(t).map(n=>this.subtractOffsets(n,i))}getElementClientRect(e){let t=e.getBoundingClientRect();if(t.left===0&&t.top===0&&t.right===0&&t.bottom===0)return t;let i=this.layoutBox.getBoundingClientRect();return this.subtractOffsets(t,i)}getElementComputedStyle(e){return this.window.getComputedStyle(e,null)}adjustLengthValue(e){return this.layoutUnitPerPixel?Math.floor(e*this.layoutUnitPerPixel)/this.layoutUnitPerPixel:e}},Es=class{constructor(e,t,i,n,o,r){if(u(this,"window",e),u(this,"fontSize",t),u(this,"pixelRatio",i),u(this,"document"),u(this,"root"),u(this,"outerZoomBox"),u(this,"contentContainer"),u(this,"layoutBox"),u(this,"width"),u(this,"height"),u(this,"scaleRatio",1),u(this,"layoutUnitPerPixel",64),u(this,"layoutUnitAdj",0),this.document=e.document,this.root=n||this.document.body,this.root.hasAttribute("data-vivliostyle-toc-box")){this.outerZoomBox=this.contentContainer=this.layoutBox=this.root,this.width=o||this.root.clientWidth,this.height=r||this.root.clientHeight;return}let s=this.root.firstElementChild;s||(s=this.document.createElement("div"),s.setAttribute("data-vivliostyle-outer-zoom-box","true"),s.role="presentation",this.root.appendChild(s));let a=s.firstElementChild;switch(a||(a=this.document.createElement("div"),a.setAttribute("data-vivliostyle-spread-container","true"),a.role="presentation",s.appendChild(a)),i>0&&CSS.supports("zoom","8")&&(I(this.root,"--viv-outputPixelRatio",`${i}`),I(this.root,"--viv-devicePixelRatio",`${e.devicePixelRatio}`),this.scaleRatio=i/e.devicePixelRatio),jo){case"chromium":this.layoutUnitPerPixel=64*(this.pixelRatio||e.devicePixelRatio),this.layoutUnitAdj=1/this.layoutUnitPerPixel;break;case"firefox":this.layoutUnitPerPixel=60,this.layoutUnitAdj=1/this.layoutUnitPerPixel;break;default:this.layoutUnitPerPixel=64,this.layoutUnitAdj=0}this.layoutUnitAdj&&I(this.root,"--viv-layoutUnitAdj",`${this.layoutUnitAdj}px`);let h=s.nextElementSibling;h||(h=this.document.createElement("div"),h.setAttribute("data-vivliostyle-layout-box","true"),h.role="presentation",this.root.appendChild(h)),this.outerZoomBox=s,this.contentContainer=a,this.layoutBox=h,this.width=o||parseFloat(e.getComputedStyle(this.root).width)||this.root.offsetWidth||e.innerWidth,this.height=r||parseFloat(e.getComputedStyle(this.root).height)||this.root.offsetHeight||e.innerHeight;let l={width:794,height:1056},c=!e.outerWidth&&!e.outerHeight||/Headless/.test(navigator.userAgent)||navigator.webdriver&&e.innerWidth===800&&e.innerHeight===600;(!this.width||!o&&c)&&(this.width=l.width),(!this.height||!r&&c)&&(this.height=l.height)}resetZoom(){I(this.outerZoomBox,"width",""),I(this.outerZoomBox,"height",""),I(this.contentContainer,"width",""),I(this.contentContainer,"height",""),I(this.contentContainer,"transform","")}zoom(e,t,i){I(this.root,"--viv-outputScale",`${i}`),I(this.outerZoomBox,"width",`${e*i}px`),I(this.outerZoomBox,"height",`${t*i}px`),I(this.contentContainer,"width",`${e}px`),I(this.contentContainer,"height",`${t}px`)}clear(){let e=this.root;for(;e.lastChild;)e.removeChild(e.lastChild)}};function No(e,t){if(e instanceof _e)for(let i of e.values)No(i,t);else if(e instanceof Qe){let i=Fo(e.url);t.fetchers.push(Et(new Image,i))}else if(e instanceof ai)for(let i of e.values)No(i,t);else if(e instanceof J)for(let i of e.values)No(i,t)}var Gx=1,Gs=class{constructor(e,t,i,n,o){u(this,"name",t),u(this,"pseudoName",i),u(this,"classes",n),u(this,"parent",o),u(this,"specified",{}),u(this,"children",[]),u(this,"pageMaster",null),u(this,"index",0),u(this,"key"),u(this,"_scope"),this._scope=e,this.key=`p${Gx++}`,o&&(this.index=o.children.length,o.children.push(this))}get scope(){return this._scope}createInstance(e){throw new Error("E_UNEXPECTED_CALL")}clone(e){throw new Error("E_UNEXPECTED_CALL")}copySpecified(e){let t=this.specified,i=e.specified;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=t[n])}cloneChildren(e){for(let t=0;t<this.children.length;t++)this.children[t].clone({parent:e})}},jx=class extends Gs{constructor(e){super(e,null,null,[],null),this.specified.width=new W(Yo,0),this.specified.height=new W(Zo,0)}},Wu=class extends ts{constructor(e,t){super(e,n),u(this,"pageMaster",t);let i=this;function n(o,r){let s=o.match(/^([^.]+)\.([^.]+)$/);if(s){let a=i.pageMaster.keyMap[s[1]];if(a){let h=this.lookupInstance(a);if(h)return r?h.resolveFunc(s[2]):h.resolveName(s[2])}}return null}}},Jf=class Qf extends Gs{constructor(t,i,n,o,r,s,a){super(t,i,n,o,r),u(this,"condition",s),u(this,"specificity",a),u(this,"keyMap",{}),t instanceof Wu||(this._scope=new Wu(t,this)),this.pageMaster=this,this.specified.width=new W(Yo,0),this.specified.height=new W(Zo,0),this.specified["wrap-flow"]=new W(y.auto,0),this.specified.position=new W(y.relative,0),this.specified.overflow=new W(y.visible,0)}createInstance(t){return new gh(t,this)}clone(t){let i=new Qf(this.scope,this.name,t.pseudoName||this.pseudoName,this.classes,this.parent,this.condition,this.specificity);return this.copySpecified(i),this.cloneChildren(i),i}resetScope(){this.scope.pageMaster=this}},eg=class tg extends Gs{constructor(t,i,n,o,r){super(t,i,n,o,r),this.pageMaster=r.pageMaster,i&&(this.pageMaster.keyMap[i]=this.key),this.specified["wrap-flow"]=new W(y.auto,0)}createInstance(t){return new Kx(t,this)}clone(t){let i=new tg(t.parent.scope,this.name,this.pseudoName,this.classes,t.parent);return this.copySpecified(i),this.cloneChildren(i),i}},rr=class ig extends Gs{constructor(t,i,n,o,r){super(t,i,n,o,r),this.pageMaster=r.pageMaster,i&&(this.pageMaster.keyMap[i]=this.key)}createInstance(t){return new Wn(t,this)}clone(t){let i=new ig(t.parent.scope,this.name,this.pseudoName,this.classes,t.parent);return this.copySpecified(i),this.cloneChildren(i),i}};function Xx(e,t,i){return!t||Z(t)?new it(e,i):t.toExpr(e,e.zero)}function be(e,t,i){return!t||t===y.auto||Z(t)?null:t.toExpr(e,i)}function qx(e,t,i){return!t||t===y.normal||Z(t)?null:t.toExpr(e,i)}function Tt(e,t,i){return!t||t===y.auto||Z(t)?e.zero:t.toExpr(e,i)}function Gu(e,t,i){return!t||Z(t)?e.zero:t===y.auto?null:t.toExpr(e,i)}function ri(e,t,i,n){return!t||i===y.none||Z(t)?e.zero:t.toExpr(e,n)}function ng(e,t,i){return!t||Z(t)?i:t===y._true?e._true:t===y._false?e._false:t.toExpr(e,e.zero)}var js=class{constructor(e,t){u(this,"parentInstance",e),u(this,"pageBox",t),u(this,"cascaded",{}),u(this,"style",{}),u(this,"autoWidth",null),u(this,"autoHeight",null),u(this,"children",[]),u(this,"isAutoWidth",!1),u(this,"isAutoHeight",!1),u(this,"isTopDependentOnAutoHeight",!1),u(this,"isRightDependentOnAutoWidth",!1),u(this,"calculatedWidth",0),u(this,"calculatedHeight",0),u(this,"pageMasterInstance",null),u(this,"namedValues",{}),u(this,"namedFuncs",{}),u(this,"vertical",!1),u(this,"rtl",!1),u(this,"suppressEmptyBoxGeneration",!1),u(this,"borderBoxSizing",!1),e&&e.children.push(this)}reset(){this.calculatedWidth=0,this.calculatedHeight=0}addNamedValues(e,t){let i=this.resolveName(e),n=this.resolveName(t);if(!i||!n)throw new Error("E_INTERNAL");return ne(this.pageBox.scope,i,n)}resolveName(e){let t=this.namedValues[e];if(t)return t;let i=this.style[e];switch(i&&(t=i.toExpr(this.pageBox.scope,this.pageBox.scope.zero)),e){case"margin-left-edge":t=this.resolveName("left");break;case"margin-top-edge":t=this.resolveName("top");break;case"margin-right-edge":t=this.addNamedValues("border-right-edge","margin-right");break;case"margin-bottom-edge":t=this.addNamedValues("border-bottom-edge","margin-bottom");break;case"border-left-edge":t=this.addNamedValues("margin-left-edge","margin-left");break;case"border-top-edge":t=this.addNamedValues("margin-top-edge","margin-top");break;case"border-right-edge":t=this.addNamedValues("padding-right-edge","border-right-width");break;case"border-bottom-edge":t=this.addNamedValues("padding-bottom-edge","border-bottom-width");break;case"padding-left-edge":t=this.addNamedValues("border-left-edge","border-left-width");break;case"padding-top-edge":t=this.addNamedValues("border-top-edge","border-top-width");break;case"padding-right-edge":t=this.addNamedValues("right-edge","padding-right");break;case"padding-bottom-edge":t=this.addNamedValues("bottom-edge","padding-bottom");break;case"left-edge":t=this.addNamedValues("padding-left-edge","padding-left");break;case"top-edge":t=this.addNamedValues("padding-top-edge","padding-top");break;case"right-edge":t=this.addNamedValues("left-edge","width");break;case"bottom-edge":t=this.addNamedValues("top-edge","height");break}if(!t){let n;if(e=="extent")n=this.vertical?"width":"height";else if(e=="measure")n=this.vertical?"height":"width";else{let o=this.vertical?ef:tf;n=e;for(let r in o)n=n.replace(r,o[r])}n!=e&&(t=this.resolveName(n))}return t&&(this.namedValues[e]=t),t}resolveFunc(e){let t=this.namedFuncs[e];if(t)return t;if(e==="columns"){let i=this.pageBox.scope,n=new Uc(i,0),o=this.resolveName("column-count"),r=this.resolveName("column-width"),s=this.resolveName("column-gap");t=ye(i,Lr(i,new vo(i,"min",[n,o]),ne(i,r,s)),s)}return t&&(this.namedFuncs[e]=t),t}initEnabled(){let e=this.pageBox.scope,t=this.style,i=ng(e,t.enabled,e._true),n=be(e,t.page,e.zero);if(n){let s=new Je(e,"page-number");i=Wt(e,i,new Fl(e,n,s))}let o=be(e,t["min-page-width"],e.zero);o&&(i=Wt(e,i,new Ea(e,new Je(e,"page-width"),o)));let r=be(e,t["min-page-height"],e.zero);r&&(i=Wt(e,i,new Ea(e,new Je(e,"page-height"),r))),i=this.boxSpecificEnabled(i),t.enabled=new j(i)}boxSpecificEnabled(e){return e}initHorizontal(){let e=this.pageBox.scope,t=this.style,i=this.parentInstance?this.parentInstance.style.width.toExpr(e,null):null,n=be(e,t.left,i),o=be(e,t["margin-left"],i),r=ri(e,t["border-left-width"],t["border-left-style"],i),s=Tt(e,t["padding-left"],i),a=be(e,t.width,i),h=be(e,t["max-width"],i),l=Tt(e,t["padding-right"],i),c=ri(e,t["border-right-width"],t["border-right-style"],i),d=be(e,t["margin-right"],i),p=be(e,t.right,i),f=ne(e,r,s),g=ne(e,r,l);if(n&&p&&a){let x=ye(e,i,ne(e,a,ne(e,ne(e,n,f),g)));o?d?p=ye(e,x,d):d=ye(e,x,ne(e,p,o)):(x=ye(e,x,p),d?o=ye(e,x,d):(o=Lr(e,x,new it(e,.5)),d=o))}else{o||(o=e.zero),d||(d=e.zero),!n&&!p&&!a&&(n=e.zero),!n&&!a?(a=this.autoWidth,this.isAutoWidth=!0):!n&&!p?n=e.zero:!a&&!p&&(a=this.autoWidth,this.isAutoWidth=!0);let x=ye(e,i,ne(e,ne(e,o,f),ne(e,d,g)));this.isAutoWidth&&(h||(h=ye(e,x,n||p)),!this.vertical&&(be(e,t["column-width"],null)||be(e,t["column-count"],null))&&(a=h,this.isAutoWidth=!1)),n?a?p||(p=ye(e,x,ne(e,n,a))):a=ye(e,x,ne(e,n,p)):n=ye(e,x,ne(e,p,a))}let v=t["snap-width"]||(this.parentInstance?this.parentInstance.style["snap-width"]:null),w=Tt(e,v,i);t.left=new j(n),t["margin-left"]=new j(o),t["border-left-width"]=new j(r),t["padding-left"]=new j(s),t.width=new j(a),t["max-width"]=new j(h||a),t["padding-right"]=new j(l),t["border-right-width"]=new j(c),t["margin-right"]=new j(d),t.right=new j(p),t["snap-width"]=new j(w)}initVertical(){let e=this.pageBox.scope,t=this.style,i=this.parentInstance?this.parentInstance.style.width.toExpr(e,null):null,n=this.parentInstance?this.parentInstance.style.height.toExpr(e,null):null,o=be(e,t.top,n),r=be(e,t["margin-top"],i),s=ri(e,t["border-top-width"],t["border-top-style"],i),a=Tt(e,t["padding-top"],i),h=be(e,t.height,n),l=be(e,t["max-height"],n),c=Tt(e,t["padding-bottom"],i),d=ri(e,t["border-bottom-width"],t["border-bottom-style"],i),p=be(e,t["margin-bottom"],i),f=be(e,t.bottom,n),g=ne(e,s,a),v=ne(e,d,c);if(o&&f&&h){let m=ye(e,n,ne(e,h,ne(e,ne(e,o,g),v)));r?p?f=ye(e,m,r):p=ye(e,m,ne(e,f,r)):(m=ye(e,m,f),p?r=ye(e,m,p):(r=Lr(e,m,new it(e,.5)),p=r))}else{r||(r=e.zero),p||(p=e.zero),!o&&!f&&!h&&(o=e.zero),!o&&!h?(h=this.autoHeight,this.isAutoHeight=!0):!o&&!f?o=e.zero:!h&&!f&&(h=this.autoHeight,this.isAutoHeight=!0);let m=ye(e,n,ne(e,ne(e,r,g),ne(e,p,v)));this.isAutoHeight&&(l||(l=ye(e,m,o||f)),this.vertical&&(be(e,t["column-width"],null)||be(e,t["column-count"],null))&&(h=l,this.isAutoHeight=!1)),o?h?f||(f=ye(e,m,ne(e,o,h))):h=ye(e,m,ne(e,f,o)):o=ye(e,m,ne(e,f,h))}let w=t["snap-height"]||(this.parentInstance?this.parentInstance.style["snap-height"]:null),x=Tt(e,w,i);t.top=new j(o),t["margin-top"]=new j(r),t["border-top-width"]=new j(s),t["padding-top"]=new j(a),t.height=new j(h),t["max-height"]=new j(l||h),t["padding-bottom"]=new j(c),t["border-bottom-width"]=new j(d),t["margin-bottom"]=new j(p),t.bottom=new j(f),t["snap-height"]=new j(x)}initColumns(){let e=this.pageBox.scope,t=this.style,i=be(e,t[this.vertical?"height":"width"],null),n=be(e,t["column-width"],i),o=be(e,t["column-count"],null),r=qx(e,t["column-gap"],null);r||(r=new qo(e,1,"em")),n&&!o&&(o=new vo(e,"floor",[Pa(e,ne(e,i,r),ne(e,n,r))]),o=new vo(e,"max",[e.one,o])),o||(o=e.one),n=ye(e,Pa(e,ne(e,i,r),o),r),t["column-width"]=new j(n),t["column-count"]=new j(o),t["column-gap"]=new j(r)}depends(e,t,i){return this.style[e].toExpr(this.pageBox.scope,null).depend(t,i)}init(e){var t;e.registerInstance(this.pageBox.key,this);let i=this.pageBox.scope,n=this.style,o=this.parentInstance?this.parentInstance.getActiveRegions(e):null,r=cl(this.cascaded,e,o,!1,null);this.vertical=Cf(r,e,this.parentInstance?this.parentInstance.vertical:!1),this.rtl=kf(r,e,this.parentInstance?this.parentInstance.rtl:!1),this.borderBoxSizing=((t=r["box-sizing"])==null?void 0:t.value)===y.border_box;let s=!!(e instanceof wh&&e.currentLayoutPosition&&new Je(i,"left-page").evaluate(e));Pf(r,n,this.vertical,this.rtl,s,(a,h)=>h.value),this.autoWidth=new we(i,()=>this.calculatedWidth,"autoWidth"),this.autoHeight=new we(i,()=>this.calculatedHeight,"autoHeight"),this.initHorizontal(),this.initVertical(),this.initColumns(),this.initEnabled()}getProp(e,t){var i,n;let o=this.style[t];return!o&&In(t)&&this.pageMasterInstance instanceof Mn&&(t==="font-size"&&e.isRelativeRootFontSize&&e.rootFontSize?o=new O(e.rootFontSize,"px"):o=(n=((i=e.styler)==null?void 0:i.rootStyle)[t])==null?void 0:n.value),o&&(o=Ss(e,o,t)),o}getPropAsNumber(e,t){var i,n;let o=this.style[t];if(o){let r=/\b(height|top|bottom)\b/.test(t)?(i=e.pageAreaHeight)!=null?i:e.pageHeight():(n=e.pageAreaWidth)!=null?n:e.pageWidth();o=Ss(e,o,t,r)}return ut(o,e)}getSpecial(e,t){let i=sf(this.cascaded,t);if(i){let n=[];for(let o=0;o<i.length;o++){let r=i[o].evaluate(e,"");r&&r!==Be&&n.push(r)}if(n.length)return n}return null}getActiveRegions(e){let t=this.getSpecial(e,"region-id");if(t){let i=[];for(let n=0;n<t.length;n++)i[n]=t[n].toString();return i}return null}propagateProperty(e,t,i,n){this.propagatePropertyToElement(e,t.element,i,n)}propagatePropertyToElement(e,t,i,n){let o=this.getProp(e,i);o&&(o.isNumeric()&&Ic(o.unit)&&(o=qc(o,e)),i==="font-family"&&(o=n.filterFontFamily(o)),(i.startsWith("background")||i==="z-index")&&t.parentElement.hasAttribute("data-vivliostyle-bleed-box")&&(t=t.parentElement),I(t,i,o.toString()))}propagateDelayedProperty(e,t,i,n){let o=this.getProp(e,i);o&&n.push(new Ul(t.element,i,o))}assignLeftPosition(e,t){let i=this.getPropAsNumber(e,"left"),n=this.getPropAsNumber(e,"margin-left"),o=this.getPropAsNumber(e,"padding-left"),r=this.getPropAsNumber(e,"border-left-width"),s=this.getPropAsNumber(e,"width");t.setHorizontalPosition(i,s),I(t.element,"margin-left",`${n}px`),I(t.element,"padding-left",`${o}px`),I(t.element,"border-left-width",`${r}px`),t.marginLeft=n,t.borderLeft=r,t.paddingLeft=o}assignRightPosition(e,t){let i=this.getPropAsNumber(e,"right"),n=this.getPropAsNumber(e,"snap-height"),o=this.getPropAsNumber(e,"margin-right"),r=this.getPropAsNumber(e,"padding-right"),s=this.getPropAsNumber(e,"border-right-width");if(I(t.element,"margin-right",`${o}px`),I(t.element,"padding-right",`${r}px`),I(t.element,"border-right-width",`${s}px`),t.marginRight=o,t.borderRight=s,this.vertical&&n>0){let a=i+t.getInsetRight(),h=a-Math.floor(a/n)*n;h>0&&(t.snapOffsetX=n-h,r+=t.snapOffsetX)}t.paddingRight=r,t.snapWidth=n}assignTopPosition(e,t){let i=this.getPropAsNumber(e,"snap-height"),n=this.getPropAsNumber(e,"top"),o=this.getPropAsNumber(e,"margin-top"),r=this.getPropAsNumber(e,"padding-top"),s=this.getPropAsNumber(e,"border-top-width");if(t.top=n,t.marginTop=o,t.borderTop=s,t.snapHeight=i,!this.vertical&&i>0){let a=n+t.getInsetTop(),h=a-Math.floor(a/i)*i;h>0&&(t.snapOffsetY=i-h,r+=t.snapOffsetY)}t.paddingTop=r,I(t.element,"top",`${n}px`),I(t.element,"margin-top",`${o}px`),I(t.element,"padding-top",`${r}px`),I(t.element,"border-top-width",`${s}px`)}assignBottomPosition(e,t){let i=this.getPropAsNumber(e,"margin-bottom"),n=this.getPropAsNumber(e,"padding-bottom"),o=this.getPropAsNumber(e,"border-bottom-width"),r=this.getPropAsNumber(e,"height")-t.snapOffsetY;I(t.element,"height",`${r}px`),I(t.element,"margin-bottom",`${i}px`),I(t.element,"padding-bottom",`${n}px`),I(t.element,"border-bottom-width",`${o}px`),t.height=r-t.snapOffsetY,t.marginBottom=i,t.borderBottom=o,t.paddingBottom=n}assignBeforePosition(e,t){this.vertical?this.assignRightPosition(e,t):this.assignTopPosition(e,t)}assignAfterPosition(e,t){this.vertical?this.assignLeftPosition(e,t):this.assignBottomPosition(e,t)}assignStartEndPosition(e,t){this.vertical?(this.assignTopPosition(e,t),this.assignBottomPosition(e,t)):(this.assignRightPosition(e,t),this.assignLeftPosition(e,t))}sizeWithMaxHeight(e,t){I(t.element,"border-top-width","0px");let i=this.getPropAsNumber(e,"max-height");this.isTopDependentOnAutoHeight?t.setVerticalPosition(0,i):(this.assignTopPosition(e,t),i-=t.snapOffsetY,t.height=i,I(t.element,"height",`${i}px`))}sizeWithMaxWidth(e,t){I(t.element,"border-left-width","0px");let i=this.getPropAsNumber(e,"max-width");if(this.isRightDependentOnAutoWidth)t.setHorizontalPosition(0,i);else{this.assignRightPosition(e,t),i-=t.snapOffsetX,t.width=i;let n=this.getPropAsNumber(e,"right");I(t.element,"right",`${n}px`),I(t.element,"width",`${i}px`)}}prepareContainer(e,t,i,n,o){(!this.parentInstance||this.vertical!=this.parentInstance.vertical)&&I(t.element,"writing-mode",this.vertical?"vertical-rl":"horizontal-tb"),(!this.parentInstance||this.rtl!=this.parentInstance.rtl)&&I(t.element,"direction",this.rtl?"rtl":"ltr"),(this.vertical?this.isAutoWidth:this.isAutoHeight)?this.vertical?this.sizeWithMaxWidth(e,t):this.sizeWithMaxHeight(e,t):(this.assignBeforePosition(e,t),this.assignAfterPosition(e,t)),(this.vertical?this.isAutoHeight:this.isAutoWidth)?this.vertical?this.sizeWithMaxHeight(e,t):this.sizeWithMaxWidth(e,t):this.assignStartEndPosition(e,t);for(let r=0;r<ju.length;r++)this.propagateProperty(e,t,ju[r],n)}transferContentProps(e,t,i,n){for(let o=0;o<qu.length;o++)this.propagateProperty(e,t,qu[o],n);if(this.style["text-overflow"]){let o=t.element.firstElementChild;I(o,"text-overflow","inherit"),I(o,"overflow","inherit")}}transferSingleUriContentProps(e,t,i){let n=()=>{var r,s;let a=(s=(r=this.cascaded.width)!=null?r:this.cascaded[this.vertical?"block-size":"inline-size"])==null?void 0:s.value;return!!a&&a!==y.auto&&!Z(a)},o=()=>{var r,s;let a=(s=(r=this.cascaded.height)!=null?r:this.cascaded[this.vertical?"inline-size":"block-size"])==null?void 0:s.value;return!!a&&a!==y.auto&&!Z(a)};for(let r=0;r<Yu.length;r++){let s=Yu[r];if(s==="width"||s==="height"){if(s==="width"&&!n()||s==="height"&&!o())continue;I(t,s,"100%");continue}this.propagatePropertyToElement(e,t,s,i)}}finishContainer(e,t,i,n,o,r,s){var a,h,l,c,d,p,f,g,v,w;this.vertical?this.calculatedWidth=t.computedBlockSize+t.snapOffsetX:this.calculatedHeight=t.computedBlockSize+t.snapOffsetY;let x=(this.vertical||!n)&&this.isAutoHeight,m=(!this.vertical||!n)&&this.isAutoWidth,S=null;if(m||x){m&&I(t.element,"width","auto"),x&&I(t.element,"height","auto");let b=n&&rs(n);b&&_s(n),S=r.getElementClientRect(n?n.element:t.element),b&&_l(n),m&&(this.calculatedWidth=Math.ceil(S.right-S.left-t.paddingLeft-t.borderLeft-t.paddingRight-t.borderRight),this.vertical&&(this.calculatedWidth+=t.snapOffsetX)),x&&(this.calculatedHeight=S.bottom-S.top-t.paddingTop-t.borderTop-t.paddingBottom-t.borderBottom,this.vertical||(this.calculatedHeight+=t.snapOffsetY))}if((this.vertical?this.isAutoHeight:this.isAutoWidth)&&this.assignStartEndPosition(e,t),(this.vertical?this.isAutoWidth:this.isAutoHeight)&&((this.vertical?this.isRightDependentOnAutoWidth:this.isTopDependentOnAutoHeight)&&this.assignBeforePosition(e,t),this.assignAfterPosition(e,t)),o>1){let b=this.getPropAsNumber(e,"column-rule-width"),C=this.getProp(e,"column-rule-style"),P=this.getProp(e,"column-rule-color");if(b>0&&C&&C!=y.none&&P!=y.transparent){let L=this.getPropAsNumber(e,"column-gap"),A=this.vertical?t.height:t.width,z=parseFloat(this.vertical?(a=n?.element.style.left)!=null?a:"":(h=n?.element.style.top)!=null?h:""),U=t.getPaddingRect(),X=n,oe=this.vertical?"border-top":"border-left";for(let k=1;k<o;k++){let _=this.vertical?(A+L)*k/o-L/2+t.paddingTop-b/2:(A+L)*k/o-L/2+t.paddingLeft-b/2,F=this.vertical?U.y1+_+b/2:U.x1+_+b/2,D=(d=(c=(l=X.pageFloatLayoutContext)==null?void 0:l.parent)==null?void 0:c.getBlockEndEdgeOfBlockStartFloats)==null?void 0:d.call(c,F),E=(g=(f=(p=X.pageFloatLayoutContext)==null?void 0:p.parent)==null?void 0:f.getBlockStartEdgeOfBlockEndFloats)==null?void 0:g.call(f,F),N=isFinite(D)?this.vertical?D-U.x1:D-U.y1:NaN,R=isFinite(E)?this.vertical?E-U.x1:E-U.y1:NaN,$=parseFloat(this.vertical?(v=n?.element.style.width)!=null?v:"":(w=n?.element.style.height)!=null?w:""),V=$>0?$:this.vertical?n.width:n.height,q=Math.max(z>0?z:0,0),Q=q+V,ee=Math.max(q,isFinite(this.vertical?R:N)?Math.max(0,this.vertical?R:N):0),pe=Math.min(Q,isFinite(this.vertical?N:R)?Math.max(0,this.vertical?N:R):Q),re=Math.max(0,pe-ee),se=t.element.ownerDocument.createElement("div");I(se,"position","absolute"),I(se,this.vertical?"left":"top",`${ee}px`),I(se,this.vertical?"top":"left",`${_}px`),I(se,this.vertical?"height":"width","0px"),I(se,this.vertical?"width":"height",`${re}px`),I(se,oe,`${b}px ${C.toString()}${P?` ${P.toString()}`:""}`),t.element.insertBefore(se,t.element.firstChild)}}}for(let b=0;b<Xu.length;b++)this.propagateProperty(e,t,Xu[b],s);for(let b of Yx){let C=this.getProp(e,b);C&&No(C,i)}for(let b=0;b<Zu.length;b++)this.propagateDelayedProperty(e,t,Zu[b],i.delayedItems)}applyCascadeAndInit(e,t){let i=this.cascaded,n=this.pageBox.specified;for(let r in n)this instanceof Mn&&this.pageBox.pseudoName=="vivliostyle-page-rule-master"&&(r==="writing-mode"||r==="direction")||Xi(r)&&Fi(i,r,ve(n,r));if(this.pageBox.pseudoName==fh)for(let r in t)(r.match(/^background-/)||r=="writing-mode")&&(i[r]=t[r]);if(this.pageBox.pseudoName=="layout-host")for(let r in t)!r.match(/^background-/)&&r!="writing-mode"&&(i[r]=t[r]);e.pushRule(this.pageBox.classes,null,i);let o=i.content;if(o){let r=Array.from(e.lastCounterChanges),s={...e.lastCounterChangeTypes};e.counterScoping.push(null),e.pushCounters(i),i.content=o.filterValue(new Do(e,null,e.counterResolver)),e.popCounters(),e.popCounters(),e.lastCounterChanges=r,e.lastCounterChangeTypes=s}this.init(e.context);for(let r of this.pageBox.children)r.createInstance(this).applyCascadeAndInit(e,t);e.popRule()}resolveAutoSizing(e){this.isAutoWidth&&(this.isRightDependentOnAutoWidth=this.depends("right",this.autoWidth,e)||this.depends("margin-right",this.autoWidth,e)||this.depends("border-right-width",this.autoWidth,e)||this.depends("padding-right",this.autoWidth,e)),this.isAutoHeight&&(this.isTopDependentOnAutoHeight=this.depends("top",this.autoHeight,e)||this.depends("margin-top",this.autoHeight,e)||this.depends("border-top-width",this.autoHeight,e)||this.depends("padding-top",this.autoHeight,e));for(let t of this.children)t.resolveAutoSizing(e)}},ju=["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","outline-offset","overflow","visibility"],Xu=["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"],Yx=["background-image","border-image-source","filter"],qu=["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-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-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","text-box-trim","text-box-edge","text-justify"],Yu=["width","height","image-resolution","object-fit","object-position"],Zu=["transform","transform-origin"],fh="background-host",Zx=class extends js{constructor(e){super(null,e)}applyCascadeAndInit(e,t){super.applyCascadeAndInit(e,t),this.children.sort((i,n)=>n.pageBox.specificity-i.pageBox.specificity||i.pageBox.index-n.pageBox.index)}},gh=class extends js{constructor(e,t){super(e,t),this.pageMasterInstance=this}boxSpecificEnabled(e){let t=this.pageBox.pageMaster;return t.condition&&(e=Wt(t.scope,e,t.condition)),e}adjustPageLayout(e,t,i){}},Kx=class extends js{constructor(e,t){super(e,t),this.pageMasterInstance=e.pageMasterInstance}},Wn=class extends js{constructor(e,t){super(e,t),this.pageMasterInstance=e.pageMasterInstance}processPartitionList(e,t,i){let n=null;if(t instanceof he&&(n=[t]),t instanceof _e&&(n=t.values),n){let o=this.pageBox.scope;for(let r=0;r<n.length;r++)if(n[r]instanceof he){let s=Ca(n[r].name,"enabled"),a=new Je(o,s);i&&(a=new Ai(o,a)),e=Wt(o,e,a)}}return e}boxSpecificEnabled(e){let t=this.pageBox.scope,i=this.style,n=ng(t,i.required,t._false)!==t._false;if(n||this.isAutoHeight){let o=Xx(t,i["flow-from"],"body"),r=new vo(t,"has-content",[o]);e=Wt(t,e,r)}if(e=this.processPartitionList(e,i["required-partitions"],!1),e=this.processPartitionList(e,i["conflicting-partitions"],!0),n){let o=this.pageMasterInstance.style.enabled,r=o?o.toExpr(t,null):t._true;r=Wt(t,r,e),this.pageMasterInstance.style.enabled=new j(r)}return e}prepareContainer(e,t,i,n,o){var r;this.pageBox.pageMaster instanceof lg||(I(t.element,"overflow","hidden"),t.element.setAttribute("data-vivliostyle-page-partition",(r=this.pageBox.name)!=null?r:"")),super.prepareContainer(e,t,i,n,o)}},mh=class extends rn{constructor(e,t,i,n){super(e,t,!1),u(this,"target",i),u(this,"validatorSet",n)}property(e,t,i){this.validatorSet.validatePropertyAndHandleShorthand(e,t,i,this)}unknownProperty(e,t){this.report(`E_INVALID_PROPERTY ${e}: ${t.toString()}`)}invalidPropertyValue(e,t){this.report(`E_INVALID_PROPERTY_VALUE ${e}: ${t.toString()}`)}simpleProperty(e,t,i){this.target.specified[e]=new W(t,i?Ld:Od)}},og=class extends mh{constructor(e,t,i,n){super(e,t,i,n)}},Jx=class rg extends mh{constructor(t,i,n,o){super(t,i,n,o),n.specified.width=new W(Bh,0),n.specified.height=new W(Bh,0)}startPartitionRule(t,i,n){let o=new rr(this.scope,t,i,n,this.target),r=new og(this.scope,this.owner,o,this.validatorSet);this.owner.pushHandler(r)}startPartitionGroupRule(t,i,n){let o=new eg(this.scope,t,i,n,this.target),r=new rg(this.scope,this.owner,o,this.validatorSet);this.owner.pushHandler(r)}},Qx=class extends mh{constructor(e,t,i,n){super(e,t,i,n)}startPartitionRule(e,t,i){let n=new rr(this.scope,e,t,i,this.target),o=new og(this.scope,this.owner,n,this.validatorSet);this.owner.pushHandler(o)}startPartitionGroupRule(e,t,i){let n=new eg(this.scope,e,t,i,this.target),o=new Jx(this.scope,this.owner,n,this.validatorSet);this.owner.pushHandler(o)}};function sg(e){var t,i;let n=(t=e["writing-mode"])==null?void 0:t.value,o=(i=e.direction)==null?void 0:i.value;return n===y.vertical_lr||n!==y.vertical_rl&&o!==y.rtl?"ltr":"rtl"}var eS={a10:{width:new O(26,"mm"),height:new O(37,"mm")},a9:{width:new O(37,"mm"),height:new O(52,"mm")},a8:{width:new O(52,"mm"),height:new O(74,"mm")},a7:{width:new O(74,"mm"),height:new O(105,"mm")},a6:{width:new O(105,"mm"),height:new O(148,"mm")},a5:{width:new O(148,"mm"),height:new O(210,"mm")},a4:{width:new O(210,"mm"),height:new O(297,"mm")},a3:{width:new O(297,"mm"),height:new O(420,"mm")},a2:{width:new O(420,"mm"),height:new O(594,"mm")},a1:{width:new O(594,"mm"),height:new O(841,"mm")},a0:{width:new O(841,"mm"),height:new O(1189,"mm")},b10:{width:new O(31,"mm"),height:new O(44,"mm")},b9:{width:new O(44,"mm"),height:new O(62,"mm")},b8:{width:new O(62,"mm"),height:new O(88,"mm")},b7:{width:new O(88,"mm"),height:new O(125,"mm")},b6:{width:new O(125,"mm"),height:new O(176,"mm")},b5:{width:new O(176,"mm"),height:new O(250,"mm")},b4:{width:new O(250,"mm"),height:new O(353,"mm")},b3:{width:new O(353,"mm"),height:new O(500,"mm")},b2:{width:new O(500,"mm"),height:new O(707,"mm")},b1:{width:new O(707,"mm"),height:new O(1e3,"mm")},b0:{width:new O(1e3,"mm"),height:new O(1414,"mm")},c10:{width:new O(28,"mm"),height:new O(40,"mm")},c9:{width:new O(40,"mm"),height:new O(57,"mm")},c8:{width:new O(57,"mm"),height:new O(81,"mm")},c7:{width:new O(81,"mm"),height:new O(114,"mm")},c6:{width:new O(114,"mm"),height:new O(162,"mm")},c5:{width:new O(162,"mm"),height:new O(229,"mm")},c4:{width:new O(229,"mm"),height:new O(324,"mm")},c3:{width:new O(324,"mm"),height:new O(458,"mm")},c2:{width:new O(458,"mm"),height:new O(648,"mm")},c1:{width:new O(648,"mm"),height:new O(917,"mm")},c0:{width:new O(917,"mm"),height:new O(1297,"mm")},"jis-b10":{width:new O(32,"mm"),height:new O(45,"mm")},"jis-b9":{width:new O(45,"mm"),height:new O(64,"mm")},"jis-b8":{width:new O(64,"mm"),height:new O(91,"mm")},"jis-b7":{width:new O(91,"mm"),height:new O(128,"mm")},"jis-b6":{width:new O(128,"mm"),height:new O(182,"mm")},"jis-b5":{width:new O(182,"mm"),height:new O(257,"mm")},"jis-b4":{width:new O(257,"mm"),height:new O(364,"mm")},"jis-b3":{width:new O(364,"mm"),height:new O(515,"mm")},"jis-b2":{width:new O(515,"mm"),height:new O(728,"mm")},"jis-b1":{width:new O(728,"mm"),height:new O(1030,"mm")},"jis-b0":{width:new O(1030,"mm"),height:new O(1456,"mm")},letter:{width:new O(8.5,"in"),height:new O(11,"in")},legal:{width:new O(8.5,"in"),height:new O(14,"in")},ledger:{width:new O(11,"in"),height:new O(17,"in")}},tS=new O(.24,"pt"),cC=new O(3,"mm"),iS=new O(10,"mm"),nS=new O(13,"mm");function Ps(e){let t={width:Yo,height:Zo,bleed:Le,bleedOffset:Le,cropOffset:Le},i=e.size;if(!(!i||i.value===y.auto)){let l=i.value,c,d;if(l.isSpaceList()?(c=l.values[0],d=l.values[1]):(c=l,d=null),c.isNumeric())t.width=c,t.height=d||c;else{let p=c.name&&eS[c.name.toLowerCase()];p&&(d&&d===y.landscape?(t.width=p.height,t.height=p.width):(t.width=p.width,t.height=p.height))}}let n=e.marks,o=e.bleed,r=n&&!Z(n.value)?n.value:y.none,s=o&&!Z(o.value)?o.value:y.auto;if(s===y.auto){if(r!==y.none){let l=!1;r.isSpaceList()?l=r.values.some(c=>c===y.crop):l=r===y.crop,l&&(t.bleed=new O(6,"pt"))}}else s.isNumeric()&&(t.bleed=s);let a=e["crop-offset"],h=a&&!Z(a.value)?a.value:y.auto;return h===y.auto?r!==y.none&&(t.bleedOffset=nS):h.isNumeric()&&(t.cropOffset=h),t}function Ku(e,t){let i={},n=Math.max(0,e.bleed.num)*t.queryUnitSize(e.bleed.unit,!1),o=!e.cropOffset.num&&e.bleedOffset.num?e.bleedOffset.num*t.queryUnitSize(e.bleedOffset.unit,!1):Math.max(0,e.cropOffset.num*t.queryUnitSize(e.cropOffset.unit,!1)-n),r=n+o,s=e.width;s===Yo?t.pref.defaultPaperSize?i.pageWidth=t.pref.defaultPaperSize.width*t.queryUnitSize("px",!1):i.pageWidth=(t.pref.spreadView?Math.floor(t.viewportWidth/2)-t.pref.pageBorder:t.viewportWidth)-r*2:i.pageWidth=s.num*t.queryUnitSize(s.unit,!1);let a=e.height;return a===Zo?t.pref.defaultPaperSize?i.pageHeight=t.pref.defaultPaperSize.height*t.queryUnitSize("px",!1):i.pageHeight=t.viewportHeight-r*2:i.pageHeight=a.num*t.queryUnitSize(a.unit,!1),i.bleed=n,i.bleedOffset=o,i.cropOffset=r,i}function ag(e,t,i){let n=e.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",t),n.setAttribute("height",i),n.style.position="absolute",n}function To(e,t,i,n){n=n||"polyline";let o=e.createElementNS("http://www.w3.org/2000/svg",n);return o.setAttribute("stroke",i===y.auto?"#010101":i.toString()),o.setAttribute("stroke-width",t),o.setAttribute("fill","none"),o}var gl=(e=>(e.TOP_LEFT="top left",e.TOP_RIGHT="top right",e.BOTTOM_LEFT="bottom left",e.BOTTOM_RIGHT="bottom right",e))(gl||{});function oS(e,t,i,n,o,r,s){let a=o;a<=r+2*Zt.mm&&(a=r+o/2);let h=Math.max(o,a),l=r+h+i/2,c=ag(e,l,l),d=[[0,r+o],[o,r+o],[o,r+o-a]],p=d.map(v=>[v[1],v[0]]);(t==="top right"||t==="bottom right")&&(d=d.map(v=>[r+h-v[0],v[1]]),p=p.map(v=>[r+h-v[0],v[1]])),(t==="bottom left"||t==="bottom right")&&(d=d.map(v=>[v[0],r+h-v[1]]),p=p.map(v=>[v[0],r+h-v[1]]));let f=To(e,i,n);f.setAttribute("points",d.map(v=>v.join(",")).join(" ")),c.appendChild(f);let g=To(e,i,n);return g.setAttribute("points",p.map(v=>v.join(",")).join(" ")),c.appendChild(g),t.split(" ").forEach(v=>{c.style[v]=`${s}px`}),c}var Ho=(e=>(e.TOP="top",e.BOTTOM="bottom",e.LEFT="left",e.RIGHT="right",e))(Ho||{});function rS(e,t,i,n,o,r){let s=o*2,a,h;t==="top"||t==="bottom"?(a=s,h=o):(a=o,h=s);let l=ag(e,a,h),c=To(e,i,n);c.setAttribute("points",`0,${h/2} ${a},${h/2}`),l.appendChild(c);let d=To(e,i,n);d.setAttribute("points",`${a/2},0 ${a/2},${h}`),l.appendChild(d);let p=To(e,i,n,"circle");p.setAttribute("cx",a/2),p.setAttribute("cy",h/2),p.setAttribute("r",o/4),l.appendChild(p);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(Ho).forEach(g=>{let v=Ho[g];v===t?l.style[v]=`${r}px`:v!==f&&(l.style[v]="0",l.style[`margin-${v}`]="auto")}),l}function sS(e,t,i,n){let o=!1,r=!1,s=e.marks;if(s){let v=s.value;v instanceof J?v.values.forEach(w=>{w===y.crop?o=!0:w===y.cross&&(r=!0)}):v===y.crop?o=!0:v===y.cross&&(r=!0)}let a=t.bleed;if(!o&&!r)return;let h=i.container,l=h.ownerDocument,c=ut(tS,n),d=Math.max(0,t.bleedOffset-ut(iS,n)),p=t.bleedOffset-d,f=e["crop-marks-line-color"],g=f&&!Z(f.value)?f.value:y.auto;o&&Object.keys(gl).forEach(v=>{let w=gl[v],x=oS(l,w,c,g,p,a,d);h.appendChild(x)}),r&&Object.keys(Ho).forEach(v=>{let w=Ho[v],x=rS(l,w,c,g,p,d);h.appendChild(x)})}var ml=(()=>{let e=["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,"outline-offset":!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 e.forEach(i=>{t[`margin-${i}`]=!0,t[`padding-${i}`]=!0,t[`border-${i}-width`]=!0,t[`border-${i}-style`]=!0,t[`border-${i}-color`]=!0}),t})(),yh={"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"}},aS=(()=>{let e=yh;return Object.keys(e).sort((t,i)=>e[t].order-e[i].order)})(),vh="vivliostyle-page-rule-master",Wo="_marginBoxes",Ns="_footnoteArea",lg=class extends Jf{constructor(e,t,i){super(e,null,vh,[],t,null,0),u(this,"pageMarginBoxes",{});let n=Ps(i),o=new lS(this.scope,this,i,n);this.createPageMarginBoxes(i),this.applySpecified(i,n)}createPageMarginBoxes(e){let t=e[Wo];t&&aS.forEach(i=>{t[i]&&(this.pageMarginBoxes[i]=new uS(this.scope,this,i,e))})}applySpecified(e,t){this.specified.position=new W(y.relative,0),this.specified.width=new W(t.width,0),this.specified.height=new W(t.height,0);for(let i in e)!ml[i]&&i!=="background-clip"&&(this.specified[i]=e[i])}createInstance(e){return new Mn(e,this)}},lS=class extends rr{constructor(e,t,i,n){super(e,null,null,[],t),u(this,"pageSize",n);let o=new hS(this.scope,this);this.applySpecified(i)}applySpecified(e){this.specified["wrap-flow"]=new W(y.auto,0),this.specified["z-index"]=new W(new lt(0),0),this.specified.position=new W(y.absolute,0),this.specified.overflow=new W(y.visible,0);for(let t in ml)ml.hasOwnProperty(t)&&(this.specified[t]=e[t])}createInstance(e){return new dS(e,this)}},hS=class extends rr{constructor(e,t){super(e,null,null,[],t),this.specified["flow-from"]=new W(B("body"),0)}createInstance(e){return new hg(e,this)}},uS=class extends rr{constructor(e,t,i,n){super(e,null,null,[],t),u(this,"marginBoxName",i),this.applySpecified(n)}applySpecified(e){let t=e[Wo][this.marginBoxName];for(let i in e){let n=e[i],o=t[i];(Qp[i]||o&&o.value===y.inherit)&&(this.specified[i]=n)}for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];n&&n.value!==Be&&n.value!==y.inherit&&n.value!==y.unset&&n.value!==y.revert&&(this.specified[i]=n)}}createInstance(e){return new ug(e,this)}},Mn=class extends gh{constructor(e,t){super(e,t),u(this,"pageAreaDimension",null),u(this,"pageMarginBoxInstances",{})}applyCascadeAndInit(e,t){let i=this.cascaded;for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n))switch(n){case"writing-mode":case"direction":i[n]=t[n]}super.applyCascadeAndInit(e,t)}initHorizontal(){let e=this.style;e.left=Le,e["margin-left"]=Le,e["border-left-width"]=Le,e["padding-left"]=Le,e["padding-right"]=Le,e["border-right-width"]=Le,e["margin-right"]=Le,e.right=Le}initVertical(){let e=this.style;e.top=Le,e["margin-top"]=Le,e["border-top-width"]=Le,e["padding-top"]=Le,e["padding-bottom"]=Le,e["border-bottom-width"]=Le,e["margin-bottom"]=Le,e.bottom=Le}setPageAreaDimension(e){this.pageAreaDimension=e;let t=this.style;t.width=new j(e.borderBoxWidth),t.height=new j(e.borderBoxHeight),t["padding-left"]=new j(e.marginLeft),t["padding-right"]=new j(e.marginRight),t["padding-top"]=new j(e.marginTop),t["padding-bottom"]=new j(e.marginBottom)}adjustPageLayout(e,t,i){let n=t.marginBoxes,o={start:this.pageAreaDimension.marginLeft,end:this.pageAreaDimension.marginRight,extent:this.pageAreaDimension.borderBoxWidth},r={start:this.pageAreaDimension.marginTop,end:this.pageAreaDimension.marginBottom,extent:this.pageAreaDimension.borderBoxHeight};this.sizeMarginBoxesAlongVariableDimension(n.top,!0,o,e,i),this.sizeMarginBoxesAlongVariableDimension(n.bottom,!0,o,e,i),this.sizeMarginBoxesAlongVariableDimension(n.left,!1,r,e,i),this.sizeMarginBoxesAlongVariableDimension(n.right,!1,r,e,i)}sizeMarginBoxesAlongVariableDimension(e,t,i,n,o){let r="start",s="center",a="end",h=this.pageBox.scope,l={},c={},d={};for(let S in e){let b=yh[S];if(b){let C=e[S],P=this.pageMarginBoxInstances[S],L=new Yr(C,P.style,t,h,o);l[b.positionAlongVariableDimension]=C,c[b.positionAlongVariableDimension]=P,d[b.positionAlongVariableDimension]=L}}let p={start:i.start.evaluate(n),end:i.end.evaluate(n),extent:i.extent.evaluate(n)},f=this.getSizesOfMarginBoxesAlongVariableDimension(d,p.extent),g=!1,v={};Object.keys(l).forEach(S=>{let b=S,C=be(h,c[b].style[t?"max-width":"max-height"],i.extent);if(C){let P=C.evaluate(n);if(f[b]>P){let L=d[b]=new Ju(l[b],c[b].style,t,h,o,P);v[b]=L.getOuterSize(),g=!0}}}),g&&(f=this.getSizesOfMarginBoxesAlongVariableDimension(d,p.extent),g=!1,[r,s,a].forEach(S=>{var b;f[S]=(b=v[S])!=null?b:f[S]}));let w={};Object.keys(l).forEach(S=>{let b=S,C=be(h,c[b].style[t?"min-width":"min-height"],i.extent);if(C){let P=C.evaluate(n);if(f[b]<P){let L=d[b]=new Ju(l[b],c[b].style,t,h,o,P);w[b]=L.getOuterSize(),g=!0}}}),g&&(f=this.getSizesOfMarginBoxesAlongVariableDimension(d,p.extent),[r,s,a].forEach(S=>{f[S]=w[S]||f[S]}));let x=p.start+p.extent,m=p.start+(p.start+p.extent);[r,s,a].forEach(S=>{let b=f[S];if(b!=null){let C=l[S],P=0;switch(S){case r:P=t?C.left:C.top;break;case s:P=(m-b)/2;break;case a:P=x-b;break}t?C.setHorizontalPosition(P,b-C.getInsetLeft()-C.getInsetRight()):C.setVerticalPosition(P,b-C.getInsetTop()-C.getInsetBottom())}})}getSizesOfMarginBoxesAlongVariableDimension(e,t){var i;let n=e.start,o=e.center,r=e.end,s={};if(o){let a=[n,r],h=new cS(a),l=this.distributeAutoMarginBoxSizes(o,h,t);l.xSize!=null&&(s.center=l.xSize);let c=(i=l.xSize)!=null?i:o.getOuterSize(),d=Math.max((t-c)/2,0);n&&(s.start=n.hasAutoSize()?d:n.getOuterSize()),r&&(s.end=r.hasAutoSize()?d:r.getOuterSize())}else{let a=this.distributeAutoMarginBoxSizes(n,r,t);a.xSize!=null&&(s.start=a.xSize),a.ySize!=null&&(s.end=a.ySize)}return s}distributeAutoMarginBoxSizes(e,t,i){let n={xSize:null,ySize:null};if(e instanceof Yr&&e.minMaxFitContent&&(n.xSize=e.getOuterSize()),t instanceof Yr&&t.minMaxFitContent&&(n.ySize=t.getOuterSize()),e&&t)if(e.hasAutoSize()&&t.hasAutoSize()){let o=e.getOuterMaxContentSize(),r=t.getOuterMaxContentSize();if(o>0&&r>0){let s=o+r;if(s<i)n.xSize=i*o/s;else{let a=e.getOuterMinContentSize(),h=t.getOuterMinContentSize(),l=a+h;l<i?n.xSize=a+(i-l)*(o-a)/(s-l):l>0&&(n.xSize=i*a/l)}n.xSize>0&&(n.ySize=i-n.xSize)}else o>0?n.xSize=i:r>0&&(n.ySize=i)}else e.hasAutoSize()?n.xSize=Math.max(i-t.getOuterSize(),0):t.hasAutoSize()&&(n.ySize=Math.max(i-e.getOuterSize(),0));else e?e.hasAutoSize()&&(n.xSize=i):t&&t.hasAutoSize()&&(n.ySize=i);return n}prepareContainer(e,t,i,n,o){t.element.setAttribute("data-vivliostyle-page-box",!0),super.prepareContainer(e,t,i,n,o)}},Yr=class{constructor(e,t,i,n,o){u(this,"container",e),u(this,"isHorizontal",i),u(this,"clientLayout",o),u(this,"hasAutoSize_"),u(this,"size",null),u(this,"minMaxFitContent",null);let r=t[i?"width":"height"];if(this.hasAutoSize_=!r||r===y.auto||Z(r),this.minMaxFitContent=r instanceof he&&(r.name==="min-content"||r.name==="max-content"||r.name==="fit-content")?r.name:null,this.minMaxFitContent){let s=this.getSize();if(this.isHorizontal){let a=s[this.minMaxFitContent==="min-content"?"min-content width":this.minMaxFitContent==="max-content"?"max-content width":"fit-content width"];this.container.setHorizontalPosition(this.container.left,a)}else{let a=s[this.minMaxFitContent==="min-content"?"min-content height":this.minMaxFitContent==="max-content"?"max-content height":"fit-content height"];this.container.setVerticalPosition(this.container.top,a)}}}hasAutoSize(){return this.hasAutoSize_}getSize(){if(!this.size){let e=this.isHorizontal?["max-content width","min-content width","fit-content width"]:["max-content height","min-content height","fit-content height"];this.size=Vl(this.clientLayout,this.container.element,e)}return this.size}getOuterMaxContentSize(){let e=this.getSize();return this.isHorizontal?this.container.getInsetLeft()+e["max-content width"]+this.container.getInsetRight():this.container.getInsetTop()+e["max-content height"]+this.container.getInsetBottom()}getOuterMinContentSize(){let e=this.getSize();return this.isHorizontal?this.container.getInsetLeft()+e["min-content width"]+this.container.getInsetRight():this.container.getInsetTop()+e["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()}},cS=class{constructor(e){u(this,"params",e)}hasAutoSize(){return this.params.some(e=>{var t;return(t=e?.hasAutoSize())!=null?t:!1})}getOuterMaxContentSize(){let e=this.params.map(t=>{var i;return(i=t?.getOuterMaxContentSize())!=null?i:0});return Math.max.apply(null,e)*e.length}getOuterMinContentSize(){let e=this.params.map(t=>{var i;return(i=t?.getOuterMinContentSize())!=null?i:0});return Math.max.apply(null,e)*e.length}getOuterSize(){let e=this.params.map(t=>{var i;return(i=t?.getOuterSize())!=null?i:0});return Math.max.apply(null,e)*e.length}},Ju=class extends Yr{constructor(e,t,i,n,o,r){super(e,t,i,n,o),u(this,"fixedSize"),this.fixedSize=r}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()}},dS=class extends Wn{constructor(e,t){super(e,t),u(this,"borderBoxWidth",null),u(this,"borderBoxHeight",null),u(this,"contentBoxWidth",null),u(this,"contentBoxHeight",null),u(this,"marginTop",null),u(this,"marginRight",null),u(this,"marginBottom",null),u(this,"marginLeft",null)}applyCascadeAndInit(e,t){for(let i in t)i.match(/^background-/)&&(this.cascaded[i]=t[i]);super.applyCascadeAndInit(e,t),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 t=this.style,i=this.pageBox.pageSize,n=this.pageBox.scope,o=e.start,r=e.end,s=e.extent,a=i[s].toExpr(n,null),h=be(n,t[s],a),l=be(n,t[`margin-${o}`],a),c=be(n,t[`margin-${r}`],a),d=Tt(n,t[`padding-${o}`],a),p=Tt(n,t[`padding-${r}`],a),f=ri(n,t[`border-${o}-width`],t[`border-${o}-style`],a),g=ri(n,t[`border-${r}-width`],t[`border-${r}-style`],a),v=ne(n,ne(n,f,d),ne(n,g,p)),w,x,m;return h?(this.borderBoxSizing?(x=h,m=ye(n,x,v)):(m=h,x=ne(n,m,v)),w=ye(n,a,x),!l&&!c?(l=Lr(n,w,new it(n,.5)),c=l):l?c=ye(n,w,l):l=ye(n,w,c)):(l||(l=n.zero),c||(c=n.zero),w=ne(n,l,c),x=ye(n,a,w),m=ye(n,x,v),h=this.borderBoxSizing?x:m),t[o]=new j(l),t[r]=new j(c),t[`margin-${o}`]=Le,t[`margin-${r}`]=Le,t[`border-${o}-width`]=new j(f),t[`border-${r}-width`]=new j(g),t[`padding-${o}`]=new j(d),t[`padding-${r}`]=new j(p),t[s]=new j(h),t[`max-${s}`]=new j(h),{borderBoxExtent:x,contentBoxExtent:m,marginStart:l,marginEnd:c}}prepareContainer(e,t,i,n,o){t.element.setAttribute("data-vivliostyle-page-area-container",!0),super.prepareContainer(e,t,i,n,o)}},hg=class extends Wn{constructor(e,t){super(e,t)}applyCascadeAndInit(e,t){for(let i in t)i.match(/^column.*$/)&&(this.cascaded[i]=t[i]);super.applyCascadeAndInit(e,{})}initHorizontal(){let e=this.style,t=this.parentInstance.style,i=this.pageBox.scope;e.left=t["padding-left"],e.width=new j(this.parentInstance.contentBoxWidth),e["margin-left"]=new j(new Cn(i,t.left.toExpr(i,null))),e["margin-right"]=new j(new Cn(i,t.right.toExpr(i,null))),e["border-left-width"]=t.left,e["border-right-width"]=t.right,e["border-left-style"]=y.solid,e["border-right-style"]=y.solid,e["border-left-color"]=y.transparent,e["border-right-color"]=y.transparent}initVertical(){let e=this.style,t=this.parentInstance.style,i=this.pageBox.scope;e.top=t["padding-top"],e.height=new j(this.parentInstance.contentBoxHeight),e["margin-top"]=new j(new Cn(i,t.top.toExpr(i,null))),e["margin-bottom"]=new j(new Cn(i,t.bottom.toExpr(i,null))),e["border-top-width"]=t.top,e["border-bottom-width"]=t.bottom,e["border-top-style"]=y.solid,e["border-bottom-style"]=y.solid,e["border-top-color"]=y.transparent,e["border-bottom-color"]=y.transparent}prepareContainer(e,t,i,n,o){t.element.setAttribute("data-vivliostyle-page-area",!0),i.pageAreaElement=t.element,super.prepareContainer(e,t,i,n,o),e.pageAreaWidth=t.width,e.pageAreaHeight=t.height}},ug=class extends Wn{constructor(e,t){super(e,t),u(this,"boxInfo"),u(this,"suppressEmptyBoxGeneration",!0);let i=t.marginBoxName;this.boxInfo=yh[i];let n=e;n.pageMarginBoxInstances[i]=this}prepareContainer(e,t,i,n,o){t.element.setAttribute("data-vivliostyle-page-margin-box",this.pageBox.marginBoxName),this.applyVerticalAlign(e,t.element),super.prepareContainer(e,t,i,n,o)}applyVerticalAlign(e,t){I(t,"display","flex"),I(t,"flex-flow",this.vertical?this.rtl?"row-reverse":"row":"column");let i=this.getProp(e,"vertical-align"),n=null;i===B("middle")?n="center":i===B("top")?n="flex-start":i===B("bottom")&&(n="flex-end"),n&&I(t,"justify-content",n);let o=this.getProp(e,"content");if(this.vertical||o instanceof Qe||o instanceof j&&o.expr instanceof we&&o.expr.str.startsWith("running-element-")){let r="center";(this.boxInfo.isInTopRow||this.boxInfo.isInBottomRow)&&(this.boxInfo.isInLeftColumn||this.boxInfo.positionAlongVariableDimension==="end"?r=this.vertical||this.rtl?"start":"end":(this.boxInfo.isInRightColumn||this.boxInfo.positionAlongVariableDimension==="start")&&(r=this.vertical||this.rtl?"end":"start")),I(t,"align-items",r)}}positionAlongVariableDimension(e,t){let i=this.style,n=this.pageBox.scope,o=e.start,r=e.end,s=e.extent,a=o==="left",h=a?t.borderBoxWidth:t.borderBoxHeight,l=be(n,i[s],h),c=a?t.marginLeft:t.marginTop;if(this.boxInfo.positionAlongVariableDimension==="start")i[o]=new j(c);else if(l){let d=Tt(n,i[`margin-${o}`],h),p=Tt(n,i[`margin-${r}`],h),f=Tt(n,i[`padding-${o}`],h),g=Tt(n,i[`padding-${r}`],h),v=ri(n,i[`border-${o}-width`],i[`border-${o}-style`],h),w=ri(n,i[`border-${r}-width`],i[`border-${r}-style`],h),x=ne(n,l,ne(n,this.borderBoxSizing?n.zero:ne(n,ne(n,f,g),ne(n,v,w)),ne(n,d,p)));switch(this.boxInfo.positionAlongVariableDimension){case"center":i[o]=new j(ne(n,c,Pa(n,ye(n,h,x),new it(n,2))));break;case"end":i[o]=new j(ye(n,ne(n,c,h),x));break}}}positionAndSizeAlongFixedDimension(e,t){let i=this.style,n=this.pageBox.scope,o=this.borderBoxSizing,r=e.inside,s=e.outside,a=e.extent,h=t[`margin${s.charAt(0).toUpperCase()}${s.substring(1)}`],l=Gu(n,i[`margin-${r}`],h),c=Gu(n,i[`margin-${s}`],h),d=Tt(n,i[`padding-${r}`],h),p=Tt(n,i[`padding-${s}`],h),f=ri(n,i[`border-${r}-width`],i[`border-${r}-style`],h),g=ri(n,i[`border-${s}-width`],i[`border-${s}-style`],h),v=be(n,i[a],h),w=null;function x(m){if(w)return w;w={extent:v?v.evaluate(m):null,marginInside:l?l.evaluate(m):null,marginOutside:c?c.evaluate(m):null};let S=h.evaluate(m),b=0;return o||[f,d,p,g].forEach(C=>{C&&(b+=C.evaluate(m))}),(w.marginInside===null||w.marginOutside===null)&&b+w.extent+w.marginInside+w.marginOutside>S&&(w.marginInside===null&&(w.marginInside=0),w.marginOutside===null&&(w.marginOutside=0)),w.extent!==null&&w.marginInside!==null&&w.marginOutside!==null&&(w.marginOutside=null),w.extent===null?(w.extent=S-b-w.marginInside-w.marginOutside,w.marginInside===null&&(w.marginInside=0),w.marginOutside===null&&(w.marginOutside=0)):typeof w.extent=="number"&&(w.marginInside===null&&typeof w.marginOutside=="number"?w.marginInside=S-b-w.extent-w.marginOutside:typeof w.marginInside=="number"&&w.marginOutside===null?w.marginOutside=S-b-w.extent-w.marginInside:w.marginInside=w.marginOutside=(S-b-w.extent)/2),w}i[a]=new j(new we(n,function(){let m=x(this).extent;return m===null?"auto":m},a)),i[`margin-${r}`]=new j(new we(n,function(){let m=x(this).marginInside;return m===null?"auto":m},`margin-${r}`)),i[`margin-${s}`]=new j(new we(n,function(){let m=x(this).marginOutside;return m===null?"auto":m},`margin-${s}`)),r==="left"?i.left=new j(ne(n,t.marginLeft,t.borderBoxWidth)):r==="top"&&(i.top=new j(ne(n,t.marginTop,t.borderBoxHeight)))}initHorizontal(){let e=this.parentInstance.pageAreaDimension;this.boxInfo.isInLeftColumn?this.positionAndSizeAlongFixedDimension({inside:"right",outside:"left",extent:"width"},e):this.boxInfo.isInRightColumn?this.positionAndSizeAlongFixedDimension({inside:"left",outside:"right",extent:"width"},e):this.positionAlongVariableDimension({start:"left",end:"right",extent:"width"},e)}initVertical(){let e=this.parentInstance.pageAreaDimension;this.boxInfo.isInTopRow?this.positionAndSizeAlongFixedDimension({inside:"bottom",outside:"top",extent:"height"},e):this.boxInfo.isInBottomRow?this.positionAndSizeAlongFixedDimension({inside:"top",outside:"bottom",extent:"height"},e):this.positionAlongVariableDimension({start:"top",end:"bottom",extent:"height"},e)}finishContainer(e,t,i,n,o,r,s){super.finishContainer(e,t,i,n,o,r,s);let a=i.marginBoxes,h=this.pageBox.marginBoxName,l=this.boxInfo;!l.isInLeftColumn&&!l.isInRightColumn?l.isInTopRow?a.top[h]=t:l.isInBottomRow&&(a.bottom[h]=t):!l.isInTopRow&&!l.isInBottomRow&&(l.isInLeftColumn?a.left[h]=t:l.isInRightColumn&&(a.right[h]=t));let c=this.parentInstance.pageAreaDimension,d=this.getProp(e,"width"),p=d instanceof he&&(d.name==="min-content"||d.name==="max-content"||d.name==="fit-content")?d.name:null,f=this.getPropAsNumber(e,"min-width"),g=this.getPropAsNumber(e,"max-width");if(p||f||g){p&&I(t.element,"width",p),f&&I(t.element,"min-width",`${f}px`),g&&I(t.element,"max-width",`${g}px`);let S=this.getProp(e,"margin-left"),b=this.getProp(e,"margin-right");if(l.isInLeftColumn){let C=c.borderBoxWidth.evaluate(e)+c.marginRight.evaluate(e);I(t.element,"right",`${C}px`),(S===y.auto||b!==y.auto)&&I(t.element,"margin-left","auto"),b===y.auto&&I(t.element,"margin-right","auto")}else l.isInRightColumn&&(I(t.element,"right","0"),(b===y.auto||S!==y.auto)&&I(t.element,"margin-right","auto"),S===y.auto&&I(t.element,"margin-left","auto"))}let v=this.getProp(e,"height"),w=v instanceof he&&(v.name==="min-content"||v.name==="max-content"||v.name==="fit-content")?v.name:null,x=this.getPropAsNumber(e,"min-height"),m=this.getPropAsNumber(e,"max-height");if(w||x||m){w&&I(t.element,"height",w),x&&I(t.element,"min-height",`${x}px`),m&&I(t.element,"max-height",`${m}px`);let S=this.getProp(e,"margin-top"),b=this.getProp(e,"margin-bottom");if(l.isInTopRow){let C=c.borderBoxHeight.evaluate(e)+c.marginBottom.evaluate(e);I(t.element,"bottom",`${C}px`),(S===y.auto||b!==y.auto)&&I(t.element,"margin-top","auto"),b===y.auto&&I(t.element,"margin-bottom","auto")}else l.isInBottomRow&&(I(t.element,"bottom","0"),(b===y.auto||S!==y.auto)&&I(t.element,"margin-bottom","auto"),S===y.auto&&I(t.element,"margin-top","auto"))}}},pS=class{constructor(e,t,i,n,o){u(this,"pageScope",t),u(this,"rootPageBoxInstance",i),u(this,"context",n),u(this,"docElementStyle",o),u(this,"pageMasterCache",{}),u(this,"pageCascadeInstance"),this.pageCascadeInstance=e,this.definePageProgression()}definePageProgression(){let e=this.pageScope,t=this.context,i=t.isVersoFirstPage,n=new Je(e,"page-number"),o=new Fl(e,new _c(e,n,new it(e,2)),i?e.one:e.zero);e.defineName("recto-page",new Ai(e,o)),e.defineName("verso-page",o),(t.pageProgression||sg(this.docElementStyle))==="ltr"?(e.defineName("left-page",o),e.defineName("right-page",new Ai(e,o))):(e.defineName("left-page",new Ai(e,o)),e.defineName("right-page",o))}getCascadedPageStyle(e){let t={};return this.pageCascadeInstance.pushRule([],e,t),this.pageCascadeInstance.popRule(),t}getPageRulePageMaster(e,t){let i=e.pageBox;if(Object.keys(t).length===0)return i.resetScope(),e;let n=this.makeCacheKey(t,i),o=this.pageMasterCache[n];return o||(i.pseudoName===fh?o=this.generatePageRuleMaster(t):o=this.generateCascadedPageMaster(t,i),this.pageMasterCache[n]=o),o.pageBox.resetScope(),o}makeCacheKey(e,t){var i;let n=this.makeCascadeValueObjectKey(e),o=((i=this.context.currentLayoutPosition)==null?void 0:i.page)%2;return`${t.key}^${n}^${o}`}makeCascadeValueObjectKey(e){let t=[];for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)){let n=e[i],o;n instanceof W?o=`${n.value}`:o=this.makeCascadeValueObjectKey(n),t.push(i+o+(n.priority||""))}return t.sort().join("^")}generatePageRuleMaster(e){let t=new lg(this.pageScope,this.rootPageBoxInstance.pageBox,e).createInstance(this.rootPageBoxInstance);return t.applyCascadeAndInit(this.pageCascadeInstance,this.docElementStyle),t.resolveAutoSizing(this.context),t}generateCascadedPageMaster(e,t){let i=t.clone({pseudoName:vh}),n=i.specified,o=e.size;if(o&&!Z(o.value)){let s=Ps(e),a=o.priority;Jt(n,"width",new W(s.width,a),this.context),Jt(n,"height",new W(s.height,a),this.context)}["counter-reset","counter-increment"].forEach(s=>{n[s]&&(e[s]=n[s])});let r=i.createInstance(this.rootPageBoxInstance);return r.applyCascadeAndInit(this.pageCascadeInstance,this.docElementStyle),r.resolveAutoSizing(this.context),r}},fS=class extends Ne{constructor(e){super(),u(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}},gS=class extends Ne{constructor(e){super(),u(this,"scope",e)}apply(e){new Je(this.scope,"page-number").evaluate(e.context)===1&&this.chained.apply(e)}getPriority(){return 2}},mS=class extends Ne{constructor(e){super(),u(this,"scope",e)}apply(e){new Je(this.scope,"blank-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 2}},yS=class extends Ne{constructor(e){super(),u(this,"scope",e)}apply(e){new Je(this.scope,"left-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},vS=class extends Ne{constructor(e){super(),u(this,"scope",e)}apply(e){new Je(this.scope,"right-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},wS=class extends Ne{constructor(e){super(),u(this,"scope",e)}apply(e){new Je(this.scope,"recto-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},bS=class extends Ne{constructor(e){super(),u(this,"scope",e)}apply(e){new Je(this.scope,"verso-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},xS=class extends sn{constructor(e,t,i){super(t,i),u(this,"scope",e),u(this,"a",t),u(this,"b",i)}apply(e){let t=e.context,i=t.layoutPositionAtPageStart.page;t.blankPageAtStart&&i--,i&&this.matchANPlusB(i)&&this.chained.apply(e)}getPriority(){return 2}},SS=class extends sn{constructor(e,t,i,n){super(t,i),u(this,"scope",e),u(this,"a",t),u(this,"b",i),u(this,"pageType",n)}apply(e){let t=e.pageTypePageIndices[this.pageType];if(t){for(let i of t)if(this.matchANPlusB(i)){this.chained.apply(e);return}}}getPriority(){return 3}},CS=class extends oh{constructor(e,t){super(e,t,null,null,null)}apply(e){kS(e.context,e.currentStyle,this.style,this.specificity,e)}};function kS(e,t,i,n,o){xs(e,t,i,n,null,null,null);let r=i[Wo];if(r){let a=si(t,Wo);for(let h in r)if(r.hasOwnProperty(h)){let l=a[h];l||(l={},a[h]=l),xs(e,l,r[h],n,null,null,null)}}let s=i[Ns];if(s){let a=si(t,Ns);for(let h in s)if(s.hasOwnProperty(h)){let l=a[h];l||(l={},a[h]=l);let c=s[h];for(let p in c)if(c.hasOwnProperty(p)&&p!=="_pseudos"){let f=c[p];f instanceof W&&Jt(l,p,f)}let d=ft(c,"_pseudos");if(d){let p=si(l,"_pseudos");for(let f in d)if(d.hasOwnProperty(f)){let g=p[f];g||(g={},p[f]=g);let v=d[f];for(let w in v)if(v.hasOwnProperty(w)){let x=v[w];x instanceof W&&Jt(g,w,x)}}}}}}var ES=class extends zo{constructor(e,t,i,n,o){super(e,t,i?.condition,i,null,n,!1),u(this,"pageProps",o),u(this,"currentPageSelectors",[]),u(this,"currentNamedPageSelector",""),u(this,"currentPseudoPageClassSelectors",[])}startPageRule(){this.startSelectorRule()}tagSelector(e,t){this.currentNamedPageSelector=t,t&&(this.chain.push(new fS(t)),this.specificity+=65536)}pseudoclassSelector(e,t){if(e=e.toLowerCase(),t)switch(e){case"nth":{let i=t[0],n=t[1];if(t.length===3&&typeof t[2]=="string"){let o=t[2];this.currentPseudoPageClassSelectors.push(`:${e}(${i}n${n<0?n:"+"+n} of ${o})`),this.chain.push(new SS(this.scope,i,n,o)),this.specificity+=65792}else this.currentPseudoPageClassSelectors.push(`:${e}(${i}n${n<0?n:"+"+n})`),this.chain.push(new xS(this.scope,i,n)),this.specificity+=256}break;default:this.reportAndSkip(`E_INVALID_PAGE_SELECTOR :${e}(${t.join("")})`);break}else switch(this.currentPseudoPageClassSelectors.push(`:${e}`),e){case"first":this.chain.push(new gS(this.scope)),this.specificity+=256;break;case"blank":this.chain.push(new mS(this.scope)),this.specificity+=256;break;case"left":this.chain.push(new yS(this.scope)),this.specificity+=1;break;case"right":this.chain.push(new vS(this.scope)),this.specificity+=1;break;case"recto":this.chain.push(new wS(this.scope)),this.specificity+=1;break;case"verso":this.chain.push(new bS(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,t,i){if((e==="bleed"||e==="marks")&&!this.currentPageSelectors.some(r=>r.selectors===null))return;super.simpleProperty(e,t,i);let n=ve(this.elementStyle,e),o=this.pageProps;if(e==="bleed"||e==="marks")o[""]||(o[""]={}),Object.keys(o).forEach(r=>{Fi(o[r],e,n)});else if(e==="size"){let r=o[""];this.currentPageSelectors.forEach(s=>{let a=new W(n.value,n.priority+s.specificity),h=s.selectors?s.selectors.join(""):"",l=o[h];l?Jt(l,e,a):(l=o[h]={},Fi(l,e,a),r&&["bleed","marks"].forEach(c=>{r[c]&&Fi(l,c,r[c])}))})}}insertNonPrimary(e){this.cascade.insertInTable(this.cascade.pagetypes,"*",e)}makeApplyRuleAction(e){return new CS(this.elementStyle,e)}startFootnoteRule(e){let t=si(this.elementStyle,Ns),i=t.area;if(i||(i={},t.area=i),e){let o=si(i,"_pseudos"),r=o[e];r||(r={},o[e]=r),i=r}let n=new cg(this.scope,this.owner,this.validatorSet,i);this.owner.pushHandler(n)}startPageMarginBoxRule(e){let t=si(this.elementStyle,Wo),i=t[e];i||(i={},t[e]=i);let n=new PS(this.scope,this.owner,this.validatorSet,i);this.owner.pushHandler(n)}},PS=class extends rn{constructor(e,t,i,n){super(e,t,!1),u(this,"validatorSet",i),u(this,"boxStyle",n)}property(e,t,i){this.validatorSet.validatePropertyAndHandleShorthand(e,t,i,this)}invalidPropertyValue(e,t){this.report(`E_INVALID_PROPERTY_VALUE ${e}: ${t.toString()}`)}unknownProperty(e,t){this.report(`E_INVALID_PROPERTY ${e}: ${t.toString()}`)}simpleProperty(e,t,i){let n=i?this.getImportantSpecificity():this.getBaseSpecificity(),o=new W(t,n);Fi(this.boxStyle,e,o)}},cg=class extends rn{constructor(e,t,i,n){super(e,t,!1),u(this,"validatorSet",i),u(this,"areaStyle",n)}property(e,t,i){this.validatorSet.validatePropertyAndHandleShorthand(e,t,i,this)}invalidPropertyValue(e,t){this.report(`E_INVALID_PROPERTY_VALUE ${e}: ${t.toString()}`)}unknownProperty(e,t){this.report(`E_INVALID_PROPERTY ${e}: ${t.toString()}`)}simpleProperty(e,t,i){let n=i?this.getImportantSpecificity():this.getBaseSpecificity(),o=new W(t,n);Fi(this.areaStyle,e,o)}},dg=class{constructor(e,t,i){u(this,"store",e),u(this,"url",t),u(this,"document",i),u(this,"lang",null),u(this,"totalOffset",-1),u(this,"root"),u(this,"body"),u(this,"head"),u(this,"last"),u(this,"lastOffset",1),u(this,"idMap"),this.root=i.documentElement;let n=null,o=null;if(this.root.namespaceURI=="http://www.w3.org/1999/xhtml"){for(let r=this.root.firstChild;r;r=r.nextSibling){if(r.nodeType!=1)continue;let s=r;if(s.namespaceURI=="http://www.w3.org/1999/xhtml")switch(s.localName){case"head":o=s;break;case"body":n=s;break}}this.lang=this.root.getAttribute("lang")}this.body=n,this.head=o,this.last=this.root,this.last.setAttribute(Ht,"0")}doc(){return new fg([this.document])}getElementOffset(e){let t=e.getAttribute(Ht);if(t)return parseInt(t,10);let i=this.lastOffset,n=this.last;for(;n!=e;){let o=n.firstChild;if(!o){for(;o=n.nextSibling,!o;)if(n=n.parentNode,n==null)throw new Error("Internal error")}n=o,o.nodeType==1?(o.setAttribute(Ht,i.toString()),++i):i+=o.textContent.length}return this.lastOffset=i,this.last=e,i-1}getNodeOffset(e,t,i){let n=0,o=e,r=null;if(o.nodeType==1){if(!i)return this.getElementOffset(o)}else{if(n=t,r=o.previousSibling,!r)return o=o.parentNode,n+=1,this.getElementOffset(o)+n;o=r}for(;;){for(;o.lastChild;)o=o.lastChild;if(o.nodeType==1)break;if(n+=o.textContent.length,r=o.previousSibling,!r){o=o.parentNode;break}o=r}return n+=1,this.getElementOffset(o)+n}getTotalOffset(){return this.totalOffset<0&&(this.totalOffset=this.getNodeOffset(this.root,0,!0)),this.totalOffset}getNodeByOffset(e){let t,i=this.root;for(;;){if(t=this.getElementOffset(i),t>=e)return i;let a=i.children;if(!a)break;let h=mi(a.length,l=>{let c=a[l];return this.getElementOffset(c)>e});if(h==0)break;i=a[h-1]}let n=t+1,o=i,r=o.firstChild||o.nextSibling,s=null;for(;;){if(r){if(r.nodeType==1||(o=r,s=o,n+=r.textContent.length,n>e&&!/^\s*$/.test(r.textContent)))break}else if(o=o.parentNode,!o)break;r=o.nextSibling}return r&&s&&/^\s*$/.test(s.textContent)&&(s=r),s||i}buildIdMap(e){let t=e.getAttribute("id");t&&!this.idMap[t]&&(this.idMap[t]=e);let i=e.getAttributeNS("http://www.w3.org/XML/1998/namespace","id");i&&!this.idMap[i]&&(this.idMap[i]=e);for(let n=e.firstElementChild;n;n=n.nextElementSibling)this.buildIdMap(n)}getElement(e){var t;let i=e.match(/([^#]*)#(.+)$/);if(!i||i[1]&&i[1]!=this.url&&((t=this.store)==null?void 0:t.get(i[1]))!==this)return null;let n=i[2],o=this.document.getElementById(n);return!o&&this.document.getElementsByName&&(o=this.document.getElementsByName(n)[0]),o||(this.idMap||(this.idMap={},this.buildIdMap(this.document.documentElement)),o=this.idMap[n]),o}},yl=(e=>(e.TEXT_HTML="text/html",e.TEXT_XML="text/xml",e.APPLICATION_XML="application/xml",e.APPLICATION_XHTML_XML="application/xhtml+xml",e.IMAGE_SVG_XML="image/svg+xml",e))(yl||{});function Ar(e,t,i){let n=i||new DOMParser,o;try{o=n.parseFromString(e,t)}catch{}if(o){let r=o.documentElement,s="parsererror";if(r.localName===s)return null;for(let a=r.firstElementChild;a;a=a.nextElementSibling)if(a.localName===s)return null}else return null;return o}function NS(e){let t=e.contentType;if(t){let n=Object.keys(yl);for(let o=0;o<n.length;o++)if(yl[n[o]]===t)return t;if(t.match(/\+xml$/))return"application/xml"}let i=e.url.match(/\.([^./#?]+)([#?]|$)/);if(i)switch(i[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 pg(e,t){let i=e.responseXML;if(!i){let o=new DOMParser,r=e.responseText;if(r!=null){let s=NS(e);if(i=Ar(r,s||"application/xml",o),i&&!s){let a=i.documentElement;a.localName.toLowerCase()==="html"&&!a.namespaceURI?i=Ar(r,"text/html",o):a.localName.toLowerCase()==="svg"&&i.contentType!=="image/svg+xml"&&(i=Ar(r,"image/svg+xml",o))}i||(i=Ar(r,"text/html",o))}}let n=i?new dg(t,e.url,i):null;return T(n)}function TS(){return new Bl(pg,"document")}var AS=class vl{constructor(t){u(this,"fn",t)}check(t){return this.fn(t)}withAttribute(t,i){return new vl(n=>this.check(n)&&n.nodeType==1&&n.getAttribute(t)==i)}withChild(t,i){return new vl(n=>{if(!this.check(n))return!1;let o=new fg([n]);return o=o.child(t),i&&(o=o.predicate(i)),o.size()>0})}},Qu=new AS(e=>!0),fg=class wl{constructor(t){u(this,"nodes",t)}asArray(){return this.nodes}size(){return this.nodes.length}predicate(t){let i=[];for(let n of this.nodes)t.check(n)&&i.push(n);return new wl(i)}forEachNode(t){let i=[],n=o=>{i.push(o)};for(let o=0;o<this.nodes.length;o++)t(this.nodes[o],n);return new wl(i)}forEach(t){let i=[];for(let n=0;n<this.nodes.length;n++)i.push(t(this.nodes[n]));return i}forEachNonNull(t){let i=[];for(let n=0;n<this.nodes.length;n++){let o=t(this.nodes[n]);o!=null&&i.push(o)}return i}child(t){return this.forEachNode((i,n)=>{for(let o=i.firstChild;o;o=o.nextSibling)o.nodeType==1&&o.localName==t&&n(o)})}childElements(){return this.forEachNode((t,i)=>{for(let n=t.firstChild;n;n=n.nextSibling)n.nodeType==1&&i(n)})}attribute(t){return this.forEachNonNull(i=>i.nodeType==1?i.getAttribute(t):null)}textContent(){return this.forEach(t=>t.textContent)}},IS=new Qo(()=>{let e=M("uaStylesheetBase"),t=Zp(),i=Ae("user-agent-base.css",Ni),n=new zo(null,null,null,null,null,t,!0);return n.startStylesheet("UA"),r0(n.cascade),Ml(Nd,n,i,null,null).thenFinish(e),e.result()},"uaStylesheetBaseFetcher");function FS(){return IS.get()}var RS=class extends qr{constructor(e,t,i,n,o,r){super(e,t,null,i,n,"counter-style"),u(this,"counterStyleName",o),u(this,"counterStyles",r)}endRule(){super.endRule(),this.counterStyles.define(this.counterStyleName,this.elementStyle)||Y.warn(`E_CSS_COUNTER_STYLE_INVALID: @counter-style ${this.counterStyleName}`)}},LS=class{constructor(e,t,i,n,o,r,s,a,h,l,c){u(this,"store",e),u(this,"rootScope",t),u(this,"pageScope",i),u(this,"cascade",n),u(this,"rootBox",o),u(this,"fontFaces",r),u(this,"footnoteProps",s),u(this,"flowProps",a),u(this,"viewportProps",h),u(this,"pageProps",l),u(this,"counterStyleStore",c),u(this,"fontDeobfuscator"),u(this,"validatorSet"),this.fontDeobfuscator=e.fontDeobfuscator,this.validatorSet=e.validatorSet,this.pageScope.defineBuiltIn("has-content",function(d){d=d;let p=this,f=p.currentLayoutPosition,g=f.firstFlowChunkOfFlow(d);return p.matchPageSide(f.startSideOfFlow(d))&&f.hasContent(d,p.lookupOffset)&&!!g&&!p.flowChunkIsAfterParentFlowForcedBreak(g)}),this.pageScope.defineName("page-number",new we(this.pageScope,function(){let d=this;return d.pageNumberOffset+d.getCurrentPageNumberForPageScope()},"page-number")),this.pageScope.defineName("blank-page",new we(this.pageScope,function(){let d=this.currentLayoutPosition;return d?.isBlankPage},"blank-page"))}sizeViewport(e,t,i,n){if(this.viewportProps.length){let o=new ka(this.rootScope,e,t,i),r=Pb(o,this.viewportProps),s=r.width,a=r.height,h=r["text-zoom"],l=1;if(s&&a||h){let c=Zt.em;if((h?h.evaluate(o,"text-zoom"):null)===y.scale&&(l=c/i,i=c,e*=l,t*=l),s&&a){let d=ut(s.evaluate(o,"width"),o),p=ut(a.evaluate(o,"height"),o);if(d>0&&p>0)return{width:n&&n.spreadView?(d+n.pageBorder)*2:d,height:p,fontSize:i}}}}return{width:e,height:t,fontSize:i}}};function ec(e){let t=new Map,i=n=>{n.formattingContext&&!t.has(n.formattingContext)&&t.set(n.formattingContext,n.formattingContext.saveState()),n.shadowSibling&&i(n.shadowSibling)};for(let n in e.flowPositions){let o=e.flowPositions[n];for(let r of o.positions){let s=r.chunkPosition.primary;for(let a of s.steps)i(a);if(r.chunkPosition.floats)for(let a of r.chunkPosition.floats)for(let h of a.steps)i(h)}}return t}function tc(e){for(let[t,i]of e)i!==void 0&&t.restoreState(i)}var wh=class extends ka{constructor(e,t,i,n,o,r,s,a,h,l,c,d,p,f){super(e.rootScope,n.width,n.height,n.fontSize),u(this,"style",e),u(this,"xmldoc",t),u(this,"viewport",n),u(this,"clientLayout",o),u(this,"fontMapper",r),u(this,"customRenderer",s),u(this,"fallbackMap",a),u(this,"pageNumberOffset",h),u(this,"documentURLTransformer",l),u(this,"counterStore",c),u(this,"cmykStore",d),u(this,"lang"),u(this,"primaryFlows",{body:!0}),u(this,"rootPageBoxInstance",null),u(this,"styler",null),u(this,"stylerMap",null),u(this,"currentLayoutPosition",null),u(this,"layoutPositionAtPageStart",null),u(this,"currentCascadedPageStyle",null),u(this,"lookupOffset",0),u(this,"faces"),u(this,"pageBoxInstances",{}),u(this,"pageManager",null),u(this,"pageNumberContextStack",[]),u(this,"rootPageFloatLayoutContext"),u(this,"pageBreaks",{}),u(this,"pageProgression",null),u(this,"isVersoFirstPage",!1),u(this,"blankPageAtStart",!1),u(this,"pageSheetSize",{}),u(this,"pageSheetHeight",0),u(this,"pageSheetWidth",0),u(this,"invalidPageAreaOnCurrentPage",!1),u(this,"repeatedInvalidPageAreaLayoutPosition",null),u(this,"semanticFootnoteFirstRefOffsets",new Map),u(this,"semanticFootnoteFirstRefOffsetsInitialized",{value:!1}),u(this,"pageGroupPageCounts",Object.create(null)),u(this,"currentPageGroupDocument",null),this.lang=t.lang||i,this.faces=new Px(this.style.fontDeobfuscator),this.rootPageFloatLayoutContext=new Sn(null,null,null,null,null,null,null),this.pageProgression=p||null,this.isVersoFirstPage=!!f;for(let g in e.flowProps){let v=e.flowProps[g],w=ve(v,"flow-consume");w&&(w.evaluate(this,"flow-consume")==y.all?this.primaryFlows[g]=!0:delete this.primaryFlows[g])}}init(){let e=M("StyleInstance.init"),t=this.counterStore.createCounterListener(this.xmldoc.url),i=this.counterStore.createCounterResolver(this.xmldoc.url,this.style.rootScope,this.style.pageScope);this.styler=new Uu(this.xmldoc,this.style.cascade,this.style.rootScope,this,this.primaryFlows,this.style.validatorSet,t,i,this.style.counterStyleStore,this.cmykStore),i.setStyler(this.styler),this.styler.resetFlowChunkStream(this),this.stylerMap={},this.stylerMap[this.xmldoc.url]=this.styler;let n=this.styler.getTopContainerStyle();this.pageProgression||(this.pageProgression=sg(n)),this.matchStartPageSide(this.styler.breakBeforeValues[0])||(this.pageNumberOffset===0?this.isVersoFirstPage=!0:this.blankPageAtStart=!0);let o=this.style.rootBox;this.rootPageBoxInstance=new Zx(o);let r=this.style.cascade.createInstance(this,t,i,this.lang,this.style.counterStyleStore,this.cmykStore);this.styler.cascade.currentPageType=this.styler.cascade.firstPageType,this.rootPageBoxInstance.applyCascadeAndInit(r,n),this.rootPageBoxInstance.resolveAutoSizing(this),this.pageManager=new pS(r,this.style.pageScope,this.rootPageBoxInstance,this,n);let s=[];for(let h of this.style.fontFaces){if(h.condition&&!h.condition.evaluate(this))continue;let l=Ex(h.properties,this),c=new Yf(l);s.push(c)}this.fontMapper.findOrLoadFonts(s,this.faces).then(()=>{Fx(this.xmldoc.document,this.viewport.window,this.styler).thenFinish(e)});let a=this.style.pageProps;return a[""]||(a[""]={}),Object.keys(a).forEach(h=>{let l=a[h];this.styler.cascade.applyVarFilter([l],this.styler,null),this.styler.cascade.applyCalcFilter(l,this.styler.context),this.styler.cascade.applyCmykFilter(l);let c=Ku(Ps(l),this);this.pageSheetSize[h]={width:c.pageWidth+c.cropOffset*2,height:c.pageHeight+c.cropOffset*2}}),e.result()}matchStartPageSide(e){let t=this.pageNumberOffset%2==(this.isVersoFirstPage?1:0),i=this.pageProgression=="ltr";switch(e){case"left":return t!==i;case"right":return t===i;case"recto":return t;case"verso":return!t;default:return!0}}getStylerForDoc(e){let t=this.stylerMap[e.url];if(!t){let i=this.style.store.getStyleForDoc(e),n=new ka(i.rootScope,this.pageWidth(),this.pageHeight(),this.initialFontSize),o=this.counterStore.createCounterListener(e.url),r=this.counterStore.createCounterResolver(e.url,i.rootScope,i.pageScope);t=new Uu(e,i.cascade,i.rootScope,n,this.primaryFlows,i.validatorSet,o,r,i.counterStyleStore,this.cmykStore),this.stylerMap[e.url]=t}return t}registerInstance(e,t){this.pageBoxInstances[e]=t}lookupInstance(e){return this.pageBoxInstances[e]}encounteredFlowChunk(e,t){let i=this.currentLayoutPosition;if(i){i.flows[e.flowName]?t=i.flows[e.flowName]:i.flows[e.flowName]=t;let n=i.flowPositions[e.flowName];n||(n=new Hv,i.flowPositions[e.flowName]=n);let o=Vv(e.element),r=new Bi(o),s=new $v(r,e);n.positions.push(s)}}evalSupportsTest(e,t,i){if(i)return e==="selector"?this.evalSupportsSelector(t):!1;if(!e)return!1;if(Xe(e))return typeof CSS<"u"&&CSS.supports(`(${e}:${t})`);let n=!0;class o{unknownProperty(h,l){n=!1}invalidPropertyValue(h,l){n=!1}simpleProperty(h,l,c){}}let r=new o,s=Ri(this.style.rootScope,new xt(t,null),"");return s?(this.xmldoc.store.validatorSet.validatePropertyAndHandleShorthand(e,s,!1,r),n):!1}getCurrentPageNumberForPageScope(){var e;return this.currentLayoutPosition?this.currentLayoutPosition.page:(e=this.pageNumberContextStack[this.pageNumberContextStack.length-1])!=null?e:0}getPageNumberContextDepth(){return this.pageNumberContextStack.length}pushPageNumberContext(e){this.pageNumberContextStack.push(e)}restorePageNumberContextDepth(e){this.pageNumberContextStack.length=e}evalSupportsSelector(e){class t extends gg{errorMsg(...s){}}let i=new t(null),n=dd(e),o=new xt(n+"{}",i);return new er($e,o,i,"").runParser(Number.POSITIVE_INFINITY,!1,!1,!1,!1)?!i.cascadeParserHandler.invalid:!1}getConsumedOffset(e){let t=Number.POSITIVE_INFINITY;for(let i=0;i<e.positions.length;i++){let n=e.positions[i].chunkPosition.primary,o=n.steps[0].node,r=n.offsetInNode,s=n.after,a=0;for(;o.ownerDocument!=this.xmldoc.document;)a++,o=n.steps[a].node,s=!1,r=0;let h=this.xmldoc.getNodeOffset(o,r,s);h<t&&(t=h)}return t}getNodePositionOffset(e){let t=e.steps[0].node,i=e.offsetInNode,n=e.after,o=0;for(;t.ownerDocument!=this.xmldoc.document;)o++,t=e.steps[o].node,n=!1,i=0;return this.xmldoc.getNodeOffset(t,i,n)}getPageStartOffset(e,t){if(!e)return 0;let i=Number.POSITIVE_INFINITY;for(let n in this.primaryFlows){let o=e.flowPositions[n];if(!t&&(!o||o.positions.length==0)&&this.currentLayoutPosition&&(this.styler.styleUntilFlowIsReached(n),o=this.currentLayoutPosition.flowPositions[n],e!=this.currentLayoutPosition&&o&&(o=o.clone(),e.flowPositions[n]=o)),o)for(let r=0;r<o.positions.length;r++){let s=o.positions[r].chunkPosition.primary,a=this.getNodePositionOffset(s);a<i&&(i=a)}}return i}getPageStartCounterOffsets(e){var t;let i=this.getPageStartOffset(e);if(!isFinite(i))return{counterOffset:i,changeOffset:i};let n=this.xmldoc.body||this.xmldoc.root,o=n?this.getFirstInFlowElementAtOrAfter(n,i):null,r=n?this.xmldoc.getElementOffset(n):i,s=i<=r,a=o===n&&s&&(t=this.getFirstInFlowChildElement(n))!=null?t:o;if(!a)return s?{counterOffset:r,changeOffset:r}:{counterOffset:i,changeOffset:i};let h=this.xmldoc.getElementOffset(a),l=i;return s&&h!==i&&(l=h),h===i&&(this.isInlineLevelElement(a)?l=Math.max(0,i-1):l=this.getDeepestFirstInFlowChildOffset(a)),{counterOffset:l,changeOffset:h}}getPageStartElement(e,t=this.getPageStartOffset(e)){var i;if(!isFinite(t))return null;let n=this.xmldoc.body||this.xmldoc.root;if(!n)return null;let o=this.getFirstInFlowElementAtOrAfter(n,t),r=this.xmldoc.getElementOffset(n),s=t<=r;if(o===n&&s)return(i=this.getFirstInFlowChildElement(n))!=null?i:o;if((o?this.xmldoc.getElementOffset(o):Number.POSITIVE_INFINITY)>t){let a=this.xmldoc.getNodeByOffset(t);if(!Ee(a)){let h=a.nodeType===Node.ELEMENT_NODE?a:a.parentElement;for(;h;){if(this.xmldoc.getElementOffset(h)<=t&&this.isPageBoundaryCandidateElement(h))return h;h=h.parentElement}}}return o}isForcedPageBreakValue(e){return Ze(e)&&e!=="column"&&e!=="region"}hasForcedPageBreakBefore(e){let t=ve(e,"break-before");if(!t)return!1;let i=t.evaluate(this,"break-before").toString();return this.isForcedPageBreakValue(i)}getExplicitPageType(e){let t=ve(e,"page");if(!t||Z(t.value))return null;let i=t.evaluate(this,"page").toString();return!i||i.toLowerCase()==="auto"?null:i}getPageGroupPageType(e){if(this.isInlineLevelElement(e))return null;let t=this.styler.getStyle(e,!1);return t?this.getExplicitPageType(t):null}getPageStartPageType(e){let t=this.getPageStartOffset(e,!0),i=this.getPageStartElement(e,t);for(;i;){let n=this.getPageGroupPageType(i);if(n)return n;if(i===this.xmldoc.root)break;i=i.parentElement}return""}getPageStartPageTypeOverride(e){if(this.getPageStartPageType(e)!=="")return;let t=this.getPageStartOffset(e,!0),i=this.getPageStartElement(e,t);if(i&&this.xmldoc.getElementOffset(i)<t)return"";for(;i&&(i=this.getFirstInFlowChildElement(i),!!i);){let n=this.getPageGroupPageType(i);if(n)return n}return""}getPreviousInFlowSibling(e){let t=e.previousElementSibling;for(;t;){if(this.isPageBoundaryCandidateElement(t))return t;t=t.previousElementSibling}return null}getFirstDocumentFlowElement(){var e;let t=this.xmldoc.body||this.xmldoc.root;if(!t)return null;let i=this.xmldoc.getElementOffset(t),n=this.getFirstInFlowElementAtOrAfter(t,i);return n===t&&(e=this.getFirstInFlowChildElement(t))!=null?e:n}getEffectiveFirstPageType(e){let t=e,i=t?this.getPageGroupPageType(t):null;for(;t;){let n=this.getFirstInFlowChildElement(t);if(!n)return i;let o=this.getPageGroupPageType(n);o&&(i=o),t=n}return i}getEffectivePageGroupStartElement(e){let t=e,i=e;for(;i;){let n=this.getFirstInFlowChildElement(i);if(!n)return t;this.getPageGroupPageType(n)&&(t=n),i=n}return t}resolveFirstPageType(){let e=this.getFirstDocumentFlowElement();return this.getEffectiveFirstPageType(e)}shouldStartPageGroup(e,t,i){let n=this.styler.getStyle(e,!1);if(!n)return!1;if(this.getFirstDocumentFlowElement()===e)return!0;let o=this.xmldoc.getElementOffset(e),r=this.xmldoc.body||this.xmldoc.root,s=this.xmldoc.getElementOffset(r);if(i<=s&&e===r||!this.getPreviousInFlowSibling(e)&&i===o)return!0;if(o!==i)return!1;if(this.hasForcedPageBreakBefore(n))return!0;let a=this.getPreviousInFlowSibling(e);if(!a)return!1;let h=this.styler.getStyle(a,!1);return h?this.getExplicitPageType(h)!==t:!1}updatePageGroupPageIndices(e){let t=this.pageManager.pageCascadeInstance;t.pageTypePageIndices=Object.create(null);let i=e?.startSideOfFlow("body")||null,n=e?.flowPositions.body,o=!!(n&&n.positions.length),r=!!i&&en(i)&&!this.matchPageSide(i)&&!o,s=!(this.blankPageAtStart&&(!e||e.page===1))&&!(e!=null&&e.isBlankPage)&&!r,a=this.getPageStartOffset(e),h=this.getPageStartElement(e,a);if(!h)return;let l=this.getEffectivePageGroupStartElement(h),c=l===h?a:this.xmldoc.getElementOffset(l),d=l.ownerDocument,p=this.currentPageGroupDocument!==d&&s;p&&(this.pageGroupPageCounts=Object.create(null),this.currentPageGroupDocument=d);let f=l;for(;f;){let g=this.getPageGroupPageType(f);if(g){let v=this.pageGroupPageCounts[g]||(this.pageGroupPageCounts[g]=new Map),w=v.get(f)||0;(w>0||s&&(p||this.shouldStartPageGroup(f,g,c)))&&(w+=1,v.set(f,w),(t.pageTypePageIndices[g]||(t.pageTypePageIndices[g]=[])).push(w))}if(f===this.xmldoc.root)break;f=f.parentElement}}preparePageGroupPageIndicesForRerender(e,t){this.pageGroupPageCounts=Object.create(null),this.currentPageGroupDocument=null;for(let i=0;i<t;i++){let n=e[i]||null;this.updatePageGroupPageIndices(n)}}getFirstInFlowElementAtOrAfter(e,t){if(this.isPageBoundaryCandidateElement(e)&&this.xmldoc.getElementOffset(e)>=t)return e;let i=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{let o=n;return this.isNormalFlowElement(o)?this.isInlineLevelElement(o)||this.xmldoc.getElementOffset(o)<t?NodeFilter.FILTER_SKIP:NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}}).firstChild();return i??null}getDeepestFirstInFlowChildOffset(e){let t=e;for(;;){let i=this.getFirstInFlowChildElement(t);if(!i)return this.xmldoc.getElementOffset(t);t=i}}getFirstInFlowChildElement(e){let t=e.firstChild;for(;t;){if(t.nodeType===Node.TEXT_NODE){if(!Ee(t))return null;t=t.nextSibling;continue}if(t.nodeType!==Node.ELEMENT_NODE){t=t.nextSibling;continue}let i=t;if(this.isNormalFlowElement(i))return this.isInlineLevelElement(i)?null:i;t=t.nextSibling}return null}isPageBoundaryCandidateElement(e){return this.isNormalFlowElement(e)&&!this.isInlineLevelElement(e)}isNormalFlowElement(e){var t,i;let n=this.styler.getStyle(e,!1);if(this.getDisplayValue(e)===y.none)return!1;let o=(t=n?.position)==null?void 0:t.evaluate(this.styler.context,"position"),r=o&&!Z(o)?o:y.static;if(wo(r)||Ro(r))return!1;let s=(i=n?.float)==null?void 0:i.evaluate(this.styler.context,"float");return(s&&!Z(s)?s:y.none)===y.none}isInlineLevelElement(e){return Ut(this.getDisplayValue(e))}getDisplayValue(e){var t;let i=this.styler.getStyle(e,!1),n=(t=i?.display)==null?void 0:t.evaluate(this.styler.context,"display");return n&&!Z(n)?n:y.inline}getPosition(e,t){if(!e)return 0;let i=Number.POSITIVE_INFINITY;for(let n in this.primaryFlows){let o=e.flowPositions[n];if(!t&&(!o||o.positions.length==0)&&this.currentLayoutPosition&&(this.styler.styleUntilFlowIsReached(n),o=this.currentLayoutPosition.flowPositions[n],e!=this.currentLayoutPosition&&o&&(o=o.clone(),e.flowPositions[n]=o)),o){let r=this.getConsumedOffset(o);r<i&&(i=r)}}return i}dumpLocation(e){Y.debug("Location - page",this.currentLayoutPosition.page),Y.debug(" current:",e),Y.debug(" lookup:",this.lookupOffset);for(let t in this.currentLayoutPosition.flowPositions){let i=this.currentLayoutPosition.flowPositions[t];for(let n of i.positions)Y.debug(" Chunk",`${t}:`,n.flowChunk.startOffset)}}matchPageSide(e){switch(e){case"left":case"right":case"recto":case"verso":return new Je(this.style.pageScope,`${e}-page`).evaluate(this);default:return!0}}updateStartSide(e){for(let t in e.flowPositions){let i=e.flowPositions[t];if(i&&i.positions.length>0){let n=i.positions[0].flowChunk;if(this.getConsumedOffset(i)===n.startOffset){let o=i.positions[0].flowChunk.breakBefore,r=i.startBreakType;i.startBreakType=lu(nt(r,o))}}}}selectPageMaster(e){var t;let i=this.currentLayoutPosition,n=this.getPosition(i);if(n==Number.POSITIVE_INFINITY&&this.hasActiveRootPageFloatLayoutContext()&&(n=(t=i.highestSeenOffset)!=null?t:this.styler.getReachedOffset()),n==Number.POSITIVE_INFINITY)return null;let o=this.rootPageBoxInstance.children,r;for(let s=0;s<o.length;s++){if(r=o[s],r.pageBox.pseudoName===vh)continue;let a=1;r.pageBox.pseudoName===fh&&!(this.actualPageWidth&&this.actualPageHeight)&&(a=1/0);let h=r.getProp(this,"utilization");h&&h.isNum()&&(a=h.num);let l=this.queryUnitSize("em",!1),c=this.pageWidth()*this.pageHeight(),d=Math.ceil(a*c/(l*l)),p=this.styler.cascade.currentPageType;this.lookupOffset=this.styler.styleUntil(n,d),this.styler.cascade.currentPageType=p,this.updateStartSide(i),this.layoutPositionAtPageStart=i.clone(),this.initLingering(),this.clearScope(this.style.pageScope);let f=r.getProp(this,"enabled");if(!f||f===y._true){if(i.page===1&&this.blankPageAtStart){r.style={};let g=e.size;e={},g&&(e.size=g)}return this.pageManager.getPageRulePageMaster(r,e)}}throw new Error("No enabled page masters")}flowChunkIsAfterParentFlowForcedBreak(e){let t=this.layoutPositionAtPageStart.flows,i=t[e.flowName].parentFlowName;if(i){let n=e.startOffset,o=t[i].forcedBreakOffsets;if(!o.length||n<o[0])return!1;let r=mi(o.length,l=>o[l]>n)-1,s=o[r],a=this.layoutPositionAtPageStart.flowPositions[i],h=this.getConsumedOffset(a);return s<h?!1:h<s?!0:!this.matchPageSide(a.startBreakType)}return!1}setFormattingContextToColumn(e,t){let i=this.currentLayoutPosition.flows[t];i.formattingContext||(i.formattingContext=new jl(null)),e.flowRootFormattingContext=i.formattingContext}beginIsolatedRootPageFloatLayoutContext(e){let t=this.rootPageFloatLayoutContext;return this.rootPageFloatLayoutContext=new Sn(null,null,null,null,null,null,null),e&&this.rootPageFloatLayoutContext.addPageFloatLayoutContextAsPreviousSibling(e),t}endIsolatedRootPageFloatLayoutContext(e){this.rootPageFloatLayoutContext=e}hasActiveRootPageFloatLayoutContext(){return this.rootPageFloatLayoutContext.getDeferredPageFloatContinuations().length>0||this.rootPageFloatLayoutContext.getPageFloatContinuationsDeferredToNext().length>0||this.rootPageFloatLayoutContext.getFloatsDeferredToNextInChildContexts().length>0}hasOnlyDeferredPageFloats(e){return this.noMorePrimaryFlows(e)&&this.hasActiveRootPageFloatLayoutContext()}layoutDeferredPageFloats(e){let t=e.pageFloatLayoutContext,i=t.getDeferredPageFloatContinuations(),n=this.counterStore.currentPageCountersStack.length>0,o=h=>{var l,c;if(!n||h.floatReference!==Pe.PAGE)return!1;let d=((c=(l=this.layoutPositionAtPageStart)==null?void 0:l.flowPositions)==null?void 0:c.body)||null,p=d?this.getConsumedOffset(d):Number.NaN,f=isFinite(p)?p:this.getPageStartOffset(this.layoutPositionAtPageStart,!0),g=this.xmldoc.getNodeOffset(h.nodePosition.steps[0].node,0,!1);return g!=null&&isFinite(f)&&g>f},r=M("layoutDeferredPageFloats"),s=!1,a=0;return r.loopWithFrame(h=>{if(a===i.length){h.breakLoop();return}let l=i[a++],c=l.float;if(o(c)){h.breakLoop();return}let d=new Vn().findByFloat(c),p=d.findPageFloatFragment(c,t);if(p&&p.hasFloat(c)){h.continueLoop();return}else if(t.isForbidden(c)||t.hasPrecedingFloatsDeferredToNext(c)){t.deferPageFloat(l),h.breakLoop();return}e.layoutPageFloatInner(l,d,null,p).then(f=>{if(!f){h.breakLoop();return}let g=t.parent.isInvalidated();if(g){h.breakLoop();return}else t.isInvalidated()&&!g&&(s=!0,t.validate());h.continueLoop()})}).then(()=>{s&&t.invalidate(),r.finish(!0)}),r.result()}getLastAfterPositionIfDeferredFloatsExists(e,t){if(e.pageFloatLayoutContext.getPageFloatContinuationsDeferredToNext().length>0)if(e.lastAfterPosition){let i;return t?(i=t.clone(),i.primary=e.lastAfterPosition):i=new Bi(e.lastAfterPosition),i}else return null;else return null}layoutColumn(e,t){let i=this.currentLayoutPosition.flowPositions[t];if(!i||!this.matchPageSide(i.startBreakType))return i?(this.setFormattingContextToColumn(e,t),e.init(),this.layoutDeferredPageFloats(e)):T(!0);this.setFormattingContextToColumn(e,t),e.init(),this.primaryFlows[t]&&e.bands.length>0&&(e.forceNonfitting=!1);let n=M("layoutColumn");return this.layoutDeferredPageFloats(e).then(()=>{if(e.pageFloatLayoutContext.isInvalidated()){n.finish(!0);return}let o=[],r=[],s=!0;n.loopWithFrame(a=>{if(e.pageFloatLayoutContext.hasContinuingFloatFragmentsInFlow(t)){a.breakLoop();return}for(;i.positions.length-r.length>0;){let h=0;for(;r.includes(h);)h++;let l=i.positions[h];if(l.flowChunk.startOffset>this.lookupOffset||this.flowChunkIsAfterParentFlowForcedBreak(l.flowChunk))break;for(let p=h+1;p<i.positions.length;p++){if(r.includes(p))continue;let f=i.positions[p];if(f.flowChunk.startOffset>this.lookupOffset||this.flowChunkIsAfterParentFlowForcedBreak(f.flowChunk))break;f.flowChunk.isBetter(l.flowChunk)&&(l=f,h=p)}let c=l.flowChunk,d=!0;if(e.layout(l.chunkPosition,s,i.breakAfter).then(p=>{if(e.pageFloatLayoutContext.isInvalidated()){a.breakLoop();return}if(s=!1,l.flowChunk.repeated&&(p===null||c.exclusive)&&o.push(h),c.exclusive){r.push(h),a.breakLoop();return}else{let f=!!p||!!e.pageBreakType,g=this.getLastAfterPositionIfDeferredFloatsExists(e,p);if(!p&&e.pageBreakType&&i.positions.length-r.length-1<=0&&(e.pageBreakType=null),e.pageBreakType&&g?(l.chunkPosition=g,i.breakAfter=e.pageBreakType,e.pageBreakType=null):(r.push(h),(p||g)&&(l.chunkPosition=p||g,o.push(h)),i.startBreakType=lu(e.pageBreakType)),f){a.breakLoop();return}}e.forceNonfitting=!1,d?d=!1:a.continueLoop()}),d){d=!1;return}}a.breakLoop()}).then(()=>{var a;if(!e.pageFloatLayoutContext.isInvalidated()){i.positions=i.positions.filter((l,c)=>o.includes(c)||!r.includes(c)),i.breakAfter==="column"&&(i.breakAfter=null),e.saveDistanceToBlockEndFloats();let h=e.pageFloatLayoutContext.getMaxReachedAfterEdge();if(e.updateMaxReachedAfterEdge(h),e.computedBlockSize===0){let l=e.pageFloatLayoutContext,c=l;for(;c;){let d=c.floatFragments.filter(p=>"isFootnote"in p.area&&p.area.isFootnote);if(d.length>0&&!c.ignoreFootnoteAreaMaxHeight&&d.some(p=>{let f=getComputedStyle(p.area.element),g=v=>v!==""&&v!=="none";return g(f.getPropertyValue("max-block-size"))||g(p.area.vertical?f.maxWidth:f.maxHeight)})){c.ignoreFootnoteAreaMaxHeight=!0;for(let p of d){l.removePageFloatFragment(p,!0);let f=(a=p.continuations[0])==null?void 0:a.float;f&&c.removeFloatDeferredToNext(f)}l.invalidate();break}c=c.parent}}}n.finish(!0)})}),n.result()}createLayoutConstraint(e){let t=this.currentLayoutPosition.page-1,i=this.counterStore.createLayoutConstraint(t);return new F0([i].concat(e.getLayoutConstraints()))}createAndLayoutColumn(e,t,i,n,o,r,s,a,h,l,c,d,p,f){let g=e.vertical?e.isAutoWidth&&e.isRightDependentOnAutoWidth||e.isAutoHeight:e.isAutoHeight&&e.isTopDependentOnAutoHeight||e.isAutoWidth,v=o.element,w=new Sn(a,Pe.COLUMN,null,s,null,null,null),x=this.currentLayoutPosition.clone(),m=M("createAndLayoutColumn"),S;return m.loopWithFrame(b=>{let C=this.createLayoutConstraint(w);if(h>1){let P=this.viewport.document.createElement("div");if(I(P,"position","absolute"),v.appendChild(P),S=new Cs(P,p,this.clientLayout,C,w),S.isNonFirstColumn=r>0,S.forceNonfitting=f,S.vertical=o.vertical,S.rtl=o.rtl,S.snapHeight=o.snapHeight,S.snapWidth=o.snapWidth,o.vertical){let L=(o.rtl?h-r-1:r)*(c+l)+o.paddingTop,A=parseFloat(v.style.width);S.setHorizontalPosition(o.paddingLeft+A-o.width,o.width),S.setVerticalPosition(L,c)}else{let L=(o.rtl?h-r-1:r)*(c+l)+o.paddingLeft;S.setVerticalPosition(o.paddingTop,o.height),S.setHorizontalPosition(L,c)}S.originX=t,S.originY=i}else S=new Cs(v,p,this.clientLayout,C,w),S.isNonFirstColumn=!1,S.copyFrom(o);S.exclusions=g?[]:n.concat(),S.innerShape=d,w.setContainer(S),(S.vertical?S.height:S.width)>=0?this.layoutColumn(S,s).then(()=>{w.isInvalidated()||w.finish(),S.pageFloatLayoutContext.isInvalidated()&&!a.isInvalidated()?(S.pageFloatLayoutContext.validate(),this.currentLayoutPosition=x.clone(),S.element!==v&&v.removeChild(S.element),b.continueLoop()):b.breakLoop()}):(w.finish(),b.breakLoop())}).then(()=>{m.finish(S)}),m.result()}setPagePageFloatLayoutContextContainer(e,t,i){(t instanceof hg||t instanceof gh&&!(t instanceof Mn))&&e.setContainer(i)}getRegionPageFloatLayoutContext(e,t,i,n){t instanceof Wn;let o=t.getProp(this,"writing-mode")||null,r=t.getProp(this,"direction")||null;return new Sn(e,Pe.REGION,i,n,null,o,r)}layoutFlowColumnsWithBalancing(e,t,i,n,o,r,s,a,h){let l=this.currentLayoutPosition.clone(),c=this.getRegionPageFloatLayoutContext(r,t,s,a),d=!0,p=()=>(this.currentLayoutPosition=l.clone(),this.layoutFlowColumns(e,t,i,n,o,r,c,s,a,h,d).thenAsync(f=>T(f?{columns:f,position:this.currentLayoutPosition}:null)));return p().thenAsync(f=>{if(!f)return T(null);if(h<=1)return T(f.columns);let g=t.getProp(this,"column-fill")||y.balance,v=this.currentLayoutPosition.flowPositions[a],w=wx(h,g,p,c,s,f.columns,v);return w?(d=!1,r.lock(),c.lock(),w.balanceColumns(f).thenAsync(x=>(r.unlock(),r.validate(),c.unlock(),this.currentLayoutPosition=x.position,T(x.columns)))):T(f.columns)})}layoutFlowColumns(e,t,i,n,o,r,s,a,h,l,c){let d=M("layoutFlowColumns"),p=this.currentLayoutPosition.clone(),f=ec(this.currentLayoutPosition),g=t.getPropAsNumber(this,"column-gap"),v=l>1?t.getPropAsNumber(this,"column-width"):a.vertical?a.height:a.width,w=t.getActiveRegions(this),x=t.getProp(this,"shape-inside"),m=ld(x,0,0,a.width,a.height,this),S=new $x(h,this,this.viewport,this.styler,w,this.xmldoc,this.faces,this.style.footnoteProps,this,e,this.customRenderer,this.fallbackMap,this.documentURLTransformer,this.style.pageProps,this.currentCascadedPageStyle,this.semanticFootnoteFirstRefOffsets,this.semanticFootnoteFirstRefOffsetsInitialized),b=0,C=null,P=[];return d.loopWithFrame(L=>{this.createAndLayoutColumn(t,i,n,o,a,b++,h,s,l,g,v,m,S,c).then(A=>{if(r.isInvalidated()){P=null,L.breakLoop();return}if((A.pageBreakType&&A.pageBreakType!=="column"||b===l)&&!s.isInvalidated()&&s.finish(),s.isInvalidated()){b=0,this.currentLayoutPosition=p.clone(),tc(f),s.validate(),s.isLocked()?(P=null,L.breakLoop()):L.continueLoop();return}C=A,P[b-1]=C,C.pageBreakType&&C.pageBreakType!="column"&&(b=l,C.pageBreakType!="region"&&(this.pageBreaks[h]=!0)),b<l?L.continueLoop():L.breakLoop()})}).then(()=>{d.finish(P)}),d.result()}layoutContainer(e,t,i,n,o,r,s){t.reset();let a=t.getProp(this,"enabled");if(a&&a!==y._true)return T(!0);let h=M("layoutContainer"),l=t.getProp(this,"wrap-flow")===y.auto,c=t.getProp(this,"flow-from"),d=this.viewport.document.createElement("div");d.role=t instanceof ug?"complementary":"presentation";let p=t.getProp(this,"position");I(d,"position",p?p.name:"absolute");let f=t instanceof Mn;t instanceof Wn?i.appendChild(d):i.insertBefore(d,i.firstChild);let g=new lp(d);g.vertical=t.vertical,g.rtl=t.rtl,g.borderBoxSizing=t.borderBoxSizing,g.exclusions=r,t.prepareContainer(this,g,e,this.faces,this.clientLayout),(g.width<=0||g.height<=0)&&(t instanceof Mn||c&&c.isIdent())&&(this.invalidPageAreaOnCurrentPage=!0,Y.warn("Negative or zero page area size")),g.originX=n,g.originY=o,n+=g.left+g.marginLeft+g.borderLeft,o+=g.top+g.marginTop+g.borderTop,this.setPagePageFloatLayoutContextContainer(s,t,g);let v,w=!1;if(!c||!c.isIdent()){let x=[],m=t.getProp(this,"content");if(m instanceof j&&m.expr instanceof we&&m.expr.str.startsWith("running-element-"))m.visit(new Oo(d,this,m,this.counterStore.getExprContentListener()));else if(It(m)){let S="span";m instanceof Qe&&(S="img");let b=this.viewport.document.createElement(S);m.visit(new Oo(b,this,m,this.counterStore.getExprContentListener())),d.appendChild(b),S=="img"&&t.transferSingleUriContentProps(this,b,this.faces),t.transferContentProps(this,g,e,this.faces);let C=b.querySelectorAll("img[src]");for(let L=0;L<C.length;L++){let A=C[L],z=A.getAttribute("src");if(!z)continue;let U=Et(A,z);x.push(U),e.fetchers.push(U)}let P=b.getAttribute("src");if(P){let L=b.querySelector("img");L||(L=b);let A=Et(L,P);x.push(A),e.fetchers.push(A)}S=="span"&&C0(b,t.getProp(this,"text-autospace"),t.getProp(this,"text-spacing-trim"),t.getProp(this,"hanging-punctuation"),this.lang,t.vertical)}else t.suppressEmptyBoxGeneration&&(i.removeChild(d),w=!0);w||t.finishContainer(this,g,e,null,1,this.clientLayout,this.faces),v=x.length?Dn(x).thenReturn(!0):T(!0)}else if(this.pageBreaks[c.toString()])s.isInvalidated()||t.finishContainer(this,g,e,null,1,this.clientLayout,this.faces),v=T(!0);else{let x=M("layoutContainer.inner"),m=c.toString(),S=t.getPropAsNumber(this,"column-count");this.layoutFlowColumnsWithBalancing(e,t,n,o,r,s,g,m,S).then(b=>{if(!s.isInvalidated()){let C=b[0];C.element===d&&(g=C),g.computedBlockSize=Math.max.apply(null,b.map(L=>L.computedBlockSize)),t.finishContainer(this,g,e,C,S,this.clientLayout,this.faces);let P=this.currentLayoutPosition.flowPositions[m];P&&P.breakAfter==="region"&&(P.breakAfter=null)}x.finish(!0)}),v=x.result()}return v.then(()=>{if(s.isInvalidated()){h.finish(!0);return}if(!t.isAutoHeight||Math.floor(g.computedBlockSize)>0){if(!w&&!l){let m=t.getProp(this,"shape-outside"),S=g.getOuterShape(m,this);r.push(S)}}else if(t.children.length==0){i.removeChild(d),h.finish(!0);return}let x=f?0:t.children.length-1;h.loop(()=>{for(;x>=0&&x<t.children.length;){let m=t.children[f?x++:x--],S=this.layoutContainer(e,m,d,n,o,r,s);if(S.isPending())return S.thenAsync(()=>T(!s.isInvalidated()));if(s.isInvalidated())break}return T(!1)}).then(()=>{h.finish(!0)})}),h.result()}processLinger(){let e=this.currentLayoutPosition.page;for(let t in this.currentLayoutPosition.flowPositions){let i=this.currentLayoutPosition.flowPositions[t];for(let n=i.positions.length-1;n>=0;n--){let o=i.positions[n];o.flowChunk.startPage>=0&&o.flowChunk.startPage+o.flowChunk.linger-1<=e&&i.positions.splice(n,1)}}}initLingering(){let e=this.currentLayoutPosition.page;for(let t in this.currentLayoutPosition.flowPositions){let i=this.currentLayoutPosition.flowPositions[t];for(let n=i.positions.length-1;n>=0;n--){let o=i.positions[n];o.flowChunk.startPage<0&&o.flowChunk.startOffset<this.lookupOffset&&(o.flowChunk.startPage=e)}}}noMorePrimaryFlows(e){for(let t in this.primaryFlows){let i=e.flowPositions[t];if(i&&i.positions.length>0)return!1}return!0}hasSameFlowPositions(e,t){if(e===t)return!0;if(!e||!t)return!1;let i=Object.keys(e.flowPositions),n=Object.keys(t.flowPositions);if(i.length!==n.length)return!1;for(let o of i)if(!e.flowPositions[o].isSamePosition(t.flowPositions[o]))return!1;return!0}checkRepeatedInvalidPageArea(e){let t=this.invalidPageAreaOnCurrentPage;if(this.invalidPageAreaOnCurrentPage=!1,!t){this.repeatedInvalidPageAreaLayoutPosition=null;return}if(e.isBlankPage||this.noMorePrimaryFlows(e))return;if(!this.hasSameFlowPositions(this.layoutPositionAtPageStart,e)){this.repeatedInvalidPageAreaLayoutPosition=null;return}let i=!!this.repeatedInvalidPageAreaLayoutPosition&&this.hasSameFlowPositions(this.repeatedInvalidPageAreaLayoutPosition,this.layoutPositionAtPageStart);if(this.repeatedInvalidPageAreaLayoutPosition=this.layoutPositionAtPageStart.clone(),i)throw new Error("Negative or zero page area size")}layoutNextPage(e,t){var i,n,o,r;let s=e.container===e.bleedBox;this.pageBreaks={},t?(this.currentLayoutPosition=t.clone(),this.styler.replayFlowElementsFromOffset(t.highestSeenOffset)):(this.currentLayoutPosition=new Wv,this.styler.replayFlowElementsFromOffset(-1)),this.lang&&e.bleedBox.setAttribute("lang",this.lang),this.invalidPageAreaOnCurrentPage=!1,t=this.currentLayoutPosition;let a=t.startSideOfFlow("body");t.isBlankPage=en(a)&&this.matchPageSide(a),e.isBlankPage=t.isBlankPage,t.page++;let h=this.hasOnlyDeferredPageFloats(t),l=h?void 0:this.getPageStartPageTypeOverride(t);if(l===""?e.pageType="":l&&(e.pageType=l),e.pageType==null){let m=t.page===1?this.resolveFirstPageType():null,S=(i=this.styler.cascade.currentPageType)!=null?i:this.styler.cascade.previousPageType,b=e.isBlankPage?this.styler.cascade.previousPageType:h?S:m??this.styler.cascade.currentPageType;if(e.pageType=b,!e.pageType){let C=this.getPageStartPageType(t);C&&(e.pageType=C)}e.pageType=(n=e.pageType)!=null?n:"",this.styler.cascade.previousPageType=this.styler.cascade.currentPageType}this.updatePageGroupPageIndices(t),this.clearScope(this.style.pageScope),this.layoutPositionAtPageStart=t.clone();let c=ec(t),d=s?{}:this.pageManager.getCascadedPageStyle(e.pageType);if(this.currentCascadedPageStyle=d,this.styler.cascade.applyVarFilter([d],this.styler,null),this.styler.cascade.applyCalcFilter(d,this.styler.context),this.styler.cascade.applyCmykFilter(d),!s){let m=new Je(this.style.pageScope,"left-page");e.side=m.evaluate(this)?"left":"right",e.container.setAttribute("data-vivliostyle-page-side",e.side)}let p=this.selectPageMaster(d);if(!p)return T(null);let f=0;if(!s){e.setAutoPageWidth(p.pageBox.specified.width.value===Yo),e.setAutoPageHeight(p.pageBox.specified.height.value===Zo);let{counterOffset:m,changeOffset:S}=this.getPageStartCounterOffsets(this.layoutPositionAtPageStart);isFinite(m)||(m=this.lookupOffset,S=this.lookupOffset),isFinite(m)&&this.styler.styleUntil(m,0);let b=this.styler.getCounterSnapshotAtOffset(m),C=S===m?b:this.styler.getCounterSnapshotAtOffset(S);b||(b=this.styler.getLastCounterSnapshot()),C||(C=b);let P=C&&C.offset===S?C:null;this.counterStore.setCurrentPageDocCounters((o=b?.counters)!=null?o:null,(r=P?.changes)!=null?r:null,P?.changeTypes),this.counterStore.setCurrentPage(e),this.counterStore.updatePageCounters(d,this);let L=Ku(Ps(d),this);this.setPageSizeAndBleed(L,e),sS(d,L,e,this),f=L.bleedOffset+L.bleed}let g=!s&&p.getProp(this,"writing-mode")||y.horizontal_tb;this.pageVertical=g!=y.horizontal_tb;let v=p.getProp(this,"direction")||y.ltr,w=new Sn(this.rootPageFloatLayoutContext,Pe.PAGE,null,null,null,g,v),x=M("layoutNextPage");return x.loopWithFrame(m=>{this.layoutContainer(e,p,e.bleedBox,f,f,[],w).then(()=>{if(w.isInvalidated()||w.finish(),w.isInvalidated()){for(this.currentLayoutPosition=this.layoutPositionAtPageStart.clone(),tc(c),w.validate();e.bleedBox.lastChild;)e.bleedBox.removeChild(e.bleedBox.lastChild);m.continueLoop()}else m.breakLoop()})}).then(()=>{e.pageFloatLayoutContext=w,p.adjustPageLayout(this,e,this.clientLayout),s||(this.processLinger(),t=this.currentLayoutPosition,this.checkRepeatedInvalidPageArea(t),Object.keys(t.flowPositions).forEach(S=>{let b=t.flowPositions[S],C=b.breakAfter;C&&(C==="page"||!this.matchPageSide(C))&&(b.breakAfter=null)})),this.currentLayoutPosition=this.layoutPositionAtPageStart=null,t.highestSeenOffset=this.styler.getReachedOffset();let m=this.style.store.getTriggersForDoc(this.xmldoc);e.finish(m,this.clientLayout),this.noMorePrimaryFlows(t)&&!this.hasActiveRootPageFloatLayoutContext()&&(t=null),x.finish(t)}),x.result()}setPageSizeAndBleed(e,t){this.actualPageWidth=e.pageWidth,this.actualPageHeight=e.pageHeight,this.pageSheetWidth=e.pageWidth+e.cropOffset*2,this.pageSheetHeight=e.pageHeight+e.cropOffset*2,t.container.style.width=`${this.pageSheetWidth}px`,t.container.style.height=`${this.pageSheetHeight}px`,t.bleedBox.style.left=`${e.bleedOffset}px`,t.bleedBox.style.right=`${e.bleedOffset}px`,t.bleedBox.style.top=`${e.bleedOffset}px`,t.bleedBox.style.bottom=`${e.bleedOffset}px`,t.bleedBox.style.padding=`${e.bleed}px`}},OS=class bl extends zo{constructor(t,i,n,o){super(t.rootScope,t,i,n,o,t.validatorSet,!n),u(this,"masterHandler",t),u(this,"insideRegion",!1)}startPageTemplateRule(){}startPageMasterRule(t,i,n){let o=new Jf(this.masterHandler.pageScope,t,i,n,this.masterHandler.rootBox,this.condition,this.owner.getBaseSpecificity());this.masterHandler.pushHandler(new Qx(o.scope,this.masterHandler,o,this.validatorSet))}startWhenRule(t){let i=t.expr;this.condition!=null&&(i=Wt(this.scope,this.condition,i)),this.masterHandler.pushHandler(new bl(this.masterHandler,i,this,this.regionId))}startDefineRule(){this.masterHandler.pushHandler(new c0(this.scope,this.owner))}startFontFaceRule(){let t={};this.masterHandler.fontFaces.push({properties:t,condition:this.condition}),this.masterHandler.pushHandler(new qr(this.scope,this.owner,null,t,this.masterHandler.validatorSet,"font-face"))}startCounterStyleRule(t){this.masterHandler.pushHandler(new RS(this.scope,this.owner,{},this.masterHandler.validatorSet,t,this.masterHandler.counterStyles))}startFlowRule(t){let i=this.masterHandler.flowProps[t];i||(i={},this.masterHandler.flowProps[t]=i),this.masterHandler.pushHandler(new qr(this.scope,this.owner,null,i,this.masterHandler.validatorSet))}startViewportRule(){let t={};this.masterHandler.viewportProps.push(t),this.masterHandler.pushHandler(new qr(this.scope,this.owner,this.condition,t,this.masterHandler.validatorSet))}startFootnoteRule(t){let i=this.masterHandler.footnoteProps;if(t){let n=si(i,"_pseudos");i=n[t],i||(i={},n[t]=i)}this.masterHandler.pushHandler(new cg(this.scope,this.owner,this.masterHandler.validatorSet,i))}startRegionRule(){this.insideRegion=!0,this.startSelectorRule()}startPageRule(){let t=new ES(this.masterHandler.pageScope,this.masterHandler,this,this.validatorSet,this.masterHandler.pageProps);this.masterHandler.pushHandler(t),t.startPageRule()}startRuleBody(){if(zo.prototype.startRuleBody.call(this),this.insideRegion){this.insideRegion=!1;let t=`R${this.masterHandler.regionCount++}`;this.special("region-id",B(t)),this.endRule();let i=new bl(this.masterHandler,this.condition,this,t);this.masterHandler.pushHandler(i),i.startRuleBody()}}},gg=class extends Ba{constructor(e){super(),u(this,"validatorSet",e),u(this,"rootScope"),u(this,"pageScope"),u(this,"rootBox"),u(this,"cascadeParserHandler"),u(this,"regionCount",0),u(this,"fontFaces",[]),u(this,"counterStyles",new jw),u(this,"footnoteProps",{}),u(this,"flowProps",{}),u(this,"viewportProps",[]),u(this,"pageProps",{}),this.rootScope=new ts(null),this.pageScope=new ts(this.rootScope),this.rootBox=new jx(this.rootScope),this.cascadeParserHandler=new OS(this,null,null,null),this.slave=this.cascadeParserHandler}};function BS(e,t){return t.parseOPSResource(e)}var MS=class extends Bl{constructor(e){super(BS,"document"),u(this,"fontDeobfuscator",e),u(this,"styleByKey",{}),u(this,"styleFetcherByKey",{}),u(this,"styleByDocURL",{}),u(this,"triggersByDocURL",{}),u(this,"validatorSet",null),u(this,"styleSheets",[]),u(this,"triggerSingleDocumentPreprocessing",!1)}init(e,t){this.setStyleSheets(e,t);let i=M("OPSDocStore.init");return this.validatorSet=Zp(),FS().then(()=>{this.triggerSingleDocumentPreprocessing=!0,i.finish(!0)}),i.result()}getStyleForDoc(e){return this.styleByDocURL[e.url]}getTriggersForDoc(e){return this.triggersByDocURL[e.url]}setStyleSheets(e,t){this.clearStyleSheets(),e&&e.forEach(this.addAuthorStyleSheet,this),t&&t.forEach(this.addUserStyleSheet,this)}clearStyleSheets(){this.styleSheets.splice(0)}addAuthorStyleSheet(e){let t=e.url;t&&(t=Ae(Fn(t),Ji)),this.styleSheets.push({url:t,text:e.text,flavor:"Author",classes:null,media:null})}addUserStyleSheet(e){let t=e.url;t&&(t=Ae(Fn(t),Ji)),this.styleSheets.push({url:t,text:e.text,flavor:"User",classes:null,media:null})}parseOPSResource(e){let t=M("OPSDocStore.load"),i=e.url,n=As(i);return pg(e,this).then(o=>{var r;if(!o){t.finish(null);return}if(this.triggerSingleDocumentPreprocessing){let p=_t("PREPROCESS_SINGLE_DOCUMENT");for(let f=0;f<p.length;f++)try{p[f](o.document)}catch(g){Y.warn("Error during single document preprocessing:",g)}}let s=[],a=o.document.getElementsByTagNameNS("http://www.idpf.org/2007/ops","trigger");for(let p=0;p<a.length;p++){let f=a[p],g=f.getAttributeNS("http://www.w3.org/2001/xml-events","observer"),v=f.getAttributeNS("http://www.w3.org/2001/xml-events","event"),w=f.getAttribute("action"),x=f.getAttribute("ref");g&&v&&w&&x&&s.push({observer:g,event:v,action:w,ref:x})}this.triggersByDocURL[i]=s;let h=[];if(h.push({url:Ae("user-agent-page.css",Ni),text:Pd,flavor:"UA",classes:null,media:null}),h.push({url:Ae("user-agent-counter-styles.css",Ni),text:Id,flavor:"UA",classes:null,media:null}),n)h.push({url:Ae("user-agent-toc.css",Ni),text:Td,flavor:"UA",classes:null,media:null});else{let p=o.document.querySelectorAll("style, link, meta");for(let f of p){let g=f.namespaceURI,v=f.localName;if(g=="http://www.w3.org/1999/xhtml")if(v=="style"){let w=f.getAttribute("class"),x=f.getAttribute("media"),m=f.getAttribute("title");h.push({url:i,text:f.textContent,flavor:"Author",classes:m?w:null,media:x})}else if(v=="link"){let w=f.getAttribute("href"),x=(r=f.getAttribute("rel"))==null?void 0:r.split(/\s+/),m=f.getAttribute("class"),S=f.getAttribute("media");if(w&&x!=null&&x.includes("stylesheet")&&(!x.includes("alternate")||m)){let b=Ae(w,i),C=f.getAttribute("title");h.push({url:b,text:null,classes:C?m:null,media:S,flavor:"Author"})}}else v=="meta"&&f.getAttribute("name")=="viewport"&&h.push({url:i,text:this.processViewportMeta(f),flavor:"Author",classes:null,media:null})}for(let f=0;f<this.styleSheets.length;f++)h.push(this.styleSheets[f])}let l="";for(let p=0;p<h.length;p++)l+=h[p].url,l+="^",h[p].text&&(l+=h[p].text),l+="^";let c=this.styleByKey[l];if(c){this.styleByDocURL[i]=c,t.finish(o);return}let d=this.styleFetcherByKey[l];d||(d=new Qo(()=>{let p=M("fetchStylesheet"),f=0,g=new gg(this.validatorSet);return p.loop(()=>{if(f<h.length){let v=h[f++];return g.startStylesheet(v.flavor),v.text!==null?Ml(v.text,g,v.url,v.classes,v.media).thenReturn(!0):_d(v.url,g,v.classes,v.media)}return T(!1)}).then(()=>{let v=g.cascadeParserHandler.finish();c=new LS(this,g.rootScope,g.pageScope,v,g.rootBox,g.fontFaces,g.footnoteProps,g.flowProps,g.viewportProps,g.pageProps,g.counterStyles),this.styleByKey[l]=c,delete this.styleFetcherByKey[l],p.finish(c)}),p.result()},`FetchStylesheet ${i}`),this.styleFetcherByKey[l]=d,d.start()),d.get().then(p=>{this.styleByDocURL[i]=p,t.finish(o)})}),t.result()}processViewportMeta(e){return""}},Ao="\u25B8",ic="\u25BE",_S="\u25B9";function bh(e){let t=Array.from(e.querySelectorAll("nav[*|type],nav[epub\\:type]"));if(t.length>0||(t=Array.from(e.querySelectorAll("[role=doc-toc]")),t.length>0))return t;let i="nav,.toc,#toc,#table-of-contents,#contents,[role=directory]";for(let n of e.querySelectorAll(i)){if(t.find(r=>r.contains(n)))continue;let o=n;/^h[1-6]$/.test(o.localName)&&(o.previousElementSibling?o=o.nextElementSibling:o=o.parentElement),o&&o.querySelector("li a[href]")&&t.push(o)}return t}function DS(e){let t=bh(e),i=[];for(let n of t)for(let o of n.querySelectorAll("li a[href]"))i.push(o);return i}var zS=class{constructor(e,t,i,n,o,r,s,a,h,l,c){u(this,"store",e),u(this,"url",t),u(this,"lang",i),u(this,"clientLayout",n),u(this,"fontMapper",o),u(this,"rendererFactory",s),u(this,"fallbackMap",a),u(this,"documentURLTransformer",h),u(this,"counterStore",l),u(this,"cmykStore",c),u(this,"pref"),u(this,"page",null),u(this,"instance",null),this.pref=Pc(r),this.pref.spreadView=!1}setAutoHeight(e,t){if(t--!=0){for(let i=e.firstChild;i;i=i.nextSibling)if(i.nodeType==1){let n=i;ki(n,"height","auto")!="auto"&&(I(n,"height","auto"),this.setAutoHeight(n,t)),ki(n,"position","static")=="absolute"&&(I(n,"position","relative"),this.setAutoHeight(n,t))}}}makeCustomRenderer(e){let t=this.rendererFactory.makeCustomRenderer(e);return(i,n,o)=>{let r=o.behavior;if(r)switch(r.toString()){case"toc-node-anchor":o.color=y.inherit,o["text-decoration"]=y.none;break;case"toc-node":o.display=y.block,o.margin=Le,o.padding=Le,o["padding-inline-start"]=new O(1.25,"em");break;case"toc-node-first-child":o.display=y.inline_block,o.margin=new O(.2,"em"),o["vertical-align"]=y.top,o.color=y.inherit,o["text-decoration"]=y.none;break;case"toc-container":o.padding=Le;break}if(!r||r.toString()!="toc-node"&&r.toString()!="toc-container")return t(i,n,o);let s=i.firstChild;s&&s.nodeType!==1&&Ee(s)&&i.replaceChild(i.ownerDocument.createComment(s.textContent),s);let a=n.getAttribute("data-adapt-class");if(a=="toc-node"){let l=n.firstChild;l.textContent!=Ao&&(l.textContent=Ao,I(l,"cursor","pointer"),l.addEventListener("click",VS,!1),l.setAttribute("role","button"),l.setAttribute("aria-expanded","false"),n.setAttribute("aria-expanded","false"),n.style.height!=="0px"&&(l.tabIndex=0))}let h=n.ownerDocument.createElement("div");if(h.setAttribute("data-adapt-process-children","true"),r.toString()=="toc-node"){let l=n.ownerDocument.createElement("div");if(l.textContent=_S,I(l,"margin","0.2em 0 0 -1em"),I(l,"margin-inline-start","-1em"),I(l,"margin-inline-end","0"),I(l,"display","inline-block"),I(l,"width","1em"),I(l,"text-align","center"),I(l,"vertical-align","top"),I(l,"cursor","default"),I(l,"font-family","Menlo,sans-serif"),h.appendChild(l),I(h,"overflow","hidden"),h.setAttribute("data-adapt-class","toc-node"),h.setAttribute("role","treeitem"),a=="toc-node"||a=="toc-container"){I(h,"height","0px");let c=i.firstElementChild;c&&c.localName==="a"&&(c.tabIndex=-1)}else n.setAttribute("role","tree")}else a=="toc-node"&&(h.setAttribute("data-adapt-class","toc-container"),h.setAttribute("role","group"),h.setAttribute("aria-hidden","true"));return T(h)}}showTOC(e,t,i,n,o){if(this.page)return T(this.page);let r=M("showTOC"),s=new Qd(e,e);this.page=s;let a=xa(this.url);return this.store.load(a).then(h=>{for(let f of bh(h.document))f.setAttribute("data-vivliostyle-role","doc-toc");let l=this.store.getStyleForDoc(h),c=l.sizeViewport(i,1e5,o);t=new Es(t.window,c.fontSize,0,e,c.width,c.height);let d=this.makeCustomRenderer(h),p=new wh(l,h,this.lang,t,this.clientLayout,this.fontMapper,d,this.fallbackMap,0,this.documentURLTransformer,this.counterStore,this.cmykStore);this.instance=p,p.pref=this.pref,p.init().then(()=>{p.layoutNextPage(s,null).then(()=>{this.setAutoHeight(e,2),r.finish(s)})})}),r.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 e(n){if(!n)return[];let o=n.querySelectorAll(":scope > [role=treeitem] > a[href]");return Array.from(o).map(t)}function t(n){let o=new URL(n.href),[,r]=o.hash.match(/^#?(.*)$/),s=n.innerText,a=n.parentElement.querySelector("[role=group]"),h=e(a);return{id:r,title:s,children:h}}let i=this.page.container.querySelector("[role=tree]");return e(i)}};function VS(e){let t=e.target,i=t.textContent==Ao;t.textContent=i?ic:Ao;let n=t.parentNode;t.setAttribute("aria-expanded",i?"true":"false"),n.setAttribute("aria-expanded",i?"true":"false");let o=n.firstChild;for(;o;){if(o.nodeType===1){let r=o,s=r.getAttribute("data-adapt-class");if(s==="toc-container"){if(r.setAttribute("aria-hidden",i?"false":"true"),r.firstChild){o=r.firstChild;continue}}else if(s==="toc-node"&&(r.style.height=i?"auto":"0px",r.children.length>=2&&(r.children[1].tabIndex=i?0:-1),r.children.length>=3&&(r.children[0].tabIndex=i?0:-1,!i))){let a=r.children[0];if(a.textContent==ic){a.textContent=Ao,a.setAttribute("aria-expanded","false"),r.setAttribute("aria-expanded","false"),o=r.children[2];continue}}}for(;!o.nextSibling&&o.parentNode!==n;)o=o.parentNode;o=o.nextSibling}e.stopPropagation()}function Ir(e){let t={};return Object.keys(e).forEach(i=>{t[i]=Array.from(e[i])}),t}function US(e){let t=Object.create(null);return Object.keys(e).forEach(i=>{t[i]=new Map(e[i])}),t}function $S(e){return/\.(x?html?|xht|svg)(?:[#?]|$)/i.test(e)||/^(?:about:|data:|blob:)/i.test(pt(e))}var nc=class extends MS{constructor(){super(null),u(this,"plainXMLStore"),u(this,"jsonStore"),u(this,"opfByURL",{}),u(this,"primaryOPFByEPubURL",{}),u(this,"deobfuscators",{}),u(this,"documents",{}),this.fontDeobfuscator=this.makeDeobfuscatorFactory(),this.plainXMLStore=TS(),this.jsonStore=Qy()}makeDeobfuscatorFactory(){return e=>this.deobfuscators[e]}loadAsPlainXML(e,t,i){return this.plainXMLStore.load(e,t,i)}startLoadingAsPlainXML(e){this.plainXMLStore.fetch(e)}loadAsJSON(e,t,i){return this.jsonStore.load(e,t,i)}loadWebPubManifest(e,t){this.loadAsJSON(e,!0).then(i=>{if(!i){this.reportLoadError(e),t.finish(null);return}let n=new Zr(this,e);n.initWithWebPubManifest(i,void 0,e).then(()=>{t.finish(n)})})}loadPubDoc(e){let t=M("loadPubDoc");if(/\.opf(?:[#?]|$)/i.test(e)){let[,i,n]=e.match(/^((?:.*\/)?)([^/]*)$/);this.loadOPF(i,n).thenFinish(t)}else/\.json(?:ld)?(?:[#?]|$)/i.test(e)?this.loadWebPubManifest(e,t):$S(e)?this.loadWebPub(e).then(i=>{if(i){t.finish(i);return}this.reportLoadError(e),t.finish(null)}):Os(e,null,"HEAD").then(i=>{if(i.status>=400)this.loadEPUBDoc(e).then(n=>{if(n){t.finish(n);return}Y.error(`Failed to fetch a source document from ${e} (${i.status}${i.statusText?" "+i.statusText:""})`),t.finish(null)});else if(!i.status&&!i.responseXML&&!i.responseText&&!i.responseBlob&&!i.contentType&&/\/[^/.]+(?:[#?]|$)/.test(e)&&(e=e.replace(/([#?]|$)/,"/$1")),i.contentType=="application/oebps-package+xml"){let[,n,o]=e.match(/^((?:.*\/)?)([^/]*)$/);this.loadOPF(n,o).thenFinish(t)}else i.contentType=="application/ld+json"||i.contentType=="application/webpub+json"||i.contentType=="application/audiobook+json"||i.contentType=="application/json"?this.loadWebPubManifest(e,t):this.loadWebPub(e).then(n=>{if(n){t.finish(n);return}this.loadEPUBDoc(e).then(o=>{if(o){t.finish(o);return}this.reportLoadError(e),t.finish(null)})})});return t.result()}loadEPUBDoc(e){let t=M("loadEPUBDoc");e.endsWith("/")||(e=e+"/"),this.startLoadingAsPlainXML(e+"META-INF/encryption.xml");let i=e+"META-INF/container.xml";return this.loadAsPlainXML(i).then(n=>{if(n){let o=n.doc().child("container").child("rootfiles").child("rootfile").attribute("full-path");for(let r of o)if(r){this.loadOPF(e,r).thenFinish(t);return}}t.finish(null)}),t.result()}loadOPF(e,t){let i=e+t,n=this.opfByURL[i];if(n)return T(n);let o=M("loadOPF");return this.loadAsPlainXML(i,!0,`Failed to fetch EPUB OPF ${i}`).then(r=>{r?(n=new Zr(this,e),this.opfByURL[i]=n,this.primaryOPFByEPubURL[e]=n,this.plainXMLStore.resources[e+"META-INF/container.xml"]?this.loadAsPlainXML(e+"META-INF/encryption.xml").then(s=>{n.initWithXMLDoc(r,s).then(()=>{o.finish(n)})}):n.initWithXMLDoc(r,null).then(()=>{o.finish(n)})):this.reportLoadError(i)}),o.result()}loadWebPub(e){let t=M("loadWebPub");return this.load(e).then(i=>{if(!i)this.reportLoadError(e),t.finish(null);else if(i.document.querySelector("a[href='META-INF/'],a[href$='/META-INF/']"))t.finish(null);else{let n=i.document,o=new Zr(this,e),r=n.querySelector("link[rel='publication'],link[rel='manifest'][type='application/webpub+json']");if(r){let s=r.getAttribute("href");if(/^#/.test(s)){let a=kl(n.getElementById(s.substr(1)).textContent);o.initWithWebPubManifest(a,n).then(()=>{t.finish(o)})}else{let a=Ae(r.getAttribute("href"),e);this.loadAsJSON(a,!0,`Failed to fetch Publication Manifest ${a}`).then(h=>{o.initWithWebPubManifest(h,n,a).then(()=>{t.finish(o)})})}}else o.initWithWebPubManifest({},n).then(()=>{o.toc&&o.toc.src===i.url&&bh(n).length===0&&(o.toc=null),t.finish(o)})}}),t.result()}addDocument(e,t){let i=M("EPUBDocStore.load"),n=pt(e);return(this.documents[n]=this.parseOPSResource({status:200,statusText:"",url:n,contentType:t.contentType,responseText:null,responseXML:t,responseBlob:null})).thenFinish(i),i.result()}reportLoadError(e){let t=n=>n.replace(/([^:/?#]|^)[/?#].*/,"$1"),i=()=>{let n=t(e);return!(n===t(Ji)||Object.keys(this.resources).find(o=>this.resources[o]&&t(o)===n)||!/^https?:?\/\/[^/]/.test(e)||/\.(xhtml|xht|xml|opf)$/i.test(e))};e.startsWith("data:")?Y.error(`Failed to load ${e}. Invalid data.`):e.startsWith("http:")&&Ji.startsWith("https:")&&!/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(?:[/?#]|$)/.test(e)?Y.error(`Failed to load ${e}. Mixed Content ("http:" content on "https:" context) is not allowed.`):i()?Y.error(`Failed to load ${e}. This may be caused by network error, incorrect URL, or the server not allowing cross-origin resource sharing (CORS).`):Y.error(`Failed to load ${e}. The target resource is invalid.`)}load(e){let t=pt(e),i=this.documents[t];if(i)return i.isPending()?i:T(i.get());{let n=M("EPUBDocStore.load");return i=super.load(t,!0,`Failed to fetch a source document from ${t}`),i.then(o=>{o?n.finish(o):this.reportLoadError(t)}),n.result()}}processViewportMeta(e){let t=e.getAttribute("content");if(!t)return"";let i={},n;for(;(n=t.match(/^,?\s*([-A-Za-z_.][-A-Za-z_0-9.]*)\s*=\s*([-+A-Za-z_0-9.]*)\s*/))!=null;)t=t.substr(n[0].length),i[n[1]]=n[2];let o=i.width-0,r=i.height-0;if(o&&r){let s=!!Object.values(this.primaryOPFByEPubURL).find(a=>a.prePaginated);return`@-epubx-viewport{width:${o}px;height:${r}px;}`+(s?`@page{size:${o}px ${r}px;margin:0;}`:"@page{margin:0;}")}return""}},oc=class{constructor(){u(this,"id",null),u(this,"src",""),u(this,"mediaType",null),u(this,"title",null),u(this,"itemRefElement",null),u(this,"spineIndex",-1),u(this,"compressedSize",0),u(this,"compressed",null),u(this,"epage",0),u(this,"epageCount",0),u(this,"startPage",null),u(this,"skipPagesBefore",null),u(this,"itemProperties"),this.itemProperties=Kg}initWithElement(e,t){this.id=e.getAttribute("id"),this.src=Ae(e.getAttribute("href"),t),this.mediaType=e.getAttribute("media-type");let i=e.getAttribute("properties");i&&(this.itemProperties=om(i.split(/\s+/)))}initWithParam(e){this.spineIndex=e.index,this.id=`item${e.index+1}`,this.src=e.url,this.startPage=e.startPage,this.skipPagesBefore=e.skipPagesBefore}};function HS(e){return e.id}function WS(e){return t=>{let i=M("deobfuscator");return GS("SHA-1",e).then(n=>{let o=t.slice(0,1040),r=t.slice(1040,t.size);Zy(o).then(s=>{let a=new DataView(s);for(let h=0;h<a.byteLength;h++){let l=a.getUint8(h);l^=n[h%20],a.setUint8(h,l)}i.finish(Fd([a,r]))})}),i.result()}}function GS(e,t){let i=M("makeDigest"),n=i.suspend();return window.crypto.subtle.digest(e,new TextEncoder().encode(t)).then(o=>{n.schedule(new Uint8Array(o))}),i.result()}var Pi={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"},yo="http://idpf.org/epub/vocab/package/meta/#",qe={language:`${Pi.dcterms}language`,title:`${Pi.dcterms}title`,creator:`${Pi.dcterms}creator`,layout:`${Pi.rendition}layout`,titleType:`${yo}title-type`,displaySeq:`${yo}display-seq`,alternateScript:`${yo}alternate-script`,role:`${yo}role`};function jS(e,t){let i={};return(n,o)=>{var r,s,a,h,l,c;let d,p,f=n.r||i,g=o.r||i;if(e==qe.title&&(d=((r=f[qe.titleType])==null?void 0:r[0].v)=="main",p=((s=g[qe.titleType])==null?void 0:s[0].v)=="main",d!=p))return d?-1:1;let v=parseInt((a=f[qe.displaySeq])==null?void 0:a[0].v,10);isNaN(v)&&(v=Number.MAX_VALUE);let w=parseInt((h=g[qe.displaySeq])==null?void 0:h[0].v,10);return isNaN(w)&&(w=Number.MAX_VALUE),v!=w?v-w:e!=qe.language&&t&&(d=((l=f[qe.language]||f[qe.alternateScript])==null?void 0:l[0].v)==t,p=((c=g[qe.language]||g[qe.alternateScript])==null?void 0:c[0].v)==t,d!=p)?d?-1:1:n.o-o.o}}function XS(e,t){let i;if(!t)i=Pi;else{i={};for(let p in Pi)i[p]=Pi[p];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),i[d[1]]=d[2]}let n=d=>{if(d){let p=d.match(/^\s*(([^:]*):)?(\S+)\s*$/);if(p){let f=p[2]?i[p[2]]:yo;if(f)return f+p[3]}}return null},o=1,r=e.childElements().forEachNonNull(d=>{if(d.localName=="meta"){let p=n(d.getAttribute("property"));if(p)return{name:p,value:d.textContent,id:d.getAttribute("id"),order:o++,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:Pi.dcterms+d.localName,order:o++,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}),s=ea(r,d=>d.refines),a=d=>rm(d,(p,f)=>p.map(g=>{let v={v:g.value,o:g.order};g.scheme&&(v.s=g.scheme);let w=s[`#${g.id}`]||[];if(w.length||g.lang||g.role){g.lang&&w.push({name:qe.language,value:g.lang,lang:null,id:null,refines:g.id,scheme:null,order:g.order,role:null}),g.role&&w.push({name:qe.role,value:g.role,lang:null,id:null,refines:g.id,scheme:null,order:g.order,role:null});let x=ea(w,m=>m.name);v.r=a(x)}return v})),h=a(ea(r,d=>d.refines?null:d.name)),l=null;h[qe.language]&&(l=h[qe.language][0].v);let c=d=>{for(let p in d){let f=d[p];f.sort(jS(p,l));for(let g=0;g<f.length;g++){let v=f[g].r;v&&c(v)}}};return c(h),h}function qS(){let e=window.MathJax;return e?e.Hub:null}var rc={"application/xhtml+xml":!0,"image/jpeg":!0,"image/png":!0,"image/svg+xml":!0,"image/gif":!0,"audio/mp3":!0},ba="viv-id-",Zr=class{constructor(e,t){u(this,"store",e),u(this,"pubURL",t),u(this,"opfXML",null),u(this,"encXML",null),u(this,"items",null),u(this,"spine",null),u(this,"itemMap",null),u(this,"itemMapByPath",null),u(this,"uid",null),u(this,"bindings",{}),u(this,"lang",null),u(this,"epageCount",0),u(this,"prePaginated",!1),u(this,"epageIsRenderedPage",!0),u(this,"epageCountCallback",null),u(this,"metadata",{}),u(this,"toc",null),u(this,"cover",null),u(this,"fallbackMap",{}),u(this,"pageProgression",null),u(this,"documentURLTransformer"),this.documentURLTransformer=this.createDocumentURLTransformer()}createDocumentURLTransformer(){let e=this;class t{constructor(){u(this,"canonicalDocumentURLCache",new Map)}getCanonicalDocumentURL(n){var o,r;let s=pt(dn(n)),a=this.canonicalDocumentURLCache.get(s);if(a)return a;for(let h of e.spine){let l=pt(dn(h.src));if(l===s)return this.canonicalDocumentURLCache.set(s,l),l;let c=(r=(o=e.store)==null?void 0:o.get(l))==null?void 0:r.url;if(c&&pt(dn(c))===s)return this.canonicalDocumentURLCache.set(s,l),l}return this.canonicalDocumentURLCache.set(s,s),s}transformFragment(n,o){let r=this.getCanonicalDocumentURL(o)+(n?`#${n}`:"");return ba+Cc(r,":")}transformURL(n,o){let r=n.match(/^([^#]*)#?(.*)$/);if(r){let s=this.getCanonicalDocumentURL(r[1]||dn(o)),a=decodeURIComponent(r[2]);if(s&&e.spine.some(h=>pt(dn(h.src))===s))return`#${this.transformFragment(a,s)}`}return n}restoreURL(n){n.charAt(0)==="#"&&(n=n.substring(1)),n.indexOf(ba)===0&&(n=n.substring(ba.length));let o=nm(n,":").match(/^([^#]*)#?(.*)$/);return o?[o[1],o[2]]:[]}}return new t}getMetadata(){return this.metadata}getPathFromURL(e){if(e.startsWith("data:"))return e===this.pubURL?"":e;if(this.pubURL){let t=Ae("",this.pubURL);return e===t||e+"/"===t?"":(t.charAt(t.length-1)!="/"&&(t+="/"),e.substr(0,t.length)==t?decodeURIComponent(e.substr(t.length)):null)}else return e}initWithXMLDoc(e,t){this.opfXML=e,this.encXML=t;let i=e.doc().child("package"),n=i.attribute("unique-identifier")[0];if(n){let h=e.getElement(`${e.url}#${n}`);h&&(this.uid=h.textContent.replace(/[ \n\r\t]/g,""))}let o={};this.items=i.child("manifest").child("item").asArray().map(h=>{let l=new oc,c=h;l.initWithElement(c,e.url);let d=c.getAttribute("fallback");return d&&!rc[l.mediaType]&&(o[l.src]=d),!this.toc&&l.itemProperties.nav&&(this.toc=l),!this.cover&&l.itemProperties["cover-image"]&&(this.cover=l),l}),this.itemMap=Fh(this.items,HS),this.itemMapByPath=Fh(this.items,h=>this.getPathFromURL(h.src));for(let h in o){let l=h;for(;;){let c=this.itemMap[o[l]];if(!c)break;if(rc[c.mediaType]){this.fallbackMap[h]=c.src;break}l=c.src}}this.spine=i.child("spine").child("itemref").asArray().map((h,l)=>{let c=h,d=c.getAttribute("idref"),p=this.itemMap[d];return p&&(p.itemRefElement=c,p.spineIndex=l),p});let r=i.child("spine").attribute("page-progression-direction")[0];r&&(this.pageProgression=gc(r));let s=t?t.doc().child("encryption").child("EncryptedData").predicate(Qu.withChild("EncryptionMethod",Qu.withAttribute("Algorithm","http://www.idpf.org/2008/embedding"))).child("CipherData").child("CipherReference").attribute("URI"):[],a=i.child("bindings").child("mediaType").asArray();for(let h=0;h<a.length;h++){let l=a[h].getAttribute("handler"),c=a[h].getAttribute("media-type");c&&l&&this.itemMap[l]&&(this.bindings[c]=this.itemMap[l].src)}if(this.metadata=XS(i.child("metadata"),i.attribute("prefix")[0]),this.metadata[qe.language]&&(this.lang=this.metadata[qe.language][0].v),this.metadata[qe.layout]&&(this.prePaginated=this.metadata[qe.layout][0].v==="pre-paginated"),s.length>0&&this.uid){let h=WS(this.uid);for(let l=0;l<s.length;l++)this.store.deobfuscators[this.pubURL+s[l]]=h}return this.prePaginated&&this.assignAutoPages(),T(!0)}assignAutoPages(){let e=0;for(let t of this.spine){let i=this.prePaginated?1:Math.ceil(t.compressedSize/1024);t.epage=e,t.epageCount=i,e+=i}this.epageCount=e,this.epageCountCallback&&this.epageCountCallback(this.epageCount)}setEPageCountMode(e){this.epageIsRenderedPage=e||this.prePaginated}countEPages(e){if(this.epageCountCallback=e,this.epageIsRenderedPage)return this.prePaginated&&this.epageCount==0&&this.assignAutoPages(),T(!0);let t=0,i=0,n=M("countEPages");return n.loopWithFrame(o=>{if(i===this.spine.length){o.breakLoop();return}let r=this.spine[i++];r.epage=t,this.store.load(r.src).then(s=>{if(!s){o.continueLoop();return}let a=1800,h=s.lang||this.lang;h&&h.match(/^(ja|ko|zh)/)&&(a/=3),r.epageCount=Math.ceil(s.getTotalOffset()/a),t+=r.epageCount,this.epageCount=t,this.epageCountCallback&&this.epageCountCallback(this.epageCount),o.continueLoop()})}).thenFinish(n),n.result()}initWithChapters(e,t){this.itemMap={},this.itemMapByPath={},this.items=[],this.spine=this.items;let i=this.opfXML=new dg(null,"",new DOMParser().parseFromString("<spine></spine>","text/xml"));return e.forEach(n=>{let o=new oc;o.initWithParam(n),o.id;let r=i.document.createElement("itemref");r.setAttribute("idref",o.id),i.root.appendChild(r),o.itemRefElement=r,this.itemMap[o.id]=o;let s=this.getPathFromURL(n.url);s==null&&(s=n.url),this.itemMapByPath[s]=o,this.items.push(o)}),t?this.store.addDocument(e[0].url,t):T(null)}initWithWebPubManifest(e,t,i){var n,o,r,s;e.readingProgression&&(this.pageProgression=e.readingProgression),this.metadata===void 0&&(this.metadata={});let a=e.name||((n=e.metadata)==null?void 0:n.title)||t?.title;a&&(this.metadata[qe.title]=(Array.isArray(a)?a:[a]).map(x=>{var m;return{v:(m=x.value)!=null?m:x}}));let h=e.author||e.creator||((o=e.metadata)==null?void 0:o.author)||Array.from((r=t?.querySelectorAll("meta[name='author'], meta[name='DC.Creator']"))!=null?r:[]).map(x=>x.content);h&&h.length!==0&&(this.metadata[qe.creator]=(Array.isArray(h)?h:[h]).map(x=>{var m;return{v:(m=x.name)!=null?m:x}}));let l=e.inLanguage||((s=e.metadata)==null?void 0:s.language)||t?.documentElement.lang||t?.documentElement.getAttribute("xml:lang");l&&(this.metadata[qe.language]=(Array.isArray(l)?l:[l]).map(x=>({v:x})));let c=pt(this.pubURL),d=this.getPathFromURL(c),p=d!==null?encodeURI(d):/^(?:about:|blob:)/i.test(c)?c:null;if(!e.readingOrder&&t&&p!==null){e.readingOrder=[p];for(let x of DS(t)){let m=x.getAttribute("href");if(/^(https?:)?\/\//.test(m)||/\.(jpe?g|png|gif|pdf|svg|mml)([#?]|$)/.test(m))continue;let S=pt(Ae(m,this.pubURL)),b=this.getPathFromURL(S),C=b!==null?encodeURI(b):S;e.readingOrder.indexOf(C)==-1&&e.readingOrder.push(C)}}let f=[],g=0,v=-1;[e.readingOrder,e.resources].forEach(x=>{x instanceof Array&&x.forEach(m=>{let S=x===e.readingOrder,b=typeof m=="string"?m:m.url||m.href,C=typeof m=="string"?"":m.encodingFormat||m.href&&m.type||"";if(S||C==="text/html"||C==="application/xhtml+xml"||!C&&m.rel!=="stylesheet"&&/(^|\/)([^/]+\.(x?html|htm|xht)|[^/.]*)([#?]|$)/.test(b)){let P=i?i.replace(/\/[^/]+$/,"/"):this.pubURL,L={url:Ae(Fn(b),P),index:g++,startPage:null,skipPagesBefore:null};m.rel==="contents"&&v===-1&&(v=L.index),f.push(L)}})});let w=M("initWithWebPubManifest");return this.initWithChapters(f).then(()=>{var x,m;v!==-1&&(this.toc=this.items[v]),this.toc||(this.toc=i?(x=this.items)==null?void 0:x[0]:this.itemMapByPath[d]);let S=(m=e.readingOrder)==null?void 0:m.length;S&&S<this.items.length&&this.items.splice(S),w.finish(!0)}),w.result()}getCFI(e,t){let i=this.spine[e],n=M("getCFI");return this.store.load(i.src).then(o=>{let r=o.getNodeByOffset(t),s=null;if(r){let a=o.getNodeOffset(r,0,!1),h=t-a,l=new Wh;l.prependPathFromNode(r,h,!1,null),i.itemRefElement&&l.prependPathFromNode(i.itemRefElement,0,!1,null),s=l.toString()}n.finish(s)}),n.result()}resolveFragment(e){return _n("resolveFragment",t=>{if(!e){t.finish(null);return}let i=new Wh;i.fromString(e);let n;if(this.opfXML){let o=i.navigate(this.opfXML.document);if(o.node.nodeType!=1||o.after||!o.ref){t.finish(null);return}let r=o.node,s=r.getAttribute("idref");if(r.localName!="itemref"||!s||!this.itemMap[s]){t.finish(null);return}n=this.itemMap[s],i=o.ref}else n=this.spine[0];this.store.load(n.src).then(o=>{let r=i.navigate(o.document),s=o.getNodeOffset(r.node,r.offset,r.after);t.finish({spineIndex:n.spineIndex,offsetInItem:s,pageIndex:-1})})},(t,i)=>{Y.warn(i,"Cannot resolve fragment:",e),t.finish(null)})}resolveEPage(e){return _n("resolveEPage",t=>{if(e<=0){t.finish({spineIndex:0,offsetInItem:0,pageIndex:-1});return}if(this.epageIsRenderedPage){let o=this.spine.findIndex(a=>a.epage==0&&a.epageCount==0||a.epage<=e&&a.epage+a.epageCount>e);o==-1&&(o=this.spine.length-1);let r=this.spine[o];(!r||r.epageCount==0)&&(r=this.spine[--o]);let s=Math.floor(e-r.epage);t.finish({spineIndex:o,offsetInItem:-1,pageIndex:s});return}let i=mi(this.spine.length,o=>{let r=this.spine[o];return r.epage+r.epageCount>e});i==this.spine.length&&i--;let n=this.spine[i];this.store.load(n.src).then(o=>{e-=n.epage,e>n.epageCount&&(e=n.epageCount);let r=0;if(e>0){let s=o.getTotalOffset();r=Math.round(s*e/n.epageCount),r==s&&r--}t.finish({spineIndex:i,offsetInItem:r,pageIndex:-1})})},(t,i)=>{Y.warn(i,"Cannot resolve epage:",e),t.finish(null)})}getEPageFromPosition(e){let t=this.spine[e.spineIndex];if(this.epageIsRenderedPage){let n=t.epage+e.pageIndex;return T(n)}if(e.offsetInItem<=0)return T(t.epage);let i=M("getEPage");return this.store.load(t.src).then(n=>{let o=n.getTotalOffset(),r=Math.min(o,e.offsetInItem);i.finish(t.epage+r*t.epageCount/o)}),i.result()}},Fr=(e,t)=>({page:e,position:{spineIndex:e.spineIndex,pageIndex:t,offsetInItem:e.offset}}),YS=class{constructor(e,t,i,n,o,r){u(this,"opf",e),u(this,"viewport",t),u(this,"fontMapper",i),u(this,"pageSheetSizeReporter",o),u(this,"spineItems",[]),u(this,"spineItemLoadingContinuations",[]),u(this,"pref"),u(this,"clientLayout"),u(this,"counterStore"),u(this,"cmykStore"),u(this,"tocAutohide",!1),u(this,"tocVisible",!1),u(this,"tocView"),u(this,"paginationProgress",{totalOffsetsBySpine:[],renderedOffsetsBySpine:[],totalOffsetsReady:!1,lastReportedPages:0,lastReportedFraction:0}),this.pref=Pc(n),this.clientLayout=new Wx(t),this.counterStore=new Km(e.documentURLTransformer),this.cmykStore=new ed,r!=null&&r.length&&this.cmykStore.registerCmykReserveMap(r)}getPage(e){let t=this.spineItems[e.spineIndex];return t?t.pages[e.pageIndex]:null}waitForPreviousSpines(e,t){if(t||e===0)return T(!0);let i=M("waitForPreviousSpines");return i.loopWithFrame(n=>{let o=!0;for(let r=0;r<e;r++){let s=this.spineItems[r];if(!s||!s.complete){o=!1;break}}o?n.breakLoop():i.sleep(100).then(()=>{n.continueLoop()})}).then(()=>{i.finish(!0)}),i.result()}getCurrentPageProgression(e){if(this.opf.pageProgression)return this.opf.pageProgression;{let t=this.spineItems[e?e.spineIndex:0];return t?t.instance.pageProgression:null}}finishPageContainer(e,t,i){t.container.style.display="none",t.container.style.visibility="visible",t.container.style.position="",t.container.style.top="",t.container.style.left="",t.container.setAttribute("data-vivliostyle-page-side",t.side);let n=e.pages[i];if(t.isFirstPage=e.item.spineIndex==0&&i==0,e.pages[i]=t,this.opf.epageIsRenderedPage){if(i==0&&e.item.spineIndex>0){let o=this.opf.spine[e.item.spineIndex-1];e.item.epage=o.epage+o.epageCount}e.item.epageCount=e.pages.length,this.opf.epageCount=this.opf.spine.reduce((o,r)=>o+r.epageCount,0),this.opf.epageCountCallback&&this.opf.epageCountCallback(this.opf.epageCount)}if(n)e.instance.viewport.contentContainer.replaceChild(t.container,n.container),n.dispatchEvent({type:"replaced",target:null,currentTarget:null,preventDefault:null,newPage:t});else{let o=null;if(i>0)o=e.pages[i-1].container.nextElementSibling;else for(let r=e.item.spineIndex+1;r<this.spineItems.length;r++){let s=this.spineItems[r];if(s&&s.pages[0]){o=s.pages[0].container;break}}e.instance.viewport.contentContainer.insertBefore(t.container,o)}this.pageSheetSizeReporter({width:e.instance.pageSheetWidth,height:e.instance.pageSheetHeight},e.instance.pageSheetSize,e.item.spineIndex,e.instance.pageNumberOffset+i)}getRenderedPageCount(){let e=0;for(let t of this.spineItems)t&&(e+=t.pages.length);return e}markSpineItemCompleteIfReady(e){e.complete=e.layoutPositions.length===e.pages.length,e.complete&&e.instance.viewport.layoutBox.removeAttribute("style")}getTotalOffsetForViewItem(e){let t=e.item.spineIndex,i=this.paginationProgress.totalOffsetsBySpine[t];return i==null&&(i=e.xmldoc.getTotalOffset(),this.paginationProgress.totalOffsetsBySpine[t]=i),i}collectTotalOffsets(){if(this.paginationProgress.totalOffsetsReady)return T(!0);let e=this.paginationProgress.totalOffsetsBySpine,t=0,i=M("collectTotalOffsets");return i.loopWithFrame(n=>{if(t===this.opf.spine.length){n.breakLoop();return}let o=t++;if(e[o]!=null){n.continueLoop();return}let r=this.opf.spine[o];this.opf.store.load(r.src).then(s=>{s&&(e[o]=s.getTotalOffset()),n.continueLoop()})}).then(()=>{this.paginationProgress.totalOffsetsReady=!0,i.finish(!0)}),i.result()}getTotalOffsetAll(){let e=0;for(let t of this.paginationProgress.totalOffsetsBySpine)t&&(e+=t);return e}getRenderedOffsetAll(){var e;let t=0,i=this.paginationProgress.totalOffsetsBySpine,n=this.paginationProgress.renderedOffsetsBySpine;for(let o=0;o<i.length;o++){let r=i[o];if(!r)continue;let s=(e=n[o])!=null?e:0;t+=Math.min(r,s)}return t}reportPaginationProgress(e,t){let i=_t("PAGINATION_PROGRESS");if(!i.length)return;let n=e.item.spineIndex,o=this.getTotalOffsetForViewItem(e),r=o;t&&(r=e.instance.getPosition(t,!0)),r<0&&(r=0),r>o&&(r=o);let s=this.paginationProgress.renderedOffsetsBySpine[n];s!=null&&r<s&&(r=s),this.paginationProgress.renderedOffsetsBySpine[n]=r;let a=this.getRenderedPageCount(),h=this.getTotalOffsetAll(),l=this.getRenderedOffsetAll(),c=h>0?l/h:0;c<this.paginationProgress.lastReportedFraction?c=this.paginationProgress.lastReportedFraction:this.paginationProgress.lastReportedFraction=c,a>this.paginationProgress.lastReportedPages&&(this.paginationProgress.lastReportedPages=a);let d={fraction:c,pages:this.paginationProgress.lastReportedPages,href:e.item.src};for(let p of i)try{p(d)}catch(f){Y.warn(f)}}isInCounterResolveScope(){return this.counterStore.currentPageCountersStack.length>0}hasNonEmptyPageType(e){return!!(e!=null&&e.pageType)&&e.pageType!==""}hasPageTypeBoundaryBetween(e,t){return e?.pageType!=null&&t?.pageType!=null&&e.pageType!==t.pageType}resolvePageTypeForRenderSlot(e,t,i,n,o,r,s){let a=!1;if(n){let h=this.hasPageTypeBoundaryBetween(o,n),l=r?.pageType===n.pageType,c=n.offset!==t.offset,d=s&&!c&&i>0;if(a=n.pageType!=null&&(d||i===0||n.pageType===o?.pageType),t.pageType=a?n.pageType:null,s){let p=e.instance.getPageStartPageTypeOverride(t.position);p===""?t.pageType="":p&&(t.pageType=p)}if(!s&&!a){let p=i>1&&h&&l?o.pageType:null;e.instance.styler.cascade.currentPageType=p,e.instance.pageManager.pageCascadeInstance.currentPageType=p}}!s&&this.hasNonEmptyPageType(o)&&this.hasNonEmptyPageType(r)&&o.pageType!==r.pageType&&(!n||n.pageType==null)&&(t.pageType=o.pageType)}evaluateNextPageRelayout(e,t,i,n,o){if(!e||t&&!i)return{needsRelayout:!1,shouldCascade:!1};let r=!!t&&(e.pageType===t.pageType||!t.pageType);return t&&n&&(!o||r)&&(t.pageType==null||e.pageType==null||e.pageType!==t.pageType)&&(t.pageType=null),{needsRelayout:!0,shouldCascade:!!t||!o}}preparePageCountersForRender(e,t){let i=e.pages[t],n=e.pageCounterStarts[t];i&&n&&(this.counterStore.currentPageCounters=Ir(n));let o=Ir(this.counterStore.currentPageCounters);return(!n||!i)&&(e.pageCounterStarts[t]=o),i}maybeRelayoutFollowingPage(e,t,i,n){if(!t)return T(!0);let o=e.layoutPositions[t.page];e.layoutPositions[t.page]=t;let r=e.pages[t.page],s=!!i&&n.offset!==i.offset,a=e.instance.hasActiveRootPageFloatLayoutContext(),h=!o||!t.isSamePosition(o)||t.highestSeenOffset!==o.highestSeenOffset||s||a,l=this.isInCounterResolveScope(),c=this.evaluateNextPageRelayout(i,r,h,s,l);return c.needsRelayout?(e.complete=!1,c.shouldCascade?this.renderSinglePage(e,t):T(!0)):T(!0)}resolveUnresolvedReferencesForPage(e,t,i,n){let o=M("resolveUnresolvedReferencesForPage"),r=this.isInCounterResolveScope()?[]:this.counterStore.getUnresolvedRefsToPage(t),s=0,a=t;return o.loopWithFrame(h=>{if(s++,s>r.length){h.breakLoop();return}let l=r[s-1];if(l.refs=l.refs.filter(c=>!c.isResolved()),l.refs.length===0){h.continueLoop();return}this.getPageViewItem(l.spineIndex).then(c=>{var d;if(!c){h.continueLoop();return}let p=c.instance.styler.cascade,f=c.instance.pageManager.pageCascadeInstance,g={currentPageType:p.currentPageType,previousPageType:p.previousPageType},v={currentPageType:f.currentPageType,previousPageType:f.previousPageType},w=US(c.instance.pageGroupPageCounts),x=c.instance.currentPageGroupDocument,m=c.instance.scopes;c.instance.scopes={};let S=l.pageIndex<c.pages.length-1,b=!!c.pages[l.pageIndex],C=b&&S,P=C&&l.pageIndex>0?(d=c.pages[l.pageIndex-1])==null?void 0:d.pageFloatLayoutContext:null,L=C?c.instance.beginIsolatedRootPageFloatLayoutContext(P):null;this.counterStore.pushPageCounters(l.pageCounters),this.counterStore.pushReferencesToSolve(l.refs);let A=c.layoutPositions[l.pageIndex];b&&c.instance.preparePageGroupPageIndicesForRerender(c.layoutPositions,l.pageIndex),this.renderSinglePage(c,A).then(z=>{C&&c.instance.endIsolatedRootPageFloatLayoutContext(L);let U=p.currentPageType;p.currentPageType=g.currentPageType,p.previousPageType=g.previousPageType,f.currentPageType=v.currentPageType,f.previousPageType=v.previousPageType,c.instance.pageGroupPageCounts=w,c.instance.currentPageGroupDocument=x,c.instance.scopes=m;let X=Ir(this.counterStore.currentPageCounters);this.counterStore.popPageCounters(),this.counterStore.popReferencesToSolve(),z.pageAndPosition.position.spineIndex===a.spineIndex&&z.pageAndPosition.position.pageIndex===i&&(a=z.pageAndPosition.page),a.pageType&&a.pageType!==g.currentPageType&&U!==z.pageAndPosition.page.pageType&&(p.currentPageType=a.pageType);let oe=c!==e,k=c.pages.length,_=c.layoutPositions[k],F=c.instance.hasActiveRootPageFloatLayoutContext();if(_&&!F){let D=oe?Ir(this.counterStore.currentPageCounters):null;oe&&(this.counterStore.currentPageCounters=X);let E=k;this.renderSinglePage(c,_).then(()=>{oe&&this.markSpineItemCompleteIfReady(c);let N=c.pages.length-E;if(oe&&N>0){this.counterStore.adjustPageCountersOfLaterSpines(c.item.spineIndex,N),this.counterStore.updateTargetCounterNodesInPages(c.pages);let R=c.item.spineIndex;for(let $=R+1;$<this.spineItems.length;$++){let V=this.spineItems[$];if(V){V.item.epage+=N;for(let q of V.pageCounterStarts)q!=null&&q.page&&(q.page=q.page.map(Q=>Q+N));this.counterStore.updatePageCounterNodesInPages(V.pages,V.pageCounterStarts)}}if(D){let $=D.page;$&&(D.page=$.map(V=>V+N))}}D&&(this.counterStore.currentPageCounters=D),h.continueLoop()});return}oe&&this.markSpineItemCompleteIfReady(c),h.continueLoop()})})}).then(()=>{a.container.parentElement||(a=e.pages[i]),a.isLastPage=!n&&e.item.spineIndex===this.opf.spine.length-1,a.isLastPage&&(this.viewport,this.counterStore.finishLastPage(this.viewport)),a.container.setAttribute("data-vivliostyle-page-index",i),a.container.setAttribute("data-vivliostyle-spine-index",a.spineIndex),o.finish(a)}),o.result()}renderSinglePage(e,t){let i=M("renderSinglePage"),n=t?Math.max(t.page,0):0,o=e.instance.getPageNumberContextDepth();e.instance.pushPageNumberContext(n+1);let r=()=>{e.instance.restorePageNumberContextDepth(o)};i.handler=(d,p)=>{r(),d.task.raise(p,d.parent)};let s=this.isInCounterResolveScope(),a=this.preparePageCountersForRender(e,n),h=n>0?e.pages[n-1]:null,l=e.pages[n+1],c=this.makePage(e,t);return this.resolvePageTypeForRenderSlot(e,c,n,a,h,l,s),e.instance.layoutNextPage(c,t).then(d=>{t=d;let p=t?t.page-1:e.layoutPositions.length-1;this.finishPageContainer(e,c,p),this.counterStore.finishPage(c.spineIndex,p),this.reportPaginationProgress(e,t),this.maybeRelayoutFollowingPage(e,t,a,c).thenAsync(()=>this.resolveUnresolvedReferencesForPage(e,c,p,t)).then(f=>{r(),i.finish({pageAndPosition:Fr(f,p),nextLayoutPosition:t})})}),i.result()}normalizeSeekPosition(e,t){let i=e.pageIndex,n=-1;if(i<0){n=e.offsetInItem;let o=mi(t.layoutPositions.length,r=>t.instance.getPosition(t.layoutPositions[r],!0)>n);o===t.layoutPositions.length?t.complete?i=t.pages.length-1:i=Number.POSITIVE_INFINITY:i=o-1}else i===Number.POSITIVE_INFINITY&&e.offsetInItem!==-1&&(n=e.offsetInItem);return{spineIndex:e.spineIndex,pageIndex:i,offsetInItem:n}}findPage(e,t){let i=M("findPage");return this.waitForPreviousSpines(e.spineIndex,t).then(()=>{this.getPageViewItem(e.spineIndex).then(n=>{if(!n){i.finish(null);return}let o=null,r;i.loopWithFrame(s=>{let a=this.normalizeSeekPosition(e,n);r=a.pageIndex,o=n.pages[r],o?s.breakLoop():n.complete?(r=n.pages.length-1,o=n.pages[r],s.breakLoop()):t?this.renderPage(a).then(h=>{h&&(o=h.page,r=h.position.pageIndex),s.breakLoop()}):r<n.layoutPositions.length&&!n.pages[r]?this.renderPage(a).then(h=>{h&&(o=h.page,r=h.position.pageIndex),s.breakLoop()}):i.sleep(100).then(()=>{s.continueLoop()})}).then(()=>{i.finish(Fr(o,r))})})}),i.result()}renderPage(e){let t=M("renderPage");return this.getPageViewItem(e.spineIndex).then(i=>{if(!i){t.finish(null);return}let n=this.normalizeSeekPosition(e,i),o=n.pageIndex,r=n.offsetInItem,s=i.pages[o];if(s){t.finish(Fr(s,o));return}t.loopWithFrame(a=>{if(o<i.layoutPositions.length){a.breakLoop();return}if(i.complete){o=i.pages.length-1,a.breakLoop();return}let h=i.layoutPositions[i.layoutPositions.length-1];this.renderSinglePage(i,h).then(l=>{let c=l.pageAndPosition.page;if(h=l.nextLayoutPosition,h){if(r>=0&&i.instance.getPosition(h)>r){s=c,o=i.layoutPositions.length-2,a.breakLoop();return}a.continueLoop()}else s=c,o=l.pageAndPosition.position.pageIndex,this.markSpineItemCompleteIfReady(i),a.breakLoop()})}).then(()=>{s=s||i.pages[o];let a=i.layoutPositions[o];if(s){t.finish(Fr(s,o));return}this.renderSinglePage(i,a).then(h=>{h.nextLayoutPosition||this.markSpineItemCompleteIfReady(i),t.finish(h.pageAndPosition)})})}),t.result()}renderAllPages(){let e=M("renderAllPages");return(_t("PAGINATION_PROGRESS").length?this.collectTotalOffsets():T(!0)).thenAsync(()=>this.renderPagesUpto({spineIndex:this.opf.spine.length-1,pageIndex:Number.POSITIVE_INFINITY,offsetInItem:-1},!1)).then(t=>{e.loopWithFrame(i=>{this.spineItems.some(n=>n?.pages.some(o=>o?.fetchers.some(r=>!r.arrived)))?e.sleep(100).then(()=>{i.continueLoop()}):i.breakLoop()}).then(()=>{e.finish(t)})}),e.result()}renderPagesUpto(e,t){let i=M("renderPagesUpto");e||(e={spineIndex:0,pageIndex:0,offsetInItem:0});let n=e.spineIndex,o=e.pageIndex,r=0;t&&(r=n);let s;return i.loopWithFrame(a=>{let h={spineIndex:r,pageIndex:r===n?o:Number.POSITIVE_INFINITY,offsetInItem:r===n?e.offsetInItem:-1};this.renderPage(h).then(l=>{s=l,++r>n?a.breakLoop():a.continueLoop()})}).then(()=>{i.finish(s)}),i.result()}firstPage(e,t){return this.findPage({spineIndex:0,pageIndex:0,offsetInItem:-1},t)}lastPage(e,t){return this.findPage({spineIndex:this.opf.spine.length-1,pageIndex:Number.POSITIVE_INFINITY,offsetInItem:-1},t)}nextPage(e,t){let i=e.spineIndex,n=e.pageIndex,o=M("nextPage");return this.getPageViewItem(i).then(r=>{if(!r){o.finish(null);return}if(r.complete&&n==r.pages.length-1){if(i>=this.opf.spine.length-1){o.finish(null);return}i++,n=0;let s=this.spineItems[i],a=s&&s.pages[0],h=r.pages[r.pages.length-1];a&&h&&a.side==h.side&&(s.pages.forEach(l=>{l.container&&l.container.remove()}),this.spineItems[i]=null,this.spineItemLoadingContinuations[i]=null)}else n++;this.findPage({spineIndex:i,pageIndex:n,offsetInItem:-1},t).thenFinish(o)}),o.result()}previousPage(e,t){let i=e.spineIndex,n=e.pageIndex;if(n==0){if(i==0)return T(null);i--,n=Number.POSITIVE_INFINITY}else n--;return this.findPage({spineIndex:i,pageIndex:n,offsetInItem:-1},t)}isRectoPage(e,t){let i=e.side==="left",n=this.getCurrentPageProgression(t)==="ltr";return!i&&n||i&&!n}getSpread(e,t){let i=this.getPage(e);if(!i)return T({left:null,right:null});let n=M("getSpread"),o=i.side==="left",r;return this.isRectoPage(i,e)?r=this.previousPage(e,t):r=this.nextPage(e,t),r.then(s=>{let a=this.getPage(e),h=s&&s.page;h&&h.side===a.side&&(h=null),o?n.finish({left:a,right:h}):n.finish({left:h,right:a})}),n.result()}nextSpread(e,t){let i=this.getPage(e);if(!i)return T(null);let n=this.isRectoPage(i,e),o=this.nextPage(e,t);return n?o:o.thenAsync(r=>{if(r){if(r.page.side===i.side)return o;let s=this.nextPage(r.position,t);return s.thenAsync(a=>a?s:o)}else return T(null)})}previousSpread(e,t){let i=this.getPage(e);if(!i)return T(null);let n=this.isRectoPage(i,e),o=this.previousPage(e,t),r=i.container.previousElementSibling;return n?o.thenAsync(s=>s?s.page.side===i.side||s.page.container!==r?o:this.previousPage(s.position,t):T(null)):o}navigateToEPage(e,t,i){let n=M("navigateToEPage");return this.opf.resolveEPage(e).then(o=>{o?this.findPage(o,i).thenFinish(n):n.finish(null)}),n.result()}navigateToFragment(e,t,i){let n=M("navigateToCFI");return this.opf.resolveFragment(e).then(o=>{o?this.findPage(o,i).thenFinish(n):n.finish(null)}),n.result()}resolveSemanticFootnoteNavigationOffset(e,t){if(!Pt(t))return null;let i=t.getAttribute("id");if(!i)return null;let n=Ae(`#${i}`,e.xmldoc.url),o=e.xmldoc.document.getElementsByTagName("a");for(let r=0;r<o.length;r++){let s=o.item(r);if(!Gt(s))continue;let a=s.getAttribute("href")||s.getAttributeNS("http://www.w3.org/1999/xlink","href");if(a&&Ae(a,e.xmldoc.url)===n)return e.xmldoc.getElementOffset(s)}return null}navigateTo(e,t,i){Y.debug("Navigate to",e);let n=this.opf.getPathFromURL(pt(e));if(!n){if(this.opf.opfXML&&e.match(/^#epubcfi\(/))n=this.opf.getPathFromURL(this.opf.opfXML.url);else if(e.charAt(0)==="#"){let s=this.opf.documentURLTransformer.restoreURL(e);this.opf.opfXML?(n=this.opf.getPathFromURL(s[0]),n==null&&(n=s[0])):n=s[0],e=s[0]+(s[1]?`#${s[1]}`:"")}if(n==null)return T(null)}let o=this.opf.itemMapByPath[n];if(!o){if(this.opf.opfXML&&n==this.opf.getPathFromURL(this.opf.opfXML.url)){let s=e.indexOf("#");if(s>=0)return this.navigateToFragment(e.substr(s+1),t,i)}return T(null)}let r=M("navigateTo");return this.waitForPreviousSpines(o.spineIndex,i).then(()=>{this.getPageViewItem(o.spineIndex).then(s=>{if(!s){r.finish(null);return}let a=s.xmldoc.getElement(e),h=a&&this.resolveSemanticFootnoteNavigationOffset(s,a),l=h??(a?s.xmldoc.getElementOffset(a):0);this.findPage({spineIndex:o.spineIndex,pageIndex:-1,offsetInItem:l},i).thenFinish(r)})}),r.result()}makePage(e,t){let i=e.instance.viewport,n=i.document.createElement("div");n.setAttribute("data-vivliostyle-page-container","true"),n.role="presentation",Io||(n.style.visibility="hidden"),i.layoutBox.appendChild(n);let o=i.document.createElement("div");o.setAttribute("data-vivliostyle-bleed-box","true"),o.role="presentation",n.appendChild(o);let r=new Qd(n,o);if(r.spineIndex=e.item.spineIndex,r.position=t,r.offset=e.instance.getPosition(t),r.offset===0&&!(e.instance.blankPageAtStart&&e.pages.length===0)){let s=this.opf.documentURLTransformer.transformFragment("",e.item.src);o.setAttribute("id",s),r.registerElementWithId(o,s)}if(i!==this.viewport){let s=Nc(this.viewport.width,this.viewport.height,i.width,i.height),a=Ri(null,new xt(s,null),"");r.delayedItems.push(new Ul(n,"transform",a))}return r}makeObjectView(e,t,i,n){let o=t.getAttribute("data"),r=null;if(o){o=Ae(o,e.url);let s=t.getAttribute("media-type");if(!s){let a=this.opf.getPathFromURL(o);if(a){let h=this.opf.itemMapByPath[a];h&&(s=h.mediaType)}}if(s){let a=this.opf.bindings[s];if(a){r=this.viewport.document.createElement("iframe"),r.style.border="none";let h=Ah(o),l=Ah(s),c=new gi;c.append(a),c.append("?src="),c.append(h),c.append("&type="),c.append(l);for(let f=t.firstChild;f;f=f.nextSibling)if(f.nodeType==1){let g=f;if(g.localName=="param"&&g.namespaceURI=="http://www.w3.org/1999/xhtml"){let v=g.getAttribute("name"),w=g.getAttribute("value");v&&w&&(c.append("&"),c.append(encodeURIComponent(v)),c.append("="),c.append(encodeURIComponent(w)))}}r.setAttribute("src",c.toString());let d=t.getAttribute("width");d&&r.setAttribute("width",d);let p=t.getAttribute("height");p&&r.setAttribute("height",p)}}}return r||(r=this.viewport.document.createElement("object"),o&&r.setAttribute("data",Fo(o)),r.setAttribute("data-adapt-process-children","true")),T(r)}makeMathJaxView(e,t,i,n){let o=qS();if(o){let r=i.ownerDocument,s=r.createElement("span");i.appendChild(s);let a=r.importNode(t,!0);this.resolveURLsInMathML(a,e),s.appendChild(a);let h=o.queue;h.Push(["Typeset",o,s]);let l=M("makeMathJaxView"),c=l.suspend();return h.Push(()=>{c.schedule(s)}),l.result()}return T(null)}resolveURLsInMathML(e,t){if(e!=null){if(e.nodeType===1&&e.tagName==="mglyph"){let i=Array.from(e.attributes);for(let n of i){if(n.name!=="src")continue;let o=Ae(n.nodeValue,t.url);n.namespaceURI?e.setAttributeNS(n.namespaceURI,n.name,o):e.setAttribute(n.name,o)}}e.firstChild&&this.resolveURLsInMathML(e.firstChild,t),e.nextSibling&&this.resolveURLsInMathML(e.nextSibling,t)}}makeCustomRenderer(e){return(t,i,n)=>t.localName=="object"&&t.namespaceURI=="http://www.w3.org/1999/xhtml"?this.makeObjectView(e,t,i,n):t.namespaceURI=="http://www.w3.org/1998/Math/MathML"?this.makeMathJaxView(e,t,i,n):t.dataset&&t.dataset.mathTypeset=="true"?this.makeMathJaxView(e,t,i,n):T(null)}getPageViewItem(e){if(e===-1||e>=this.opf.spine.length)return T(null);let t=this.spineItems[e];if(t)return T(t);let i=M("getPageViewItem"),n=this.spineItemLoadingContinuations[e];if(n){let s=i.suspend();return n.push(s),i.result()}else n=this.spineItemLoadingContinuations[e]=[];let o=this.opf.spine[e],r=this.opf.store;return r.load(o.src).then(s=>{var a;let h=o.itemRefElement.getAttribute("properties");h&&s.root.setAttribute("data-vivliostyle-epub-spine-properties",h),o.title=s.document.title;let l=r.getStyleForDoc(s),c=this.makeCustomRenderer(s),d=this.viewport,p=l.sizeViewport(d.width,d.height,d.fontSize,this.pref);(p.width!=d.width||p.height!=d.height||p.fontSize!=d.fontSize)&&(d=new Es(d.window,p.fontSize,d.pixelRatio,d.root,p.width,p.height));let f=(a=this.spineItems[0])==null?void 0:a.instance.isVersoFirstPage,g=this.spineItems[e-1],v,w;if(o.startPage!==null)v=o.startPage-1,w=v;else{if(e>0&&(!g||!g.complete))v=o.epage||e,!this.opf.prePaginated&&v%2==(f?1:0)&&v++,w=v;else{v=g?g.instance.pageNumberOffset+g.pages.length:0;let S=g&&g.pageCounterStarts[g.pages.length-1],b=S&&S.page;if(b&&b.length)w=b[b.length-1]+1;else{let C=this.counterStore.currentPageCounters.page;w=!C||!C.length?v:C[C.length-1]}}o.skipPagesBefore!==null&&(v+=o.skipPagesBefore,w+=o.skipPagesBefore)}this.counterStore.forceSetPageCounter(w);let x=new wh(l,s,this.opf.lang,d,this.clientLayout,this.fontMapper,c,this.opf.fallbackMap,v,this.opf.documentURLTransformer,this.counterStore,this.cmykStore,this.opf.pageProgression,f);x.pref=this.pref;let m=this.opf.metadata&&this.opf.metadata[qe.title];x.pubTitle=m&&m[0]&&m[0].v||"",x.docTitle=o.title||"",x.init().then(()=>{!this.opf.pageProgression&&x.pageProgression&&(this.opf.pageProgression=x.pageProgression),t={item:o,xmldoc:s,instance:x,layoutPositions:[null],pages:[],complete:!1,pageCounterStarts:[]},this.spineItems[e]=t,i.finish(t),n.forEach(S=>{S.schedule(t)})})}),i.result()}removeRenderedPages(){let e=this.spineItems;for(let t of e)t&&t.pages.splice(0);this.viewport.clear()}hasAutoSizedPages(){let e=this.spineItems;for(let t of e)if(t){let i=t.pages;for(let n of i)if(n.isAutoPageWidth&&n.isAutoPageHeight)return!0}return!1}hasPages(){return this.spineItems.some(e=>e&&e.pages.length>0)}showTOC(e){let t=this.opf,i=t.toc;if(this.tocAutohide=e,!i)return T(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"),T(this.tocView.page);let n=M("showTOC");this.tocView||(this.tocView=new zS(t.store,i.src,t.lang,this.clientLayout,this.fontMapper,this.pref,this,t.fallbackMap,t.documentURLTransformer,this.counterStore,this.cmykStore));let o=this.viewport,r=Math.min(344,Math.round(.67*o.width)-16),s=o.height-6,a=o.document.createElement("div");return o.root.appendChild(a),Io||(a.style.visibility="hidden"),a.style.width=`${r+16}px`,a.style.maxHeight=`${s}px`,a.setAttribute("data-vivliostyle-toc-box","true"),a.setAttribute("role","navigation"),this.tocView.showTOC(a,o,r,s,this.viewport.fontSize).then(h=>{a.style.visibility="visible",a.setAttribute("aria-hidden","false"),n.finish(h)}),n.result()}hideTOC(){this.tocVisible=!1,this.tocView&&this.tocView.hideTOC()}isTOCVisible(){return this.tocVisible&&!!this.tocView&&this.tocView.isTOCVisible()}},sc="data-vivliostyle-viewer-status",ZS="data-vivliostyle-spread-view",mg=(e=>(e.SINGLE_PAGE="singlePage",e.SPREAD="spread",e.AUTO_SPREAD="autoSpread",e))(mg||{}),KS=class{constructor(e,t,i,n){u(this,"window",e),u(this,"viewportElement",t),u(this,"instanceId",i),u(this,"callbackFn",n),u(this,"fontMapper"),u(this,"kick"),u(this,"sendCommand"),u(this,"resizeListener"),u(this,"hyperlinkListener"),u(this,"pageRuleStyleElement"),u(this,"pageSheetSizeAlreadySet",!1),u(this,"renderTask",null),u(this,"actions"),u(this,"readyState"),u(this,"packageURL"),u(this,"opf"),u(this,"touchActive"),u(this,"touchX"),u(this,"touchY"),u(this,"needResize"),u(this,"resized"),u(this,"needRefresh"),u(this,"viewportSize"),u(this,"currentPage"),u(this,"currentSpread"),u(this,"pagePosition"),u(this,"fontSize"),u(this,"zoom"),u(this,"fitToScreen"),u(this,"pageViewMode"),u(this,"waitForLoading"),u(this,"renderAllPages"),u(this,"pref"),u(this,"pageSizes"),u(this,"pixelRatio"),u(this,"pixelRatioLimit"),u(this,"viewport"),u(this,"opfView"),u(this,"cmykReserveMap"),u(this,"cmykReserveMapUrl"),u(this,"paginationProgressHook",null);let o=t.ownerDocument,r=(s,a)=>{let h=o.getElementById(s);return h||(h=o.createElement("style"),h.id=s,a&&(h.textContent=a),o.head.appendChild(h)),h};r("vivliostyle-viewport-screen-css",Sd),r("vivliostyle-viewport-css",Cd),r("vivliostyle-polyfill-css",Ad),t.setAttribute("data-vivliostyle-viewer-viewport",!0),Io&&t.setAttribute("data-vivliostyle-debug",!0),t.setAttribute(sc,"loading"),this.fontMapper=new Nx(o.head,t),this.init(),this.kick=()=>{},this.sendCommand=()=>{},this.resizeListener=()=>{this.needResize=!0,this.resized=!0,this.kick()},this.pageReplacedListener=this.pageReplacedListener.bind(this),this.hyperlinkListener=s=>{},this.pageRuleStyleElement=r("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=Ec(),this.pageSizes=[],this.pixelRatioLimit=jo==="chromium"&&"currentCSSZoom"in Element.prototype?16:0,this.pixelRatio=Math.min(8,this.pixelRatioLimit)}addLogListeners(){let e=vc;Y.addListener(e.DEBUG,t=>{this.callback({t:"debug",content:t})}),Y.addListener(e.INFO,t=>{this.callback({t:"info",content:t})}),Y.addListener(e.WARN,t=>{this.callback({t:"warn",content:t})}),Y.addListener(e.ERROR,t=>{this.callback({t:"error",content:t})})}ensurePaginationProgressListener(){if(this.paginationProgressHook)return;let e=t=>{this.callback({t:"paginationprogress",...t})};this.paginationProgressHook=e,Ft("PAGINATION_PROGRESS",e)}removePaginationProgressListener(){this.paginationProgressHook&&(Cl("PAGINATION_PROGRESS",this.paginationProgressHook),this.paginationProgressHook=null)}callback(e){e.i=this.instanceId,this.callbackFn(e)}setReadyState(e){if(this.readyState!==e){this.readyState=e,this.viewportElement.setAttribute(sc,e);let t=this.getCurrentPageProgression();t&&this.viewportElement.setAttribute("data-vivliostyle-page-progression",t),this.callback({t:"readystatechange"})}}loadPublication(e){Nt.registerStartTiming("beforeRender"),this.setReadyState("loading");let t=e.url,i=e.fragment,n=e.authorStyleSheet,o=e.userStyleSheet;this.cmykReserveMapUrl=e.cmykReserveMapUrl,this.viewport=null;let r=M("loadPublication");return this.configure(e).then(()=>{let s=new nc;s.init(n,o).then(()=>{let a=Ae(Fn(t),this.window.location.href);this.packageURL=[a],s.loadPubDoc(a).then(h=>{h?(this.opf=h,this.loadCmykReserveMap(s).then(()=>{this.render(i).then(()=>{r.finish(!0)})})):r.finish(!1)})})}),r.result()}loadXML(e){Nt.registerStartTiming("beforeRender"),this.setReadyState("loading");let t=e.url,i=e.document,n=e.fragment,o=e.authorStyleSheet,r=e.userStyleSheet;this.cmykReserveMapUrl=e.cmykReserveMapUrl,this.viewport=null;let s=M("loadXML");return this.configure(e).then(()=>{let a=new nc;a.init(o,r).then(()=>{let h=t.map((l,c)=>({url:Ae(Fn(l.url),this.window.location.href),index:c,startPage:l.startPage,skipPagesBefore:l.skipPagesBefore}));this.packageURL=h.map(l=>l.url),this.opf=new Zr(a,""),this.opf.initWithChapters(h,i).then(()=>{this.loadCmykReserveMap(a).then(()=>{this.render(n).then(()=>{s.finish(!0)})})})})}),s.result()}render(e){this.cancelRenderingTask();let t;return e?t=this.opf.resolveFragment(e).thenAsync(i=>(this.pagePosition=i,T(!0))):t=T(!0),t.thenAsync(()=>(Nt.registerEndTiming("beforeRender"),this.resize()))}resolveLength(e){let t=parseFloat(e),i=/[a-z]+$/,n;if(typeof e=="string"&&(n=e.match(i))){let o=n[0];if(o==="em"||o==="rem")return t*this.fontSize;let r=Zt[o];if(r)return t*r}return t}configure(e){if(typeof e.autoresize=="boolean"&&(e.autoresize?(this.viewportSize=null,this.window.addEventListener("resize",this.resizeListener,!1),this.needResize=!0):this.window.removeEventListener("resize",this.resizeListener,!1)),typeof e.fontSize=="number"){let t=e.fontSize;t>=5&&t<=72&&this.fontSize!=t&&(this.fontSize=t,this.needResize=!0)}if(typeof e.viewport=="object"&&e.viewport){let t=e.viewport,i={marginLeft:this.resolveLength(t["margin-left"])||0,marginRight:this.resolveLength(t["margin-right"])||0,marginTop:this.resolveLength(t["margin-top"])||0,marginBottom:this.resolveLength(t["margin-bottom"])||0,width:this.resolveLength(t.width)||0,height:this.resolveLength(t.height)||0};(i.width>=200||i.height>=200)&&(this.window.removeEventListener("resize",this.resizeListener,!1),this.viewportSize=i,this.needResize=!0)}if(typeof e.hyphenate=="boolean"&&(this.pref.hyphenate=e.hyphenate,this.needResize=!0),typeof e.horizontal=="boolean"&&(this.pref.horizontal=e.horizontal,this.needResize=!0),typeof e.nightMode=="boolean"&&(this.pref.nightMode=e.nightMode,this.needResize=!0),typeof e.lineHeight=="number"&&(this.pref.lineHeight=e.lineHeight,this.needResize=!0),typeof e.columnWidth=="number"&&(this.pref.columnWidth=e.columnWidth,this.needResize=!0),typeof e.fontFamily=="string"&&(this.pref.fontFamily=e.fontFamily,this.needResize=!0),typeof e.load=="boolean"&&(this.waitForLoading=e.load),typeof e.renderAllPages=="boolean"&&(this.renderAllPages=e.renderAllPages),typeof e.userAgentRootURL=="string"&&(Ph(e.userAgentRootURL.replace(/resources\/?$/,"")),Nh(e.userAgentRootURL)),typeof e.rootURL=="string"&&(Ph(e.rootURL),Nh(`${Ji}resources/`)),typeof e.pageViewMode=="string"&&e.pageViewMode!==this.pageViewMode&&(this.pageViewMode=e.pageViewMode,this.needResize=!0),typeof e.pageBorder=="number"&&e.pageBorder!==this.pref.pageBorder&&(this.viewport=null,this.pref.pageBorder=e.pageBorder,this.needResize=!0),typeof e.zoom=="number"&&e.zoom!==this.zoom&&(this.zoom=e.zoom,this.needRefresh=!0),typeof e.fitToScreen=="boolean"&&e.fitToScreen!==this.fitToScreen&&(this.fitToScreen=e.fitToScreen,this.needRefresh=!0),typeof e.defaultPaperSize=="object"&&typeof e.defaultPaperSize.width=="number"&&typeof e.defaultPaperSize.height=="number"&&(this.viewport=null,this.pref.defaultPaperSize=e.defaultPaperSize,this.needResize=!0),typeof e.allowScripts=="boolean"&&e.allowScripts!==vi&&(Tx(e.allowScripts),this.needResize=!0),typeof e.pixelRatio=="number"){let t=Math.min(e.pixelRatio,this.pixelRatioLimit);t!==this.pixelRatio&&(this.pixelRatio=t,this.needResize=!0)}return this.configurePlugins(e),T(!0)}configurePlugins(e){_t("CONFIGURATION").forEach(t=>{let i=t(e);this.needResize=i.needResize||this.needResize,this.needRefresh=i.needRefresh||this.needRefresh})}pageReplacedListener(e){let t=this.currentPage,i=this.currentSpread,n=e.target;i?(i.left===n||i.right===n)&&this.showCurrent(e.newPage):t===e.target&&this.showCurrent(e.newPage)}forCurrentPages(e){let t=[];this.currentPage&&t.push(this.currentPage),this.currentSpread&&(t.push(this.currentSpread.left),t.push(this.currentSpread.right)),t.forEach(i=>{i&&e(i)})}removePageListeners(){this.forCurrentPages(e=>{e.removeEventListener("hyperlink",this.hyperlinkListener,!1),e.removeEventListener("replaced",this.pageReplacedListener,!1)})}hidePages(){this.removePageListeners(),this.forCurrentPages(e=>{I(e.container,"display","none")}),this.currentPage=null,this.currentSpread=null}showSinglePage(e){e.addEventListener("hyperlink",this.hyperlinkListener,!1),e.addEventListener("replaced",this.pageReplacedListener,!1),I(e.container,"visibility","visible"),I(e.container,"display","block")}showPage(e){this.hidePages(),this.currentPage=e,e.container.style.marginLeft="",e.container.style.marginRight="",this.showSinglePage(e)}showSpread(e){if(this.hidePages(),this.currentSpread=e,e.left&&e.right){let t=parseFloat(e.left.container.style.width),i=parseFloat(e.right.container.style.width);t&&i&&t!==i&&(t<i?e.left.container.style.marginLeft=`${i-t}px`:e.right.container.style.marginRight=`${t-i}px`)}e.left&&(this.showSinglePage(e.left),e.right?e.left.container.removeAttribute("data-vivliostyle-unpaired-page"):e.left.container.setAttribute("data-vivliostyle-unpaired-page",!0)),e.right&&(this.showSinglePage(e.right),e.left?e.right.container.removeAttribute("data-vivliostyle-unpaired-page"):e.right.container.setAttribute("data-vivliostyle-unpaired-page",!0))}reportPosition(){let e=M("reportPosition");return this.pagePosition,this.opf.getCFI(this.pagePosition.spineIndex,this.pagePosition.offsetInItem).then(t=>{let i=this.currentPage;(this.waitForLoading&&i.fetchers.length>0?Dn(i.fetchers):T(!0)).then(()=>{this.sendLocationNotification(i,t).thenFinish(e)})}),e.result()}createViewport(){let e=this.viewportElement;if(this.viewportSize){let t=this.viewportSize;return e.style.marginLeft=`${t.marginLeft}px`,e.style.marginRight=`${t.marginRight}px`,e.style.marginTop=`${t.marginTop}px`,e.style.marginBottom=`${t.marginBottom}px`,new Es(this.window,this.fontSize,this.pixelRatio,e,t.width,t.height)}else return new Es(this.window,this.fontSize,this.pixelRatio,e)}resolveSpreadView(e,t){switch(this.pageViewMode){case"singlePage":return!1;case"spread":return!0;default:return e!=null&&(e.width-this.pref.pageBorder)/e.height>=(t?t.width*2/t.height:1.45)&&(!!t||e.width>800)}}updateSpreadView(e){this.pref.spreadView=e,this.viewportElement.setAttribute(ZS,e.toString())}sizeIsGood(){var e;let t=this.createViewport(),i=((e=this.opfView)==null?void 0:e.hasPages())&&!this.opfView.hasAutoSizedPages(),n=this.resolveSpreadView(t,this.resized&&i?this.pageSizes[0]:null);this.resized=!1;let o=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:!o&&t.width==this.viewport.width&&t.height==this.viewport.height||!o&&t.width==this.viewport.width&&t.height!=this.viewport.height&&/Android|iPhone|iPad|iPod/.test(navigator.userAgent)?!0:i?(this.viewport.width=t.width,this.viewport.height=t.height,this.needRefresh=!0,!0):!1}setPageSize(e,t,i,n){this.pageSizes[n]=e,this.setPageSizePageRules(t,i,n),n===0&&this.pageViewMode==="autoSpread"&&!this.opfView.hasAutoSizedPages()&&this.updateSpreadView(this.resolveSpreadView(this.viewport,e))}setPageSizePageRules(e,t,i){var n,o;if(this.pageRuleStyleElement&&(!this.pageSheetSizeAlreadySet||this.pageSizes[i].width!==((n=this.pageSizes[i-1])==null?void 0:n.width)||this.pageSizes[i].height!==((o=this.pageSizes[i-1])==null?void 0:o.height))){let s=function(g){let v=g*.75;return Math.ceil(v)};var r=s;let a=Math.max(...this.pageSizes.map(g=>g.width)),h=Math.max(...this.pageSizes.map(g=>g.height)),l=s(a),c=s(h),d=l*((this.pixelRatio||1)-1)+2,p=c*((this.pixelRatio||1)-1)+2,f=`@page {size: ${l}pt ${c}pt; margin: 0 ${-d}pt ${-p}pt 0;}`;this.pageRuleStyleElement.textContent=f,this.pageSheetSizeAlreadySet=!0}}removePageSizePageRules(){this.pageRuleStyleElement&&(this.pageRuleStyleElement.textContent="",this.pageSheetSizeAlreadySet=!1)}loadCmykReserveMap(e){if(!this.cmykReserveMapUrl)return this.cmykReserveMap=void 0,T(!0);let t=Ae(Fn(this.cmykReserveMapUrl),Ji),i=M("loadCmykReserveMap");return e.loadAsJSON(t).then(n=>{Pm(n)?this.cmykReserveMap=n:(Y.warn("Invalid cmykReserveMap data, ignoring"),this.cmykReserveMap=void 0),i.finish(!0)}),i.result()}reset(){let e=!1,t=!1;this.opfView&&(e=this.opfView.tocVisible,t=this.opfView.tocAutohide,this.opfView.removeRenderedPages()),this.pageSizes=[],this.removePageSizePageRules(),this.viewport=this.createViewport(),this.viewport.resetZoom(),this.opfView=new YS(this.opf,this.viewport,this.fontMapper,this.pref,this.setPageSize.bind(this),this.cmykReserveMap),e&&this.sendCommand({a:"toc",v:"show",autohide:t})}showCurrent(e,t){this.needRefresh=!1,this.removePageListeners();let i=this.resolveSpreadView(this.viewport,e.dimensions);return i!==this.pref.spreadView&&this.updateSpreadView(i),i?this.opfView.getSpread(this.pagePosition,t).thenAsync(n=>!n.left&&!n.right?T(null):n.left&&n.right&&(!this.resolveSpreadView(this.viewport,n.left.dimensions)||!this.resolveSpreadView(this.viewport,n.right.dimensions))?(this.updateSpreadView(!1),this.showPage(e),this.setPageZoom(e),this.currentPage=e,T(null)):(this.showSpread(n),this.setSpreadZoom(n),this.currentPage=e.side==="left"?n.left:n.right,T(null))):(this.showPage(e),this.setPageZoom(e),this.currentPage=e,T(null))}setPageZoom(e){var t;let i=this.getAdjustedZoomFactor(e.dimensions);(t=this.viewport)==null||t.zoom(e.dimensions.width,e.dimensions.height,i)}setSpreadZoom(e){var t;let i=this.getSpreadDimensions(e);(t=this.viewport)==null||t.zoom(i.width,i.height,this.getAdjustedZoomFactor(i))}getAdjustedZoomFactor(e){return this.fitToScreen?this.calculateZoomFactorToFitInsideViewPort(e):this.zoom}getSpreadDimensions(e){let t=0,i=0;return e.left&&(t+=e.left.dimensions.width,i=e.left.dimensions.height),e.right&&(t+=e.right.dimensions.width,i=Math.max(i,e.right.dimensions.height)),e.left&&e.right&&(t+=this.pref.pageBorder*2,t+=Math.abs(e.left.dimensions.width-e.right.dimensions.width)),{width:t,height:i}}queryZoomFactor(e){if(!this.currentPage)throw new Error("no page exists.");if(e==="fit inside viewport"){let t;return this.pref.spreadView?(this.currentSpread,t=this.getSpreadDimensions(this.currentSpread)):t=this.currentPage.dimensions,this.calculateZoomFactorToFitInsideViewPort(t)}else throw new Error(`unknown zoom type: ${e}`)}calculateZoomFactorToFitInsideViewPort(e){if(!this.viewport)return this.zoom;let t=this.viewport.width/e.width,i=this.viewport.height/e.height;return Math.min(t,i)}cancelRenderingTask(){this.renderTask&&this.renderTask.interrupt(new ac),this.renderTask=null}resize(){if(this.needResize=!1,this.needRefresh=!1,this.sizeIsGood())return T(!0);this.setReadyState("loading"),this.cancelRenderingTask();let e=La().getScheduler().run(()=>_n("resize",t=>{if(!this.opf){t.finish(!1);return}this.renderTask=e,Nt.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(i=>{if(!i){t.finish(!1);return}this.pagePosition=i.position,this.showCurrent(i.page,!0).then(()=>{this.setReadyState("interactive"),this.opf.countEPages(n=>{let o={t:"nav",epageCount:n,first:this.currentPage.isFirstPage,last:this.isLastPageForNotification(this.currentPage),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(n=>{(this.renderAllPages?this.opfView.renderAllPages():T(null)).then(()=>{this.renderTask===e&&(this.renderTask=null),Nt.registerEndTiming("render (resize)"),vi&&Kf(this.window)?Rx(this.window).then(()=>{this.renderAllPages&&this.setReadyState("complete"),this.callback({t:"loaded"}),t.finish(n)}):(this.renderAllPages&&this.setReadyState("complete"),this.callback({t:"loaded"}),t.finish(n))})})})})})},(t,i)=>{if(i instanceof ac)Nt.registerEndTiming("render (resize)"),Y.debug(i.message);else throw i}));return T(!0)}sendLocationNotification(e,t){let i=M("sendLocationNotification"),n={t:"nav",first:e.isFirstPage,last:this.isLastPageForNotification(e),metadata:this.opf.metadata,docTitle:this.opf.spine[e.spineIndex].title};return this.opf.getEPageFromPosition(this.pagePosition).then(o=>{n.epage=o,n.epageCount=this.opf.epageCount,t&&(n.cfi=t),this.callback(n),i.finish(!0)}),i.result()}isLastPageForNotification(e){if(!this.opfView||!this.pagePosition)return e.isLastPage;let t=this.opfView.spineItems[this.pagePosition.spineIndex];if(!t||!t.complete)return!1;let i=t.item.spineIndex===this.opf.spine.length-1,n=this.pagePosition.pageIndex===t.pages.length-1;return i&&n}getCurrentPageProgression(){return this.opfView?this.opfView.getCurrentPageProgression(this.pagePosition):null}moveTo(e){var t;let i;if(this.readyState!=="complete"&&e.where!=="next"&&this.setReadyState("loading"),typeof e.where=="string"){let o;switch(e.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 T(!0)}o&&(i=()=>o.call(this.opfView,this.pagePosition,!this.renderAllPages))}else if(typeof e.epage=="number"){let o=e.epage;i=()=>this.opfView.navigateToEPage(o,this.pagePosition,!this.renderAllPages)}else if(typeof e.url=="string"){let o=e.url;i=()=>this.opfView.navigateTo(o,this.pagePosition,!this.renderAllPages)}else if(typeof((t=e.position)==null?void 0:t.spineIndex)=="number"){let o=e.position;i=()=>this.opfView.findPage(o,!this.renderAllPages)}else return T(!0);if(!this.opfView)return T(!0);let n=M("moveTo");return i.call(this.opfView).then(o=>{let r;if(o){this.pagePosition=o.position;let s=M("moveTo.showCurrent");r=s.result(),this.showCurrent(o.page,!this.renderAllPages).then(()=>{this.reportPosition().thenFinish(s)})}else r=T(!0);r.then(s=>{this.readyState==="loading"&&this.setReadyState("interactive"),n.finish(s)})}),n.result()}showTOC(e){let t=!!e.autohide,i=e.v,n=this.opfView.isTOCVisible(),o=t!=this.opfView.tocAutohide&&i!="hide";if(n){if(i=="show"&&!o)return T(!0)}else if(i=="hide")return T(!0);if(n&&i!="show")return this.opfView.hideTOC(),T(!0);{let r=M("showTOC");return this.opfView.showTOC(t).then(s=>{if(s){if(o&&(s.listeners={}),t){let a=()=>{this.opfView.hideTOC()};s.addEventListener("hyperlink",a,!1)}s.addEventListener("hyperlink",this.hyperlinkListener,!1)}r.finish(!0)}),r.result()}}runCommand(e){let t=e.a||"";return _n("runCommand",i=>{let n=this.actions[t];n?n.call(this,e).then(()=>{this.callback({t:"done",a:t}),i.finish(!0)}):(Y.error("No such action:",t),i.finish(!0))},(i,n)=>{Y.error(n,"Error during action:",t),i.finish(!0)})}initEmbed(e){let t=lc(e),i=null,n=this;Wy(()=>{let o=M("commandLoop"),r=La().getScheduler();return n.hyperlinkListener=s=>{let a=s,h=a.href.charAt(0)==="#"||n.packageURL.some(l=>a.href.substr(0,l.length)==l);if(h){s.preventDefault();let l={t:"hyperlink",href:a.href,internal:h};r.run(()=>(n.callback(l),T(!0)))}},o.loopWithFrame(s=>{if(n.needResize)n.resize().then(()=>{s.continueLoop()});else if(n.needRefresh)n.currentPage&&n.showCurrent(n.currentPage,!this.renderAllPages).then(()=>{s.continueLoop()});else if(t){let a=t;t=null,n.runCommand(a).then(()=>{s.continueLoop()})}else{let a=M("waitForCommand");i=a.suspend(this),a.result().then(()=>{s.continueLoop()})}}).thenFinish(o),o.result()}),n.kick=()=>{let o=i;o&&(i=null,o.schedule(!0))},n.sendCommand=o=>t?!1:(t=lc(o),n.kick(),!0),this.window.adapt_command=n.sendCommand}},yg=(e=>(e.FIT_INSIDE_VIEWPORT="fit inside viewport",e))(yg||{}),ac=class vg extends Error{constructor(){super(),u(this,"name","RenderingCanceledError"),u(this,"message","Page rendering has been canceled"),u(this,"stack"),Object.setPrototypeOf(this,vg.prototype),this.stack=new Error().stack}};function lc(e){return typeof e=="string"?kl(e):e}var hc=Sl;function JS(){return{autoResize:!0,fontSize:16,pageBorderWidth:1,renderAllPages:!0,pageViewMode:"autoSpread",zoom:1,fitToScreen:!1,defaultPaperSize:void 0,allowScripts:!0,pixelRatio:8}}function uc(e){let t={};return Object.keys(e).forEach(i=>{let n=e[i];switch(i){case"autoResize":t.autoresize=n;break;case"pageBorderWidth":t.pageBorder=n;break;default:t[i]=n}}),t}var wg=class{constructor(e,t){u(this,"settings",e),u(this,"initialized",!1),u(this,"adaptViewer_"),u(this,"options"),u(this,"eventTarget"),u(this,"readyState"),fc(e.debug),this.adaptViewer_=new KS(e.window||window,e.viewportElement,"main",this.dispatcher.bind(this)),this.options=JS(),t&&this.setOptions(t),this.eventTarget=new Nl,Object.defineProperty(this,"readyState",{get(){return this.adaptViewer_.readyState}})}setOptions(e){let t=Object.assign({a:"configure"},uc(e));this.adaptViewer_.sendCommand(t),Object.assign(this.options,e)}dispatcher(e){let t={type:e.t},i=e;Object.keys(i).forEach(n=>{n!=="t"&&(t[n]=i[n])}),this.eventTarget.dispatchEvent(t)}addListener(e,t){e==="paginationprogress"&&this.adaptViewer_.ensurePaginationProgressListener(),this.eventTarget.addEventListener(e,t,!1)}removeListener(e,t){var i;this.eventTarget.removeEventListener(e,t,!1),e==="paginationprogress"&&!((i=this.eventTarget.listeners[e])!=null&&i.length)&&this.adaptViewer_.removePaginationProgressListener()}loadDocument(e,t,i){if(!e||(Array.isArray(e)?!e[0]||typeof e[0]!="string"&&!e[0].url:typeof e!="string"&&!e.url)){this.eventTarget.dispatchEvent({type:"error",content:{error:new Error("No URL specified")}});return}this.loadDocumentOrPublication(e,null,t,i)}loadPublication(e,t,i){if(!e){this.eventTarget.dispatchEvent({type:"error",content:{error:new Error("No URL specified")}});return}this.loadDocumentOrPublication(null,e,t,i)}loadDocumentOrPublication(e,t,i,n){let o=i||{};function r(l){if(l)return l.map(c=>({url:c.url||null,text:c.text||null}))}let s=r(o.authorStyleSheet),a=r(o.userStyleSheet);n&&Object.assign(this.options,n);let h=Object.assign({a:e?"loadXML":"loadPublication",userAgentRootURL:this.settings.userAgentRootURL,url:QS(e)||t,document:o.documentObject,fragment:o.fragment,authorStyleSheet:s,userStyleSheet:a,cmykReserveMapUrl:o.cmykReserveMapUrl},uc(this.options));this.initialized?this.adaptViewer_.sendCommand(h):(this.initialized=!0,this.adaptViewer_.initEmbed(h))}getCurrentPageProgression(){return this.adaptViewer_.getCurrentPageProgression()}resolveNavigation(e){switch(e){case"left":return this.getCurrentPageProgression()===hc.LTR?"previous":"next";case"right":return this.getCurrentPageProgression()===hc.LTR?"next":"previous";default:return e}}navigateToPage(e,t){e==="epage"?this.adaptViewer_.sendCommand({a:"moveTo",epage:t}):this.adaptViewer_.sendCommand({a:"moveTo",where:this.resolveNavigation(e)})}navigateToInternalUrl(e){this.adaptViewer_.sendCommand({a:"moveTo",url:e})}navigateToPosition(e){var t,i;this.adaptViewer_.sendCommand({a:"moveTo",position:{spineIndex:e.spineIndex,pageIndex:(t=e.pageIndex)!=null?t:-1,offsetInItem:(i=e.offsetInItem)!=null?i:-1}})}isTOCVisible(){return this.adaptViewer_.opfView&&this.adaptViewer_.opfView.opf&&this.adaptViewer_.opfView.opf.toc?!!this.adaptViewer_.opfView.isTOCVisible():null}showTOC(e,t){let i=e==null?"toggle":e?"show":"hide";this.adaptViewer_.sendCommand({a:"toc",v:i,autohide:t})}queryZoomFactor(e){return this.adaptViewer_.queryZoomFactor(e)}getPageSizes(){return this.adaptViewer_.pageSizes}getTOC(){var e,t;return(t=(e=this.adaptViewer_.opfView)==null?void 0:e.tocView)==null?void 0:t.getTOC()}getMetadata(){return this.adaptViewer_.opf.getMetadata()}getCover(){return this.adaptViewer_.opf.cover}getCmykMap(){var e;let t=(e=this.adaptViewer_)==null?void 0:e.opfView;return t!=null&&t.cmykStore?t.cmykStore.toJSON():{}}};function QS(e){function t(n){return typeof n=="number"?n:null}function i(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(e)?e.map(i):e?[i(e)]:null}var bg=(e=>(e.PREVIOUS="previous",e.NEXT="next",e.LEFT="left",e.RIGHT="right",e.FIRST="first",e.LAST="last",e.EPAGE="epage",e))(bg||{}),eC=yg,tC=mg;Nt.forceRegisterEndTiming("load_vivliostyle");var iC=class{constructor(e,{title:t="",printCallback:i=s=>s.print(),errorCallback:n=null,hideIframe:o=!0,removeIframe:r=!0}){u(this,"htmlDoc"),u(this,"title"),u(this,"printCallback"),u(this,"errorCallback"),u(this,"hideIframe"),u(this,"removeIframe"),u(this,"iframe"),u(this,"iframeWin"),u(this,"window"),this.htmlDoc=e,this.title=t,this.printCallback=i,this.errorCallback=n,this.hideIframe=o,this.removeIframe=r}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=`
1878
+ `),i.toString()}},Px=class{constructor(e){u(this,"deobfuscator",e),u(this,"familyMap",{})}registerFamily(e,t){let i=e.family,n=this.familyMap[i],r=t.family;if(n){if(n!=r)throw new Error(`E_FONT_FAMILY_INCONSISTENT ${e.family}`)}else this.familyMap[i]=r}filterFontFamily(e){if(e instanceof Oe){let t=e.values,i=[];for(let n of t){let r=this.familyMap[n.stringValue()];r&&i.push(B(r)),i.push(n)}return new Oe(i)}else{let t=this.familyMap[e.stringValue()];return t?new Oe([B(t),e]):e}}},Nx=class{constructor(e,t,i){u(this,"head",e),u(this,"body",t),u(this,"srcURLMap",{}),u(this,"familyPrefix"),u(this,"familyCounter",0),this.familyPrefix=i||"Fnt_"}getViewFontFamily(e,t){let i=e.family,n=t.familyMap[i];return n||(n=this.familyPrefix+ ++this.familyCounter,t.familyMap[i]=n,n)}initFont(e,t,i){let n=M("initFont"),r=e.src,o={};for(let l of dh(e.properties))o[l]=e.properties[l];let s=this.getViewFontFamily(e,i);o["font-family"]=B(s);let a=new Yf(o),h=this.head.ownerDocument.createElement("style");return h.textContent=a.makeAtRule(r,t),this.head.appendChild(h),Y.debug("Load font:",r),n.finish(a),n.result()}loadFont(e,t){let i=e.src,n=e.family+";"+i+";"+e.fontTraitKey,r=this.srcURLMap[n];return r?r.piggyback(o=>{t.registerFamily(e,o),Y.debug("Found already-loaded font:",i)}):(r=new Jr(()=>{let o=M("loadFont"),s=i.replace(/^url\("([^"]+)"\).*$/,"$1"),a=t.deobfuscator?t.deobfuscator(s):null;return a?Os(s,"blob").then(h=>{if(!h.responseBlob){o.finish(null);return}a(h.responseBlob).then(l=>{this.initFont(e,l,t).thenFinish(o)})}):this.initFont(e,null,t).thenFinish(o),o.result()},`loadFont ${i}`),this.srcURLMap[n]=r,r.start()),r}findOrLoadFonts(e,t){let i=[];for(let n of e){if(!n.src||!n.family){Y.warn("E_FONT_FACE_INVALID");continue}i.push(this.loadFont(n,t))}return Dn(i).thenAsync(()=>this.waitFontLoading())}waitFontLoading(){let e=this.head.ownerDocument.fonts,t=0;if(e.forEach(n=>{n.status==="unloaded"&&(t++,n.load().catch(r=>{}))}),t===0)return T(!0);let i=M("waitFontLoading");return i.loop(()=>i.sleep(20).thenAsync(()=>e.status==="loading"?T(!0):T(!1))).thenFinish(i),i.result()}},vi=!0;function Tx(e){vi=e}var Ki=[];function Hu(e,t){return e===t||(e.src||t.src?e.src===t.src:e.textContent===t.textContent)}function Zf(e){let t=Array.from(e.querySelectorAll("body > :not(script):not(link):not(style) ~ script"));return Array.from(e.querySelectorAll("head > script, body > script")).filter(i=>!t.includes(i))}function ph(e,t,i){if(!vi||!(i!=null&&i.inHead)&&!(i!=null&&i.atEnd)&&Zf(e.ownerDocument).includes(e))return T(!1);let n=e.textContent,r=e.src,o=e.type==="module",s=r&&r.includes("/MathJax.js");if(s){if(t.document.head.querySelector("script[src*='/MathJax.js']"))return T(!0);t.MathJax||(t.MathJax={MathML:{extensions:["content-mathml.js"]},showProcessingMessages:!1,messageStyle:"none",skipStartupTypeset:!0,CommonHTML:{linebreaks:{automatic:!0}},"fast-preview":{disabled:!0},AuthorInit:function(){t.MathJax.Hub.processSectionDelay=0}})}let a=(o||r)&&e.async&&!s,h=(o&&!a||r&&e.defer)&&!s,l=!(i!=null&&i.atEnd)&&(i?.forceDefer||h||a);if(Kf(t)||(t.onload=null),l)return Ki.some(d=>Hu(d,e))||Ki.push(e),T(!0);for(let d of t.document.head.getElementsByTagName("script"))d.hasAttribute("data-vivliostyle-scripting")&&Hu(d,e)&&t.document.head.removeChild(d);let c=t.document.createElement("script");c.textContent=n,r&&(c.src=r),c.async=a,c.defer=h,c.setAttribute("data-vivliostyle-scripting","true");for(let d of e.attributes)["src","async","defer"].includes(d.name)||c.setAttribute(d.name,d.value);if(Y.debug("script:",r),r){let d=Et(c);return t.document.head.appendChild(c),Dn([d])}else return t.document.head.appendChild(c),T(!0)}function Ax(e,t){var i;let n={},r=s=>{var a;let h=(a=s["font-family"])==null?void 0:a.value;if(h)if(h.values)for(let c of h.values)n[c.stringValue()]=!0;else n[h.stringValue()]=!0;let l=s._marginBoxes;if(l)for(let c of Object.values(l))r(c)},o=s=>{if(s instanceof rh)r(s.style);else if(s instanceof Yn||Array.isArray(s))for(let a of Object.values(s))o(a)};for(let s of Object.values(t.cascade.code))for(let a of Object.values(s??{}))o(a);for(let s of e.querySelectorAll("[style]"))(i=s.style)!=null&&i.fontFamily&&(n[s.style.fontFamily]=!0);return Object.keys(n).join(",")}function Ix(e,t,i){var n;let r=(n=t.document.querySelector("[data-vivliostyle-textcontent]"))!=null?n:t.document.createElement("div");return r.style.position="fixed",r.style.fontSize="0",r.setAttribute("data-vivliostyle-textcontent","true"),r.setAttribute("aria-hidden","true"),r.style.fontFamily=Ax(e,i),r.textContent=e.documentElement.textContent,t.document.body.appendChild(r),r}function Fx(e,t,i){if(!vi)return T(!1);let n=Zf(e);if(n.length===0)return T(!1);let r=n.some(c=>!(c.async||c.defer||c.type==="module")),o=r?Ix(e,t,i):null,s=t.document.fonts,a=t.$,h=!1,l=M("loadScripts");return l.loop(()=>{if(n.length===0)return r?l.sleep(20).thenAsync(()=>{var d,p;return s.status==="loading"||t.document.documentElement.classList.contains("wf-loading")||(d=t.FontJSON)!=null&&d.Font&&(p=t.ret)!=null&&p.readyState&&t.ret.readyState<4?T(!0):T(!1)}):T(!1);let c=n.shift();return ph(c,t,{inHead:!0,forceDefer:h}).thenAsync(()=>(!h&&t.$!==a&&(Ki.push(c),h=!0),n.length===0&&r&&(Y.debug("dispatchEvent: DOMContentLoaded (document)"),t.document.dispatchEvent(new Event("DOMContentLoaded"))),T(!0)))}).then(()=>{o&&o.remove(),l.finish(!0)}),l.result()}function Rx(e){if(!vi)return T(!1);let t=M("loadScripts");return t.loop(()=>Ki.length===0?T(!1):ph(Ki.shift(),e,{atEnd:!0}).thenReturn(Ki.length>0)).then(()=>{Y.debug("dispatchEvent: DOMContentLoaded (window)"),e.dispatchEvent(new Event("DOMContentLoaded")),Y.debug("dispatchEvent: load (window)"),e.dispatchEvent(new Event("load")),t.finish(!0)}),t.result()}function Kf(e){return vi?Ki.length>0||!!e.document.head.querySelector("script[data-vivliostyle-scripting]"):!1}var Lx=e=>String(e).replace(/[\u0000-\u001F"\\\u2028\u2029]/g,Pl),Ox=e=>`"${Lx(e)}"`,wa=(e,t,i)=>Ox(i.transformURL(xi(String(e)),t)),Bx=(e,t,i)=>e.replace(/[uU][rR][lL]\(\s*"((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^"\r\n])+)"/gm,(n,r)=>`url(${wa(r,t,i)}`).replace(/[uU][rR][lL]\(\s*'((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^'\r\n])+)'/gm,(n,r)=>`url(${wa(r,t,i)}`).replace(/[uU][rR][lL]\(\s*((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^"'\r\n\)\s])+)/gm,(n,r)=>`url(${wa(r,t,i)}`),Mx={},_x=new Set(["base","body","head","html","link","meta","script","style","title"]);function Dx(e){if(e instanceof K)return e;if(e instanceof J){let t=[];for(let i of e.values)if(i instanceof K)t.push(i.str);else return null;if(t.length>0)return new K(t.join(""))}return null}function zx(e){return e instanceof Qe?e:e instanceof J&&e.values[0]instanceof Qe&&e.values.slice(1).every(t=>t instanceof K&&t.str.trim()==="")?e.values[0]:null}function Vx(e){if(Gr!=="webkit")return!1;let t=e["--viv-marker-content"];if(!t)return!1;let i=zx(t);if(i)return e["list-style-type"]=y.none,e["list-style-image"]=i,delete e["--viv-marker-content"],!0;let n=Dx(t);return n?(e["list-style-type"]=n,e["list-style-image"]=y.none,!0):!1}function Ux(e){e.addEventListener("load",()=>{e.contentWindow.navigator.epubReadingSystem={name:"adapt",version:"0.1",layoutStyle:"paginated",hasFeature:function(t,i){return t==="mouse-events"}}},!1)}var fl=class gr extends Nl{constructor(t,i,n,r,o,s,a,h,l,c,d,p,f,g,v,w=new Map,x={value:!1}){super(),u(this,"flowName",t),u(this,"context",i),u(this,"viewport",n),u(this,"styler",r),u(this,"regionIds",o),u(this,"xmldoc",s),u(this,"docFaces",a),u(this,"footnoteStyle",h),u(this,"stylerProducer",l),u(this,"page",c),u(this,"customRenderer",d),u(this,"fallbackMap",p),u(this,"documentURLTransformer",f),u(this,"pageProps",g),u(this,"cascadedPageStyle",v),u(this,"semanticFootnoteFirstRefOffsets",w),u(this,"semanticFootnoteFirstRefOffsetsInitialized",x),u(this,"document"),u(this,"exprContentListener"),u(this,"computedStyleParentFontSizeOverride",null),u(this,"computedStyleParentLineHeightOverride",null),u(this,"nodeContext",null),u(this,"viewRoot",null),u(this,"isFootnote",!1),u(this,"sourceNode",null),u(this,"offsetInNode",0),u(this,"viewNode",null),this.document=n.document,this.exprContentListener=r.counterListener.getExprContentListener()}clone(){return new gr(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,this.pageProps,this.cascadedPageStyle,this.semanticFootnoteFirstRefOffsets,this.semanticFootnoteFirstRefOffsetsInitialized)}getExplicitPageType(t){let i=t?.page;if(!i||Z(i.value))return null;let n=i.evaluate(this.context,"page").toString();return!n||n.toLowerCase()==="auto"?null:n}isNormalFlowElement(t){var i,n,r;let o=this.styler.getStyle(t,!1),s=(i=o?.display)==null?void 0:i.evaluate(this.styler.context,"display");if((s&&!Z(s)?s:y.inline)===y.none)return!1;let a=(n=o?.position)==null?void 0:n.evaluate(this.styler.context,"position"),h=a&&!Z(a)?a:y.static;if(vr(h)||Fr(h))return!1;let l=(r=o?.float)==null?void 0:r.evaluate(this.styler.context,"float");return(l&&!Z(l)?l:y.none)===y.none}getFirstInFlowChildElement(t){var i;let n=t.firstChild;for(;n;){if(n.nodeType===Node.TEXT_NODE){if(!Ee(n))return null;n=n.nextSibling;continue}if(n.nodeType!==Node.ELEMENT_NODE){n=n.nextSibling;continue}let r=n;if(this.isNormalFlowElement(r)){let o=this.styler.getStyle(r,!1),s=(i=o?.display)==null?void 0:i.evaluate(this.styler.context,"display"),a=s&&!Z(s)?s:y.inline;return Ut(a)?null:r}n=n.nextSibling}return null}getEffectiveStartPageType(t,i){let n=i,r=t;for(;r;){let o=this.getFirstInFlowChildElement(r);if(!o)return n;let s=this.getExplicitPageType(this.styler.getStyle(o,!1));s&&(n=s),r=o}return n}syncTextNodePageTypeBoundary(t){if(t.sourceNode.nodeType!==Node.TEXT_NODE||Ee(t.sourceNode)||t.fragmentIndex!==1)return;let i=t.pageType;this.styler.cascade.currentPageType!==i&&(en(t.breakBefore)||(t.breakBefore=nt(t.breakBefore,"page")),i!==this.styler.cascade.previousPageType&&(this.styler.cascade.previousPageType=this.styler.cascade.currentPageType),this.styler.cascade.currentPageType=i)}syncSemanticFootnoteCounterToTarget(t){if(t.localName!=="a"||!Gt(t)||!cu(t,this.xmldoc.url,r=>this.xmldoc.getElementOffset(r),this.semanticFootnoteFirstRefOffsets,this.semanticFootnoteFirstRefOffsetsInitialized))return;let i=t.getAttribute(Cr);if(!i)return;let n=pp(t,this.xmldoc.url,r=>this.xmldoc.getElement(r));n&&n.setAttribute(Cr,i)}createPseudoelementShadow(t,i,n,r,o,s,a,h){var l,c;let d=this.getPseudoMap(n,this.regionIds,this.isFootnote,this.nodeContext,s);if(!d)return h;let p=[],f=pr.createElementNS("http://www.pyroxy.com/ns/shadow","root"),g=f,v=Gt(t)&&!!d["footnote-call"]&&It((l=d["footnote-call"].content)==null?void 0:l.value);for(let m of k0){let S;if(m){if(!d[m])continue;let b=Pt(t),C=t.namespaceURI==="http://www.pyroxy.com/ns/shadow"&&t.localName==="include"&&t.classList.contains("-vivliostyle-footnote-content");if(m=="footnote-call"&&!Gt(t)||m=="footnote-marker"&&!(b||C||i&&this.isFootnote)&&!((c=this.nodeContext)!=null&&c.pluginProps.nestedFootnoteDetached))continue;if(m.match(/^first-/)){let P=r.display;if(!P||P===y.inline)continue;let L=t.firstElementChild;if(L&&Ee(L.previousSibling)){let A=o.getStyle(L,!1);if(A){let z=ve(A,"display");if(z!=null&&z.value&&z.value!==y.inline)continue}}}if(m==="before"||m==="after"||m==="footnote-call"||m==="footnote-marker"){let P=d[m].content,L=(m==="before"||m==="after")&&(r.float===y.footnote||b||C)&&!!P;if(!P||!It(P.value)&&!L)continue}p.push(m),S=pr.createElementNS("http://www.w3.org/1999/xhtml","span"),Er(S,m)}else{if(v)continue;S=pr.createElementNS("http://www.pyroxy.com/ns/shadow","content")}g.appendChild(S),m.match(/^first-/)&&(g=S)}if(!p.length)return h;let w=new ma(t,n,o,s,this.exprContentListener),x=new Bo(t,f,null,a,h,st.ROOTLESS,w);return h||x}getPseudoMap(t,i,n,r,o){let s=ft(t,"_pseudos");if(!s)return null;let a={};for(let h in s){let l=a[h]={};kr(l,s[h],o),ul(l,o,s[h]),Ef(s[h],i,n,(c,d)=>{kr(l,d,o),Sf(d,p=>{kr(l,p,o)})})}return a}createRefShadow(t,i,n,r,o){let s=M("createRefShadow");return this.xmldoc.store.load(t).then(a=>{let h=a;if(h){let l=h.getElement(t);if(l){let c=this.stylerProducer.getStylerForDoc(h);o=new Bo(n,l,h,r,o,i,c)}}s.finish(o)}),s.result()}createShadows(t,i,n,r,o,s,a){let h=M("createShadows"),l=null,c=r.template,d;if(c instanceof Qe||c===y.footnote)if(c!==y.footnote||cu(t,this.xmldoc.url,p=>this.xmldoc.getElementOffset(p),this.semanticFootnoteFirstRefOffsets,this.semanticFootnoteFirstRefOffsetsInitialized)){let p=c instanceof Qe?c.url:Ae("user-agent.xml#footnote",Ni);d=this.createRefShadow(p,st.ROOTLESS,t,a,l)}else d=T(l);else d=T(l);return d.then(p=>{let f=null;if(t.namespaceURI=="http://www.pyroxy.com/ns/shadow"&&t.localName=="include"){let v=t.getAttribute("href"),w=null;v?w=a?a.xmldoc:this.xmldoc:a&&(a.owner.namespaceURI=="http://www.w3.org/1999/xhtml"?v=a.owner.getAttribute("href"):v=a.owner.getAttributeNS("http://www.w3.org/1999/xlink","href"),w=a.parentShadow?a.parentShadow.xmldoc:this.xmldoc),v&&(v=Qo(v,w.url),f=this.createRefShadow(v,st.ROOTED,t,a,p))}f==null&&(f=T(p));let g=null;f.then(v=>{if(r.display===y.table_cell){let w=Ae("user-agent.xml#table-cell",Ni);g=this.createRefShadow(w,st.ROOTLESS,t,a,v)}else g=T(v);g.then(w=>{w=this.createPseudoelementShadow(t,i,n,r,o,s,a,w),h.finish(w)})})}),h.result()}setViewRoot(t,i){this.viewRoot=t,this.isFootnote=i}computeStyle(t,i,n,r){var o;let s=this.context,a=cl(n,s,this.regionIds,this.isFootnote,this.nodeContext),h=!((o=this.nodeContext)!=null&&o.parent);h&&(!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 l=t;t=Cf(a,s,t);let c=!h&&t!==l;i=kf(a,s,i);let d=(x,m)=>{let S;c&&(t?/^(min-|max-)?(height|inline-size)$/.test(x)&&(S=s.pageAreaHeight):/^(min-|max-)?(width|inline-size)$/.test(x)&&(S=s.pageAreaWidth));let b=m.evaluate(s,x,S,t);return x=="font-family"&&(b=this.docFaces.filterFontFamily(b)),b},p=!!new Je(s.style.pageScope,"left-page").evaluate(s);if(Pf(a,r,t,i,p,d),c){let x=r[t?"height":"width"];(!x||x===y.auto)&&(r[t?"height":"width"]=y.max_content)}if(vr(r.position))return r.position=y.fixed,r.visibility=y.hidden,t;let f=r.position,g=r.float,v=r.display||(this.sourceNode&&this.sourceNode.namespaceURI==="http://www.w3.org/1999/xhtml"?y.inline:void 0),w=zd(v,f,g,this.sourceNode===this.xmldoc.root);return["display","position","float"].forEach(x=>{w[x]&&(r[x]=w[x])}),t}inheritFromSourceParent(t){var i,n;let r=this.nodeContext.sourceNode,o=[],s=null,a=r instanceof Element&&r.namespaceURI==="http://www.pyroxy.com/ns/shadow"&&r.localName==="include"&&r.classList.contains("-vivliostyle-footnote-content"),h=this.isFootnote&&(!((i=this.nodeContext)!=null&&i.parent)||a),l=this.nodeContext.shadowContext;if(r instanceof Element&&r.namespaceURI==="http://www.pyroxy.com/ns/shadow"&&r.localName==="include"&&r.classList.contains("-vivliostyle-footnote-content")){let w=l?.owner;if(w instanceof Element&&Gt(w)){let x=w.getAttribute("href")||w.getAttributeNS("http://www.w3.org/1999/xlink","href");if(x){let m=Qo(x,this.xmldoc.url),S=this.xmldoc.getElement(m);S&&Pt(S)&&((n=S.parentNode)==null?void 0:n.nodeType)===1&&(r=S.parentNode,l=null)}}}let c=-1;for(;r&&r.nodeType==1;){let w=l&&l.root==r,x=!!w&&l.type==st.ROOTED&&Pt(r);if(!w||l.type==st.ROOTLESS||x){let m=(l?l.styler:this.styler).getStyle(r,!1);o.push(m),s=s||Sa(r)}w&&!x?(r=l.owner,l=l.parentShadow):(r=r.parentNode,c++)}let d=new Set;if(o.length>0){let w=o[0],x=cl(w,this.context,this.regionIds,this.isFootnote,this.nodeContext);for(let m in x){if(!In(m))continue;let S=x[m].evaluate(this.context,m);S&&S!==y.inherit&&S!==y.unset&&S!==y.revert&&S!==Me&&d.add(m)}}let p=c===0,f=this.context.queryUnitSize("em",p),g={"font-size":new W(new O(f,"px"),0)};p&&(g["line-height"]=new W(new At(this.context.pref.lineHeight),0));let v=new Nb(g,this.context);for(let w=o.length-1;w>=0;--w){let x=o[w],m=[];for(let C in x)In(C)&&m.push(C);m.sort(_h);let S,b;for(let C of m){if(w>0&&h&&C.startsWith("--viv-marker-")||w>0&&d.has(C))continue;v.setPropName(C);let P=ve(x,C),L=P;if(P.value===y.initial)delete g[C];else if(!Z(P.value)){if(C==="font-size"&&w===o.length-1&&this.context.isRelativeRootFontSize&&this.context.rootFontSize)L=new W(new O(this.context.rootFontSize,"px"),P.priority);else if(C==="line-height"&&w===o.length-1&&this.context.rootLineHeight&&P.value instanceof O&&(P.value.unit==="lh"||P.value.unit==="rlh"))L=new W(new O(this.context.rootLineHeight,"px"),P.priority);else if(w===0&&P.value instanceof O&&P.value.unit==="lh"){let A=this.getLineHeightUnitSize(C,S,b);A!=null&&(L=new W(new O(P.value.num*A,"px"),P.priority))}else Xe(C)||(L=P.filterValue(v));C==="font-size"?S=L.value:C==="line-height"&&(b=L.value),g[C]=L}}}for(let w in t)In(w)||(g[w]=t[w]);return{lang:s,elementStyle:g}}resolveURL(t){return t=Ae(t,this.xmldoc.url),this.fallbackMap[t]||t}inheritLangAttribute(){this.nodeContext.lang=Sa(this.nodeContext.sourceNode)||this.nodeContext.parent&&this.nodeContext.parent.lang||this.nodeContext.lang}transferPolyfilledInheritedProps(t){let i=mb().filter(n=>t[n]);if(i.length){let n=this.nodeContext.inheritedProps;if(this.nodeContext.parent){n=this.nodeContext.inheritedProps={};for(let r in this.nodeContext.parent.inheritedProps)n[r]=this.nodeContext.parent.inheritedProps[r]}i.forEach(r=>{let o=t[r];if(o){if(Z(o))o===y.initial&&(n[r]=void 0);else if(o instanceof lt)n[r]=o.num;else if(o instanceof he)n[r]=o.name;else if(o instanceof O){let s=o;switch(s.unit){case"dpi":case"dpcm":case"dppx":n[r]=s.num*Zt[s.unit];break;default:n[r]=o}}else n[r]=o;["widows","orphans"].includes(r)||delete t[r]}})}}resolveFormattingContext(t,i,n,r,o,s){let a=_t("RESOLVE_FORMATTING_CONTEXT");for(let h=0;h<a.length;h++){let l=a[h](t,i,n,r,o,s);if(l){t.formattingContext=l;return}}}createElementView(t,i){var n,r;let o=!0,s=M("createElementView"),a=this.sourceNode,h=this.nodeContext.shadowContext?this.nodeContext.shadowContext.styler:this.styler,l=h.getStyle(a,!1);if(this.syncSemanticFootnoteCounterToTarget(a),!this.nodeContext.shadowContext){let P=this.xmldoc.getElementOffset(a);$s.registerFragmentIndex(P,this.nodeContext.fragmentIndex,0)}let c={},d={getStyle:P=>this.styler.getStyle(P,!1),getProp:(P,L)=>P?ve(P,L):null,getStyleMap:(P,L)=>ft(P,L),getMutableStyleMap:(P,L)=>si(P,L),createCascadeValue:(P,L)=>new W(P,L),filterFootnoteMarkerContent:(P,L)=>P.filterValue(new _r(this.styler.cascade,L,this.styler.cascade.counterResolver,"footnote-marker")).value};if(!this.nodeContext.parent){let P=this.inheritFromSourceParent(l);l=P.elementStyle,this.nodeContext.lang=P.lang}let p=l.position,f=l.float,g=l["float-reference"],v=f&&!Z(f.value)&&f.value!==y.none&&g&&!Z(g.value)?jv(g.value.toString()):null,w=!!this.nodeContext.shadowContext&&this.nodeContext.shadowContext.type===st.ROOTED&&Pt(a);if(this.nodeContext.parent&&(vr(p?.value)||v&&Ii(v)||w)){let P=this.inheritFromSourceParent(l);l=P.elementStyle,this.nodeContext.lang=P.lang}l=Zv(a,l,this.nodeContext.shadowContext,this.xmldoc.url,P=>this.xmldoc.getElement(P),Cr,d),l=Kv(a,l,this.nodeContext.shadowContext,this.context,d),this.nodeContext.vertical=this.computeStyle(this.nodeContext.vertical,this.nodeContext.direction==="rtl",l,c),v&&Ii(v)&&c.display===y.block&&(c.display=y.flow_root),h.processContent(a,c,this.nodeContext),this.transferPolyfilledInheritedProps(c),this.inheritLangAttribute(),c.direction&&(this.nodeContext.direction=c.direction.toString());let x=c["flow-into"];if(x&&x.toString()!=this.flowName)return s.finish(!1),s.result();if(vi&&a.localName==="script"&&a.namespaceURI==="http://www.w3.org/1999/xhtml")return ph(a,this.viewport.window).thenFinish(s),s.result();let m=c.display;if(Pt(a)&&!w&&a.hasAttribute(dp)&&(m=c.display=y.none),Z(m)&&(m===y.initial||m===y.unset?m=y.inline:m===y.inherit?m=((n=this.nodeContext.parent)==null?void 0:n.display)&&B((r=this.nodeContext.parent)==null?void 0:r.display):m=null),m===y.none)return s.finish(!1),s.result();let S=this.nodeContext.parent==null,b=c[this.nodeContext.vertical?"width":"height"],C=(m===y.grid||m===y.inline_grid)&&!!b&&!(b===y.auto||Z(b));return this.nodeContext.flexContainer=m===y.flex||C,this.createShadows(a,S,l,c,h,this.context,this.nodeContext.shadowContext).then(P=>{var L,A;this.nodeContext.nodeShadow=P;let z=c.position,U=c.float,X=c.clear,re=this.nodeContext.vertical?y.vertical_rl:y.horizontal_tb,k=this.nodeContext.parent?this.nodeContext.parent.vertical?y.vertical_rl:y.horizontal_tb:re,_=hv(a),F=c["column-count"],D=c["column-width"],E=F&&F!==y.auto&&!Z(F)||D&&D!==y.auto&&!Z(D);this.nodeContext.establishesBFC=cv(m,z,U,c.overflow,re,k,E||_),this.nodeContext.containingBlockForAbsolute=dv(z),this.nodeContext.isInsideBFC()&&U!==y.footnote&&!(v&&Ii(v))&&(U=null,X=null);let N=null,R=!1,$=this.isFootnote&&(!((L=this.nodeContext)!=null&&L.parent)||this.nodeContext.pluginProps.nestedFootnoteDetached||w),V=Jv(a,this.nodeContext.shadowContext,d);Qv(V.sourceStyle,c,this.context),N=V.footnoteDisplay;let q=U instanceof J||U===y.left||U===y.right||U===y.top||U===y.bottom||U===y.inline_start||U===y.inline_end||U===y.block_start||U===y.block_end||U===y.snap_block||U===y.snap_inline||U===y.inside||U===y.outside||U===y.footnote;if(U&&(delete c.float,U===y.footnote))if(N=c["footnote-display"]||N,R=!!c["--viv-marker-content"],$){q=!1;let G=N?.toString();G&&(c["--viv-footnote-display"]=B(G)),m=R?B("list-item"):G==="inline"||G==="compact"?y.inline:y.block,c.display=m}else c.display=y.inline;if($&&Pt(a)){R=R||!!c["--viv-marker-content"];let G=N?.toString();G&&(c["--viv-footnote-display"]=B(G)),R&&(m=c.display=B("list-item")),!R&&(G==="inline"||G==="compact")&&(m=c.display=y.inline)}X&&(X===y.inherit&&this.nodeContext.parent&&this.nodeContext.parent.clearSide&&(X=B(this.nodeContext.parent.clearSide)),(X===y.left||X===y.right||X===y.top||X===y.bottom||X===y.inline_start||X===y.inline_end||X===y.block_start||X===y.block_end||X===y.inside||X===y.outside||X===y.both||X===y.all||X===y.same||X===y.column||X===y.region||X===y.page)&&(delete c.clear,(q||c.display&&c.display!=y.inline)&&(this.nodeContext.clearSide=X.toString())));let Q=ur(m)&&!!(c["ua-list-item-count"]||c["--viv-marker-content"]),ee=c["break-inside"];(q||ee&&!Z(ee)&&ee!==y.auto)&&this.nodeContext.breakPenalty++,m&&m!==y.inline&&Ut(m)&&this.nodeContext.breakPenalty++,this.nodeContext.inline=!q&&!m||Ut(m)||Ud(m),this.nodeContext.display=m?m.toString():"inline",this.nodeContext.floatSide=q?U.toString():null,this.nodeContext.floatReference=v||Pe.INLINE;let pe=c["float-min-wrap-block"];this.nodeContext.floatMinWrapBlock=pe&&!Z(pe)?pe:null;let oe=this.isInsideNonRootMultiColumn(),se=c["column-span"];if(this.nodeContext.columnSpan=!oe&&se&&!Z(se)?se:null,!this.nodeContext.inline){let G=c["break-after"];G&&!Z(G)&&!(oe&&G===y.column)&&(this.nodeContext.breakAfter=G.toString(),Da[this.nodeContext.breakAfter]&&(c["break-after"]=y.column));let Dt=c["break-before"];Dt&&!Z(Dt)&&!(oe&&Dt===y.column)&&(this.nodeContext.breakBefore=Dt.toString(),Da[this.nodeContext.breakBefore]&&(this.isAtStartOfPage()?delete c["break-before"]:c["break-before"]=y.column),this.nodeContext.fragmentIndex!==1&&(this.nodeContext.breakBefore=null));let qt=c.page,an=qt&&!Z(qt)?qt.toString():null,zt=an;!zt&&!this.nodeContext.parent&&(this.nodeContext.shadowContext||m===y.table_header_group||m===y.table_footer_group)&&(zt=this.styler.cascade.currentPageType),!zt||zt.toLowerCase()==="auto"?zt=this.nodeContext.pageType:this.nodeContext.pageType=zt;let Kn=an!=null&&an.toLowerCase()!=="auto",wi=Kn?this.nodeContext.fragmentIndex===1?this.getEffectiveStartPageType(a,zt):(A=this.styler.cascade.currentPageType)!=null?A:zt:zt;this.styler.cascade.currentPageType!==wi&&!(!Kn&&c.position===y.fixed)&&(this.nodeContext.fragmentIndex===1&&!en(this.nodeContext.breakBefore)&&(this.nodeContext.breakBefore="page"),wi!==this.styler.cascade.previousPageType&&(this.styler.cascade.previousPageType=this.styler.cascade.currentPageType),this.styler.cascade.currentPageType=wi)}this.nodeContext.captionSide=c["caption-side"]&&c["caption-side"].toString()||"top";let De=c["border-collapse"];if(!De||De===B("separate")){let G=c["border-spacing"],Dt,qt;G&&(G instanceof J?(Dt=G.values[0],qt=G.values[1]):Dt=qt=G,Dt.isNumeric()&&(this.nodeContext.inlineBorderSpacing=ut(Dt,this.context)),qt.isNumeric()&&(this.nodeContext.blockBorderSpacing=ut(qt,this.context)))}let Te=c["footnote-policy"]||V.footnotePolicy;Te&&!Z(Te)&&(c["--viv-footnote-policy"]=Te),this.nodeContext.footnotePolicy=Te&&!Z(Te)?Te:null;let fe=c["x-first-pseudo"];if(fe){let G=this.nodeContext.parent?this.nodeContext.parent.firstPseudo:null;this.nodeContext.firstPseudo=new Uv(G,fe.num)}this.nodeContext.inline||this.processAfterIfcontinues(a,l,h,this.context);let Ce=c["white-space"];if(Ce){let G=ep(Ce.toString());G!==null&&(this.nodeContext.whitespace=G)}let ge=c["hyphenate-character"];ge&&ge instanceof K&&(this.nodeContext.hyphenateCharacter=ge.str);let Ie=c["word-break"],Be=c["line-break"],Fe=c["overflow-wrap"];(Ie===y.break_all||Be===y.anywhere||Fe===y.break_word||Fe===y.anywhere)&&(this.nodeContext.breakWord=!0),this.resolveFormattingContext(this.nodeContext,t,m,z,U,S),this.nodeContext.parent&&this.nodeContext.parent.formattingContext&&(t=this.nodeContext.parent.formattingContext.isFirstTime(this.nodeContext,t)),this.nodeContext.inline||(this.nodeContext.repeatOnBreak=this.processRepeatOnBreak(c),this.findAndProcessRepeatingElements(a,h));let He=!1,gt=null,Zn=[],Rt=a.namespaceURI,me=a.localName,oo=me;Rt=="http://www.w3.org/1999/xhtml"?(_x.has(me)?me="div":me=="vide_"?me="video":me=="audi_"?me="audio":me=="object"&&(He=!!this.customRenderer),a.hasAttribute(hh)&&a.hasAttribute("src")&&c.content instanceof Qe&&(me="img")):Rt=="http://www.idpf.org/2007/ops"?(me="span",Rt="http://www.w3.org/1999/xhtml"):Rt=="http://www.pyroxy.com/ns/shadow"?(Rt="http://www.w3.org/1999/xhtml",me=this.nodeContext.inline?"span":"div"):He=!!this.customRenderer,Q?t?(me="li",c["--viv-marker-content"]&&(Vx(c)||(c["list-style-type"]=y.none,c["list-style-image"]=y.none))):(m=Ut(m)?y.inline:y.block,c.display=m,me="div"):me=="body"||me=="li"?me="div":me=="q"&&(me="span"),c.behavior&&c.behavior.toString()!="none"&&this.customRenderer&&(He=!0),a.dataset&&a.getAttribute("data-math-typeset")==="true"&&(He=!0);let Xs;if(He){let G=this.nodeContext.parent?this.nodeContext.parent.viewNode:null;Xs=this.customRenderer(a,G,c)}else Xs=T(null);Xs.then(G=>{var Dt,qt,an,zt,Kn;if(G)He&&(o=G.getAttribute("data-adapt-process-children")=="true");else if(c.display===y.none){s.finish(!1);return}else G=this.createElement(Rt,me);if(!S&&E&&c["column-fill"]===y.auto){let We=this.nodeContext.vertical?c.width:c.height;(!We||We===y.auto||Z(We))&&(G.setAttribute("data-viv-saved-column-fill","auto"),c["column-fill"]=y.balance)}me!=oo&&(G.setAttribute("data-vivliostyle-original-tag",oo),(oo==="html"||oo==="body")&&(G.role="presentation")),me=="a"&&G.addEventListener("click",this.page.hrefHandler,!1),gt&&(this.applyPseudoelementStyle(this.nodeContext,"inner",gt),G.appendChild(gt)),G.localName=="iframe"&&G.namespaceURI=="http://www.w3.org/1999/xhtml"&&Ux(G);let wi=this.nodeContext.inheritedProps["image-resolution"],qs=[],Ys=c.width,Zs=c.height,Cg=a.getAttribute("width"),kg=a.getAttribute("height"),Ks=Ys===y.auto||!Ys&&!Cg,Js=Zs===y.auto||!Zs&&!kg,xh=a.attributes,Eg=xh.length,Jn=null,Sh=null;m===y.table_cell&&((an=(qt=(Dt=this.nodeContext.parent)==null?void 0:Dt.viewNode)==null?void 0:qt.lastElementChild)==null?void 0:an.localName)==="a"&&G.appendChild(this.nodeContext.parent.viewNode.lastElementChild);for(let We=0;We<Eg;We++){let St=xh[We],ht=St.namespaceURI,ae=St.localName,ke=St.nodeValue;if(ht){if(ht=="http://www.w3.org/2000/xmlns/")continue;ht=="http://www.w3.org/1999/xlink"&&ae=="href"&&(ke=this.documentURLTransformer.transformURL(this.resolveURL(ke),this.xmldoc.url))}else{if(!vi&&ae.match(/^on/)||ae=="style")continue;if(ae==="media"&&me==="source"&&Rt==="http://www.w3.org/1999/xhtml"&&((zt=a.parentElement)==null?void 0:zt.localName)==="picture")try{let Ge=this.context.rootScope,mt=new Bs(Ge),ao=new xt(ke,mt),Ch=Dd(ao,mt,"");if(Ch){if(Ch.toExpr().evaluate(this.context))continue;ke="not all"}}catch{}if((ae=="id"||ae=="name")&&t){let Ge=this.documentURLTransformer.transformFragment(ke,this.xmldoc.url);G.setAttribute(ae,ke),G.setAttribute("data-vivliostyle-id",Ge);let mt=G.ownerDocument.createElement("a");mt.setAttribute(ae,Ge),mt.setAttribute(zn,"1"),mt.style.position="absolute",G.appendChild(mt),this.page.registerElementWithId(G,Ge);continue}if(ae=="src"||ae=="href"||ae=="poster")ke=this.resolveURL(ke),ae==="href"?ke=this.documentURLTransformer.transformURL(ke,this.xmldoc.url):ke=Ir(ke),ae==="src"&&(ke=xc(ke));else if(ae=="srcset")ke=ke.split(",").map(Ge=>{let mt=Ge.trim().split(/\s+/),ao=Ir(this.resolveURL(mt[0]));return mt.length>1?`${ao} ${mt.slice(1).join(" ")}`:ao}).join(",");else if(ae==="data"&&He&&me==="object"&&G.hasAttribute("data"))continue;if(ae==="poster"&&me==="video"&&Rt==="http://www.w3.org/1999/xhtml"){let Ge=new Image,mt=Et(Ge,ke);Ks&&Js?(Zn.push(mt),qs.push({image:Ge,element:G,fetcher:mt})):this.page.fetchers.push(mt)}}if(Rt=="http://www.w3.org/2000/svg"&&/^[A-Z\-]+$/.test(ae)&&(ae=ae.toLowerCase()),this.isSVGUrlAttribute(ae)&&(ke=Bx(ke,this.xmldoc.url,this.documentURLTransformer)),ht){let Ge=Mx[ht];Ge&&(ae=`${Ge}:${ae}`)}if(ae=="src"&&!ht&&(me=="img"||me=="input")&&Rt=="http://www.w3.org/1999/xhtml")Jn=ke;else if(ae=="alt"&&!ht&&me=="img"&&Rt=="http://www.w3.org/1999/xhtml")Sh=ke;else if(ae=="href"&&me=="image"&&Rt=="http://www.w3.org/2000/svg"&&(ht=="http://www.w3.org/1999/xlink"||!ht))ht||G.setAttribute(ae,ke),this.page.fetchers.push(Et(G,ke));else if(ht)G.setAttributeNS(ht,ae,ke);else try{G.setAttribute(ae,ke)}catch(Ge){Y.warn(Ge)}}if(Jn){let We=me==="input"?new Image:G,St=Et(We,Jn,Sh);We!==G&&(G.src=Jn);let ht=()=>{var ae,ke;if(c.position===y.fixed)return!0;for(let Ge=(ae=this.nodeContext.parent)==null?void 0:ae.viewNode;Ge&&Ge!==this.viewRoot;Ge=Ge.parentElement)if(((ke=Ge.style)==null?void 0:ke.position)==="fixed")return!0;return!1};!Ks&&!Js&&!(()=>{let ae=this.nodeContext.vertical?Ys:Zs;return ae instanceof O&&ae.unit==="%"})()&&!ht()?this.page.fetchers.push(St):(Ks&&Js&&wi&&wi!==1&&qs.push({image:We,element:G,fetcher:St}),Zn.push(St))}else!Jn&&me==="img"&&Rt==="http://www.w3.org/1999/xhtml"&&(G.srcset||((Kn=a.parentElement)==null?void 0:Kn.localName)==="picture")&&this.page.fetchers.push(Et(G));delete c.content;let so=c["--viv-marker-content"];if(so){let We=so instanceof J?so.values:[so];for(let St of We)St instanceof Qe&&St.url&&Zn.push(Et(new Image,St.url))}if(G.localName==="object"&&G.namespaceURI==="http://www.w3.org/1999/xhtml"&&G.hasAttribute("data")&&this.page.fetchers.push(Et(G)),G.localName==="embed"&&G.namespaceURI==="http://www.w3.org/1999/xhtml"&&G.hasAttribute("src")&&this.page.fetchers.push(Et(G)),G.localName==="iframe"&&G.namespaceURI==="http://www.w3.org/1999/xhtml"&&G.hasAttribute("src")){let We=G;We.loading==="lazy"&&(We.loading="eager"),this.page.fetchers.push(Et(G))}if(this.preprocessElementStyle(c),this.applyComputedStyles(G,c),this.nodeContext.inline)t||(Ct(G,"inline-start"),Nn(G)&&Ct(G,"clone"));else if(t){if(!Fr(c.position)){let We=c["margin-break"],St=this.getBreakTypeAt(this.nodeContext),ht=St!==null,ae=St==="auto";(We===y.discard&&ht||We!==y.keep&&ae&&!this.nodeContext.floatSide)&&sa(G,"block-start")}}else{let We=this.nodeContext.vertical?"width":"height";ki(G,We)&&I(G,We,this.nodeContext.display==="table-row"?"0.01px":""),Ct(G,"block-start"),Nn(G)&&Ct(G,"clone"),sa(G,"block-start")}Q&&c["ua-list-item-count"]&&G.setAttribute("value",c["ua-list-item-count"].stringValue()),this.viewNode=G,Zn.length?Dn(Zn).then(()=>{wi>0&&this.modifyElemDimensionWithImageResolution(qs,wi,c,this.nodeContext.vertical),s.finish(o)}):s.timeSlice().then(()=>{s.finish(o)})})}),s.result()}isAtStartOfPage(){var t,i;for(let n=this.nodeContext;n!=null&&n.parent&&!n.after;n=n.parent){let r=n===this.nodeContext&&!n.viewNode?(t=n.parent.viewNode)==null?void 0:t.lastChild:(i=n.viewNode)==null?void 0:i.previousSibling;for(;r&&(Ee(r,n.parent.whitespace)||Ot(r));)r=r.previousSibling;if(r)return!1}return!0}isInsideNonRootMultiColumn(){var t;let i=(t=this.nodeContext.parent)==null?void 0:t.viewNode;return!!(i&&eo(i))}getBreakTypeAt(t){var i,n,r,o,s;if(this.isInsideTable(t))return null;for(let h=t;h&&!h.after;h=h.parent){if(Ze(h.breakBefore))return h.breakBefore;if(h.fragmentIndex===1&&!h.parent)return h.sourceNode===h.sourceNode.ownerDocument.documentElement?"page":null;if((i=h.parent)!=null&&i.floatSide)return null;let l=(n=h.parent)==null?void 0:n.viewNode;if(l){let c=this.viewport.window.getComputedStyle(l),d=parseFloat(c.paddingBlockStart),p=parseFloat(c.borderBlockStartWidth);if(d||p)return null;let f=l?.firstChild;for(;f&&(Ee(f,h.parent.whitespace)||!h.floatSide&&Ot(f));)f=f.nextSibling;if(f&&f!==h.viewNode)return null}}let a=(s=(o=(r=this.context)==null?void 0:r.currentLayoutPosition)==null?void 0:o.flowPositions[this.flowName])==null?void 0:s.startBreakType;return Ze(a)?a:"auto"}isInsideTable(t){for(let i=t;i&&!i.after;i=i.parent)if(i.display&&i.display.startsWith("table"))return!0;return!1}processAfterIfcontinues(t,i,n,r){let o=this.getPseudoMap(i,this.regionIds,this.isFootnote,this.nodeContext,r);if(o&&o["after-if-continues"]&&o["after-if-continues"].content){let s=new ma(t,i,n,r,this.exprContentListener);this.nodeContext.afterIfContinues=new P0(t,s)}}isSVGUrlAttribute(t){return gr.SVG_URL_ATTRIBUTES.includes(t.toLowerCase())}modifyElemDimensionWithImageResolution(t,i,n,r){t.forEach(o=>{if(o.fetcher.get().get()==="load"){let s=o.image,a=s.width/i,h=s.height/i,l=o.element;if(a>0&&h>0){if(n["box-sizing"]===y.border_box&&(n["border-left-style"]!==y.none&&(a+=ut(n["border-left-width"],this.context)),n["border-right-style"]!==y.none&&(a+=ut(n["border-right-width"],this.context)),n["border-top-style"]!==y.none&&(h+=ut(n["border-top-width"],this.context)),n["border-bottom-style"]!==y.none&&(h+=ut(n["border-bottom-width"],this.context))),i>1){let c=n["max-width"]||y.none,d=n["max-height"]||y.none;if(c===y.none&&d===y.none)I(l,"max-width",`${a}px`);else if(c!==y.none&&d===y.none)I(l,"width",`${a}px`);else if(c===y.none&&d!==y.none)I(l,"height",`${h}px`);else{c.isNumeric(),d.isNumeric();let p=c,f=d;p.unit!=="%"?I(l,"max-width",`${Math.min(a,ut(p,this.context))}px`):f.unit!=="%"?I(l,"max-height",`${Math.min(h,ut(f,this.context))}px`):r?I(l,"height",`${h}px`):I(l,"width",`${a}px`)}}else if(i<1){let c=n["min-width"]||Le,d=n["min-height"]||Le;c.isNumeric(),c.isNumeric();let p=c,f=d;p.num===0&&f.num===0?I(l,"min-width",`${a}px`):p.num!==0&&f.num===0?I(l,"width",`${a}px`):p.num===0&&f.num!==0?I(l,"height",`${h}px`):p.unit!=="%"?I(l,"min-width",`${Math.max(a,ut(p,this.context))}px`):f.unit!=="%"?I(l,"min-height",`${Math.max(h,ut(f,this.context))}px`):r?I(l,"height",`${h}px`):I(l,"width",`${a}px`)}}}})}preprocessElementStyle(t){_t("PREPROCESS_ELEMENT_STYLE").forEach(i=>{i(this.nodeContext,t)})}findAndProcessRepeatingElements(t,i){for(let n=t.firstChild;n;n=n.nextSibling){if(n.nodeType!==1)continue;let r={},o=i.getStyle(n,!1);if(this.computeStyle(this.nodeContext.vertical,this.nodeContext.direction==="rtl",o,r),!this.processRepeatOnBreak(r))continue;if(this.nodeContext.formattingContext instanceof tn&&!this.nodeContext.belongsTo(this.nodeContext.formattingContext))return;let s=this.nodeContext.parent,a=s&&s.formattingContext;this.nodeContext.formattingContext=new tn(a,this.nodeContext.sourceNode),this.nodeContext.formattingContext.initializeRepetitiveElements(this.nodeContext.vertical);return}}processRepeatOnBreak(t){let i=t["repeat-on-break"];return i!==y.none&&((i===y.auto||Z(i))&&(t.display===y.table_header_group?i=y.header:t.display===y.table_footer_group?i=y.footer:i=y.none),i&&i!==y.none)?i.toString():null}createTextNodeView(){let t=M("createTextNodeView");return this.preprocessTextContent().then(()=>{let i=this.offsetInNode||0,n=hu(this.nodeContext.preprocessedTextContent).substr(i);this.viewNode=document.createTextNode(n),t.finish(!0)}),t.result()}preprocessTextContent(){if(this.nodeContext.preprocessedTextContent!=null)return T(!0);let t,i=t=this.sourceNode.textContent,n=M("preprocessTextContent"),r=_t("PREPROCESS_TEXT_CONTENT"),o=0;return n.loop(()=>o>=r.length?T(!1):r[o++](this.nodeContext,i).thenAsync(s=>(i=s,T(!0)))).then(()=>{this.nodeContext.preprocessedTextContent=Av(t,i),n.finish(!0)}),n.result()}createNodeView(t,i){let n=M("createNodeView"),r,o=!0;return this.sourceNode.nodeType==1?r=this.createElementView(t,i):this.sourceNode.nodeType==8?(this.viewNode=null,r=T(!0)):r=this.createTextNodeView(),r.then(s=>{var a;if(o=s,this.nodeContext.viewNode=this.viewNode,this.viewNode){let h=(d,p)=>d?.nodeType===1&&Yt(d)===p,l=this.nodeContext.parent,c=l?h(this.viewNode,"after")&&h(l.viewNode,"first-letter")&&(a=l.viewNode)!=null&&a.hasChildNodes()?l.parent.viewNode:l.viewNode:this.viewRoot;this.nodeContext.pluginProps.nestedFootnoteDetached&&(c=this.viewRoot),c&&(this.nodeContext.inline&&!(this.viewNode.nodeType===3&&Ee(this.viewNode))&&!c.hasChildNodes()&&Zd(c).includes("block-start")&&Ct(c,"text-start"),c.appendChild(this.viewNode),mv(this.viewNode))}n.finish(o)}),n.result()}setCurrent(t,i,n){return this.nodeContext=t,t?(this.sourceNode=t.sourceNode,this.offsetInNode=t.offsetInNode):(this.sourceNode=null,this.offsetInNode=-1),this.viewNode=null,this.nodeContext?this.createNodeView(i,!!n):T(!0)}processShadowContent(t){if(t.shadowContext==null||t.sourceNode.localName!="content"||t.sourceNode.namespaceURI!="http://www.pyroxy.com/ns/shadow")return t;let i=t.boxOffset,n=t.shadowContext,r=t.parent,o,s,a=n.subShadow||n.parentShadow;n.subShadow?(o=n.subShadow.root,s=n.subShadow.type,s==st.ROOTLESS&&(o=o.firstChild)):(o=n.owner.firstChild,s=st.ROOTLESS);let h=t.sourceNode.nextSibling;if(h?(t.sourceNode=h,t.resetView()):t.shadowSibling?t=t.shadowSibling:o?t=null:(t=t.parent.modify(),t.after=!0),o){let l=new xn(o,r,i);return l.shadowContext=a,l.shadowType=s,l.shadowSibling=t,this.processShadowContent(l)}return t.boxOffset=i,t}nextPositionInTree(t){let i=t.boxOffset+1;if(t.after){if(!t.parent)return null;if(t.shadowType!=st.ROOTED){let n=t.sourceNode.nextSibling;if(n)return t=t.modify(),t.boxOffset=i,t.sourceNode=n,t.resetView(),this.processShadowContent(t)}return t.shadowSibling?(t=t.shadowSibling.modify(),t.boxOffset=i,t):(t=t.parent.modify(),t.boxOffset=i,t.after=!0,t)}else{if(t.nodeShadow){let r=t.nodeShadow.root;if(t.nodeShadow.type==st.ROOTLESS&&(r=r.firstChild),r){let o=new xn(r,t,i);return o.shadowContext=t.nodeShadow,o.shadowType=t.nodeShadow.type,this.processShadowContent(o)}}let n=t.sourceNode.firstChild;if(n)return this.processShadowContent(new xn(n,t,i));if(t.sourceNode.nodeType!=1){let r=hu(t.preprocessedTextContent);i+=r.length-1-t.offsetInNode}return t=t.modify(),t.boxOffset=i,t.after=!0,t}}findImmediateFootnoteCallSibling(t){let i=this.xmldoc.getElementOffset(t.sourceNode),n=t.viewNode;if(!n)return null;let r=n.previousSibling;for(;r;){if(r.nodeType===Node.TEXT_NODE){if(r.textContent.trim().length===0){r=r.previousSibling;continue}return null}if(r.nodeType===Node.ELEMENT_NODE){let o=r;return Yt(o)==="footnote-call"&&o.getAttribute(gr.FOOTNOTE_CALL_OWNER_ATTR)===i.toString()?o:null}return null}return null}isSemanticFootnoteElement(t){let i=t.sourceNode;return i instanceof Element&&Pt(i)}insertFootnoteCall(t){var i,n;let r=M("insertFootnoteCall"),o=pr.createElementNS("http://www.w3.org/1999/xhtml","span");Er(o,"footnote-call");let s=this.xmldoc.getElementOffset(t.sourceNode);o.setAttribute(gr.FOOTNOTE_CALL_OWNER_ATTR,s.toString());let a=new xn(o,t.parent,t.boxOffset);a.inline=!0;let h=new ma(t.sourceNode,this.styler.getStyle(t.sourceNode,!1),this.styler,this.context,this.exprContentListener);return a.shadowContext=new Bo(t.sourceNode,o,null,((i=t.parent)==null?void 0:i.shadowContext)||null,null,st.ROOTLESS,h),a.shadowSibling=t,t.boxOffset++,(n=t.viewNode)!=null&&n.parentNode&&t.viewNode.parentNode.removeChild(t.viewNode),this.setCurrent(a,!0,!1).then(l=>{if(l&&o.hasChildNodes())r.finish(a);else{let c=a.modify();c.after=!0,a.viewNode||(c.inline=!0),r.finish(c)}}),r.result()}nextInTree(t,i){let n=this.nextPositionInTree(t);if(!n||n.after)return T(n);this.syncTextNodePageTypeBoundary(n);let r=M("nextInTree");return this.setCurrent(n,!0,i).then(o=>{if((!n.viewNode||!o)&&(n=n.modify(),n.after=!0,n.viewNode||(n.inline=!0)),n.floatSide==="footnote"&&!(this.isFootnote&&!n.parent)&&!n.after&&!n.pluginProps.footnoteCallProcessed&&!n.shadowContext&&!this.isSemanticFootnoteElement(n)){let s=this.findImmediateFootnoteCallSibling(n);s!=null&&s.parentNode&&s.parentNode.removeChild(s),this.isFootnote&&n.parent&&(n.pluginProps.nestedFootnoteDetached=1),n.pluginProps.footnoteCallProcessed=1,this.insertFootnoteCall(n).then(a=>{this.dispatchEvent({type:"nextInTree",nodeContext:a}),r.finish(a)});return}this.dispatchEvent({type:"nextInTree",nodeContext:n}),r.finish(n)}),r.result()}addImageFetchers(t){Pr(t,this.page)}applyComputedStyles(t,i){var n,r,o;let s=i["background-image"];s&&this.addImageFetchers(s);let a=i["border-image-source"];a&&this.addImageFetchers(a);let h=i["list-style-image"];h&&this.addImageFetchers(h);let l=i["mask-image"];l&&this.addImageFetchers(l);let c=i["clip-path"];c&&this.addImageFetchers(c);let d=i.filter;d&&this.addImageFetchers(d);let p=i["shape-outside"];p&&this.addImageFetchers(p);let f=i["--viv-marker-content"];f&&this.addImageFetchers(f);let g=i.position===y.relative,v=((n=this.nodeContext)==null?void 0:n.parent)===null&&((r=this.sourceNode)==null?void 0:r.parentElement)===null&&!!((o=this.viewRoot)!=null&&o.parentElement),w=Object.keys(i);w.sort(_h);let x,m;for(let S of w){if(Hx[S])continue;let b=i[S];if(!(!b||b===Me&&!Xe(S))){if(b=b.visit(new jm(this.xmldoc.url,this.documentURLTransformer)),b instanceof O)if(b.unit==="em"){let C=this.getEmUnitSize(S,x);C!=null&&(b=new O(b.num*C,"px"))}else if(b.unit==="lh"){let C=this.getLineHeightUnitSize(S,x,m);C!=null&&(b=new O(b.num*C,"px"))}else Ic(b.unit)&&(b=qc(b,this.context));if((S==="font-size"||S==="line-height")&&(S==="font-size"?x=b:m=b,this.viewport.layoutUnitAdj&&b instanceof O&&b.unit!=="%"&&b.unit!=="em"&&b.unit!=="lh"&&(b=new fn(`calc(${b.toString()} - var(--viv-layoutUnitAdj))`))),Rv[S]||g&&Lv[S]){this.page.delayedItems.push(new Ul(t,S,b));continue}v&&this.page.pageAreaElement&&In(S)?(I(this.page.pageAreaElement.parentElement.parentElement,S,b.toString()),S!=="writing-mode"&&S!=="direction"&&I(this.viewport.layoutBox,S,b.toString())):I(t,S,b.toString())}}}parsePlusLayoutUnitAdj(t){if(t.endsWith("px")){let i=parseFloat(t);if(!isNaN(i))return Math.round((i+this.viewport.layoutUnitAdj)*this.viewport.layoutUnitPerPixel)/this.viewport.layoutUnitPerPixel}return null}getFootnoteAreaInheritedMetrics(){var t,i;let n=(i=(t=this.page.pageAreaElement)==null?void 0:t.parentElement)==null?void 0:i.parentElement,r=n?this.viewport.window.getComputedStyle(n):null,o=r&&this.parsePlusLayoutUnitAdj(r.fontSize)||this.context.rootFontSize||this.context.initialFontSize,s=r&&this.parsePlusLayoutUnitAdj(r.lineHeight)||this.context.rootLineHeight||o*this.context.pref.lineHeight;return{fontSize:o,lineHeight:s}}getComputedFontMetrics(t,i){var n,r,o;let s=this.viewport.window.getComputedStyle(t),a=(n=this.parsePlusLayoutUnitAdj(s.fontSize))!=null?n:i.fontSize,h=(o=(r=this.parsePlusLayoutUnitAdj(s.lineHeight))!=null?r:i.lineHeight)!=null?o:a!=null?a*this.context.pref.lineHeight:null;return{fontSize:a,lineHeight:h}}getParentViewStyle(){var t,i,n;return((n=(i=(t=this.nodeContext)==null?void 0:t.parent)==null?void 0:i.viewNode)==null?void 0:n.nodeType)===1?this.viewport.window.getComputedStyle(this.nodeContext.parent.viewNode):null}getParentComputedMetrics(t){var i,n;return{fontSize:(i=this.computedStyleParentFontSizeOverride)!=null?i:t?this.parsePlusLayoutUnitAdj(t.fontSize):this.context.rootFontSize,lineHeight:(n=this.computedStyleParentLineHeightOverride)!=null?n:t?this.parsePlusLayoutUnitAdj(t.lineHeight):this.context.rootLineHeight}}getLineHeightUnitSize(t,i,n){var r,o,s;let a=this.getParentViewStyle(),h=this.getParentComputedMetrics(a),l=h.lineHeight;if(t==="line-height"||t==="font-size")return l;let c=null;if(n)if(n instanceof At||n instanceof O&&(n.unit==="em"||n.unit==="%"))c=n instanceof O&&n.unit==="%"?n.num/100:n.num;else{if(n instanceof O&&n.unit!=="lh"){let d=this.context.queryUnitSize(n.unit,!1);if(d!=null)return n.num*d}return null}if(c==null)for(let d=(o=(r=this.nodeContext)==null?void 0:r.parent)==null?void 0:o.viewNode;d&&d.nodeType===1;d=d.parentNode){let p=(s=d?.style)==null?void 0:s.lineHeight;if(p){/^[0-9.]+$/.test(p)&&(c=parseFloat(p));break}}if(c!=null){if(i&&!(i instanceof O))return null;let d=h.fontSize;if(i instanceof O){let p=rl(i,d,this.context).num;return typeof p!="number"||isNaN(p)?null:c*p}else return d==null?null:c*d}return l}getEmUnitSize(t,i){let n=this.getParentViewStyle(),r=this.getParentComputedMetrics(n).fontSize;if(t==="font-size"||i==null)return r;if(i instanceof O){let o=rl(i,r,this.context).num;if(typeof o=="number"&&!isNaN(o))return o}return null}applyPseudoelementStyle(t,i,n){if(t.after)return;let r=this.sourceNode,o=(t.shadowContext?t.shadowContext.styler:this.styler).getStyle(r,!1),s=ft(o,"_pseudos");if(!s||(o=s[i],!o))return;let a={};t.vertical=this.computeStyle(t.vertical,t.direction==="rtl",o,a);let h=a.content;It(h)&&(h.visit(new Lr(n,this.context,h,this.exprContentListener)),delete a.content),this.applyComputedStyles(n,a)}peelOff(t,i){let n=M("peelOff"),r=t.firstPseudo,o=t.offsetInNode,s=t.after;if(i>0){let d=t.viewNode.textContent;t.viewNode.textContent=d.substr(0,i),o+=i}else if(!s&&t.viewNode&&o==0){let d=t.viewNode.parentNode;d&&d.removeChild(t.viewNode)}let a=t.boxOffset+i,h=[];for(;t&&t.firstPseudo===r;)h.push(t),t=t.parent;let l=h.pop(),c=l.shadowSibling;return n.loop(()=>{for(;h.length>0;){l=h.pop(),t=new xn(l.sourceNode,t,a),h.length==0&&(t.offsetInNode=o,t.after=s),t.shadowType=l.shadowType,t.shadowContext=l.shadowContext,t.nodeShadow=l.nodeShadow,t.shadowSibling=l.shadowSibling?l.shadowSibling:c,c=null;let d=this.setCurrent(t,!1);if(d.isPending())return d}return T(!1)}).then(()=>{n.finish(t)}),n.result()}createElement(t,i){return t=="http://www.w3.org/1999/xhtml"?this.document.createElement(i):this.document.createElementNS(t,i)}applyFootnoteStyle(t,i,n){var r;let o={},s=[],a=this.footnoteStyle;if(this.cascadedPageStyle){let p=ft(this.cascadedPageStyle,Ns);p&&p.area&&(a=p.area)}let h=ft(a,"_pseudos");t=this.computeStyle(t,i,a,o);let l=this.getFootnoteAreaInheritedMetrics();!o["font-size"]&&l.fontSize!=null&&(o["font-size"]=new O(l.fontSize,"px")),delete o.content;let c=this.computedStyleParentFontSizeOverride,d=this.computedStyleParentLineHeightOverride;this.computedStyleParentFontSizeOverride=l.fontSize,this.computedStyleParentLineHeightOverride=l.lineHeight;try{this.applyComputedStyles(n,o);let p=this.getComputedFontMetrics(n,l);if(this.computedStyleParentFontSizeOverride=p.fontSize,this.computedStyleParentLineHeightOverride=p.lineHeight,h&&h.before){let f=h.before,g=!!ve(f,"display"),v={},w=this.createElement("http://www.w3.org/1999/xhtml","span");Er(w,"before"),n.appendChild(w),this.computeStyle(t,i,f,v),g||(v.display=y.block);let x=ve(f,"content");if(x){let S=((r=this.sourceNode)==null?void 0:r.nodeType)===1?this.sourceNode:this.xmldoc.root;v.content=x.filterValue(new _r(this.styler.cascade,S,this.styler.cascade.counterResolver,"before")).evaluate(this.context,"content")}let m=v.content;if(It(m)){m.visit(new Lr(w,this.context,m,this.exprContentListener));let S=w.querySelectorAll("img[src]");for(let C=0;C<S.length;C++){let P=S[C],L=P.getAttribute("src");if(!L)continue;let A=Et(P,L);s.push(A),this.page.fetchers.push(A)}let b=w.getAttribute("src");if(b){let C=w.querySelector("img");C||(C=this.document.createElement("img"),C.setAttribute("src",b),w.appendChild(C));let P=Et(C,b);s.push(P),this.page.fetchers.push(P)}}delete v.content,this.applyComputedStyles(w,v)}}finally{this.computedStyleParentFontSizeOverride=c,this.computedStyleParentLineHeightOverride=d}return s.length?Dn(s).thenReturn(t):T(t)}processFragmentedBlockEdge(t){var i,n,r;let o=!t.inline&&t.after?t.parent:t,s=!1;if(t.inline&&t.after&&!t.shadowContext&&((i=t.sourceNode.nextSibling)==null?void 0:i.nodeType)===1){let h=t.sourceNode.nextSibling,l=(n=ve(this.styler.getStyle(h,!1),"display"))==null?void 0:n.value.toString();s=l&&!Ut(l)||h.getAttribute("data-math-typeset")==="true"&&/^\s*(\$\$|\\\[)/.test(h.textContent)}let a=0;for(let h=o;h;h=h.parent){if(((r=h.viewNode)==null?void 0:r.nodeType)!==1)continue;let l=h.viewNode;if(l.style)if(h.inline){if(Ct(l,"inline-end"),Nn(l)){let c=h.vertical?l.offsetWidth:l.offsetHeight;Ct(l,"clone"),(h.vertical?l.offsetWidth:l.offsetHeight)>c&&this.fixClonedBoxDecorationOverflow(l)}}else{let c=this.nodeContext.vertical?"width":"height";if(ki(l,c)&&I(l,c,""),Ct(l,"block-end"),!a++&&h!==o){let{textAlign:d}=this.viewport.window.getComputedStyle(l);if(d==="justify"&&!s){let p=this.createChildAnonymousBlockIfNeeded(l);p?p!==l?Kd(p,["block-start","text-start","block-end","text-end","justify"]):(Ct(l,"text-end"),Ct(l,"justify")):Ct(l,"text-end")}else Ct(l,"text-end")}Nn(l)&&Ct(l,"clone"),sa(l,"block-end")}}}fixClonedBoxDecorationOverflow(t){let i=this.viewport.window.getComputedStyle(t),n=parseFloat(i.paddingInlineEnd),r=parseFloat(i.borderInlineEndWidth),o=-(n+r);isNaN(o)||(t.style.marginInlineEnd=`${o}px`)}createChildAnonymousBlockIfNeeded(t){let i=o=>{let{display:s,position:a,float:h}=this.viewport.window.getComputedStyle(o);if(o.localName==="ruby"||ji[o.localName])return!1;if(o.localName==="br")return!0;if((s==="inline"||s==="contents")&&o.hasChildNodes()){let l=o.lastElementChild;if(l&&(!l.nextSibling||l.nextSibling===o.lastChild&&Ee(l.nextSibling))){let c=i(l);if(c||c===null)return c}for(let c=l?.previousElementSibling;c;c=c.previousElementSibling){let d=i(c);if(d||d===null)return null}return!1}if(s==="none"||a==="absolute"||a==="fixed"||h&&h!=="none"||o.hasAttribute(zn)){let l=o.previousElementSibling;return l&&(l.nextSibling===o||l.nextSibling===o.previousSibling&&Ee(l.nextSibling))?i(l):!1}return!(!s||Ut(s))},n=null;for(let o=t.lastElementChild;o;o=o.previousElementSibling){let s=i(o);if(s){n=o;break}if(s===null)return null}if(!n)return t;if(n===t.lastElementChild&&(!n.nextSibling||n.nextSibling===t.lastChild&&Ee(n.nextSibling)))return null;let r=t.ownerDocument.createElement("span");r.className="viv-anonymous-block";for(let o=n.nextSibling,s=null;o;o=s)s=o.nextSibling,r.appendChild(o);return t.appendChild(r),r}convertLengthToPx(t,i,n){let r=t.num,o=t.unit;if(um(o)){let s=i;for(;s&&s.nodeType!==1;)s=s.parentNode;let a=parseFloat(n.getElementComputedStyle(s)["font-size"]);return this.context,nh(t,a,this.context).num}else{let s=this.context.queryUnitSize(o,!1);return s?r*s:t}}isSameNodePositionStep(t,i){if(t.shadowContext){if(!i.shadowContext)return!1;let n=t.node.nodeType===1?t.node:t.node.parentElement,r=i.node.nodeType===1?i.node:i.node.parentElement;return t.shadowContext.owner===i.shadowContext.owner&&Yt(n)===Yt(r)}else return t.node===i.node}isSameNodePosition(t,i){return t.offsetInNode===i.offsetInNode&&t.after==i.after&&t.steps.length===i.steps.length&&t.steps.every((n,r)=>{let o=i.steps[r];return this.isSameNodePositionStep(n,o)})}isPseudoelement(t){return!!Yt(t)}};u(fl,"SVG_URL_ATTRIBUTES",["color-profile","clip-path","cursor","filter","marker","marker-start","marker-end","marker-mid","fill","stroke","mask"]),u(fl,"FOOTNOTE_CALL_OWNER_ATTR","data-viv-footnote-call-owner");var $x=fl,Hx={"float-min-wrap-block":!0,"float-reference":!0,"flow-into":!0,"flow-linger":!0,"flow-options":!0,"flow-priority":!0,"footnote-display":!0,"footnote-policy":!0,"margin-break":!0,page:!0},Wx=class{constructor(e){u(this,"layoutBox"),u(this,"window"),u(this,"pixelRatio"),u(this,"scaleRatio"),u(this,"layoutUnitPerPixel"),this.layoutBox=e.layoutBox,this.window=e.window,this.pixelRatio=e.pixelRatio,this.scaleRatio=e.scaleRatio,this.layoutUnitPerPixel=e.layoutUnitPerPixel}subtractOffsets(e,t){let i=t.left,n=t.top;return{left:e.left-i,top:e.top-n,right:e.right-i,bottom:e.bottom-n,width:e.width,height:e.height}}getRangeClientRects(e){let t=e.getClientRects(),i=this.layoutBox.getBoundingClientRect();return Array.from(t).map(n=>this.subtractOffsets(n,i))}getElementClientRect(e){let t=e.getBoundingClientRect();if(t.left===0&&t.top===0&&t.right===0&&t.bottom===0)return t;let i=this.layoutBox.getBoundingClientRect();return this.subtractOffsets(t,i)}getElementComputedStyle(e){return this.window.getComputedStyle(e,null)}adjustLengthValue(e){return this.layoutUnitPerPixel?Math.floor(e*this.layoutUnitPerPixel)/this.layoutUnitPerPixel:e}},Es=class{constructor(e,t,i,n,r,o){if(u(this,"window",e),u(this,"fontSize",t),u(this,"pixelRatio",i),u(this,"document"),u(this,"root"),u(this,"outerZoomBox"),u(this,"contentContainer"),u(this,"layoutBox"),u(this,"width"),u(this,"height"),u(this,"scaleRatio",1),u(this,"layoutUnitPerPixel",64),u(this,"layoutUnitAdj",0),this.document=e.document,this.root=n||this.document.body,this.root.hasAttribute("data-vivliostyle-toc-box")){this.outerZoomBox=this.contentContainer=this.layoutBox=this.root,this.width=r||this.root.clientWidth,this.height=o||this.root.clientHeight;return}let s=this.root.firstElementChild;s||(s=this.document.createElement("div"),s.setAttribute("data-vivliostyle-outer-zoom-box","true"),s.role="presentation",this.root.appendChild(s));let a=s.firstElementChild;switch(a||(a=this.document.createElement("div"),a.setAttribute("data-vivliostyle-spread-container","true"),a.role="presentation",s.appendChild(a)),i>0&&CSS.supports("zoom","8")&&(I(this.root,"--viv-outputPixelRatio",`${i}`),I(this.root,"--viv-devicePixelRatio",`${e.devicePixelRatio}`),this.scaleRatio=i/e.devicePixelRatio),Gr){case"chromium":this.layoutUnitPerPixel=64*(this.pixelRatio||e.devicePixelRatio),this.layoutUnitAdj=1/this.layoutUnitPerPixel;break;case"firefox":this.layoutUnitPerPixel=60,this.layoutUnitAdj=1/this.layoutUnitPerPixel;break;default:this.layoutUnitPerPixel=64,this.layoutUnitAdj=0}this.layoutUnitAdj&&I(this.root,"--viv-layoutUnitAdj",`${this.layoutUnitAdj}px`);let h=s.nextElementSibling;h||(h=this.document.createElement("div"),h.setAttribute("data-vivliostyle-layout-box","true"),h.role="presentation",this.root.appendChild(h)),this.outerZoomBox=s,this.contentContainer=a,this.layoutBox=h,this.width=r||parseFloat(e.getComputedStyle(this.root).width)||this.root.offsetWidth||e.innerWidth,this.height=o||parseFloat(e.getComputedStyle(this.root).height)||this.root.offsetHeight||e.innerHeight;let l={width:794,height:1056},c=!e.outerWidth&&!e.outerHeight||/Headless/.test(navigator.userAgent)||navigator.webdriver&&e.innerWidth===800&&e.innerHeight===600;(!this.width||!r&&c)&&(this.width=l.width),(!this.height||!o&&c)&&(this.height=l.height)}resetZoom(){I(this.outerZoomBox,"width",""),I(this.outerZoomBox,"height",""),I(this.contentContainer,"width",""),I(this.contentContainer,"height",""),I(this.contentContainer,"transform","")}zoom(e,t,i){I(this.root,"--viv-outputScale",`${i}`),I(this.outerZoomBox,"width",`${e*i}px`),I(this.outerZoomBox,"height",`${t*i}px`),I(this.contentContainer,"width",`${e}px`),I(this.contentContainer,"height",`${t}px`)}clear(){let e=this.root;for(;e.lastChild;)e.removeChild(e.lastChild)}};function Pr(e,t){if(e instanceof Oe)for(let i of e.values)Pr(i,t);else if(e instanceof Qe){let i=Ir(e.url);t.fetchers.push(Et(new Image,i))}else if(e instanceof ai)for(let i of e.values)Pr(i,t);else if(e instanceof J)for(let i of e.values)Pr(i,t)}var Gx=1,Gs=class{constructor(e,t,i,n,r){u(this,"name",t),u(this,"pseudoName",i),u(this,"classes",n),u(this,"parent",r),u(this,"specified",{}),u(this,"children",[]),u(this,"pageMaster",null),u(this,"index",0),u(this,"key"),u(this,"_scope"),this._scope=e,this.key=`p${Gx++}`,r&&(this.index=r.children.length,r.children.push(this))}get scope(){return this._scope}createInstance(e){throw new Error("E_UNEXPECTED_CALL")}clone(e){throw new Error("E_UNEXPECTED_CALL")}copySpecified(e){let t=this.specified,i=e.specified;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=t[n])}cloneChildren(e){for(let t=0;t<this.children.length;t++)this.children[t].clone({parent:e})}},jx=class extends Gs{constructor(e){super(e,null,null,[],null),this.specified.width=new W(qr,0),this.specified.height=new W(Yr,0)}},Wu=class extends ts{constructor(e,t){super(e,n),u(this,"pageMaster",t);let i=this;function n(r,o){let s=r.match(/^([^.]+)\.([^.]+)$/);if(s){let a=i.pageMaster.keyMap[s[1]];if(a){let h=this.lookupInstance(a);if(h)return o?h.resolveFunc(s[2]):h.resolveName(s[2])}}return null}}},Jf=class Qf extends Gs{constructor(t,i,n,r,o,s,a){super(t,i,n,r,o),u(this,"condition",s),u(this,"specificity",a),u(this,"keyMap",{}),t instanceof Wu||(this._scope=new Wu(t,this)),this.pageMaster=this,this.specified.width=new W(qr,0),this.specified.height=new W(Yr,0),this.specified["wrap-flow"]=new W(y.auto,0),this.specified.position=new W(y.relative,0),this.specified.overflow=new W(y.visible,0)}createInstance(t){return new gh(t,this)}clone(t){let i=new Qf(this.scope,this.name,t.pseudoName||this.pseudoName,this.classes,this.parent,this.condition,this.specificity);return this.copySpecified(i),this.cloneChildren(i),i}resetScope(){this.scope.pageMaster=this}},eg=class tg extends Gs{constructor(t,i,n,r,o){super(t,i,n,r,o),this.pageMaster=o.pageMaster,i&&(this.pageMaster.keyMap[i]=this.key),this.specified["wrap-flow"]=new W(y.auto,0)}createInstance(t){return new Kx(t,this)}clone(t){let i=new tg(t.parent.scope,this.name,this.pseudoName,this.classes,t.parent);return this.copySpecified(i),this.cloneChildren(i),i}},ro=class ig extends Gs{constructor(t,i,n,r,o){super(t,i,n,r,o),this.pageMaster=o.pageMaster,i&&(this.pageMaster.keyMap[i]=this.key)}createInstance(t){return new Wn(t,this)}clone(t){let i=new ig(t.parent.scope,this.name,this.pseudoName,this.classes,t.parent);return this.copySpecified(i),this.cloneChildren(i),i}};function Xx(e,t,i){return!t||Z(t)?new it(e,i):t.toExpr(e,e.zero)}function be(e,t,i){return!t||t===y.auto||Z(t)?null:t.toExpr(e,i)}function qx(e,t,i){return!t||t===y.normal||Z(t)?null:t.toExpr(e,i)}function Tt(e,t,i){return!t||t===y.auto||Z(t)?e.zero:t.toExpr(e,i)}function Gu(e,t,i){return!t||Z(t)?e.zero:t===y.auto?null:t.toExpr(e,i)}function oi(e,t,i,n){return!t||i===y.none||Z(t)?e.zero:t.toExpr(e,n)}function ng(e,t,i){return!t||Z(t)?i:t===y._true?e._true:t===y._false?e._false:t.toExpr(e,e.zero)}var js=class{constructor(e,t){u(this,"parentInstance",e),u(this,"pageBox",t),u(this,"cascaded",{}),u(this,"style",{}),u(this,"autoWidth",null),u(this,"autoHeight",null),u(this,"children",[]),u(this,"isAutoWidth",!1),u(this,"isAutoHeight",!1),u(this,"isTopDependentOnAutoHeight",!1),u(this,"isRightDependentOnAutoWidth",!1),u(this,"calculatedWidth",0),u(this,"calculatedHeight",0),u(this,"pageMasterInstance",null),u(this,"namedValues",{}),u(this,"namedFuncs",{}),u(this,"vertical",!1),u(this,"rtl",!1),u(this,"suppressEmptyBoxGeneration",!1),u(this,"borderBoxSizing",!1),e&&e.children.push(this)}reset(){this.calculatedWidth=0,this.calculatedHeight=0}addNamedValues(e,t){let i=this.resolveName(e),n=this.resolveName(t);if(!i||!n)throw new Error("E_INTERNAL");return ne(this.pageBox.scope,i,n)}resolveName(e){let t=this.namedValues[e];if(t)return t;let i=this.style[e];switch(i&&(t=i.toExpr(this.pageBox.scope,this.pageBox.scope.zero)),e){case"margin-left-edge":t=this.resolveName("left");break;case"margin-top-edge":t=this.resolveName("top");break;case"margin-right-edge":t=this.addNamedValues("border-right-edge","margin-right");break;case"margin-bottom-edge":t=this.addNamedValues("border-bottom-edge","margin-bottom");break;case"border-left-edge":t=this.addNamedValues("margin-left-edge","margin-left");break;case"border-top-edge":t=this.addNamedValues("margin-top-edge","margin-top");break;case"border-right-edge":t=this.addNamedValues("padding-right-edge","border-right-width");break;case"border-bottom-edge":t=this.addNamedValues("padding-bottom-edge","border-bottom-width");break;case"padding-left-edge":t=this.addNamedValues("border-left-edge","border-left-width");break;case"padding-top-edge":t=this.addNamedValues("border-top-edge","border-top-width");break;case"padding-right-edge":t=this.addNamedValues("right-edge","padding-right");break;case"padding-bottom-edge":t=this.addNamedValues("bottom-edge","padding-bottom");break;case"left-edge":t=this.addNamedValues("padding-left-edge","padding-left");break;case"top-edge":t=this.addNamedValues("padding-top-edge","padding-top");break;case"right-edge":t=this.addNamedValues("left-edge","width");break;case"bottom-edge":t=this.addNamedValues("top-edge","height");break}if(!t){let n;if(e=="extent")n=this.vertical?"width":"height";else if(e=="measure")n=this.vertical?"height":"width";else{let r=this.vertical?ef:tf;n=e;for(let o in r)n=n.replace(o,r[o])}n!=e&&(t=this.resolveName(n))}return t&&(this.namedValues[e]=t),t}resolveFunc(e){let t=this.namedFuncs[e];if(t)return t;if(e==="columns"){let i=this.pageBox.scope,n=new Uc(i,0),r=this.resolveName("column-count"),o=this.resolveName("column-width"),s=this.resolveName("column-gap");t=ye(i,Lo(i,new yr(i,"min",[n,r]),ne(i,o,s)),s)}return t&&(this.namedFuncs[e]=t),t}initEnabled(){let e=this.pageBox.scope,t=this.style,i=ng(e,t.enabled,e._true),n=be(e,t.page,e.zero);if(n){let s=new Je(e,"page-number");i=Wt(e,i,new Fl(e,n,s))}let r=be(e,t["min-page-width"],e.zero);r&&(i=Wt(e,i,new Ea(e,new Je(e,"page-width"),r)));let o=be(e,t["min-page-height"],e.zero);o&&(i=Wt(e,i,new Ea(e,new Je(e,"page-height"),o))),i=this.boxSpecificEnabled(i),t.enabled=new j(i)}boxSpecificEnabled(e){return e}initHorizontal(){let e=this.pageBox.scope,t=this.style,i=this.parentInstance?this.parentInstance.style.width.toExpr(e,null):null,n=be(e,t.left,i),r=be(e,t["margin-left"],i),o=oi(e,t["border-left-width"],t["border-left-style"],i),s=Tt(e,t["padding-left"],i),a=be(e,t.width,i),h=be(e,t["max-width"],i),l=Tt(e,t["padding-right"],i),c=oi(e,t["border-right-width"],t["border-right-style"],i),d=be(e,t["margin-right"],i),p=be(e,t.right,i),f=ne(e,o,s),g=ne(e,o,l);if(n&&p&&a){let x=ye(e,i,ne(e,a,ne(e,ne(e,n,f),g)));r?d?p=ye(e,x,d):d=ye(e,x,ne(e,p,r)):(x=ye(e,x,p),d?r=ye(e,x,d):(r=Lo(e,x,new it(e,.5)),d=r))}else{r||(r=e.zero),d||(d=e.zero),!n&&!p&&!a&&(n=e.zero),!n&&!a?(a=this.autoWidth,this.isAutoWidth=!0):!n&&!p?n=e.zero:!a&&!p&&(a=this.autoWidth,this.isAutoWidth=!0);let x=ye(e,i,ne(e,ne(e,r,f),ne(e,d,g)));this.isAutoWidth&&(h||(h=ye(e,x,n||p)),!this.vertical&&(be(e,t["column-width"],null)||be(e,t["column-count"],null))&&(a=h,this.isAutoWidth=!1)),n?a?p||(p=ye(e,x,ne(e,n,a))):a=ye(e,x,ne(e,n,p)):n=ye(e,x,ne(e,p,a))}let v=t["snap-width"]||(this.parentInstance?this.parentInstance.style["snap-width"]:null),w=Tt(e,v,i);t.left=new j(n),t["margin-left"]=new j(r),t["border-left-width"]=new j(o),t["padding-left"]=new j(s),t.width=new j(a),t["max-width"]=new j(h||a),t["padding-right"]=new j(l),t["border-right-width"]=new j(c),t["margin-right"]=new j(d),t.right=new j(p),t["snap-width"]=new j(w)}initVertical(){let e=this.pageBox.scope,t=this.style,i=this.parentInstance?this.parentInstance.style.width.toExpr(e,null):null,n=this.parentInstance?this.parentInstance.style.height.toExpr(e,null):null,r=be(e,t.top,n),o=be(e,t["margin-top"],i),s=oi(e,t["border-top-width"],t["border-top-style"],i),a=Tt(e,t["padding-top"],i),h=be(e,t.height,n),l=be(e,t["max-height"],n),c=Tt(e,t["padding-bottom"],i),d=oi(e,t["border-bottom-width"],t["border-bottom-style"],i),p=be(e,t["margin-bottom"],i),f=be(e,t.bottom,n),g=ne(e,s,a),v=ne(e,d,c);if(r&&f&&h){let m=ye(e,n,ne(e,h,ne(e,ne(e,r,g),v)));o?p?f=ye(e,m,o):p=ye(e,m,ne(e,f,o)):(m=ye(e,m,f),p?o=ye(e,m,p):(o=Lo(e,m,new it(e,.5)),p=o))}else{o||(o=e.zero),p||(p=e.zero),!r&&!f&&!h&&(r=e.zero),!r&&!h?(h=this.autoHeight,this.isAutoHeight=!0):!r&&!f?r=e.zero:!h&&!f&&(h=this.autoHeight,this.isAutoHeight=!0);let m=ye(e,n,ne(e,ne(e,o,g),ne(e,p,v)));this.isAutoHeight&&(l||(l=ye(e,m,r||f)),this.vertical&&(be(e,t["column-width"],null)||be(e,t["column-count"],null))&&(h=l,this.isAutoHeight=!1)),r?h?f||(f=ye(e,m,ne(e,r,h))):h=ye(e,m,ne(e,f,r)):r=ye(e,m,ne(e,f,h))}let w=t["snap-height"]||(this.parentInstance?this.parentInstance.style["snap-height"]:null),x=Tt(e,w,i);t.top=new j(r),t["margin-top"]=new j(o),t["border-top-width"]=new j(s),t["padding-top"]=new j(a),t.height=new j(h),t["max-height"]=new j(l||h),t["padding-bottom"]=new j(c),t["border-bottom-width"]=new j(d),t["margin-bottom"]=new j(p),t.bottom=new j(f),t["snap-height"]=new j(x)}initColumns(){let e=this.pageBox.scope,t=this.style,i=be(e,t[this.vertical?"height":"width"],null),n=be(e,t["column-width"],i),r=be(e,t["column-count"],null),o=qx(e,t["column-gap"],null);o||(o=new Xr(e,1,"em")),n&&!r&&(r=new yr(e,"floor",[Pa(e,ne(e,i,o),ne(e,n,o))]),r=new yr(e,"max",[e.one,r])),r||(r=e.one),n=ye(e,Pa(e,ne(e,i,o),r),o),t["column-width"]=new j(n),t["column-count"]=new j(r),t["column-gap"]=new j(o)}depends(e,t,i){return this.style[e].toExpr(this.pageBox.scope,null).depend(t,i)}init(e){var t;e.registerInstance(this.pageBox.key,this);let i=this.pageBox.scope,n=this.style,r=this.parentInstance?this.parentInstance.getActiveRegions(e):null,o=cl(this.cascaded,e,r,!1,null);this.vertical=Cf(o,e,this.parentInstance?this.parentInstance.vertical:!1),this.rtl=kf(o,e,this.parentInstance?this.parentInstance.rtl:!1),this.borderBoxSizing=((t=o["box-sizing"])==null?void 0:t.value)===y.border_box;let s=!!(e instanceof wh&&e.currentLayoutPosition&&new Je(i,"left-page").evaluate(e));Pf(o,n,this.vertical,this.rtl,s,(a,h)=>h.value),this.autoWidth=new we(i,()=>this.calculatedWidth,"autoWidth"),this.autoHeight=new we(i,()=>this.calculatedHeight,"autoHeight"),this.initHorizontal(),this.initVertical(),this.initColumns(),this.initEnabled()}getProp(e,t){var i,n;let r=this.style[t];return!r&&In(t)&&this.pageMasterInstance instanceof Mn&&(t==="font-size"&&e.isRelativeRootFontSize&&e.rootFontSize?r=new O(e.rootFontSize,"px"):r=(n=((i=e.styler)==null?void 0:i.rootStyle)[t])==null?void 0:n.value),r&&(r=Ss(e,r,t)),r}getPropAsNumber(e,t){var i,n;let r=this.style[t];if(r){let o=/\b(height|top|bottom)\b/.test(t)?(i=e.pageAreaHeight)!=null?i:e.pageHeight():(n=e.pageAreaWidth)!=null?n:e.pageWidth();r=Ss(e,r,t,o)}return ut(r,e)}getSpecial(e,t){let i=sf(this.cascaded,t);if(i){let n=[];for(let r=0;r<i.length;r++){let o=i[r].evaluate(e,"");o&&o!==Me&&n.push(o)}if(n.length)return n}return null}getActiveRegions(e){let t=this.getSpecial(e,"region-id");if(t){let i=[];for(let n=0;n<t.length;n++)i[n]=t[n].toString();return i}return null}propagateProperty(e,t,i,n){this.propagatePropertyToElement(e,t.element,i,n)}propagatePropertyToElement(e,t,i,n){let r=this.getProp(e,i);r&&(r.isNumeric()&&Ic(r.unit)&&(r=qc(r,e)),i==="font-family"&&(r=n.filterFontFamily(r)),(i.startsWith("background")||i==="z-index")&&t.parentElement.hasAttribute("data-vivliostyle-bleed-box")&&(t=t.parentElement),I(t,i,r.toString()))}propagateDelayedProperty(e,t,i,n){let r=this.getProp(e,i);r&&n.push(new Ul(t.element,i,r))}assignLeftPosition(e,t){let i=this.getPropAsNumber(e,"left"),n=this.getPropAsNumber(e,"margin-left"),r=this.getPropAsNumber(e,"padding-left"),o=this.getPropAsNumber(e,"border-left-width"),s=this.getPropAsNumber(e,"width");t.setHorizontalPosition(i,s),I(t.element,"margin-left",`${n}px`),I(t.element,"padding-left",`${r}px`),I(t.element,"border-left-width",`${o}px`),t.marginLeft=n,t.borderLeft=o,t.paddingLeft=r}assignRightPosition(e,t){let i=this.getPropAsNumber(e,"right"),n=this.getPropAsNumber(e,"snap-height"),r=this.getPropAsNumber(e,"margin-right"),o=this.getPropAsNumber(e,"padding-right"),s=this.getPropAsNumber(e,"border-right-width");if(I(t.element,"margin-right",`${r}px`),I(t.element,"padding-right",`${o}px`),I(t.element,"border-right-width",`${s}px`),t.marginRight=r,t.borderRight=s,this.vertical&&n>0){let a=i+t.getInsetRight(),h=a-Math.floor(a/n)*n;h>0&&(t.snapOffsetX=n-h,o+=t.snapOffsetX)}t.paddingRight=o,t.snapWidth=n}assignTopPosition(e,t){let i=this.getPropAsNumber(e,"snap-height"),n=this.getPropAsNumber(e,"top"),r=this.getPropAsNumber(e,"margin-top"),o=this.getPropAsNumber(e,"padding-top"),s=this.getPropAsNumber(e,"border-top-width");if(t.top=n,t.marginTop=r,t.borderTop=s,t.snapHeight=i,!this.vertical&&i>0){let a=n+t.getInsetTop(),h=a-Math.floor(a/i)*i;h>0&&(t.snapOffsetY=i-h,o+=t.snapOffsetY)}t.paddingTop=o,I(t.element,"top",`${n}px`),I(t.element,"margin-top",`${r}px`),I(t.element,"padding-top",`${o}px`),I(t.element,"border-top-width",`${s}px`)}assignBottomPosition(e,t){let i=this.getPropAsNumber(e,"margin-bottom"),n=this.getPropAsNumber(e,"padding-bottom"),r=this.getPropAsNumber(e,"border-bottom-width"),o=this.getPropAsNumber(e,"height")-t.snapOffsetY;I(t.element,"height",`${o}px`),I(t.element,"margin-bottom",`${i}px`),I(t.element,"padding-bottom",`${n}px`),I(t.element,"border-bottom-width",`${r}px`),t.height=o-t.snapOffsetY,t.marginBottom=i,t.borderBottom=r,t.paddingBottom=n}assignBeforePosition(e,t){this.vertical?this.assignRightPosition(e,t):this.assignTopPosition(e,t)}assignAfterPosition(e,t){this.vertical?this.assignLeftPosition(e,t):this.assignBottomPosition(e,t)}assignStartEndPosition(e,t){this.vertical?(this.assignTopPosition(e,t),this.assignBottomPosition(e,t)):(this.assignRightPosition(e,t),this.assignLeftPosition(e,t))}sizeWithMaxHeight(e,t){I(t.element,"border-top-width","0px");let i=this.getPropAsNumber(e,"max-height");this.isTopDependentOnAutoHeight?t.setVerticalPosition(0,i):(this.assignTopPosition(e,t),i-=t.snapOffsetY,t.height=i,I(t.element,"height",`${i}px`))}sizeWithMaxWidth(e,t){I(t.element,"border-left-width","0px");let i=this.getPropAsNumber(e,"max-width");if(this.isRightDependentOnAutoWidth)t.setHorizontalPosition(0,i);else{this.assignRightPosition(e,t),i-=t.snapOffsetX,t.width=i;let n=this.getPropAsNumber(e,"right");I(t.element,"right",`${n}px`),I(t.element,"width",`${i}px`)}}prepareContainer(e,t,i,n,r){(!this.parentInstance||this.vertical!=this.parentInstance.vertical)&&I(t.element,"writing-mode",this.vertical?"vertical-rl":"horizontal-tb"),(!this.parentInstance||this.rtl!=this.parentInstance.rtl)&&I(t.element,"direction",this.rtl?"rtl":"ltr"),(this.vertical?this.isAutoWidth:this.isAutoHeight)?this.vertical?this.sizeWithMaxWidth(e,t):this.sizeWithMaxHeight(e,t):(this.assignBeforePosition(e,t),this.assignAfterPosition(e,t)),(this.vertical?this.isAutoHeight:this.isAutoWidth)?this.vertical?this.sizeWithMaxHeight(e,t):this.sizeWithMaxWidth(e,t):this.assignStartEndPosition(e,t);for(let o=0;o<ju.length;o++)this.propagateProperty(e,t,ju[o],n)}transferContentProps(e,t,i,n){for(let r=0;r<qu.length;r++)this.propagateProperty(e,t,qu[r],n);if(this.style["text-overflow"]){let r=t.element.firstElementChild;I(r,"text-overflow","inherit"),I(r,"overflow","inherit")}}transferSingleUriContentProps(e,t,i){let n=()=>{var o,s;let a=(s=(o=this.cascaded.width)!=null?o:this.cascaded[this.vertical?"block-size":"inline-size"])==null?void 0:s.value;return!!a&&a!==y.auto&&!Z(a)},r=()=>{var o,s;let a=(s=(o=this.cascaded.height)!=null?o:this.cascaded[this.vertical?"inline-size":"block-size"])==null?void 0:s.value;return!!a&&a!==y.auto&&!Z(a)};for(let o=0;o<Yu.length;o++){let s=Yu[o];if(s==="width"||s==="height"){if(s==="width"&&!n()||s==="height"&&!r())continue;I(t,s,"100%");continue}this.propagatePropertyToElement(e,t,s,i)}}finishContainer(e,t,i,n,r,o,s){var a,h,l,c,d,p,f,g,v,w;this.vertical?this.calculatedWidth=t.computedBlockSize+t.snapOffsetX:this.calculatedHeight=t.computedBlockSize+t.snapOffsetY;let x=(this.vertical||!n)&&this.isAutoHeight,m=(!this.vertical||!n)&&this.isAutoWidth,S=null;if(m||x){m&&I(t.element,"width","auto"),x&&I(t.element,"height","auto");let b=n&&os(n);b&&_s(n),S=o.getElementClientRect(n?n.element:t.element),b&&_l(n),m&&(this.calculatedWidth=Math.ceil(S.right-S.left-t.paddingLeft-t.borderLeft-t.paddingRight-t.borderRight),this.vertical&&(this.calculatedWidth+=t.snapOffsetX)),x&&(this.calculatedHeight=S.bottom-S.top-t.paddingTop-t.borderTop-t.paddingBottom-t.borderBottom,this.vertical||(this.calculatedHeight+=t.snapOffsetY))}if((this.vertical?this.isAutoHeight:this.isAutoWidth)&&this.assignStartEndPosition(e,t),(this.vertical?this.isAutoWidth:this.isAutoHeight)&&((this.vertical?this.isRightDependentOnAutoWidth:this.isTopDependentOnAutoHeight)&&this.assignBeforePosition(e,t),this.assignAfterPosition(e,t)),r>1){let b=this.getPropAsNumber(e,"column-rule-width"),C=this.getProp(e,"column-rule-style"),P=this.getProp(e,"column-rule-color");if(b>0&&C&&C!=y.none&&P!=y.transparent){let L=this.getPropAsNumber(e,"column-gap"),A=this.vertical?t.height:t.width,z=parseFloat(this.vertical?(a=n?.element.style.left)!=null?a:"":(h=n?.element.style.top)!=null?h:""),U=t.getPaddingRect(),X=n,re=this.vertical?"border-top":"border-left";for(let k=1;k<r;k++){let _=this.vertical?(A+L)*k/r-L/2+t.paddingTop-b/2:(A+L)*k/r-L/2+t.paddingLeft-b/2,F=this.vertical?U.y1+_+b/2:U.x1+_+b/2,D=(d=(c=(l=X.pageFloatLayoutContext)==null?void 0:l.parent)==null?void 0:c.getBlockEndEdgeOfBlockStartFloats)==null?void 0:d.call(c,F),E=(g=(f=(p=X.pageFloatLayoutContext)==null?void 0:p.parent)==null?void 0:f.getBlockStartEdgeOfBlockEndFloats)==null?void 0:g.call(f,F),N=isFinite(D)?this.vertical?D-U.x1:D-U.y1:NaN,R=isFinite(E)?this.vertical?E-U.x1:E-U.y1:NaN,$=parseFloat(this.vertical?(v=n?.element.style.width)!=null?v:"":(w=n?.element.style.height)!=null?w:""),V=$>0?$:this.vertical?n.width:n.height,q=Math.max(z>0?z:0,0),Q=q+V,ee=Math.max(q,isFinite(this.vertical?R:N)?Math.max(0,this.vertical?R:N):0),pe=Math.min(Q,isFinite(this.vertical?N:R)?Math.max(0,this.vertical?N:R):Q),oe=Math.max(0,pe-ee),se=t.element.ownerDocument.createElement("div");I(se,"position","absolute"),I(se,this.vertical?"left":"top",`${ee}px`),I(se,this.vertical?"top":"left",`${_}px`),I(se,this.vertical?"height":"width","0px"),I(se,this.vertical?"width":"height",`${oe}px`),I(se,re,`${b}px ${C.toString()}${P?` ${P.toString()}`:""}`),t.element.insertBefore(se,t.element.firstChild)}}}for(let b=0;b<Xu.length;b++)this.propagateProperty(e,t,Xu[b],s);for(let b of Yx){let C=this.getProp(e,b);C&&Pr(C,i)}for(let b=0;b<Zu.length;b++)this.propagateDelayedProperty(e,t,Zu[b],i.delayedItems)}applyCascadeAndInit(e,t){let i=this.cascaded,n=this.pageBox.specified;for(let o in n)this instanceof Mn&&this.pageBox.pseudoName=="vivliostyle-page-rule-master"&&(o==="writing-mode"||o==="direction")||Xi(o)&&Fi(i,o,ve(n,o));if(this.pageBox.pseudoName==fh)for(let o in t)(o.match(/^background-/)||o=="writing-mode")&&(i[o]=t[o]);if(this.pageBox.pseudoName=="layout-host")for(let o in t)!o.match(/^background-/)&&o!="writing-mode"&&(i[o]=t[o]);e.pushRule(this.pageBox.classes,null,i);let r=i.content;if(r){let o=Array.from(e.lastCounterChanges),s={...e.lastCounterChangeTypes};e.counterScoping.push(null),e.pushCounters(i),i.content=r.filterValue(new _r(e,null,e.counterResolver)),e.popCounters(),e.popCounters(),e.lastCounterChanges=o,e.lastCounterChangeTypes=s}this.init(e.context);for(let o of this.pageBox.children)o.createInstance(this).applyCascadeAndInit(e,t);e.popRule()}resolveAutoSizing(e){this.isAutoWidth&&(this.isRightDependentOnAutoWidth=this.depends("right",this.autoWidth,e)||this.depends("margin-right",this.autoWidth,e)||this.depends("border-right-width",this.autoWidth,e)||this.depends("padding-right",this.autoWidth,e)),this.isAutoHeight&&(this.isTopDependentOnAutoHeight=this.depends("top",this.autoHeight,e)||this.depends("margin-top",this.autoHeight,e)||this.depends("border-top-width",this.autoHeight,e)||this.depends("padding-top",this.autoHeight,e));for(let t of this.children)t.resolveAutoSizing(e)}},ju=["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","outline-offset","overflow","visibility"],Xu=["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"],Yx=["background-image","border-image-source","filter"],qu=["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-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-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","text-box-trim","text-box-edge","text-justify"],Yu=["width","height","image-resolution","object-fit","object-position"],Zu=["transform","transform-origin"],fh="background-host",Zx=class extends js{constructor(e){super(null,e)}applyCascadeAndInit(e,t){super.applyCascadeAndInit(e,t),this.children.sort((i,n)=>n.pageBox.specificity-i.pageBox.specificity||i.pageBox.index-n.pageBox.index)}},gh=class extends js{constructor(e,t){super(e,t),this.pageMasterInstance=this}boxSpecificEnabled(e){let t=this.pageBox.pageMaster;return t.condition&&(e=Wt(t.scope,e,t.condition)),e}adjustPageLayout(e,t,i){}},Kx=class extends js{constructor(e,t){super(e,t),this.pageMasterInstance=e.pageMasterInstance}},Wn=class extends js{constructor(e,t){super(e,t),this.pageMasterInstance=e.pageMasterInstance}processPartitionList(e,t,i){let n=null;if(t instanceof he&&(n=[t]),t instanceof Oe&&(n=t.values),n){let r=this.pageBox.scope;for(let o=0;o<n.length;o++)if(n[o]instanceof he){let s=Ca(n[o].name,"enabled"),a=new Je(r,s);i&&(a=new Ai(r,a)),e=Wt(r,e,a)}}return e}boxSpecificEnabled(e){let t=this.pageBox.scope,i=this.style,n=ng(t,i.required,t._false)!==t._false;if(n||this.isAutoHeight){let r=Xx(t,i["flow-from"],"body"),o=new yr(t,"has-content",[r]);e=Wt(t,e,o)}if(e=this.processPartitionList(e,i["required-partitions"],!1),e=this.processPartitionList(e,i["conflicting-partitions"],!0),n){let r=this.pageMasterInstance.style.enabled,o=r?r.toExpr(t,null):t._true;o=Wt(t,o,e),this.pageMasterInstance.style.enabled=new j(o)}return e}prepareContainer(e,t,i,n,r){var o;this.pageBox.pageMaster instanceof lg||(I(t.element,"overflow","hidden"),t.element.setAttribute("data-vivliostyle-page-partition",(o=this.pageBox.name)!=null?o:"")),super.prepareContainer(e,t,i,n,r)}},mh=class extends on{constructor(e,t,i,n){super(e,t,!1),u(this,"target",i),u(this,"validatorSet",n)}property(e,t,i){this.validatorSet.validatePropertyAndHandleShorthand(e,t,i,this)}unknownProperty(e,t){this.report(`E_INVALID_PROPERTY ${e}: ${t.toString()}`)}invalidPropertyValue(e,t){this.report(`E_INVALID_PROPERTY_VALUE ${e}: ${t.toString()}`)}simpleProperty(e,t,i){this.target.specified[e]=new W(t,i?Ld:Od)}},rg=class extends mh{constructor(e,t,i,n){super(e,t,i,n)}},Jx=class og extends mh{constructor(t,i,n,r){super(t,i,n,r),n.specified.width=new W(Bh,0),n.specified.height=new W(Bh,0)}startPartitionRule(t,i,n){let r=new ro(this.scope,t,i,n,this.target),o=new rg(this.scope,this.owner,r,this.validatorSet);this.owner.pushHandler(o)}startPartitionGroupRule(t,i,n){let r=new eg(this.scope,t,i,n,this.target),o=new og(this.scope,this.owner,r,this.validatorSet);this.owner.pushHandler(o)}},Qx=class extends mh{constructor(e,t,i,n){super(e,t,i,n)}startPartitionRule(e,t,i){let n=new ro(this.scope,e,t,i,this.target),r=new rg(this.scope,this.owner,n,this.validatorSet);this.owner.pushHandler(r)}startPartitionGroupRule(e,t,i){let n=new eg(this.scope,e,t,i,this.target),r=new Jx(this.scope,this.owner,n,this.validatorSet);this.owner.pushHandler(r)}};function sg(e){var t,i;let n=(t=e["writing-mode"])==null?void 0:t.value,r=(i=e.direction)==null?void 0:i.value;return n===y.vertical_lr||n!==y.vertical_rl&&r!==y.rtl?"ltr":"rtl"}var eS={a10:{width:new O(26,"mm"),height:new O(37,"mm")},a9:{width:new O(37,"mm"),height:new O(52,"mm")},a8:{width:new O(52,"mm"),height:new O(74,"mm")},a7:{width:new O(74,"mm"),height:new O(105,"mm")},a6:{width:new O(105,"mm"),height:new O(148,"mm")},a5:{width:new O(148,"mm"),height:new O(210,"mm")},a4:{width:new O(210,"mm"),height:new O(297,"mm")},a3:{width:new O(297,"mm"),height:new O(420,"mm")},a2:{width:new O(420,"mm"),height:new O(594,"mm")},a1:{width:new O(594,"mm"),height:new O(841,"mm")},a0:{width:new O(841,"mm"),height:new O(1189,"mm")},b10:{width:new O(31,"mm"),height:new O(44,"mm")},b9:{width:new O(44,"mm"),height:new O(62,"mm")},b8:{width:new O(62,"mm"),height:new O(88,"mm")},b7:{width:new O(88,"mm"),height:new O(125,"mm")},b6:{width:new O(125,"mm"),height:new O(176,"mm")},b5:{width:new O(176,"mm"),height:new O(250,"mm")},b4:{width:new O(250,"mm"),height:new O(353,"mm")},b3:{width:new O(353,"mm"),height:new O(500,"mm")},b2:{width:new O(500,"mm"),height:new O(707,"mm")},b1:{width:new O(707,"mm"),height:new O(1e3,"mm")},b0:{width:new O(1e3,"mm"),height:new O(1414,"mm")},c10:{width:new O(28,"mm"),height:new O(40,"mm")},c9:{width:new O(40,"mm"),height:new O(57,"mm")},c8:{width:new O(57,"mm"),height:new O(81,"mm")},c7:{width:new O(81,"mm"),height:new O(114,"mm")},c6:{width:new O(114,"mm"),height:new O(162,"mm")},c5:{width:new O(162,"mm"),height:new O(229,"mm")},c4:{width:new O(229,"mm"),height:new O(324,"mm")},c3:{width:new O(324,"mm"),height:new O(458,"mm")},c2:{width:new O(458,"mm"),height:new O(648,"mm")},c1:{width:new O(648,"mm"),height:new O(917,"mm")},c0:{width:new O(917,"mm"),height:new O(1297,"mm")},"jis-b10":{width:new O(32,"mm"),height:new O(45,"mm")},"jis-b9":{width:new O(45,"mm"),height:new O(64,"mm")},"jis-b8":{width:new O(64,"mm"),height:new O(91,"mm")},"jis-b7":{width:new O(91,"mm"),height:new O(128,"mm")},"jis-b6":{width:new O(128,"mm"),height:new O(182,"mm")},"jis-b5":{width:new O(182,"mm"),height:new O(257,"mm")},"jis-b4":{width:new O(257,"mm"),height:new O(364,"mm")},"jis-b3":{width:new O(364,"mm"),height:new O(515,"mm")},"jis-b2":{width:new O(515,"mm"),height:new O(728,"mm")},"jis-b1":{width:new O(728,"mm"),height:new O(1030,"mm")},"jis-b0":{width:new O(1030,"mm"),height:new O(1456,"mm")},letter:{width:new O(8.5,"in"),height:new O(11,"in")},legal:{width:new O(8.5,"in"),height:new O(14,"in")},ledger:{width:new O(11,"in"),height:new O(17,"in")}},tS=new O(.24,"pt"),cC=new O(3,"mm"),iS=new O(10,"mm"),nS=new O(13,"mm");function Ps(e){let t={width:qr,height:Yr,bleed:Le,bleedOffset:Le,cropOffset:Le},i=e.size;if(!(!i||i.value===y.auto)){let l=i.value,c,d;if(l.isSpaceList()?(c=l.values[0],d=l.values[1]):(c=l,d=null),c.isNumeric())t.width=c,t.height=d||c;else{let p=c.name&&eS[c.name.toLowerCase()];p&&(d&&d===y.landscape?(t.width=p.height,t.height=p.width):(t.width=p.width,t.height=p.height))}}let n=e.marks,r=e.bleed,o=n&&!Z(n.value)?n.value:y.none,s=r&&!Z(r.value)?r.value:y.auto;if(s===y.auto){if(o!==y.none){let l=!1;o.isSpaceList()?l=o.values.some(c=>c===y.crop):l=o===y.crop,l&&(t.bleed=new O(6,"pt"))}}else s.isNumeric()&&(t.bleed=s);let a=e["crop-offset"],h=a&&!Z(a.value)?a.value:y.auto;return h===y.auto?o!==y.none&&(t.bleedOffset=nS):h.isNumeric()&&(t.cropOffset=h),t}function Ku(e,t){let i={},n=Math.max(0,e.bleed.num)*t.queryUnitSize(e.bleed.unit,!1),r=!e.cropOffset.num&&e.bleedOffset.num?e.bleedOffset.num*t.queryUnitSize(e.bleedOffset.unit,!1):Math.max(0,e.cropOffset.num*t.queryUnitSize(e.cropOffset.unit,!1)-n),o=n+r,s=e.width;s===qr?t.pref.defaultPaperSize?i.pageWidth=t.pref.defaultPaperSize.width*t.queryUnitSize("px",!1):i.pageWidth=(t.pref.spreadView?Math.floor(t.viewportWidth/2)-t.pref.pageBorder:t.viewportWidth)-o*2:i.pageWidth=s.num*t.queryUnitSize(s.unit,!1);let a=e.height;return a===Yr?t.pref.defaultPaperSize?i.pageHeight=t.pref.defaultPaperSize.height*t.queryUnitSize("px",!1):i.pageHeight=t.viewportHeight-o*2:i.pageHeight=a.num*t.queryUnitSize(a.unit,!1),i.bleed=n,i.bleedOffset=r,i.cropOffset=o,i}function ag(e,t,i){let n=e.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",t),n.setAttribute("height",i),n.style.position="absolute",n}function Nr(e,t,i,n){n=n||"polyline";let r=e.createElementNS("http://www.w3.org/2000/svg",n);return r.setAttribute("stroke",i===y.auto?"#010101":i.toString()),r.setAttribute("stroke-width",t),r.setAttribute("fill","none"),r}var gl=(e=>(e.TOP_LEFT="top left",e.TOP_RIGHT="top right",e.BOTTOM_LEFT="bottom left",e.BOTTOM_RIGHT="bottom right",e))(gl||{});function rS(e,t,i,n,r,o,s){let a=r;a<=o+2*Zt.mm&&(a=o+r/2);let h=Math.max(r,a),l=o+h+i/2,c=ag(e,l,l),d=[[0,o+r],[r,o+r],[r,o+r-a]],p=d.map(v=>[v[1],v[0]]);(t==="top right"||t==="bottom right")&&(d=d.map(v=>[o+h-v[0],v[1]]),p=p.map(v=>[o+h-v[0],v[1]])),(t==="bottom left"||t==="bottom right")&&(d=d.map(v=>[v[0],o+h-v[1]]),p=p.map(v=>[v[0],o+h-v[1]]));let f=Nr(e,i,n);f.setAttribute("points",d.map(v=>v.join(",")).join(" ")),c.appendChild(f);let g=Nr(e,i,n);return g.setAttribute("points",p.map(v=>v.join(",")).join(" ")),c.appendChild(g),t.split(" ").forEach(v=>{c.style[v]=`${s}px`}),c}var $r=(e=>(e.TOP="top",e.BOTTOM="bottom",e.LEFT="left",e.RIGHT="right",e))($r||{});function oS(e,t,i,n,r,o){let s=r*2,a,h;t==="top"||t==="bottom"?(a=s,h=r):(a=r,h=s);let l=ag(e,a,h),c=Nr(e,i,n);c.setAttribute("points",`0,${h/2} ${a},${h/2}`),l.appendChild(c);let d=Nr(e,i,n);d.setAttribute("points",`${a/2},0 ${a/2},${h}`),l.appendChild(d);let p=Nr(e,i,n,"circle");p.setAttribute("cx",a/2),p.setAttribute("cy",h/2),p.setAttribute("r",r/4),l.appendChild(p);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($r).forEach(g=>{let v=$r[g];v===t?l.style[v]=`${o}px`:v!==f&&(l.style[v]="0",l.style[`margin-${v}`]="auto")}),l}function sS(e,t,i,n){let r=!1,o=!1,s=e.marks;if(s){let v=s.value;v instanceof J?v.values.forEach(w=>{w===y.crop?r=!0:w===y.cross&&(o=!0)}):v===y.crop?r=!0:v===y.cross&&(o=!0)}let a=t.bleed;if(!r&&!o)return;let h=i.container,l=h.ownerDocument,c=ut(tS,n),d=Math.max(0,t.bleedOffset-ut(iS,n)),p=t.bleedOffset-d,f=e["crop-marks-line-color"],g=f&&!Z(f.value)?f.value:y.auto;r&&Object.keys(gl).forEach(v=>{let w=gl[v],x=rS(l,w,c,g,p,a,d);h.appendChild(x)}),o&&Object.keys($r).forEach(v=>{let w=$r[v],x=oS(l,w,c,g,p,d);h.appendChild(x)})}var ml=(()=>{let e=["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,"outline-offset":!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 e.forEach(i=>{t[`margin-${i}`]=!0,t[`padding-${i}`]=!0,t[`border-${i}-width`]=!0,t[`border-${i}-style`]=!0,t[`border-${i}-color`]=!0}),t})(),yh={"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"}},aS=(()=>{let e=yh;return Object.keys(e).sort((t,i)=>e[t].order-e[i].order)})(),vh="vivliostyle-page-rule-master",Hr="_marginBoxes",Ns="_footnoteArea",lg=class extends Jf{constructor(e,t,i){super(e,null,vh,[],t,null,0),u(this,"pageMarginBoxes",{});let n=Ps(i),r=new lS(this.scope,this,i,n);this.createPageMarginBoxes(i),this.applySpecified(i,n)}createPageMarginBoxes(e){let t=e[Hr];t&&aS.forEach(i=>{t[i]&&(this.pageMarginBoxes[i]=new uS(this.scope,this,i,e))})}applySpecified(e,t){this.specified.position=new W(y.relative,0),this.specified.width=new W(t.width,0),this.specified.height=new W(t.height,0);for(let i in e)!ml[i]&&i!=="background-clip"&&(this.specified[i]=e[i])}createInstance(e){return new Mn(e,this)}},lS=class extends ro{constructor(e,t,i,n){super(e,null,null,[],t),u(this,"pageSize",n);let r=new hS(this.scope,this);this.applySpecified(i)}applySpecified(e){this.specified["wrap-flow"]=new W(y.auto,0),this.specified["z-index"]=new W(new lt(0),0),this.specified.position=new W(y.absolute,0),this.specified.overflow=new W(y.visible,0);for(let t in ml)ml.hasOwnProperty(t)&&(this.specified[t]=e[t])}createInstance(e){return new dS(e,this)}},hS=class extends ro{constructor(e,t){super(e,null,null,[],t),this.specified["flow-from"]=new W(B("body"),0)}createInstance(e){return new hg(e,this)}},uS=class extends ro{constructor(e,t,i,n){super(e,null,null,[],t),u(this,"marginBoxName",i),this.applySpecified(n)}applySpecified(e){let t=e[Hr][this.marginBoxName];for(let i in e){let n=e[i],r=t[i];(Qp[i]||r&&r.value===y.inherit)&&(this.specified[i]=n)}for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];n&&n.value!==Me&&n.value!==y.inherit&&n.value!==y.unset&&n.value!==y.revert&&(this.specified[i]=n)}}createInstance(e){return new ug(e,this)}},Mn=class extends gh{constructor(e,t){super(e,t),u(this,"pageAreaDimension",null),u(this,"pageMarginBoxInstances",{})}applyCascadeAndInit(e,t){let i=this.cascaded;for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n))switch(n){case"writing-mode":case"direction":i[n]=t[n]}super.applyCascadeAndInit(e,t)}initHorizontal(){let e=this.style;e.left=Le,e["margin-left"]=Le,e["border-left-width"]=Le,e["padding-left"]=Le,e["padding-right"]=Le,e["border-right-width"]=Le,e["margin-right"]=Le,e.right=Le}initVertical(){let e=this.style;e.top=Le,e["margin-top"]=Le,e["border-top-width"]=Le,e["padding-top"]=Le,e["padding-bottom"]=Le,e["border-bottom-width"]=Le,e["margin-bottom"]=Le,e.bottom=Le}setPageAreaDimension(e){this.pageAreaDimension=e;let t=this.style;t.width=new j(e.borderBoxWidth),t.height=new j(e.borderBoxHeight),t["padding-left"]=new j(e.marginLeft),t["padding-right"]=new j(e.marginRight),t["padding-top"]=new j(e.marginTop),t["padding-bottom"]=new j(e.marginBottom)}adjustPageLayout(e,t,i){let n=t.marginBoxes,r={start:this.pageAreaDimension.marginLeft,end:this.pageAreaDimension.marginRight,extent:this.pageAreaDimension.borderBoxWidth},o={start:this.pageAreaDimension.marginTop,end:this.pageAreaDimension.marginBottom,extent:this.pageAreaDimension.borderBoxHeight};this.sizeMarginBoxesAlongVariableDimension(n.top,!0,r,e,i),this.sizeMarginBoxesAlongVariableDimension(n.bottom,!0,r,e,i),this.sizeMarginBoxesAlongVariableDimension(n.left,!1,o,e,i),this.sizeMarginBoxesAlongVariableDimension(n.right,!1,o,e,i)}sizeMarginBoxesAlongVariableDimension(e,t,i,n,r){let o="start",s="center",a="end",h=this.pageBox.scope,l={},c={},d={};for(let S in e){let b=yh[S];if(b){let C=e[S],P=this.pageMarginBoxInstances[S],L=new Yo(C,P.style,t,h,r);l[b.positionAlongVariableDimension]=C,c[b.positionAlongVariableDimension]=P,d[b.positionAlongVariableDimension]=L}}let p={start:i.start.evaluate(n),end:i.end.evaluate(n),extent:i.extent.evaluate(n)},f=this.getSizesOfMarginBoxesAlongVariableDimension(d,p.extent),g=!1,v={};Object.keys(l).forEach(S=>{let b=S,C=be(h,c[b].style[t?"max-width":"max-height"],i.extent);if(C){let P=C.evaluate(n);if(f[b]>P){let L=d[b]=new Ju(l[b],c[b].style,t,h,r,P);v[b]=L.getOuterSize(),g=!0}}}),g&&(f=this.getSizesOfMarginBoxesAlongVariableDimension(d,p.extent),g=!1,[o,s,a].forEach(S=>{var b;f[S]=(b=v[S])!=null?b:f[S]}));let w={};Object.keys(l).forEach(S=>{let b=S,C=be(h,c[b].style[t?"min-width":"min-height"],i.extent);if(C){let P=C.evaluate(n);if(f[b]<P){let L=d[b]=new Ju(l[b],c[b].style,t,h,r,P);w[b]=L.getOuterSize(),g=!0}}}),g&&(f=this.getSizesOfMarginBoxesAlongVariableDimension(d,p.extent),[o,s,a].forEach(S=>{f[S]=w[S]||f[S]}));let x=p.start+p.extent,m=p.start+(p.start+p.extent);[o,s,a].forEach(S=>{let b=f[S];if(b!=null){let C=l[S],P=0;switch(S){case o:P=t?C.left:C.top;break;case s:P=(m-b)/2;break;case a:P=x-b;break}t?C.setHorizontalPosition(P,b-C.getInsetLeft()-C.getInsetRight()):C.setVerticalPosition(P,b-C.getInsetTop()-C.getInsetBottom())}})}getSizesOfMarginBoxesAlongVariableDimension(e,t){var i;let n=e.start,r=e.center,o=e.end,s={};if(r){let a=[n,o],h=new cS(a),l=this.distributeAutoMarginBoxSizes(r,h,t);l.xSize!=null&&(s.center=l.xSize);let c=(i=l.xSize)!=null?i:r.getOuterSize(),d=Math.max((t-c)/2,0);n&&(s.start=n.hasAutoSize()?d:n.getOuterSize()),o&&(s.end=o.hasAutoSize()?d:o.getOuterSize())}else{let a=this.distributeAutoMarginBoxSizes(n,o,t);a.xSize!=null&&(s.start=a.xSize),a.ySize!=null&&(s.end=a.ySize)}return s}distributeAutoMarginBoxSizes(e,t,i){let n={xSize:null,ySize:null};if(e instanceof Yo&&e.minMaxFitContent&&(n.xSize=e.getOuterSize()),t instanceof Yo&&t.minMaxFitContent&&(n.ySize=t.getOuterSize()),e&&t)if(e.hasAutoSize()&&t.hasAutoSize()){let r=e.getOuterMaxContentSize(),o=t.getOuterMaxContentSize();if(r>0&&o>0){let s=r+o;if(s<i)n.xSize=i*r/s;else{let a=e.getOuterMinContentSize(),h=t.getOuterMinContentSize(),l=a+h;l<i?n.xSize=a+(i-l)*(r-a)/(s-l):l>0&&(n.xSize=i*a/l)}n.xSize>0&&(n.ySize=i-n.xSize)}else r>0?n.xSize=i:o>0&&(n.ySize=i)}else e.hasAutoSize()?n.xSize=Math.max(i-t.getOuterSize(),0):t.hasAutoSize()&&(n.ySize=Math.max(i-e.getOuterSize(),0));else e?e.hasAutoSize()&&(n.xSize=i):t&&t.hasAutoSize()&&(n.ySize=i);return n}prepareContainer(e,t,i,n,r){t.element.setAttribute("data-vivliostyle-page-box",!0),super.prepareContainer(e,t,i,n,r)}},Yo=class{constructor(e,t,i,n,r){u(this,"container",e),u(this,"isHorizontal",i),u(this,"clientLayout",r),u(this,"hasAutoSize_"),u(this,"size",null),u(this,"minMaxFitContent",null);let o=t[i?"width":"height"];if(this.hasAutoSize_=!o||o===y.auto||Z(o),this.minMaxFitContent=o instanceof he&&(o.name==="min-content"||o.name==="max-content"||o.name==="fit-content")?o.name:null,this.minMaxFitContent){let s=this.getSize();if(this.isHorizontal){let a=s[this.minMaxFitContent==="min-content"?"min-content width":this.minMaxFitContent==="max-content"?"max-content width":"fit-content width"];this.container.setHorizontalPosition(this.container.left,a)}else{let a=s[this.minMaxFitContent==="min-content"?"min-content height":this.minMaxFitContent==="max-content"?"max-content height":"fit-content height"];this.container.setVerticalPosition(this.container.top,a)}}}hasAutoSize(){return this.hasAutoSize_}getSize(){if(!this.size){let e=this.isHorizontal?["max-content width","min-content width","fit-content width"]:["max-content height","min-content height","fit-content height"];this.size=Vl(this.clientLayout,this.container.element,e)}return this.size}getOuterMaxContentSize(){let e=this.getSize();return this.isHorizontal?this.container.getInsetLeft()+e["max-content width"]+this.container.getInsetRight():this.container.getInsetTop()+e["max-content height"]+this.container.getInsetBottom()}getOuterMinContentSize(){let e=this.getSize();return this.isHorizontal?this.container.getInsetLeft()+e["min-content width"]+this.container.getInsetRight():this.container.getInsetTop()+e["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()}},cS=class{constructor(e){u(this,"params",e)}hasAutoSize(){return this.params.some(e=>{var t;return(t=e?.hasAutoSize())!=null?t:!1})}getOuterMaxContentSize(){let e=this.params.map(t=>{var i;return(i=t?.getOuterMaxContentSize())!=null?i:0});return Math.max.apply(null,e)*e.length}getOuterMinContentSize(){let e=this.params.map(t=>{var i;return(i=t?.getOuterMinContentSize())!=null?i:0});return Math.max.apply(null,e)*e.length}getOuterSize(){let e=this.params.map(t=>{var i;return(i=t?.getOuterSize())!=null?i:0});return Math.max.apply(null,e)*e.length}},Ju=class extends Yo{constructor(e,t,i,n,r,o){super(e,t,i,n,r),u(this,"fixedSize"),this.fixedSize=o}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()}},dS=class extends Wn{constructor(e,t){super(e,t),u(this,"borderBoxWidth",null),u(this,"borderBoxHeight",null),u(this,"contentBoxWidth",null),u(this,"contentBoxHeight",null),u(this,"marginTop",null),u(this,"marginRight",null),u(this,"marginBottom",null),u(this,"marginLeft",null)}applyCascadeAndInit(e,t){for(let i in t)i.match(/^background-/)&&(this.cascaded[i]=t[i]);super.applyCascadeAndInit(e,t),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 t=this.style,i=this.pageBox.pageSize,n=this.pageBox.scope,r=e.start,o=e.end,s=e.extent,a=i[s].toExpr(n,null),h=be(n,t[s],a),l=be(n,t[`margin-${r}`],a),c=be(n,t[`margin-${o}`],a),d=Tt(n,t[`padding-${r}`],a),p=Tt(n,t[`padding-${o}`],a),f=oi(n,t[`border-${r}-width`],t[`border-${r}-style`],a),g=oi(n,t[`border-${o}-width`],t[`border-${o}-style`],a),v=ne(n,ne(n,f,d),ne(n,g,p)),w,x,m;return h?(this.borderBoxSizing?(x=h,m=ye(n,x,v)):(m=h,x=ne(n,m,v)),w=ye(n,a,x),!l&&!c?(l=Lo(n,w,new it(n,.5)),c=l):l?c=ye(n,w,l):l=ye(n,w,c)):(l||(l=n.zero),c||(c=n.zero),w=ne(n,l,c),x=ye(n,a,w),m=ye(n,x,v),h=this.borderBoxSizing?x:m),t[r]=new j(l),t[o]=new j(c),t[`margin-${r}`]=Le,t[`margin-${o}`]=Le,t[`border-${r}-width`]=new j(f),t[`border-${o}-width`]=new j(g),t[`padding-${r}`]=new j(d),t[`padding-${o}`]=new j(p),t[s]=new j(h),t[`max-${s}`]=new j(h),{borderBoxExtent:x,contentBoxExtent:m,marginStart:l,marginEnd:c}}prepareContainer(e,t,i,n,r){t.element.setAttribute("data-vivliostyle-page-area-container",!0),super.prepareContainer(e,t,i,n,r)}},hg=class extends Wn{constructor(e,t){super(e,t)}applyCascadeAndInit(e,t){for(let i in t)i.match(/^column.*$/)&&(this.cascaded[i]=t[i]);super.applyCascadeAndInit(e,{})}initHorizontal(){let e=this.style,t=this.parentInstance.style,i=this.pageBox.scope;e.left=t["padding-left"],e.width=new j(this.parentInstance.contentBoxWidth),e["margin-left"]=new j(new Cn(i,t.left.toExpr(i,null))),e["margin-right"]=new j(new Cn(i,t.right.toExpr(i,null))),e["border-left-width"]=t.left,e["border-right-width"]=t.right,e["border-left-style"]=y.solid,e["border-right-style"]=y.solid,e["border-left-color"]=y.transparent,e["border-right-color"]=y.transparent}initVertical(){let e=this.style,t=this.parentInstance.style,i=this.pageBox.scope;e.top=t["padding-top"],e.height=new j(this.parentInstance.contentBoxHeight),e["margin-top"]=new j(new Cn(i,t.top.toExpr(i,null))),e["margin-bottom"]=new j(new Cn(i,t.bottom.toExpr(i,null))),e["border-top-width"]=t.top,e["border-bottom-width"]=t.bottom,e["border-top-style"]=y.solid,e["border-bottom-style"]=y.solid,e["border-top-color"]=y.transparent,e["border-bottom-color"]=y.transparent}prepareContainer(e,t,i,n,r){t.element.setAttribute("data-vivliostyle-page-area",!0),i.pageAreaElement=t.element,super.prepareContainer(e,t,i,n,r),e.pageAreaWidth=t.width,e.pageAreaHeight=t.height}},ug=class extends Wn{constructor(e,t){super(e,t),u(this,"boxInfo"),u(this,"suppressEmptyBoxGeneration",!0);let i=t.marginBoxName;this.boxInfo=yh[i];let n=e;n.pageMarginBoxInstances[i]=this}prepareContainer(e,t,i,n,r){t.element.setAttribute("data-vivliostyle-page-margin-box",this.pageBox.marginBoxName),this.applyVerticalAlign(e,t.element),super.prepareContainer(e,t,i,n,r)}applyVerticalAlign(e,t){I(t,"display","flex"),I(t,"flex-flow",this.vertical?this.rtl?"row-reverse":"row":"column");let i=this.getProp(e,"vertical-align"),n=null;i===B("middle")?n="center":i===B("top")?n="flex-start":i===B("bottom")&&(n="flex-end"),n&&I(t,"justify-content",n);let r=this.getProp(e,"content");if(this.vertical||r instanceof Qe||r instanceof j&&r.expr instanceof we&&r.expr.str.startsWith("running-element-")){let o="center";(this.boxInfo.isInTopRow||this.boxInfo.isInBottomRow)&&(this.boxInfo.isInLeftColumn||this.boxInfo.positionAlongVariableDimension==="end"?o=this.vertical||this.rtl?"start":"end":(this.boxInfo.isInRightColumn||this.boxInfo.positionAlongVariableDimension==="start")&&(o=this.vertical||this.rtl?"end":"start")),I(t,"align-items",o)}}positionAlongVariableDimension(e,t){let i=this.style,n=this.pageBox.scope,r=e.start,o=e.end,s=e.extent,a=r==="left",h=a?t.borderBoxWidth:t.borderBoxHeight,l=be(n,i[s],h),c=a?t.marginLeft:t.marginTop;if(this.boxInfo.positionAlongVariableDimension==="start")i[r]=new j(c);else if(l){let d=Tt(n,i[`margin-${r}`],h),p=Tt(n,i[`margin-${o}`],h),f=Tt(n,i[`padding-${r}`],h),g=Tt(n,i[`padding-${o}`],h),v=oi(n,i[`border-${r}-width`],i[`border-${r}-style`],h),w=oi(n,i[`border-${o}-width`],i[`border-${o}-style`],h),x=ne(n,l,ne(n,this.borderBoxSizing?n.zero:ne(n,ne(n,f,g),ne(n,v,w)),ne(n,d,p)));switch(this.boxInfo.positionAlongVariableDimension){case"center":i[r]=new j(ne(n,c,Pa(n,ye(n,h,x),new it(n,2))));break;case"end":i[r]=new j(ye(n,ne(n,c,h),x));break}}}positionAndSizeAlongFixedDimension(e,t){let i=this.style,n=this.pageBox.scope,r=this.borderBoxSizing,o=e.inside,s=e.outside,a=e.extent,h=t[`margin${s.charAt(0).toUpperCase()}${s.substring(1)}`],l=Gu(n,i[`margin-${o}`],h),c=Gu(n,i[`margin-${s}`],h),d=Tt(n,i[`padding-${o}`],h),p=Tt(n,i[`padding-${s}`],h),f=oi(n,i[`border-${o}-width`],i[`border-${o}-style`],h),g=oi(n,i[`border-${s}-width`],i[`border-${s}-style`],h),v=be(n,i[a],h),w=null;function x(m){if(w)return w;w={extent:v?v.evaluate(m):null,marginInside:l?l.evaluate(m):null,marginOutside:c?c.evaluate(m):null};let S=h.evaluate(m),b=0;return r||[f,d,p,g].forEach(C=>{C&&(b+=C.evaluate(m))}),(w.marginInside===null||w.marginOutside===null)&&b+w.extent+w.marginInside+w.marginOutside>S&&(w.marginInside===null&&(w.marginInside=0),w.marginOutside===null&&(w.marginOutside=0)),w.extent!==null&&w.marginInside!==null&&w.marginOutside!==null&&(w.marginOutside=null),w.extent===null?(w.extent=S-b-w.marginInside-w.marginOutside,w.marginInside===null&&(w.marginInside=0),w.marginOutside===null&&(w.marginOutside=0)):typeof w.extent=="number"&&(w.marginInside===null&&typeof w.marginOutside=="number"?w.marginInside=S-b-w.extent-w.marginOutside:typeof w.marginInside=="number"&&w.marginOutside===null?w.marginOutside=S-b-w.extent-w.marginInside:w.marginInside=w.marginOutside=(S-b-w.extent)/2),w}i[a]=new j(new we(n,function(){let m=x(this).extent;return m===null?"auto":m},a)),i[`margin-${o}`]=new j(new we(n,function(){let m=x(this).marginInside;return m===null?"auto":m},`margin-${o}`)),i[`margin-${s}`]=new j(new we(n,function(){let m=x(this).marginOutside;return m===null?"auto":m},`margin-${s}`)),o==="left"?i.left=new j(ne(n,t.marginLeft,t.borderBoxWidth)):o==="top"&&(i.top=new j(ne(n,t.marginTop,t.borderBoxHeight)))}initHorizontal(){let e=this.parentInstance.pageAreaDimension;this.boxInfo.isInLeftColumn?this.positionAndSizeAlongFixedDimension({inside:"right",outside:"left",extent:"width"},e):this.boxInfo.isInRightColumn?this.positionAndSizeAlongFixedDimension({inside:"left",outside:"right",extent:"width"},e):this.positionAlongVariableDimension({start:"left",end:"right",extent:"width"},e)}initVertical(){let e=this.parentInstance.pageAreaDimension;this.boxInfo.isInTopRow?this.positionAndSizeAlongFixedDimension({inside:"bottom",outside:"top",extent:"height"},e):this.boxInfo.isInBottomRow?this.positionAndSizeAlongFixedDimension({inside:"top",outside:"bottom",extent:"height"},e):this.positionAlongVariableDimension({start:"top",end:"bottom",extent:"height"},e)}finishContainer(e,t,i,n,r,o,s){super.finishContainer(e,t,i,n,r,o,s);let a=i.marginBoxes,h=this.pageBox.marginBoxName,l=this.boxInfo;!l.isInLeftColumn&&!l.isInRightColumn?l.isInTopRow?a.top[h]=t:l.isInBottomRow&&(a.bottom[h]=t):!l.isInTopRow&&!l.isInBottomRow&&(l.isInLeftColumn?a.left[h]=t:l.isInRightColumn&&(a.right[h]=t));let c=this.parentInstance.pageAreaDimension,d=this.getProp(e,"width"),p=d instanceof he&&(d.name==="min-content"||d.name==="max-content"||d.name==="fit-content")?d.name:null,f=this.getPropAsNumber(e,"min-width"),g=this.getPropAsNumber(e,"max-width");if(p||f||g){p&&I(t.element,"width",p),f&&I(t.element,"min-width",`${f}px`),g&&I(t.element,"max-width",`${g}px`);let S=this.getProp(e,"margin-left"),b=this.getProp(e,"margin-right");if(l.isInLeftColumn){let C=c.borderBoxWidth.evaluate(e)+c.marginRight.evaluate(e);I(t.element,"right",`${C}px`),(S===y.auto||b!==y.auto)&&I(t.element,"margin-left","auto"),b===y.auto&&I(t.element,"margin-right","auto")}else l.isInRightColumn&&(I(t.element,"right","0"),(b===y.auto||S!==y.auto)&&I(t.element,"margin-right","auto"),S===y.auto&&I(t.element,"margin-left","auto"))}let v=this.getProp(e,"height"),w=v instanceof he&&(v.name==="min-content"||v.name==="max-content"||v.name==="fit-content")?v.name:null,x=this.getPropAsNumber(e,"min-height"),m=this.getPropAsNumber(e,"max-height");if(w||x||m){w&&I(t.element,"height",w),x&&I(t.element,"min-height",`${x}px`),m&&I(t.element,"max-height",`${m}px`);let S=this.getProp(e,"margin-top"),b=this.getProp(e,"margin-bottom");if(l.isInTopRow){let C=c.borderBoxHeight.evaluate(e)+c.marginBottom.evaluate(e);I(t.element,"bottom",`${C}px`),(S===y.auto||b!==y.auto)&&I(t.element,"margin-top","auto"),b===y.auto&&I(t.element,"margin-bottom","auto")}else l.isInBottomRow&&(I(t.element,"bottom","0"),(b===y.auto||S!==y.auto)&&I(t.element,"margin-bottom","auto"),S===y.auto&&I(t.element,"margin-top","auto"))}}},pS=class{constructor(e,t,i,n,r){u(this,"pageScope",t),u(this,"rootPageBoxInstance",i),u(this,"context",n),u(this,"docElementStyle",r),u(this,"pageMasterCache",{}),u(this,"pageCascadeInstance"),this.pageCascadeInstance=e,this.definePageProgression()}definePageProgression(){let e=this.pageScope,t=this.context,i=t.isVersoFirstPage,n=new Je(e,"page-number"),r=new Fl(e,new _c(e,n,new it(e,2)),i?e.one:e.zero);e.defineName("recto-page",new Ai(e,r)),e.defineName("verso-page",r),(t.pageProgression||sg(this.docElementStyle))==="ltr"?(e.defineName("left-page",r),e.defineName("right-page",new Ai(e,r))):(e.defineName("left-page",new Ai(e,r)),e.defineName("right-page",r))}getCascadedPageStyle(e){let t={};return this.pageCascadeInstance.pushRule([],e,t),this.pageCascadeInstance.popRule(),t}getPageRulePageMaster(e,t){let i=e.pageBox;if(Object.keys(t).length===0)return i.resetScope(),e;let n=this.makeCacheKey(t,i),r=this.pageMasterCache[n];return r||(i.pseudoName===fh?r=this.generatePageRuleMaster(t):r=this.generateCascadedPageMaster(t,i),this.pageMasterCache[n]=r),r.pageBox.resetScope(),r}makeCacheKey(e,t){var i;let n=this.makeCascadeValueObjectKey(e),r=((i=this.context.currentLayoutPosition)==null?void 0:i.page)%2;return`${t.key}^${n}^${r}`}makeCascadeValueObjectKey(e){let t=[];for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)){let n=e[i],r;n instanceof W?r=`${n.value}`:r=this.makeCascadeValueObjectKey(n),t.push(i+r+(n.priority||""))}return t.sort().join("^")}generatePageRuleMaster(e){let t=new lg(this.pageScope,this.rootPageBoxInstance.pageBox,e).createInstance(this.rootPageBoxInstance);return t.applyCascadeAndInit(this.pageCascadeInstance,this.docElementStyle),t.resolveAutoSizing(this.context),t}generateCascadedPageMaster(e,t){let i=t.clone({pseudoName:vh}),n=i.specified,r=e.size;if(r&&!Z(r.value)){let s=Ps(e),a=r.priority;Jt(n,"width",new W(s.width,a),this.context),Jt(n,"height",new W(s.height,a),this.context)}["counter-reset","counter-increment"].forEach(s=>{n[s]&&(e[s]=n[s])});let o=i.createInstance(this.rootPageBoxInstance);return o.applyCascadeAndInit(this.pageCascadeInstance,this.docElementStyle),o.resolveAutoSizing(this.context),o}},fS=class extends Ne{constructor(e){super(),u(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}},gS=class extends Ne{constructor(e){super(),u(this,"scope",e)}apply(e){new Je(this.scope,"page-number").evaluate(e.context)===1&&this.chained.apply(e)}getPriority(){return 2}},mS=class extends Ne{constructor(e){super(),u(this,"scope",e)}apply(e){new Je(this.scope,"blank-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 2}},yS=class extends Ne{constructor(e){super(),u(this,"scope",e)}apply(e){new Je(this.scope,"left-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},vS=class extends Ne{constructor(e){super(),u(this,"scope",e)}apply(e){new Je(this.scope,"right-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},wS=class extends Ne{constructor(e){super(),u(this,"scope",e)}apply(e){new Je(this.scope,"recto-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},bS=class extends Ne{constructor(e){super(),u(this,"scope",e)}apply(e){new Je(this.scope,"verso-page").evaluate(e.context)&&this.chained.apply(e)}getPriority(){return 1}},xS=class extends sn{constructor(e,t,i){super(t,i),u(this,"scope",e),u(this,"a",t),u(this,"b",i)}apply(e){let t=e.context,i=t.layoutPositionAtPageStart.page;t.blankPageAtStart&&i--,i&&this.matchANPlusB(i)&&this.chained.apply(e)}getPriority(){return 2}},SS=class extends sn{constructor(e,t,i,n){super(t,i),u(this,"scope",e),u(this,"a",t),u(this,"b",i),u(this,"pageType",n)}apply(e){let t=e.pageTypePageIndices[this.pageType];if(t){for(let i of t)if(this.matchANPlusB(i)){this.chained.apply(e);return}}}getPriority(){return 3}},CS=class extends rh{constructor(e,t){super(e,t,null,null,null)}apply(e){kS(e.context,e.currentStyle,this.style,this.specificity,e)}};function kS(e,t,i,n,r){xs(e,t,i,n,null,null,null);let o=i[Hr];if(o){let a=si(t,Hr);for(let h in o)if(o.hasOwnProperty(h)){let l=a[h];l||(l={},a[h]=l),xs(e,l,o[h],n,null,null,null)}}let s=i[Ns];if(s){let a=si(t,Ns);for(let h in s)if(s.hasOwnProperty(h)){let l=a[h];l||(l={},a[h]=l);let c=s[h];for(let p in c)if(c.hasOwnProperty(p)&&p!=="_pseudos"){let f=c[p];f instanceof W&&Jt(l,p,f)}let d=ft(c,"_pseudos");if(d){let p=si(l,"_pseudos");for(let f in d)if(d.hasOwnProperty(f)){let g=p[f];g||(g={},p[f]=g);let v=d[f];for(let w in v)if(v.hasOwnProperty(w)){let x=v[w];x instanceof W&&Jt(g,w,x)}}}}}}var ES=class extends Dr{constructor(e,t,i,n,r){super(e,t,i?.condition,i,null,n,!1),u(this,"pageProps",r),u(this,"currentPageSelectors",[]),u(this,"currentNamedPageSelector",""),u(this,"currentPseudoPageClassSelectors",[])}startPageRule(){this.startSelectorRule()}tagSelector(e,t){this.currentNamedPageSelector=t,t&&(this.chain.push(new fS(t)),this.specificity+=65536)}pseudoclassSelector(e,t){if(e=e.toLowerCase(),t)switch(e){case"nth":{let i=t[0],n=t[1];if(t.length===3&&typeof t[2]=="string"){let r=t[2];this.currentPseudoPageClassSelectors.push(`:${e}(${i}n${n<0?n:"+"+n} of ${r})`),this.chain.push(new SS(this.scope,i,n,r)),this.specificity+=65792}else this.currentPseudoPageClassSelectors.push(`:${e}(${i}n${n<0?n:"+"+n})`),this.chain.push(new xS(this.scope,i,n)),this.specificity+=256}break;default:this.reportAndSkip(`E_INVALID_PAGE_SELECTOR :${e}(${t.join("")})`);break}else switch(this.currentPseudoPageClassSelectors.push(`:${e}`),e){case"first":this.chain.push(new gS(this.scope)),this.specificity+=256;break;case"blank":this.chain.push(new mS(this.scope)),this.specificity+=256;break;case"left":this.chain.push(new yS(this.scope)),this.specificity+=1;break;case"right":this.chain.push(new vS(this.scope)),this.specificity+=1;break;case"recto":this.chain.push(new wS(this.scope)),this.specificity+=1;break;case"verso":this.chain.push(new bS(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,t,i){if((e==="bleed"||e==="marks")&&!this.currentPageSelectors.some(o=>o.selectors===null))return;super.simpleProperty(e,t,i);let n=ve(this.elementStyle,e),r=this.pageProps;if(e==="bleed"||e==="marks")r[""]||(r[""]={}),Object.keys(r).forEach(o=>{Fi(r[o],e,n)});else if(e==="size"){let o=r[""];this.currentPageSelectors.forEach(s=>{let a=new W(n.value,n.priority+s.specificity),h=s.selectors?s.selectors.join(""):"",l=r[h];l?Jt(l,e,a):(l=r[h]={},Fi(l,e,a),o&&["bleed","marks"].forEach(c=>{o[c]&&Fi(l,c,o[c])}))})}}insertNonPrimary(e){this.cascade.insertInTable(this.cascade.pagetypes,"*",e)}makeApplyRuleAction(e){return new CS(this.elementStyle,e)}startFootnoteRule(e){let t=si(this.elementStyle,Ns),i=t.area;if(i||(i={},t.area=i),e){let r=si(i,"_pseudos"),o=r[e];o||(o={},r[e]=o),i=o}let n=new cg(this.scope,this.owner,this.validatorSet,i);this.owner.pushHandler(n)}startPageMarginBoxRule(e){let t=si(this.elementStyle,Hr),i=t[e];i||(i={},t[e]=i);let n=new PS(this.scope,this.owner,this.validatorSet,i);this.owner.pushHandler(n)}},PS=class extends on{constructor(e,t,i,n){super(e,t,!1),u(this,"validatorSet",i),u(this,"boxStyle",n)}property(e,t,i){this.validatorSet.validatePropertyAndHandleShorthand(e,t,i,this)}invalidPropertyValue(e,t){this.report(`E_INVALID_PROPERTY_VALUE ${e}: ${t.toString()}`)}unknownProperty(e,t){this.report(`E_INVALID_PROPERTY ${e}: ${t.toString()}`)}simpleProperty(e,t,i){let n=i?this.getImportantSpecificity():this.getBaseSpecificity(),r=new W(t,n);Fi(this.boxStyle,e,r)}},cg=class extends on{constructor(e,t,i,n){super(e,t,!1),u(this,"validatorSet",i),u(this,"areaStyle",n)}property(e,t,i){this.validatorSet.validatePropertyAndHandleShorthand(e,t,i,this)}invalidPropertyValue(e,t){this.report(`E_INVALID_PROPERTY_VALUE ${e}: ${t.toString()}`)}unknownProperty(e,t){this.report(`E_INVALID_PROPERTY ${e}: ${t.toString()}`)}simpleProperty(e,t,i){let n=i?this.getImportantSpecificity():this.getBaseSpecificity(),r=new W(t,n);Fi(this.areaStyle,e,r)}},dg=class{constructor(e,t,i){u(this,"store",e),u(this,"url",t),u(this,"document",i),u(this,"lang",null),u(this,"totalOffset",-1),u(this,"root"),u(this,"body"),u(this,"head"),u(this,"last"),u(this,"lastOffset",1),u(this,"idMap"),this.root=i.documentElement;let n=null,r=null;if(this.root.namespaceURI=="http://www.w3.org/1999/xhtml"){for(let o=this.root.firstChild;o;o=o.nextSibling){if(o.nodeType!=1)continue;let s=o;if(s.namespaceURI=="http://www.w3.org/1999/xhtml")switch(s.localName){case"head":r=s;break;case"body":n=s;break}}this.lang=this.root.getAttribute("lang")}this.body=n,this.head=r,this.last=this.root,this.last.setAttribute(Ht,"0")}doc(){return new fg([this.document])}getElementOffset(e){let t=e.getAttribute(Ht);if(t)return parseInt(t,10);let i=this.lastOffset,n=this.last;for(;n!=e;){let r=n.firstChild;if(!r){for(;r=n.nextSibling,!r;)if(n=n.parentNode,n==null)throw new Error("Internal error")}n=r,r.nodeType==1?(r.setAttribute(Ht,i.toString()),++i):i+=r.textContent.length}return this.lastOffset=i,this.last=e,i-1}getNodeOffset(e,t,i){let n=0,r=e,o=null;if(r.nodeType==1){if(!i)return this.getElementOffset(r)}else{if(n=t,o=r.previousSibling,!o)return r=r.parentNode,n+=1,this.getElementOffset(r)+n;r=o}for(;;){for(;r.lastChild;)r=r.lastChild;if(r.nodeType==1)break;if(n+=r.textContent.length,o=r.previousSibling,!o){r=r.parentNode;break}r=o}return n+=1,this.getElementOffset(r)+n}getTotalOffset(){return this.totalOffset<0&&(this.totalOffset=this.getNodeOffset(this.root,0,!0)),this.totalOffset}getNodeByOffset(e){let t,i=this.root;for(;;){if(t=this.getElementOffset(i),t>=e)return i;let a=i.children;if(!a)break;let h=mi(a.length,l=>{let c=a[l];return this.getElementOffset(c)>e});if(h==0)break;i=a[h-1]}let n=t+1,r=i,o=r.firstChild||r.nextSibling,s=null;for(;;){if(o){if(o.nodeType==1||(r=o,s=r,n+=o.textContent.length,n>e&&!/^\s*$/.test(o.textContent)))break}else if(r=r.parentNode,!r)break;o=r.nextSibling}return o&&s&&/^\s*$/.test(s.textContent)&&(s=o),s||i}buildIdMap(e){let t=e.getAttribute("id");t&&!this.idMap[t]&&(this.idMap[t]=e);let i=e.getAttributeNS("http://www.w3.org/XML/1998/namespace","id");i&&!this.idMap[i]&&(this.idMap[i]=e);for(let n=e.firstElementChild;n;n=n.nextElementSibling)this.buildIdMap(n)}getElement(e){var t;let i=e.match(/([^#]*)#(.+)$/);if(!i||i[1]&&i[1]!=this.url&&((t=this.store)==null?void 0:t.get(i[1]))!==this)return null;let n=i[2],r=this.document.getElementById(n);return!r&&this.document.getElementsByName&&(r=this.document.getElementsByName(n)[0]),r||(this.idMap||(this.idMap={},this.buildIdMap(this.document.documentElement)),r=this.idMap[n]),r}},yl=(e=>(e.TEXT_HTML="text/html",e.TEXT_XML="text/xml",e.APPLICATION_XML="application/xml",e.APPLICATION_XHTML_XML="application/xhtml+xml",e.IMAGE_SVG_XML="image/svg+xml",e))(yl||{});function Ao(e,t,i){let n=i||new DOMParser,r;try{r=n.parseFromString(e,t)}catch{}if(r){let o=r.documentElement,s="parsererror";if(o.localName===s)return null;for(let a=o.firstElementChild;a;a=a.nextElementSibling)if(a.localName===s)return null}else return null;return r}function NS(e){let t=e.contentType;if(t){let n=Object.keys(yl);for(let r=0;r<n.length;r++)if(yl[n[r]]===t)return t;if(t.match(/\+xml$/))return"application/xml"}let i=e.url.match(/\.([^./#?]+)([#?]|$)/);if(i)switch(i[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 pg(e,t){let i=e.responseXML;if(!i){let r=new DOMParser,o=e.responseText;if(o!=null){let s=NS(e);if(i=Ao(o,s||"application/xml",r),i&&!s){let a=i.documentElement;a.localName.toLowerCase()==="html"&&!a.namespaceURI?i=Ao(o,"text/html",r):a.localName.toLowerCase()==="svg"&&i.contentType!=="image/svg+xml"&&(i=Ao(o,"image/svg+xml",r))}i||(i=Ao(o,"text/html",r))}}let n=i?new dg(t,e.url,i):null;return T(n)}function TS(){return new Bl(pg,"document")}var AS=class vl{constructor(t){u(this,"fn",t)}check(t){return this.fn(t)}withAttribute(t,i){return new vl(n=>this.check(n)&&n.nodeType==1&&n.getAttribute(t)==i)}withChild(t,i){return new vl(n=>{if(!this.check(n))return!1;let r=new fg([n]);return r=r.child(t),i&&(r=r.predicate(i)),r.size()>0})}},Qu=new AS(e=>!0),fg=class wl{constructor(t){u(this,"nodes",t)}asArray(){return this.nodes}size(){return this.nodes.length}predicate(t){let i=[];for(let n of this.nodes)t.check(n)&&i.push(n);return new wl(i)}forEachNode(t){let i=[],n=r=>{i.push(r)};for(let r=0;r<this.nodes.length;r++)t(this.nodes[r],n);return new wl(i)}forEach(t){let i=[];for(let n=0;n<this.nodes.length;n++)i.push(t(this.nodes[n]));return i}forEachNonNull(t){let i=[];for(let n=0;n<this.nodes.length;n++){let r=t(this.nodes[n]);r!=null&&i.push(r)}return i}child(t){return this.forEachNode((i,n)=>{for(let r=i.firstChild;r;r=r.nextSibling)r.nodeType==1&&r.localName==t&&n(r)})}childElements(){return this.forEachNode((t,i)=>{for(let n=t.firstChild;n;n=n.nextSibling)n.nodeType==1&&i(n)})}attribute(t){return this.forEachNonNull(i=>i.nodeType==1?i.getAttribute(t):null)}textContent(){return this.forEach(t=>t.textContent)}},IS=new Jr(()=>{let e=M("uaStylesheetBase"),t=Zp(),i=Ae("user-agent-base.css",Ni),n=new Dr(null,null,null,null,null,t,!0);return n.startStylesheet("UA"),o0(n.cascade),Ml(Nd,n,i,null,null).thenFinish(e),e.result()},"uaStylesheetBaseFetcher");function FS(){return IS.get()}var RS=class extends qo{constructor(e,t,i,n,r,o){super(e,t,null,i,n,"counter-style"),u(this,"counterStyleName",r),u(this,"counterStyles",o)}endRule(){super.endRule(),this.counterStyles.define(this.counterStyleName,this.elementStyle)||Y.warn(`E_CSS_COUNTER_STYLE_INVALID: @counter-style ${this.counterStyleName}`)}},LS=class{constructor(e,t,i,n,r,o,s,a,h,l,c){u(this,"store",e),u(this,"rootScope",t),u(this,"pageScope",i),u(this,"cascade",n),u(this,"rootBox",r),u(this,"fontFaces",o),u(this,"footnoteProps",s),u(this,"flowProps",a),u(this,"viewportProps",h),u(this,"pageProps",l),u(this,"counterStyleStore",c),u(this,"fontDeobfuscator"),u(this,"validatorSet"),this.fontDeobfuscator=e.fontDeobfuscator,this.validatorSet=e.validatorSet,this.pageScope.defineBuiltIn("has-content",function(d){d=d;let p=this,f=p.currentLayoutPosition,g=f.firstFlowChunkOfFlow(d);return p.matchPageSide(f.startSideOfFlow(d))&&f.hasContent(d,p.lookupOffset)&&!!g&&!p.flowChunkIsAfterParentFlowForcedBreak(g)}),this.pageScope.defineName("page-number",new we(this.pageScope,function(){let d=this;return d.pageNumberOffset+d.getCurrentPageNumberForPageScope()},"page-number")),this.pageScope.defineName("blank-page",new we(this.pageScope,function(){let d=this.currentLayoutPosition;return d?.isBlankPage},"blank-page"))}sizeViewport(e,t,i,n){if(this.viewportProps.length){let r=new ka(this.rootScope,e,t,i),o=Pb(r,this.viewportProps),s=o.width,a=o.height,h=o["text-zoom"],l=1;if(s&&a||h){let c=Zt.em;if((h?h.evaluate(r,"text-zoom"):null)===y.scale&&(l=c/i,i=c,e*=l,t*=l),s&&a){let d=ut(s.evaluate(r,"width"),r),p=ut(a.evaluate(r,"height"),r);if(d>0&&p>0)return{width:n&&n.spreadView?(d+n.pageBorder)*2:d,height:p,fontSize:i}}}}return{width:e,height:t,fontSize:i}}};function ec(e){let t=new Map,i=n=>{n.formattingContext&&!t.has(n.formattingContext)&&t.set(n.formattingContext,n.formattingContext.saveState()),n.shadowSibling&&i(n.shadowSibling)};for(let n in e.flowPositions){let r=e.flowPositions[n];for(let o of r.positions){let s=o.chunkPosition.primary;for(let a of s.steps)i(a);if(o.chunkPosition.floats)for(let a of o.chunkPosition.floats)for(let h of a.steps)i(h)}}return t}function tc(e){for(let[t,i]of e)i!==void 0&&t.restoreState(i)}var wh=class extends ka{constructor(e,t,i,n,r,o,s,a,h,l,c,d,p,f){super(e.rootScope,n.width,n.height,n.fontSize),u(this,"style",e),u(this,"xmldoc",t),u(this,"viewport",n),u(this,"clientLayout",r),u(this,"fontMapper",o),u(this,"customRenderer",s),u(this,"fallbackMap",a),u(this,"pageNumberOffset",h),u(this,"documentURLTransformer",l),u(this,"counterStore",c),u(this,"cmykStore",d),u(this,"lang"),u(this,"primaryFlows",{body:!0}),u(this,"rootPageBoxInstance",null),u(this,"styler",null),u(this,"stylerMap",null),u(this,"currentLayoutPosition",null),u(this,"layoutPositionAtPageStart",null),u(this,"currentCascadedPageStyle",null),u(this,"lookupOffset",0),u(this,"faces"),u(this,"pageBoxInstances",{}),u(this,"pageManager",null),u(this,"pageNumberContextStack",[]),u(this,"rootPageFloatLayoutContext"),u(this,"pageBreaks",{}),u(this,"pageProgression",null),u(this,"isVersoFirstPage",!1),u(this,"blankPageAtStart",!1),u(this,"pageSheetSize",{}),u(this,"pageSheetHeight",0),u(this,"pageSheetWidth",0),u(this,"invalidPageAreaOnCurrentPage",!1),u(this,"repeatedInvalidPageAreaLayoutPosition",null),u(this,"semanticFootnoteFirstRefOffsets",new Map),u(this,"semanticFootnoteFirstRefOffsetsInitialized",{value:!1}),u(this,"pageGroupPageCounts",Object.create(null)),u(this,"currentPageGroupDocument",null),this.lang=t.lang||i,this.faces=new Px(this.style.fontDeobfuscator),this.rootPageFloatLayoutContext=new Sn(null,null,null,null,null,null,null),this.pageProgression=p||null,this.isVersoFirstPage=!!f;for(let g in e.flowProps){let v=e.flowProps[g],w=ve(v,"flow-consume");w&&(w.evaluate(this,"flow-consume")==y.all?this.primaryFlows[g]=!0:delete this.primaryFlows[g])}}init(){let e=M("StyleInstance.init"),t=this.counterStore.createCounterListener(this.xmldoc.url),i=this.counterStore.createCounterResolver(this.xmldoc.url,this.style.rootScope,this.style.pageScope);this.styler=new Uu(this.xmldoc,this.style.cascade,this.style.rootScope,this,this.primaryFlows,this.style.validatorSet,t,i,this.style.counterStyleStore,this.cmykStore),i.setStyler(this.styler),this.styler.resetFlowChunkStream(this),this.stylerMap={},this.stylerMap[this.xmldoc.url]=this.styler;let n=this.styler.getTopContainerStyle();this.pageProgression||(this.pageProgression=sg(n)),this.matchStartPageSide(this.styler.breakBeforeValues[0])||(this.pageNumberOffset===0?this.isVersoFirstPage=!0:this.blankPageAtStart=!0);let r=this.style.rootBox;this.rootPageBoxInstance=new Zx(r);let o=this.style.cascade.createInstance(this,t,i,this.lang,this.style.counterStyleStore,this.cmykStore);this.styler.cascade.currentPageType=this.styler.cascade.firstPageType,this.rootPageBoxInstance.applyCascadeAndInit(o,n),this.rootPageBoxInstance.resolveAutoSizing(this),this.pageManager=new pS(o,this.style.pageScope,this.rootPageBoxInstance,this,n);let s=[];for(let h of this.style.fontFaces){if(h.condition&&!h.condition.evaluate(this))continue;let l=Ex(h.properties,this),c=new Yf(l);s.push(c)}this.fontMapper.findOrLoadFonts(s,this.faces).then(()=>{Fx(this.xmldoc.document,this.viewport.window,this.styler).thenFinish(e)});let a=this.style.pageProps;return a[""]||(a[""]={}),Object.keys(a).forEach(h=>{let l=a[h];this.styler.cascade.applyVarFilter([l],this.styler,null),this.styler.cascade.applyCalcFilter(l,this.styler.context),this.styler.cascade.applyCmykFilter(l);let c=Ku(Ps(l),this);this.pageSheetSize[h]={width:c.pageWidth+c.cropOffset*2,height:c.pageHeight+c.cropOffset*2}}),e.result()}matchStartPageSide(e){let t=this.pageNumberOffset%2==(this.isVersoFirstPage?1:0),i=this.pageProgression=="ltr";switch(e){case"left":return t!==i;case"right":return t===i;case"recto":return t;case"verso":return!t;default:return!0}}getStylerForDoc(e){let t=this.stylerMap[e.url];if(!t){let i=this.style.store.getStyleForDoc(e),n=new ka(i.rootScope,this.pageWidth(),this.pageHeight(),this.initialFontSize),r=this.counterStore.createCounterListener(e.url),o=this.counterStore.createCounterResolver(e.url,i.rootScope,i.pageScope);t=new Uu(e,i.cascade,i.rootScope,n,this.primaryFlows,i.validatorSet,r,o,i.counterStyleStore,this.cmykStore),this.stylerMap[e.url]=t}return t}registerInstance(e,t){this.pageBoxInstances[e]=t}lookupInstance(e){return this.pageBoxInstances[e]}encounteredFlowChunk(e,t){let i=this.currentLayoutPosition;if(i){i.flows[e.flowName]?t=i.flows[e.flowName]:i.flows[e.flowName]=t;let n=i.flowPositions[e.flowName];n||(n=new Hv,i.flowPositions[e.flowName]=n);let r=Vv(e.element),o=new Bi(r),s=new $v(o,e);n.positions.push(s)}}evalSupportsTest(e,t,i){if(i)return e==="selector"?this.evalSupportsSelector(t):!1;if(!e)return!1;if(Xe(e))return typeof CSS<"u"&&CSS.supports(`(${e}:${t})`);let n=!0;class r{unknownProperty(h,l){n=!1}invalidPropertyValue(h,l){n=!1}simpleProperty(h,l,c){}}let o=new r,s=Ri(this.style.rootScope,new xt(t,null),"");return s?(this.xmldoc.store.validatorSet.validatePropertyAndHandleShorthand(e,s,!1,o),n):!1}getCurrentPageNumberForPageScope(){var e;return this.currentLayoutPosition?this.currentLayoutPosition.page:(e=this.pageNumberContextStack[this.pageNumberContextStack.length-1])!=null?e:0}getPageNumberContextDepth(){return this.pageNumberContextStack.length}pushPageNumberContext(e){this.pageNumberContextStack.push(e)}restorePageNumberContextDepth(e){this.pageNumberContextStack.length=e}evalSupportsSelector(e){class t extends gg{errorMsg(...s){}}let i=new t(null),n=dd(e),r=new xt(n+"{}",i);return new Qr($e,r,i,"").runParser(Number.POSITIVE_INFINITY,!1,!1,!1,!1)?!i.cascadeParserHandler.invalid:!1}getConsumedOffset(e){let t=Number.POSITIVE_INFINITY;for(let i=0;i<e.positions.length;i++){let n=e.positions[i].chunkPosition.primary,r=n.steps[0].node,o=n.offsetInNode,s=n.after,a=0;for(;r.ownerDocument!=this.xmldoc.document;)a++,r=n.steps[a].node,s=!1,o=0;let h=this.xmldoc.getNodeOffset(r,o,s);h<t&&(t=h)}return t}getNodePositionOffset(e){let t=e.steps[0].node,i=e.offsetInNode,n=e.after,r=0;for(;t.ownerDocument!=this.xmldoc.document;)r++,t=e.steps[r].node,n=!1,i=0;return this.xmldoc.getNodeOffset(t,i,n)}getPageStartOffset(e,t){if(!e)return 0;let i=Number.POSITIVE_INFINITY;for(let n in this.primaryFlows){let r=e.flowPositions[n];if(!t&&(!r||r.positions.length==0)&&this.currentLayoutPosition&&(this.styler.styleUntilFlowIsReached(n),r=this.currentLayoutPosition.flowPositions[n],e!=this.currentLayoutPosition&&r&&(r=r.clone(),e.flowPositions[n]=r)),r)for(let o=0;o<r.positions.length;o++){let s=r.positions[o].chunkPosition.primary,a=this.getNodePositionOffset(s);a<i&&(i=a)}}return i}getPageStartCounterOffsets(e){var t;let i=this.getPageStartOffset(e);if(!isFinite(i))return{counterOffset:i,changeOffset:i};let n=this.xmldoc.body||this.xmldoc.root,r=n?this.getFirstInFlowElementAtOrAfter(n,i):null,o=n?this.xmldoc.getElementOffset(n):i,s=i<=o,a=r===n&&s&&(t=this.getFirstInFlowChildElement(n))!=null?t:r;if(!a)return s?{counterOffset:o,changeOffset:o}:{counterOffset:i,changeOffset:i};let h=this.xmldoc.getElementOffset(a),l=i;return s&&h!==i&&(l=h),h===i&&(this.isInlineLevelElement(a)?l=Math.max(0,i-1):l=this.getDeepestFirstInFlowChildOffset(a)),{counterOffset:l,changeOffset:h}}getPageStartElement(e,t=this.getPageStartOffset(e)){var i;if(!isFinite(t))return null;let n=this.xmldoc.body||this.xmldoc.root;if(!n)return null;let r=this.getFirstInFlowElementAtOrAfter(n,t),o=this.xmldoc.getElementOffset(n),s=t<=o;if(r===n&&s)return(i=this.getFirstInFlowChildElement(n))!=null?i:r;if((r?this.xmldoc.getElementOffset(r):Number.POSITIVE_INFINITY)>t){let a=this.xmldoc.getNodeByOffset(t);if(!Ee(a)){let h=a.nodeType===Node.ELEMENT_NODE?a:a.parentElement;for(;h;){if(this.xmldoc.getElementOffset(h)<=t&&this.isPageBoundaryCandidateElement(h))return h;h=h.parentElement}}}return r}isForcedPageBreakValue(e){return Ze(e)&&e!=="column"&&e!=="region"}hasForcedPageBreakBefore(e){let t=ve(e,"break-before");if(!t)return!1;let i=t.evaluate(this,"break-before").toString();return this.isForcedPageBreakValue(i)}getExplicitPageType(e){let t=ve(e,"page");if(!t||Z(t.value))return null;let i=t.evaluate(this,"page").toString();return!i||i.toLowerCase()==="auto"?null:i}getPageGroupPageType(e){if(this.isInlineLevelElement(e))return null;let t=this.styler.getStyle(e,!1);return t?this.getExplicitPageType(t):null}getPageStartPageType(e){let t=this.getPageStartOffset(e,!0),i=this.getPageStartElement(e,t);for(;i;){let n=this.getPageGroupPageType(i);if(n)return n;if(i===this.xmldoc.root)break;i=i.parentElement}return""}getPageStartPageTypeOverride(e){if(this.getPageStartPageType(e)!=="")return;let t=this.getPageStartOffset(e,!0),i=this.getPageStartElement(e,t);if(i&&this.xmldoc.getElementOffset(i)<t)return"";for(;i&&(i=this.getFirstInFlowChildElement(i),!!i);){let n=this.getPageGroupPageType(i);if(n)return n}return""}getPreviousInFlowSibling(e){let t=e.previousElementSibling;for(;t;){if(this.isPageBoundaryCandidateElement(t))return t;t=t.previousElementSibling}return null}getFirstDocumentFlowElement(){var e;let t=this.xmldoc.body||this.xmldoc.root;if(!t)return null;let i=this.xmldoc.getElementOffset(t),n=this.getFirstInFlowElementAtOrAfter(t,i);return n===t&&(e=this.getFirstInFlowChildElement(t))!=null?e:n}getEffectiveFirstPageType(e){let t=e,i=t?this.getPageGroupPageType(t):null;for(;t;){let n=this.getFirstInFlowChildElement(t);if(!n)return i;let r=this.getPageGroupPageType(n);r&&(i=r),t=n}return i}getEffectivePageGroupStartElement(e){let t=e,i=e;for(;i;){let n=this.getFirstInFlowChildElement(i);if(!n)return t;this.getPageGroupPageType(n)&&(t=n),i=n}return t}resolveFirstPageType(){let e=this.getFirstDocumentFlowElement();return this.getEffectiveFirstPageType(e)}shouldStartPageGroup(e,t,i){let n=this.styler.getStyle(e,!1);if(!n)return!1;if(this.getFirstDocumentFlowElement()===e)return!0;let r=this.xmldoc.getElementOffset(e),o=this.xmldoc.body||this.xmldoc.root,s=this.xmldoc.getElementOffset(o);if(i<=s&&e===o||!this.getPreviousInFlowSibling(e)&&i===r)return!0;if(r!==i)return!1;if(this.hasForcedPageBreakBefore(n))return!0;let a=this.getPreviousInFlowSibling(e);if(!a)return!1;let h=this.styler.getStyle(a,!1);return h?this.getExplicitPageType(h)!==t:!1}updatePageGroupPageIndices(e){let t=this.pageManager.pageCascadeInstance;t.pageTypePageIndices=Object.create(null);let i=e?.startSideOfFlow("body")||null,n=e?.flowPositions.body,r=!!(n&&n.positions.length),o=!!i&&en(i)&&!this.matchPageSide(i)&&!r,s=!(this.blankPageAtStart&&(!e||e.page===1))&&!(e!=null&&e.isBlankPage)&&!o,a=this.getPageStartOffset(e),h=this.getPageStartElement(e,a);if(!h)return;let l=this.getEffectivePageGroupStartElement(h),c=l===h?a:this.xmldoc.getElementOffset(l),d=l.ownerDocument,p=this.currentPageGroupDocument!==d&&s;p&&(this.pageGroupPageCounts=Object.create(null),this.currentPageGroupDocument=d);let f=l;for(;f;){let g=this.getPageGroupPageType(f);if(g){let v=this.pageGroupPageCounts[g]||(this.pageGroupPageCounts[g]=new Map),w=v.get(f)||0;(w>0||s&&(p||this.shouldStartPageGroup(f,g,c)))&&(w+=1,v.set(f,w),(t.pageTypePageIndices[g]||(t.pageTypePageIndices[g]=[])).push(w))}if(f===this.xmldoc.root)break;f=f.parentElement}}preparePageGroupPageIndicesForRerender(e,t){this.pageGroupPageCounts=Object.create(null),this.currentPageGroupDocument=null;for(let i=0;i<t;i++){let n=e[i]||null;this.updatePageGroupPageIndices(n)}}getFirstInFlowElementAtOrAfter(e,t){if(this.isPageBoundaryCandidateElement(e)&&this.xmldoc.getElementOffset(e)>=t)return e;let i=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{let r=n;return this.isNormalFlowElement(r)?this.isInlineLevelElement(r)||this.xmldoc.getElementOffset(r)<t?NodeFilter.FILTER_SKIP:NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}}).firstChild();return i??null}getDeepestFirstInFlowChildOffset(e){let t=e;for(;;){let i=this.getFirstInFlowChildElement(t);if(!i)return this.xmldoc.getElementOffset(t);t=i}}getFirstInFlowChildElement(e){let t=e.firstChild;for(;t;){if(t.nodeType===Node.TEXT_NODE){if(!Ee(t))return null;t=t.nextSibling;continue}if(t.nodeType!==Node.ELEMENT_NODE){t=t.nextSibling;continue}let i=t;if(this.isNormalFlowElement(i))return this.isInlineLevelElement(i)?null:i;t=t.nextSibling}return null}isPageBoundaryCandidateElement(e){return this.isNormalFlowElement(e)&&!this.isInlineLevelElement(e)}isNormalFlowElement(e){var t,i;let n=this.styler.getStyle(e,!1);if(this.getDisplayValue(e)===y.none)return!1;let r=(t=n?.position)==null?void 0:t.evaluate(this.styler.context,"position"),o=r&&!Z(r)?r:y.static;if(vr(o)||Fr(o))return!1;let s=(i=n?.float)==null?void 0:i.evaluate(this.styler.context,"float");return(s&&!Z(s)?s:y.none)===y.none}isInlineLevelElement(e){return Ut(this.getDisplayValue(e))}getDisplayValue(e){var t;let i=this.styler.getStyle(e,!1),n=(t=i?.display)==null?void 0:t.evaluate(this.styler.context,"display");return n&&!Z(n)?n:y.inline}getPosition(e,t){if(!e)return 0;let i=Number.POSITIVE_INFINITY;for(let n in this.primaryFlows){let r=e.flowPositions[n];if(!t&&(!r||r.positions.length==0)&&this.currentLayoutPosition&&(this.styler.styleUntilFlowIsReached(n),r=this.currentLayoutPosition.flowPositions[n],e!=this.currentLayoutPosition&&r&&(r=r.clone(),e.flowPositions[n]=r)),r){let o=this.getConsumedOffset(r);o<i&&(i=o)}}return i}dumpLocation(e){Y.debug("Location - page",this.currentLayoutPosition.page),Y.debug(" current:",e),Y.debug(" lookup:",this.lookupOffset);for(let t in this.currentLayoutPosition.flowPositions){let i=this.currentLayoutPosition.flowPositions[t];for(let n of i.positions)Y.debug(" Chunk",`${t}:`,n.flowChunk.startOffset)}}matchPageSide(e){switch(e){case"left":case"right":case"recto":case"verso":return new Je(this.style.pageScope,`${e}-page`).evaluate(this);default:return!0}}updateStartSide(e){for(let t in e.flowPositions){let i=e.flowPositions[t];if(i&&i.positions.length>0){let n=i.positions[0].flowChunk;if(this.getConsumedOffset(i)===n.startOffset){let r=i.positions[0].flowChunk.breakBefore,o=i.startBreakType;i.startBreakType=lu(nt(o,r))}}}}selectPageMaster(e){var t;let i=this.currentLayoutPosition,n=this.getPosition(i);if(n==Number.POSITIVE_INFINITY&&this.hasActiveRootPageFloatLayoutContext()&&(n=(t=i.highestSeenOffset)!=null?t:this.styler.getReachedOffset()),n==Number.POSITIVE_INFINITY)return null;let r=this.rootPageBoxInstance.children,o;for(let s=0;s<r.length;s++){if(o=r[s],o.pageBox.pseudoName===vh)continue;let a=1;o.pageBox.pseudoName===fh&&!(this.actualPageWidth&&this.actualPageHeight)&&(a=1/0);let h=o.getProp(this,"utilization");h&&h.isNum()&&(a=h.num);let l=this.queryUnitSize("em",!1),c=this.pageWidth()*this.pageHeight(),d=Math.ceil(a*c/(l*l)),p=this.styler.cascade.currentPageType;this.lookupOffset=this.styler.styleUntil(n,d),this.styler.cascade.currentPageType=p,this.updateStartSide(i),this.layoutPositionAtPageStart=i.clone(),this.initLingering(),this.clearScope(this.style.pageScope);let f=o.getProp(this,"enabled");if(!f||f===y._true){if(i.page===1&&this.blankPageAtStart){o.style={};let g=e.size;e={},g&&(e.size=g)}return this.pageManager.getPageRulePageMaster(o,e)}}throw new Error("No enabled page masters")}flowChunkIsAfterParentFlowForcedBreak(e){let t=this.layoutPositionAtPageStart.flows,i=t[e.flowName].parentFlowName;if(i){let n=e.startOffset,r=t[i].forcedBreakOffsets;if(!r.length||n<r[0])return!1;let o=mi(r.length,l=>r[l]>n)-1,s=r[o],a=this.layoutPositionAtPageStart.flowPositions[i],h=this.getConsumedOffset(a);return s<h?!1:h<s?!0:!this.matchPageSide(a.startBreakType)}return!1}setFormattingContextToColumn(e,t){let i=this.currentLayoutPosition.flows[t];i.formattingContext||(i.formattingContext=new jl(null)),e.flowRootFormattingContext=i.formattingContext}beginIsolatedRootPageFloatLayoutContext(e){let t=this.rootPageFloatLayoutContext;return this.rootPageFloatLayoutContext=new Sn(null,null,null,null,null,null,null),e&&this.rootPageFloatLayoutContext.addPageFloatLayoutContextAsPreviousSibling(e),t}endIsolatedRootPageFloatLayoutContext(e){this.rootPageFloatLayoutContext=e}hasActiveRootPageFloatLayoutContext(){return this.rootPageFloatLayoutContext.getDeferredPageFloatContinuations().length>0||this.rootPageFloatLayoutContext.getPageFloatContinuationsDeferredToNext().length>0||this.rootPageFloatLayoutContext.getFloatsDeferredToNextInChildContexts().length>0}hasOnlyDeferredPageFloats(e){return this.noMorePrimaryFlows(e)&&this.hasActiveRootPageFloatLayoutContext()}layoutDeferredPageFloats(e){let t=e.pageFloatLayoutContext,i=t.getDeferredPageFloatContinuations(),n=this.counterStore.currentPageCountersStack.length>0,r=h=>{var l,c;if(!n||h.floatReference!==Pe.PAGE)return!1;let d=((c=(l=this.layoutPositionAtPageStart)==null?void 0:l.flowPositions)==null?void 0:c.body)||null,p=d?this.getConsumedOffset(d):Number.NaN,f=isFinite(p)?p:this.getPageStartOffset(this.layoutPositionAtPageStart,!0),g=this.xmldoc.getNodeOffset(h.nodePosition.steps[0].node,0,!1);return g!=null&&isFinite(f)&&g>f},o=M("layoutDeferredPageFloats"),s=!1,a=0;return o.loopWithFrame(h=>{if(a===i.length){h.breakLoop();return}let l=i[a++],c=l.float;if(r(c)){h.breakLoop();return}let d=new Vn().findByFloat(c),p=d.findPageFloatFragment(c,t);if(p&&p.hasFloat(c)){h.continueLoop();return}else if(t.isForbidden(c)||t.hasPrecedingFloatsDeferredToNext(c)){t.deferPageFloat(l),h.breakLoop();return}e.layoutPageFloatInner(l,d,null,p).then(f=>{if(!f){h.breakLoop();return}let g=t.parent.isInvalidated();if(g){h.breakLoop();return}else t.isInvalidated()&&!g&&(s=!0,t.validate());h.continueLoop()})}).then(()=>{s&&t.invalidate(),o.finish(!0)}),o.result()}getLastAfterPositionIfDeferredFloatsExists(e,t){if(e.pageFloatLayoutContext.getPageFloatContinuationsDeferredToNext().length>0)if(e.lastAfterPosition){let i;return t?(i=t.clone(),i.primary=e.lastAfterPosition):i=new Bi(e.lastAfterPosition),i}else return null;else return null}layoutColumn(e,t){let i=this.currentLayoutPosition.flowPositions[t];if(!i||!this.matchPageSide(i.startBreakType))return i?(this.setFormattingContextToColumn(e,t),e.init(),this.layoutDeferredPageFloats(e)):T(!0);this.setFormattingContextToColumn(e,t),e.init(),this.primaryFlows[t]&&e.bands.length>0&&(e.forceNonfitting=!1);let n=M("layoutColumn");return this.layoutDeferredPageFloats(e).then(()=>{if(e.pageFloatLayoutContext.isInvalidated()){n.finish(!0);return}let r=[],o=[],s=!0;n.loopWithFrame(a=>{if(e.pageFloatLayoutContext.hasContinuingFloatFragmentsInFlow(t)){a.breakLoop();return}for(;i.positions.length-o.length>0;){let h=0;for(;o.includes(h);)h++;let l=i.positions[h];if(l.flowChunk.startOffset>this.lookupOffset||this.flowChunkIsAfterParentFlowForcedBreak(l.flowChunk))break;for(let p=h+1;p<i.positions.length;p++){if(o.includes(p))continue;let f=i.positions[p];if(f.flowChunk.startOffset>this.lookupOffset||this.flowChunkIsAfterParentFlowForcedBreak(f.flowChunk))break;f.flowChunk.isBetter(l.flowChunk)&&(l=f,h=p)}let c=l.flowChunk,d=!0;if(e.layout(l.chunkPosition,s,i.breakAfter).then(p=>{if(e.pageFloatLayoutContext.isInvalidated()){a.breakLoop();return}if(s=!1,l.flowChunk.repeated&&(p===null||c.exclusive)&&r.push(h),c.exclusive){o.push(h),a.breakLoop();return}else{let f=!!p||!!e.pageBreakType,g=this.getLastAfterPositionIfDeferredFloatsExists(e,p);if(!p&&e.pageBreakType&&i.positions.length-o.length-1<=0&&(e.pageBreakType=null),e.pageBreakType&&g?(l.chunkPosition=g,i.breakAfter=e.pageBreakType,e.pageBreakType=null):(o.push(h),(p||g)&&(l.chunkPosition=p||g,r.push(h)),i.startBreakType=lu(e.pageBreakType)),f){a.breakLoop();return}}e.forceNonfitting=!1,d?d=!1:a.continueLoop()}),d){d=!1;return}}a.breakLoop()}).then(()=>{var a;if(!e.pageFloatLayoutContext.isInvalidated()){i.positions=i.positions.filter((l,c)=>r.includes(c)||!o.includes(c)),i.breakAfter==="column"&&(i.breakAfter=null),e.saveDistanceToBlockEndFloats();let h=e.pageFloatLayoutContext.getMaxReachedAfterEdge();if(e.updateMaxReachedAfterEdge(h),e.computedBlockSize===0){let l=e.pageFloatLayoutContext,c=l;for(;c;){let d=c.floatFragments.filter(p=>"isFootnote"in p.area&&p.area.isFootnote);if(d.length>0&&!c.ignoreFootnoteAreaMaxHeight&&d.some(p=>{let f=getComputedStyle(p.area.element),g=v=>v!==""&&v!=="none";return g(f.getPropertyValue("max-block-size"))||g(p.area.vertical?f.maxWidth:f.maxHeight)})){c.ignoreFootnoteAreaMaxHeight=!0;for(let p of d){l.removePageFloatFragment(p,!0);let f=(a=p.continuations[0])==null?void 0:a.float;f&&c.removeFloatDeferredToNext(f)}l.invalidate();break}c=c.parent}}}n.finish(!0)})}),n.result()}createLayoutConstraint(e){let t=this.currentLayoutPosition.page-1,i=this.counterStore.createLayoutConstraint(t);return new F0([i].concat(e.getLayoutConstraints()))}createAndLayoutColumn(e,t,i,n,r,o,s,a,h,l,c,d,p,f){let g=e.vertical?e.isAutoWidth&&e.isRightDependentOnAutoWidth||e.isAutoHeight:e.isAutoHeight&&e.isTopDependentOnAutoHeight||e.isAutoWidth,v=r.element,w=new Sn(a,Pe.COLUMN,null,s,null,null,null),x=this.currentLayoutPosition.clone(),m=M("createAndLayoutColumn"),S;return m.loopWithFrame(b=>{let C=this.createLayoutConstraint(w);if(h>1){let P=this.viewport.document.createElement("div");if(I(P,"position","absolute"),v.appendChild(P),S=new Cs(P,p,this.clientLayout,C,w),S.isNonFirstColumn=o>0,S.forceNonfitting=f,S.vertical=r.vertical,S.rtl=r.rtl,S.snapHeight=r.snapHeight,S.snapWidth=r.snapWidth,r.vertical){let L=(r.rtl?h-o-1:o)*(c+l)+r.paddingTop,A=parseFloat(v.style.width);S.setHorizontalPosition(r.paddingLeft+A-r.width,r.width),S.setVerticalPosition(L,c)}else{let L=(r.rtl?h-o-1:o)*(c+l)+r.paddingLeft;S.setVerticalPosition(r.paddingTop,r.height),S.setHorizontalPosition(L,c)}S.originX=t,S.originY=i}else S=new Cs(v,p,this.clientLayout,C,w),S.isNonFirstColumn=!1,S.copyFrom(r);S.exclusions=g?[]:n.concat(),S.innerShape=d,w.setContainer(S),(S.vertical?S.height:S.width)>=0?this.layoutColumn(S,s).then(()=>{w.isInvalidated()||w.finish(),S.pageFloatLayoutContext.isInvalidated()&&!a.isInvalidated()?(S.pageFloatLayoutContext.validate(),this.currentLayoutPosition=x.clone(),S.element!==v&&v.removeChild(S.element),b.continueLoop()):b.breakLoop()}):(w.finish(),b.breakLoop())}).then(()=>{m.finish(S)}),m.result()}setPagePageFloatLayoutContextContainer(e,t,i){(t instanceof hg||t instanceof gh&&!(t instanceof Mn))&&e.setContainer(i)}getRegionPageFloatLayoutContext(e,t,i,n){t instanceof Wn;let r=t.getProp(this,"writing-mode")||null,o=t.getProp(this,"direction")||null;return new Sn(e,Pe.REGION,i,n,null,r,o)}layoutFlowColumnsWithBalancing(e,t,i,n,r,o,s,a,h){let l=this.currentLayoutPosition.clone(),c=this.getRegionPageFloatLayoutContext(o,t,s,a),d=!0,p=()=>(this.currentLayoutPosition=l.clone(),this.layoutFlowColumns(e,t,i,n,r,o,c,s,a,h,d).thenAsync(f=>T(f?{columns:f,position:this.currentLayoutPosition}:null)));return p().thenAsync(f=>{if(!f)return T(null);if(h<=1)return T(f.columns);let g=t.getProp(this,"column-fill")||y.balance,v=this.currentLayoutPosition.flowPositions[a],w=wx(h,g,p,c,s,f.columns,v);return w?(d=!1,o.lock(),c.lock(),w.balanceColumns(f).thenAsync(x=>(o.unlock(),o.validate(),c.unlock(),this.currentLayoutPosition=x.position,T(x.columns)))):T(f.columns)})}layoutFlowColumns(e,t,i,n,r,o,s,a,h,l,c){let d=M("layoutFlowColumns"),p=this.currentLayoutPosition.clone(),f=ec(this.currentLayoutPosition),g=t.getPropAsNumber(this,"column-gap"),v=l>1?t.getPropAsNumber(this,"column-width"):a.vertical?a.height:a.width,w=t.getActiveRegions(this),x=t.getProp(this,"shape-inside"),m=ld(x,0,0,a.width,a.height,this),S=new $x(h,this,this.viewport,this.styler,w,this.xmldoc,this.faces,this.style.footnoteProps,this,e,this.customRenderer,this.fallbackMap,this.documentURLTransformer,this.style.pageProps,this.currentCascadedPageStyle,this.semanticFootnoteFirstRefOffsets,this.semanticFootnoteFirstRefOffsetsInitialized),b=0,C=null,P=[];return d.loopWithFrame(L=>{this.createAndLayoutColumn(t,i,n,r,a,b++,h,s,l,g,v,m,S,c).then(A=>{if(o.isInvalidated()){P=null,L.breakLoop();return}if((A.pageBreakType&&A.pageBreakType!=="column"||b===l)&&!s.isInvalidated()&&s.finish(),s.isInvalidated()){b=0,this.currentLayoutPosition=p.clone(),tc(f),s.validate(),s.isLocked()?(P=null,L.breakLoop()):L.continueLoop();return}C=A,P[b-1]=C,C.pageBreakType&&C.pageBreakType!="column"&&(b=l,C.pageBreakType!="region"&&(this.pageBreaks[h]=!0)),b<l?L.continueLoop():L.breakLoop()})}).then(()=>{d.finish(P)}),d.result()}layoutContainer(e,t,i,n,r,o,s){t.reset();let a=t.getProp(this,"enabled");if(a&&a!==y._true)return T(!0);let h=M("layoutContainer"),l=t.getProp(this,"wrap-flow")===y.auto,c=t.getProp(this,"flow-from"),d=this.viewport.document.createElement("div");d.role=t instanceof ug?"complementary":"presentation";let p=t.getProp(this,"position");I(d,"position",p?p.name:"absolute");let f=t instanceof Mn;t instanceof Wn?i.appendChild(d):i.insertBefore(d,i.firstChild);let g=new lp(d);g.vertical=t.vertical,g.rtl=t.rtl,g.borderBoxSizing=t.borderBoxSizing,g.exclusions=o,t.prepareContainer(this,g,e,this.faces,this.clientLayout),(g.width<=0||g.height<=0)&&(t instanceof Mn||c&&c.isIdent())&&(this.invalidPageAreaOnCurrentPage=!0,Y.warn("Negative or zero page area size")),g.originX=n,g.originY=r,n+=g.left+g.marginLeft+g.borderLeft,r+=g.top+g.marginTop+g.borderTop,this.setPagePageFloatLayoutContextContainer(s,t,g);let v,w=!1;if(!c||!c.isIdent()){let x=[],m=t.getProp(this,"content");if(m instanceof j&&m.expr instanceof we&&m.expr.str.startsWith("running-element-"))m.visit(new Lr(d,this,m,this.counterStore.getExprContentListener()));else if(It(m)){let S="span";m instanceof Qe&&(S="img");let b=this.viewport.document.createElement(S);m.visit(new Lr(b,this,m,this.counterStore.getExprContentListener())),d.appendChild(b),S=="img"&&t.transferSingleUriContentProps(this,b,this.faces),t.transferContentProps(this,g,e,this.faces);let C=b.querySelectorAll("img[src]");for(let L=0;L<C.length;L++){let A=C[L],z=A.getAttribute("src");if(!z)continue;let U=Et(A,z);x.push(U),e.fetchers.push(U)}let P=b.getAttribute("src");if(P){let L=b.querySelector("img");L||(L=b);let A=Et(L,P);x.push(A),e.fetchers.push(A)}S=="span"&&C0(b,t.getProp(this,"text-autospace"),t.getProp(this,"text-spacing-trim"),t.getProp(this,"hanging-punctuation"),this.lang,t.vertical)}else t.suppressEmptyBoxGeneration&&(i.removeChild(d),w=!0);w||t.finishContainer(this,g,e,null,1,this.clientLayout,this.faces),v=x.length?Dn(x).thenReturn(!0):T(!0)}else if(this.pageBreaks[c.toString()])s.isInvalidated()||t.finishContainer(this,g,e,null,1,this.clientLayout,this.faces),v=T(!0);else{let x=M("layoutContainer.inner"),m=c.toString(),S=t.getPropAsNumber(this,"column-count");this.layoutFlowColumnsWithBalancing(e,t,n,r,o,s,g,m,S).then(b=>{if(!s.isInvalidated()){let C=b[0];C.element===d&&(g=C),g.computedBlockSize=Math.max.apply(null,b.map(L=>L.computedBlockSize)),t.finishContainer(this,g,e,C,S,this.clientLayout,this.faces);let P=this.currentLayoutPosition.flowPositions[m];P&&P.breakAfter==="region"&&(P.breakAfter=null)}x.finish(!0)}),v=x.result()}return v.then(()=>{if(s.isInvalidated()){h.finish(!0);return}if(!t.isAutoHeight||Math.floor(g.computedBlockSize)>0){if(!w&&!l){let m=t.getProp(this,"shape-outside"),S=g.getOuterShape(m,this);o.push(S)}}else if(t.children.length==0){i.removeChild(d),h.finish(!0);return}let x=f?0:t.children.length-1;h.loop(()=>{for(;x>=0&&x<t.children.length;){let m=t.children[f?x++:x--],S=this.layoutContainer(e,m,d,n,r,o,s);if(S.isPending())return S.thenAsync(()=>T(!s.isInvalidated()));if(s.isInvalidated())break}return T(!1)}).then(()=>{h.finish(!0)})}),h.result()}processLinger(){let e=this.currentLayoutPosition.page;for(let t in this.currentLayoutPosition.flowPositions){let i=this.currentLayoutPosition.flowPositions[t];for(let n=i.positions.length-1;n>=0;n--){let r=i.positions[n];r.flowChunk.startPage>=0&&r.flowChunk.startPage+r.flowChunk.linger-1<=e&&i.positions.splice(n,1)}}}initLingering(){let e=this.currentLayoutPosition.page;for(let t in this.currentLayoutPosition.flowPositions){let i=this.currentLayoutPosition.flowPositions[t];for(let n=i.positions.length-1;n>=0;n--){let r=i.positions[n];r.flowChunk.startPage<0&&r.flowChunk.startOffset<this.lookupOffset&&(r.flowChunk.startPage=e)}}}noMorePrimaryFlows(e){for(let t in this.primaryFlows){let i=e.flowPositions[t];if(i&&i.positions.length>0)return!1}return!0}hasSameFlowPositions(e,t){if(e===t)return!0;if(!e||!t)return!1;let i=Object.keys(e.flowPositions),n=Object.keys(t.flowPositions);if(i.length!==n.length)return!1;for(let r of i)if(!e.flowPositions[r].isSamePosition(t.flowPositions[r]))return!1;return!0}checkRepeatedInvalidPageArea(e){let t=this.invalidPageAreaOnCurrentPage;if(this.invalidPageAreaOnCurrentPage=!1,!t){this.repeatedInvalidPageAreaLayoutPosition=null;return}if(e.isBlankPage||this.noMorePrimaryFlows(e))return;if(!this.hasSameFlowPositions(this.layoutPositionAtPageStart,e)){this.repeatedInvalidPageAreaLayoutPosition=null;return}let i=!!this.repeatedInvalidPageAreaLayoutPosition&&this.hasSameFlowPositions(this.repeatedInvalidPageAreaLayoutPosition,this.layoutPositionAtPageStart);if(this.repeatedInvalidPageAreaLayoutPosition=this.layoutPositionAtPageStart.clone(),i)throw new Error("Negative or zero page area size")}layoutNextPage(e,t){var i,n,r,o;let s=e.container===e.bleedBox;this.pageBreaks={},t?(this.currentLayoutPosition=t.clone(),this.styler.replayFlowElementsFromOffset(t.highestSeenOffset)):(this.currentLayoutPosition=new Wv,this.styler.replayFlowElementsFromOffset(-1)),this.lang&&e.bleedBox.setAttribute("lang",this.lang),this.invalidPageAreaOnCurrentPage=!1,t=this.currentLayoutPosition;let a=t.startSideOfFlow("body");t.isBlankPage=en(a)&&this.matchPageSide(a),e.isBlankPage=t.isBlankPage,t.page++;let h=this.hasOnlyDeferredPageFloats(t),l=h?void 0:this.getPageStartPageTypeOverride(t);if(l===""?e.pageType="":l&&(e.pageType=l),e.pageType==null){let m=t.page===1?this.resolveFirstPageType():null,S=(i=this.styler.cascade.currentPageType)!=null?i:this.styler.cascade.previousPageType,b=e.isBlankPage?this.styler.cascade.previousPageType:h?S:m??this.styler.cascade.currentPageType;if(e.pageType=b,!e.pageType){let C=this.getPageStartPageType(t);C&&(e.pageType=C)}e.pageType=(n=e.pageType)!=null?n:"",this.styler.cascade.previousPageType=this.styler.cascade.currentPageType}this.updatePageGroupPageIndices(t),this.clearScope(this.style.pageScope),this.layoutPositionAtPageStart=t.clone();let c=ec(t),d=s?{}:this.pageManager.getCascadedPageStyle(e.pageType);if(this.currentCascadedPageStyle=d,this.styler.cascade.applyVarFilter([d],this.styler,null),this.styler.cascade.applyCalcFilter(d,this.styler.context),this.styler.cascade.applyCmykFilter(d),!s){let m=new Je(this.style.pageScope,"left-page");e.side=m.evaluate(this)?"left":"right",e.container.setAttribute("data-vivliostyle-page-side",e.side)}let p=this.selectPageMaster(d);if(!p)return T(null);let f=0;if(!s){e.setAutoPageWidth(p.pageBox.specified.width.value===qr),e.setAutoPageHeight(p.pageBox.specified.height.value===Yr);let{counterOffset:m,changeOffset:S}=this.getPageStartCounterOffsets(this.layoutPositionAtPageStart);isFinite(m)||(m=this.lookupOffset,S=this.lookupOffset),isFinite(m)&&this.styler.styleUntil(m,0);let b=this.styler.getCounterSnapshotAtOffset(m),C=S===m?b:this.styler.getCounterSnapshotAtOffset(S);b||(b=this.styler.getLastCounterSnapshot()),C||(C=b);let P=C&&C.offset===S?C:null;this.counterStore.setCurrentPageDocCounters((r=b?.counters)!=null?r:null,(o=P?.changes)!=null?o:null,P?.changeTypes),this.counterStore.setCurrentPage(e),this.counterStore.updatePageCounters(d,this);let L=Ku(Ps(d),this);this.setPageSizeAndBleed(L,e),sS(d,L,e,this),f=L.bleedOffset+L.bleed}let g=!s&&p.getProp(this,"writing-mode")||y.horizontal_tb;this.pageVertical=g!=y.horizontal_tb;let v=p.getProp(this,"direction")||y.ltr,w=new Sn(this.rootPageFloatLayoutContext,Pe.PAGE,null,null,null,g,v),x=M("layoutNextPage");return x.loopWithFrame(m=>{this.layoutContainer(e,p,e.bleedBox,f,f,[],w).then(()=>{if(w.isInvalidated()||w.finish(),w.isInvalidated()){for(this.currentLayoutPosition=this.layoutPositionAtPageStart.clone(),tc(c),w.validate();e.bleedBox.lastChild;)e.bleedBox.removeChild(e.bleedBox.lastChild);m.continueLoop()}else m.breakLoop()})}).then(()=>{e.pageFloatLayoutContext=w,p.adjustPageLayout(this,e,this.clientLayout),s||(this.processLinger(),t=this.currentLayoutPosition,this.checkRepeatedInvalidPageArea(t),Object.keys(t.flowPositions).forEach(S=>{let b=t.flowPositions[S],C=b.breakAfter;C&&(C==="page"||!this.matchPageSide(C))&&(b.breakAfter=null)})),this.currentLayoutPosition=this.layoutPositionAtPageStart=null,t.highestSeenOffset=this.styler.getReachedOffset();let m=this.style.store.getTriggersForDoc(this.xmldoc);e.finish(m,this.clientLayout),this.noMorePrimaryFlows(t)&&!this.hasActiveRootPageFloatLayoutContext()&&(t=null),x.finish(t)}),x.result()}setPageSizeAndBleed(e,t){this.actualPageWidth=e.pageWidth,this.actualPageHeight=e.pageHeight,this.pageSheetWidth=e.pageWidth+e.cropOffset*2,this.pageSheetHeight=e.pageHeight+e.cropOffset*2,t.container.style.width=`${this.pageSheetWidth}px`,t.container.style.height=`${this.pageSheetHeight}px`,t.bleedBox.style.left=`${e.bleedOffset}px`,t.bleedBox.style.right=`${e.bleedOffset}px`,t.bleedBox.style.top=`${e.bleedOffset}px`,t.bleedBox.style.bottom=`${e.bleedOffset}px`,t.bleedBox.style.padding=`${e.bleed}px`}},OS=class bl extends Dr{constructor(t,i,n,r){super(t.rootScope,t,i,n,r,t.validatorSet,!n),u(this,"masterHandler",t),u(this,"insideRegion",!1)}startPageTemplateRule(){}startPageMasterRule(t,i,n){let r=new Jf(this.masterHandler.pageScope,t,i,n,this.masterHandler.rootBox,this.condition,this.owner.getBaseSpecificity());this.masterHandler.pushHandler(new Qx(r.scope,this.masterHandler,r,this.validatorSet))}startWhenRule(t){let i=t.expr;this.condition!=null&&(i=Wt(this.scope,this.condition,i)),this.masterHandler.pushHandler(new bl(this.masterHandler,i,this,this.regionId))}startDefineRule(){this.masterHandler.pushHandler(new c0(this.scope,this.owner))}startFontFaceRule(){let t={};this.masterHandler.fontFaces.push({properties:t,condition:this.condition}),this.masterHandler.pushHandler(new qo(this.scope,this.owner,null,t,this.masterHandler.validatorSet,"font-face"))}startCounterStyleRule(t){this.masterHandler.pushHandler(new RS(this.scope,this.owner,{},this.masterHandler.validatorSet,t,this.masterHandler.counterStyles))}startFlowRule(t){let i=this.masterHandler.flowProps[t];i||(i={},this.masterHandler.flowProps[t]=i),this.masterHandler.pushHandler(new qo(this.scope,this.owner,null,i,this.masterHandler.validatorSet))}startViewportRule(){let t={};this.masterHandler.viewportProps.push(t),this.masterHandler.pushHandler(new qo(this.scope,this.owner,this.condition,t,this.masterHandler.validatorSet))}startFootnoteRule(t){let i=this.masterHandler.footnoteProps;if(t){let n=si(i,"_pseudos");i=n[t],i||(i={},n[t]=i)}this.masterHandler.pushHandler(new cg(this.scope,this.owner,this.masterHandler.validatorSet,i))}startRegionRule(){this.insideRegion=!0,this.startSelectorRule()}startPageRule(){let t=new ES(this.masterHandler.pageScope,this.masterHandler,this,this.validatorSet,this.masterHandler.pageProps);this.masterHandler.pushHandler(t),t.startPageRule()}startRuleBody(){if(Dr.prototype.startRuleBody.call(this),this.insideRegion){this.insideRegion=!1;let t=`R${this.masterHandler.regionCount++}`;this.special("region-id",B(t)),this.endRule();let i=new bl(this.masterHandler,this.condition,this,t);this.masterHandler.pushHandler(i),i.startRuleBody()}}},gg=class extends Ba{constructor(e){super(),u(this,"validatorSet",e),u(this,"rootScope"),u(this,"pageScope"),u(this,"rootBox"),u(this,"cascadeParserHandler"),u(this,"regionCount",0),u(this,"fontFaces",[]),u(this,"counterStyles",new jw),u(this,"footnoteProps",{}),u(this,"flowProps",{}),u(this,"viewportProps",[]),u(this,"pageProps",{}),this.rootScope=new ts(null),this.pageScope=new ts(this.rootScope),this.rootBox=new jx(this.rootScope),this.cascadeParserHandler=new OS(this,null,null,null),this.slave=this.cascadeParserHandler}};function BS(e,t){return t.parseOPSResource(e)}var MS=class extends Bl{constructor(e){super(BS,"document"),u(this,"fontDeobfuscator",e),u(this,"styleByKey",{}),u(this,"styleFetcherByKey",{}),u(this,"styleByDocURL",{}),u(this,"triggersByDocURL",{}),u(this,"validatorSet",null),u(this,"styleSheets",[]),u(this,"triggerSingleDocumentPreprocessing",!1)}init(e,t){this.setStyleSheets(e,t);let i=M("OPSDocStore.init");return this.validatorSet=Zp(),FS().then(()=>{this.triggerSingleDocumentPreprocessing=!0,i.finish(!0)}),i.result()}getStyleForDoc(e){return this.styleByDocURL[e.url]}getTriggersForDoc(e){return this.triggersByDocURL[e.url]}setStyleSheets(e,t){this.clearStyleSheets(),e&&e.forEach(this.addAuthorStyleSheet,this),t&&t.forEach(this.addUserStyleSheet,this)}clearStyleSheets(){this.styleSheets.splice(0)}addAuthorStyleSheet(e){let t=e.url;t&&(t=Ae(Fn(t),Ji)),this.styleSheets.push({url:t,text:e.text,flavor:"Author",classes:null,media:null})}addUserStyleSheet(e){let t=e.url;t&&(t=Ae(Fn(t),Ji)),this.styleSheets.push({url:t,text:e.text,flavor:"User",classes:null,media:null})}parseOPSResource(e){let t=M("OPSDocStore.load"),i=e.url,n=As(i);return pg(e,this).then(r=>{var o;if(!r){t.finish(null);return}if(this.triggerSingleDocumentPreprocessing){let p=_t("PREPROCESS_SINGLE_DOCUMENT");for(let f=0;f<p.length;f++)try{p[f](r.document)}catch(g){Y.warn("Error during single document preprocessing:",g)}}let s=[],a=r.document.getElementsByTagNameNS("http://www.idpf.org/2007/ops","trigger");for(let p=0;p<a.length;p++){let f=a[p],g=f.getAttributeNS("http://www.w3.org/2001/xml-events","observer"),v=f.getAttributeNS("http://www.w3.org/2001/xml-events","event"),w=f.getAttribute("action"),x=f.getAttribute("ref");g&&v&&w&&x&&s.push({observer:g,event:v,action:w,ref:x})}this.triggersByDocURL[i]=s;let h=[];if(h.push({url:Ae("user-agent-page.css",Ni),text:Pd,flavor:"UA",classes:null,media:null}),h.push({url:Ae("user-agent-counter-styles.css",Ni),text:Id,flavor:"UA",classes:null,media:null}),n)h.push({url:Ae("user-agent-toc.css",Ni),text:Td,flavor:"UA",classes:null,media:null});else{let p=r.document.querySelectorAll("style, link, meta");for(let f of p){let g=f.namespaceURI,v=f.localName;if(g=="http://www.w3.org/1999/xhtml")if(v=="style"){let w=f.getAttribute("class"),x=f.getAttribute("media"),m=f.getAttribute("title");h.push({url:i,text:f.textContent,flavor:"Author",classes:m?w:null,media:x})}else if(v=="link"){let w=f.getAttribute("href"),x=(o=f.getAttribute("rel"))==null?void 0:o.split(/\s+/),m=f.getAttribute("class"),S=f.getAttribute("media");if(w&&x!=null&&x.includes("stylesheet")&&(!x.includes("alternate")||m)){let b=Ae(w,i),C=f.getAttribute("title");h.push({url:b,text:null,classes:C?m:null,media:S,flavor:"Author"})}}else v=="meta"&&f.getAttribute("name")=="viewport"&&h.push({url:i,text:this.processViewportMeta(f),flavor:"Author",classes:null,media:null})}for(let f=0;f<this.styleSheets.length;f++)h.push(this.styleSheets[f])}let l="";for(let p=0;p<h.length;p++)l+=h[p].url,l+="^",h[p].text&&(l+=h[p].text),l+="^";let c=this.styleByKey[l];if(c){this.styleByDocURL[i]=c,t.finish(r);return}let d=this.styleFetcherByKey[l];d||(d=new Jr(()=>{let p=M("fetchStylesheet"),f=0,g=new gg(this.validatorSet);return p.loop(()=>{if(f<h.length){let v=h[f++];return g.startStylesheet(v.flavor),v.text!==null?Ml(v.text,g,v.url,v.classes,v.media).thenReturn(!0):_d(v.url,g,v.classes,v.media)}return T(!1)}).then(()=>{let v=g.cascadeParserHandler.finish();c=new LS(this,g.rootScope,g.pageScope,v,g.rootBox,g.fontFaces,g.footnoteProps,g.flowProps,g.viewportProps,g.pageProps,g.counterStyles),this.styleByKey[l]=c,delete this.styleFetcherByKey[l],p.finish(c)}),p.result()},`FetchStylesheet ${i}`),this.styleFetcherByKey[l]=d,d.start()),d.get().then(p=>{this.styleByDocURL[i]=p,t.finish(r)})}),t.result()}processViewportMeta(e){return""}},Tr="\u25B8",ic="\u25BE",_S="\u25B9";function bh(e){let t=Array.from(e.querySelectorAll("nav[*|type],nav[epub\\:type]"));if(t.length>0||(t=Array.from(e.querySelectorAll("[role=doc-toc]")),t.length>0))return t;let i="nav,.toc,#toc,#table-of-contents,#contents,[role=directory]";for(let n of e.querySelectorAll(i)){if(t.find(o=>o.contains(n)))continue;let r=n;/^h[1-6]$/.test(r.localName)&&(r.previousElementSibling?r=r.nextElementSibling:r=r.parentElement),r&&r.querySelector("li a[href]")&&t.push(r)}return t}function DS(e){let t=bh(e),i=[];for(let n of t)for(let r of n.querySelectorAll("li a[href]"))i.push(r);return i}var zS=class{constructor(e,t,i,n,r,o,s,a,h,l,c){u(this,"store",e),u(this,"url",t),u(this,"lang",i),u(this,"clientLayout",n),u(this,"fontMapper",r),u(this,"rendererFactory",s),u(this,"fallbackMap",a),u(this,"documentURLTransformer",h),u(this,"counterStore",l),u(this,"cmykStore",c),u(this,"pref"),u(this,"page",null),u(this,"instance",null),this.pref=Pc(o),this.pref.spreadView=!1}setAutoHeight(e,t){if(t--!=0){for(let i=e.firstChild;i;i=i.nextSibling)if(i.nodeType==1){let n=i;ki(n,"height","auto")!="auto"&&(I(n,"height","auto"),this.setAutoHeight(n,t)),ki(n,"position","static")=="absolute"&&(I(n,"position","relative"),this.setAutoHeight(n,t))}}}makeCustomRenderer(e){let t=this.rendererFactory.makeCustomRenderer(e);return(i,n,r)=>{let o=r.behavior;if(o)switch(o.toString()){case"toc-node-anchor":r.color=y.inherit,r["text-decoration"]=y.none;break;case"toc-node":r.display=y.block,r.margin=Le,r.padding=Le,r["padding-inline-start"]=new O(1.25,"em");break;case"toc-node-first-child":r.display=y.inline_block,r.margin=new O(.2,"em"),r["vertical-align"]=y.top,r.color=y.inherit,r["text-decoration"]=y.none;break;case"toc-container":r.padding=Le;break}if(!o||o.toString()!="toc-node"&&o.toString()!="toc-container")return t(i,n,r);let s=i.firstChild;s&&s.nodeType!==1&&Ee(s)&&i.replaceChild(i.ownerDocument.createComment(s.textContent),s);let a=n.getAttribute("data-adapt-class");if(a=="toc-node"){let l=n.firstChild;l.textContent!=Tr&&(l.textContent=Tr,I(l,"cursor","pointer"),l.addEventListener("click",VS,!1),l.setAttribute("role","button"),l.setAttribute("aria-expanded","false"),n.setAttribute("aria-expanded","false"),n.style.height!=="0px"&&(l.tabIndex=0))}let h=n.ownerDocument.createElement("div");if(h.setAttribute("data-adapt-process-children","true"),o.toString()=="toc-node"){let l=n.ownerDocument.createElement("div");if(l.textContent=_S,I(l,"margin","0.2em 0 0 -1em"),I(l,"margin-inline-start","-1em"),I(l,"margin-inline-end","0"),I(l,"display","inline-block"),I(l,"width","1em"),I(l,"text-align","center"),I(l,"vertical-align","top"),I(l,"cursor","default"),I(l,"font-family","Menlo,sans-serif"),h.appendChild(l),I(h,"overflow","hidden"),h.setAttribute("data-adapt-class","toc-node"),h.setAttribute("role","treeitem"),a=="toc-node"||a=="toc-container"){I(h,"height","0px");let c=i.firstElementChild;c&&c.localName==="a"&&(c.tabIndex=-1)}else n.setAttribute("role","tree")}else a=="toc-node"&&(h.setAttribute("data-adapt-class","toc-container"),h.setAttribute("role","group"),h.setAttribute("aria-hidden","true"));return T(h)}}showTOC(e,t,i,n,r){if(this.page)return T(this.page);let o=M("showTOC"),s=new Qd(e,e);this.page=s;let a=xa(this.url);return this.store.load(a).then(h=>{for(let f of bh(h.document))f.setAttribute("data-vivliostyle-role","doc-toc");let l=this.store.getStyleForDoc(h),c=l.sizeViewport(i,1e5,r);t=new Es(t.window,c.fontSize,0,e,c.width,c.height);let d=this.makeCustomRenderer(h),p=new wh(l,h,this.lang,t,this.clientLayout,this.fontMapper,d,this.fallbackMap,0,this.documentURLTransformer,this.counterStore,this.cmykStore);this.instance=p,p.pref=this.pref,p.init().then(()=>{p.layoutNextPage(s,null).then(()=>{this.setAutoHeight(e,2),o.finish(s)})})}),o.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 e(n){if(!n)return[];let r=n.querySelectorAll(":scope > [role=treeitem] > a[href]");return Array.from(r).map(t)}function t(n){let r=new URL(n.href),[,o]=r.hash.match(/^#?(.*)$/),s=n.innerText,a=n.parentElement.querySelector("[role=group]"),h=e(a);return{id:o,title:s,children:h}}let i=this.page.container.querySelector("[role=tree]");return e(i)}};function VS(e){let t=e.target,i=t.textContent==Tr;t.textContent=i?ic:Tr;let n=t.parentNode;t.setAttribute("aria-expanded",i?"true":"false"),n.setAttribute("aria-expanded",i?"true":"false");let r=n.firstChild;for(;r;){if(r.nodeType===1){let o=r,s=o.getAttribute("data-adapt-class");if(s==="toc-container"){if(o.setAttribute("aria-hidden",i?"false":"true"),o.firstChild){r=o.firstChild;continue}}else if(s==="toc-node"&&(o.style.height=i?"auto":"0px",o.children.length>=2&&(o.children[1].tabIndex=i?0:-1),o.children.length>=3&&(o.children[0].tabIndex=i?0:-1,!i))){let a=o.children[0];if(a.textContent==ic){a.textContent=Tr,a.setAttribute("aria-expanded","false"),o.setAttribute("aria-expanded","false"),r=o.children[2];continue}}}for(;!r.nextSibling&&r.parentNode!==n;)r=r.parentNode;r=r.nextSibling}e.stopPropagation()}function Io(e){let t={};return Object.keys(e).forEach(i=>{t[i]=Array.from(e[i])}),t}function US(e){let t=Object.create(null);return Object.keys(e).forEach(i=>{t[i]=new Map(e[i])}),t}function $S(e){return/\.(x?html?|xht|svg)(?:[#?]|$)/i.test(e)||/^(?:about:|data:|blob:)/i.test(pt(e))}var nc=class extends MS{constructor(){super(null),u(this,"plainXMLStore"),u(this,"jsonStore"),u(this,"opfByURL",{}),u(this,"primaryOPFByEPubURL",{}),u(this,"deobfuscators",{}),u(this,"documents",{}),this.fontDeobfuscator=this.makeDeobfuscatorFactory(),this.plainXMLStore=TS(),this.jsonStore=Qy()}makeDeobfuscatorFactory(){return e=>this.deobfuscators[e]}loadAsPlainXML(e,t,i){return this.plainXMLStore.load(e,t,i)}startLoadingAsPlainXML(e){this.plainXMLStore.fetch(e)}loadAsJSON(e,t,i){return this.jsonStore.load(e,t,i)}loadWebPubManifest(e,t){this.loadAsJSON(e,!0).then(i=>{if(!i){this.reportLoadError(e),t.finish(null);return}let n=new Zo(this,e);n.initWithWebPubManifest(i,void 0,e).then(()=>{t.finish(n)})})}loadPubDoc(e){let t=M("loadPubDoc");if(/\.opf(?:[#?]|$)/i.test(e)){let[,i,n]=e.match(/^((?:.*\/)?)([^/]*)$/);this.loadOPF(i,n).thenFinish(t)}else/\.json(?:ld)?(?:[#?]|$)/i.test(e)?this.loadWebPubManifest(e,t):$S(e)?this.loadWebPub(e).then(i=>{if(i){t.finish(i);return}this.reportLoadError(e),t.finish(null)}):Os(e,null,"HEAD").then(i=>{if(i.status>=400)this.loadEPUBDoc(e).then(n=>{if(n){t.finish(n);return}Y.error(`Failed to fetch a source document from ${e} (${i.status}${i.statusText?" "+i.statusText:""})`),t.finish(null)});else if(!i.status&&!i.responseXML&&!i.responseText&&!i.responseBlob&&!i.contentType&&/\/[^/.]+(?:[#?]|$)/.test(e)&&(e=e.replace(/([#?]|$)/,"/$1")),i.contentType=="application/oebps-package+xml"){let[,n,r]=e.match(/^((?:.*\/)?)([^/]*)$/);this.loadOPF(n,r).thenFinish(t)}else i.contentType=="application/ld+json"||i.contentType=="application/webpub+json"||i.contentType=="application/audiobook+json"||i.contentType=="application/json"?this.loadWebPubManifest(e,t):this.loadWebPub(e).then(n=>{if(n){t.finish(n);return}this.loadEPUBDoc(e).then(r=>{if(r){t.finish(r);return}this.reportLoadError(e),t.finish(null)})})});return t.result()}loadEPUBDoc(e){let t=M("loadEPUBDoc");e.endsWith("/")||(e=e+"/"),this.startLoadingAsPlainXML(e+"META-INF/encryption.xml");let i=e+"META-INF/container.xml";return this.loadAsPlainXML(i).then(n=>{if(n){let r=n.doc().child("container").child("rootfiles").child("rootfile").attribute("full-path");for(let o of r)if(o){this.loadOPF(e,o).thenFinish(t);return}}t.finish(null)}),t.result()}loadOPF(e,t){let i=e+t,n=this.opfByURL[i];if(n)return T(n);let r=M("loadOPF");return this.loadAsPlainXML(i,!0,`Failed to fetch EPUB OPF ${i}`).then(o=>{o?(n=new Zo(this,e),this.opfByURL[i]=n,this.primaryOPFByEPubURL[e]=n,this.plainXMLStore.resources[e+"META-INF/container.xml"]?this.loadAsPlainXML(e+"META-INF/encryption.xml").then(s=>{n.initWithXMLDoc(o,s).then(()=>{r.finish(n)})}):n.initWithXMLDoc(o,null).then(()=>{r.finish(n)})):this.reportLoadError(i)}),r.result()}loadWebPub(e){let t=M("loadWebPub");return this.load(e).then(i=>{if(!i)this.reportLoadError(e),t.finish(null);else if(i.document.querySelector("a[href='META-INF/'],a[href$='/META-INF/']"))t.finish(null);else{let n=i.document,r=new Zo(this,e),o=n.querySelector("link[rel='publication'],link[rel='manifest'][type='application/webpub+json']");if(o){let s=o.getAttribute("href");if(/^#/.test(s)){let a=kl(n.getElementById(s.substr(1)).textContent);r.initWithWebPubManifest(a,n).then(()=>{t.finish(r)})}else{let a=Ae(o.getAttribute("href"),e);this.loadAsJSON(a,!0,`Failed to fetch Publication Manifest ${a}`).then(h=>{r.initWithWebPubManifest(h,n,a).then(()=>{t.finish(r)})})}}else r.initWithWebPubManifest({},n).then(()=>{r.toc&&r.toc.src===i.url&&bh(n).length===0&&(r.toc=null),t.finish(r)})}}),t.result()}addDocument(e,t){let i=M("EPUBDocStore.load"),n=pt(e);return(this.documents[n]=this.parseOPSResource({status:200,statusText:"",url:n,contentType:t.contentType,responseText:null,responseXML:t,responseBlob:null})).thenFinish(i),i.result()}reportLoadError(e){let t=n=>n.replace(/([^:/?#]|^)[/?#].*/,"$1"),i=()=>{let n=t(e);return!(n===t(Ji)||Object.keys(this.resources).find(r=>this.resources[r]&&t(r)===n)||!/^https?:?\/\/[^/]/.test(e)||/\.(xhtml|xht|xml|opf)$/i.test(e))};e.startsWith("data:")?Y.error(`Failed to load ${e}. Invalid data.`):e.startsWith("http:")&&Ji.startsWith("https:")&&!/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(?:[/?#]|$)/.test(e)?Y.error(`Failed to load ${e}. Mixed Content ("http:" content on "https:" context) is not allowed.`):i()?Y.error(`Failed to load ${e}. This may be caused by network error, incorrect URL, or the server not allowing cross-origin resource sharing (CORS).`):Y.error(`Failed to load ${e}. The target resource is invalid.`)}load(e){let t=pt(e),i=this.documents[t];if(i)return i.isPending()?i:T(i.get());{let n=M("EPUBDocStore.load");return i=super.load(t,!0,`Failed to fetch a source document from ${t}`),i.then(r=>{r?n.finish(r):this.reportLoadError(t)}),n.result()}}processViewportMeta(e){let t=e.getAttribute("content");if(!t)return"";let i={},n;for(;(n=t.match(/^,?\s*([-A-Za-z_.][-A-Za-z_0-9.]*)\s*=\s*([-+A-Za-z_0-9.]*)\s*/))!=null;)t=t.substr(n[0].length),i[n[1]]=n[2];let r=i.width-0,o=i.height-0;if(r&&o){let s=!!Object.values(this.primaryOPFByEPubURL).find(a=>a.prePaginated);return`@-epubx-viewport{width:${r}px;height:${o}px;}`+(s?`@page{size:${r}px ${o}px;margin:0;}`:"@page{margin:0;}")}return""}},rc=class{constructor(){u(this,"id",null),u(this,"src",""),u(this,"mediaType",null),u(this,"title",null),u(this,"itemRefElement",null),u(this,"spineIndex",-1),u(this,"compressedSize",0),u(this,"compressed",null),u(this,"epage",0),u(this,"epageCount",0),u(this,"startPage",null),u(this,"skipPagesBefore",null),u(this,"itemProperties"),this.itemProperties=Kg}initWithElement(e,t){this.id=e.getAttribute("id"),this.src=Ae(e.getAttribute("href"),t),this.mediaType=e.getAttribute("media-type");let i=e.getAttribute("properties");i&&(this.itemProperties=rm(i.split(/\s+/)))}initWithParam(e){this.spineIndex=e.index,this.id=`item${e.index+1}`,this.src=e.url,this.startPage=e.startPage,this.skipPagesBefore=e.skipPagesBefore}};function HS(e){return e.id}function WS(e){return t=>{let i=M("deobfuscator");return GS("SHA-1",e).then(n=>{let r=t.slice(0,1040),o=t.slice(1040,t.size);Zy(r).then(s=>{let a=new DataView(s);for(let h=0;h<a.byteLength;h++){let l=a.getUint8(h);l^=n[h%20],a.setUint8(h,l)}i.finish(Fd([a,o]))})}),i.result()}}function GS(e,t){let i=M("makeDigest"),n=i.suspend();return window.crypto.subtle.digest(e,new TextEncoder().encode(t)).then(r=>{n.schedule(new Uint8Array(r))}),i.result()}var Pi={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"},mr="http://idpf.org/epub/vocab/package/meta/#",qe={language:`${Pi.dcterms}language`,title:`${Pi.dcterms}title`,creator:`${Pi.dcterms}creator`,layout:`${Pi.rendition}layout`,titleType:`${mr}title-type`,displaySeq:`${mr}display-seq`,alternateScript:`${mr}alternate-script`,role:`${mr}role`};function jS(e,t){let i={};return(n,r)=>{var o,s,a,h,l,c;let d,p,f=n.r||i,g=r.r||i;if(e==qe.title&&(d=((o=f[qe.titleType])==null?void 0:o[0].v)=="main",p=((s=g[qe.titleType])==null?void 0:s[0].v)=="main",d!=p))return d?-1:1;let v=parseInt((a=f[qe.displaySeq])==null?void 0:a[0].v,10);isNaN(v)&&(v=Number.MAX_VALUE);let w=parseInt((h=g[qe.displaySeq])==null?void 0:h[0].v,10);return isNaN(w)&&(w=Number.MAX_VALUE),v!=w?v-w:e!=qe.language&&t&&(d=((l=f[qe.language]||f[qe.alternateScript])==null?void 0:l[0].v)==t,p=((c=g[qe.language]||g[qe.alternateScript])==null?void 0:c[0].v)==t,d!=p)?d?-1:1:n.o-r.o}}function XS(e,t){let i;if(!t)i=Pi;else{i={};for(let p in Pi)i[p]=Pi[p];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),i[d[1]]=d[2]}let n=d=>{if(d){let p=d.match(/^\s*(([^:]*):)?(\S+)\s*$/);if(p){let f=p[2]?i[p[2]]:mr;if(f)return f+p[3]}}return null},r=1,o=e.childElements().forEachNonNull(d=>{if(d.localName=="meta"){let p=n(d.getAttribute("property"));if(p)return{name:p,value:d.textContent,id:d.getAttribute("id"),order:r++,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:Pi.dcterms+d.localName,order:r++,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}),s=ea(o,d=>d.refines),a=d=>om(d,(p,f)=>p.map(g=>{let v={v:g.value,o:g.order};g.scheme&&(v.s=g.scheme);let w=s[`#${g.id}`]||[];if(w.length||g.lang||g.role){g.lang&&w.push({name:qe.language,value:g.lang,lang:null,id:null,refines:g.id,scheme:null,order:g.order,role:null}),g.role&&w.push({name:qe.role,value:g.role,lang:null,id:null,refines:g.id,scheme:null,order:g.order,role:null});let x=ea(w,m=>m.name);v.r=a(x)}return v})),h=a(ea(o,d=>d.refines?null:d.name)),l=null;h[qe.language]&&(l=h[qe.language][0].v);let c=d=>{for(let p in d){let f=d[p];f.sort(jS(p,l));for(let g=0;g<f.length;g++){let v=f[g].r;v&&c(v)}}};return c(h),h}function qS(){let e=window.MathJax;return e?e.Hub:null}var oc={"application/xhtml+xml":!0,"image/jpeg":!0,"image/png":!0,"image/svg+xml":!0,"image/gif":!0,"audio/mp3":!0},ba="viv-id-",Zo=class{constructor(e,t){u(this,"store",e),u(this,"pubURL",t),u(this,"opfXML",null),u(this,"encXML",null),u(this,"items",null),u(this,"spine",null),u(this,"itemMap",null),u(this,"itemMapByPath",null),u(this,"uid",null),u(this,"bindings",{}),u(this,"lang",null),u(this,"epageCount",0),u(this,"prePaginated",!1),u(this,"epageIsRenderedPage",!0),u(this,"epageCountCallback",null),u(this,"metadata",{}),u(this,"toc",null),u(this,"cover",null),u(this,"fallbackMap",{}),u(this,"pageProgression",null),u(this,"documentURLTransformer"),this.documentURLTransformer=this.createDocumentURLTransformer()}createDocumentURLTransformer(){let e=this;class t{constructor(){u(this,"canonicalDocumentURLCache",new Map)}getCanonicalDocumentURL(n){var r,o;let s=pt(dn(n)),a=this.canonicalDocumentURLCache.get(s);if(a)return a;for(let h of e.spine){let l=pt(dn(h.src));if(l===s)return this.canonicalDocumentURLCache.set(s,l),l;let c=(o=(r=e.store)==null?void 0:r.get(l))==null?void 0:o.url;if(c&&pt(dn(c))===s)return this.canonicalDocumentURLCache.set(s,l),l}return this.canonicalDocumentURLCache.set(s,s),s}transformFragment(n,r){let o=this.getCanonicalDocumentURL(r)+(n?`#${n}`:"");return ba+Cc(o,":")}transformURL(n,r){let o=n.match(/^([^#]*)#?(.*)$/);if(o){let s=this.getCanonicalDocumentURL(o[1]||dn(r)),a=decodeURIComponent(o[2]);if(s&&e.spine.some(h=>pt(dn(h.src))===s))return`#${this.transformFragment(a,s)}`}return n}restoreURL(n){n.charAt(0)==="#"&&(n=n.substring(1)),n.indexOf(ba)===0&&(n=n.substring(ba.length));let r=nm(n,":").match(/^([^#]*)#?(.*)$/);return r?[r[1],r[2]]:[]}}return new t}getMetadata(){return this.metadata}getPathFromURL(e){if(e.startsWith("data:"))return e===this.pubURL?"":e;if(this.pubURL){let t=Ae("",this.pubURL);return e===t||e+"/"===t?"":(t.charAt(t.length-1)!="/"&&(t+="/"),e.substr(0,t.length)==t?decodeURIComponent(e.substr(t.length)):null)}else return e}initWithXMLDoc(e,t){this.opfXML=e,this.encXML=t;let i=e.doc().child("package"),n=i.attribute("unique-identifier")[0];if(n){let h=e.getElement(`${e.url}#${n}`);h&&(this.uid=h.textContent.replace(/[ \n\r\t]/g,""))}let r={};this.items=i.child("manifest").child("item").asArray().map(h=>{let l=new rc,c=h;l.initWithElement(c,e.url);let d=c.getAttribute("fallback");return d&&!oc[l.mediaType]&&(r[l.src]=d),!this.toc&&l.itemProperties.nav&&(this.toc=l),!this.cover&&l.itemProperties["cover-image"]&&(this.cover=l),l}),this.itemMap=Fh(this.items,HS),this.itemMapByPath=Fh(this.items,h=>this.getPathFromURL(h.src));for(let h in r){let l=h;for(;;){let c=this.itemMap[r[l]];if(!c)break;if(oc[c.mediaType]){this.fallbackMap[h]=c.src;break}l=c.src}}this.spine=i.child("spine").child("itemref").asArray().map((h,l)=>{let c=h,d=c.getAttribute("idref"),p=this.itemMap[d];return p&&(p.itemRefElement=c,p.spineIndex=l),p});let o=i.child("spine").attribute("page-progression-direction")[0];o&&(this.pageProgression=gc(o));let s=t?t.doc().child("encryption").child("EncryptedData").predicate(Qu.withChild("EncryptionMethod",Qu.withAttribute("Algorithm","http://www.idpf.org/2008/embedding"))).child("CipherData").child("CipherReference").attribute("URI"):[],a=i.child("bindings").child("mediaType").asArray();for(let h=0;h<a.length;h++){let l=a[h].getAttribute("handler"),c=a[h].getAttribute("media-type");c&&l&&this.itemMap[l]&&(this.bindings[c]=this.itemMap[l].src)}if(this.metadata=XS(i.child("metadata"),i.attribute("prefix")[0]),this.metadata[qe.language]&&(this.lang=this.metadata[qe.language][0].v),this.metadata[qe.layout]&&(this.prePaginated=this.metadata[qe.layout][0].v==="pre-paginated"),s.length>0&&this.uid){let h=WS(this.uid);for(let l=0;l<s.length;l++)this.store.deobfuscators[this.pubURL+s[l]]=h}return this.prePaginated&&this.assignAutoPages(),T(!0)}assignAutoPages(){let e=0;for(let t of this.spine){let i=this.prePaginated?1:Math.ceil(t.compressedSize/1024);t.epage=e,t.epageCount=i,e+=i}this.epageCount=e,this.epageCountCallback&&this.epageCountCallback(this.epageCount)}setEPageCountMode(e){this.epageIsRenderedPage=e||this.prePaginated}countEPages(e){if(this.epageCountCallback=e,this.epageIsRenderedPage)return this.prePaginated&&this.epageCount==0&&this.assignAutoPages(),T(!0);let t=0,i=0,n=M("countEPages");return n.loopWithFrame(r=>{if(i===this.spine.length){r.breakLoop();return}let o=this.spine[i++];o.epage=t,this.store.load(o.src).then(s=>{if(!s){r.continueLoop();return}let a=1800,h=s.lang||this.lang;h&&h.match(/^(ja|ko|zh)/)&&(a/=3),o.epageCount=Math.ceil(s.getTotalOffset()/a),t+=o.epageCount,this.epageCount=t,this.epageCountCallback&&this.epageCountCallback(this.epageCount),r.continueLoop()})}).thenFinish(n),n.result()}initWithChapters(e,t){this.itemMap={},this.itemMapByPath={},this.items=[],this.spine=this.items;let i=this.opfXML=new dg(null,"",new DOMParser().parseFromString("<spine></spine>","text/xml"));return e.forEach(n=>{let r=new rc;r.initWithParam(n),r.id;let o=i.document.createElement("itemref");o.setAttribute("idref",r.id),i.root.appendChild(o),r.itemRefElement=o,this.itemMap[r.id]=r;let s=this.getPathFromURL(n.url);s==null&&(s=n.url),this.itemMapByPath[s]=r,this.items.push(r)}),t?this.store.addDocument(e[0].url,t):T(null)}initWithWebPubManifest(e,t,i){var n,r,o,s;e.readingProgression&&(this.pageProgression=e.readingProgression),this.metadata===void 0&&(this.metadata={});let a=e.name||((n=e.metadata)==null?void 0:n.title)||t?.title;a&&(this.metadata[qe.title]=(Array.isArray(a)?a:[a]).map(x=>{var m;return{v:(m=x.value)!=null?m:x}}));let h=e.author||e.creator||((r=e.metadata)==null?void 0:r.author)||Array.from((o=t?.querySelectorAll("meta[name='author'], meta[name='DC.Creator']"))!=null?o:[]).map(x=>x.content);h&&h.length!==0&&(this.metadata[qe.creator]=(Array.isArray(h)?h:[h]).map(x=>{var m;return{v:(m=x.name)!=null?m:x}}));let l=e.inLanguage||((s=e.metadata)==null?void 0:s.language)||t?.documentElement.lang||t?.documentElement.getAttribute("xml:lang");l&&(this.metadata[qe.language]=(Array.isArray(l)?l:[l]).map(x=>({v:x})));let c=pt(this.pubURL),d=this.getPathFromURL(c),p=d!==null?encodeURI(d):/^(?:about:|blob:)/i.test(c)?c:null;if(!e.readingOrder&&t&&p!==null){e.readingOrder=[p];for(let x of DS(t)){let m=x.getAttribute("href");if(/^(https?:)?\/\//.test(m)||/\.(jpe?g|png|gif|pdf|svg|mml)([#?]|$)/.test(m))continue;let S=pt(Ae(m,this.pubURL)),b=this.getPathFromURL(S),C=b!==null?encodeURI(b):S;e.readingOrder.indexOf(C)==-1&&e.readingOrder.push(C)}}let f=[],g=0,v=-1;[e.readingOrder,e.resources].forEach(x=>{x instanceof Array&&x.forEach(m=>{let S=x===e.readingOrder,b=typeof m=="string"?m:m.url||m.href,C=typeof m=="string"?"":m.encodingFormat||m.href&&m.type||"";if(S||C==="text/html"||C==="application/xhtml+xml"||!C&&m.rel!=="stylesheet"&&/(^|\/)([^/]+\.(x?html|htm|xht)|[^/.]*)([#?]|$)/.test(b)){let P=i?i.replace(/\/[^/]+$/,"/"):this.pubURL,L={url:Ae(Fn(b),P),index:g++,startPage:null,skipPagesBefore:null};m.rel==="contents"&&v===-1&&(v=L.index),f.push(L)}})});let w=M("initWithWebPubManifest");return this.initWithChapters(f).then(()=>{var x,m;v!==-1&&(this.toc=this.items[v]),this.toc||(this.toc=i?(x=this.items)==null?void 0:x[0]:this.itemMapByPath[d]);let S=(m=e.readingOrder)==null?void 0:m.length;S&&S<this.items.length&&this.items.splice(S),w.finish(!0)}),w.result()}getCFI(e,t){let i=this.spine[e],n=M("getCFI");return this.store.load(i.src).then(r=>{let o=r.getNodeByOffset(t),s=null;if(o){let a=r.getNodeOffset(o,0,!1),h=t-a,l=new Wh;l.prependPathFromNode(o,h,!1,null),i.itemRefElement&&l.prependPathFromNode(i.itemRefElement,0,!1,null),s=l.toString()}n.finish(s)}),n.result()}resolveFragment(e){return _n("resolveFragment",t=>{if(!e){t.finish(null);return}let i=new Wh;i.fromString(e);let n;if(this.opfXML){let r=i.navigate(this.opfXML.document);if(r.node.nodeType!=1||r.after||!r.ref){t.finish(null);return}let o=r.node,s=o.getAttribute("idref");if(o.localName!="itemref"||!s||!this.itemMap[s]){t.finish(null);return}n=this.itemMap[s],i=r.ref}else n=this.spine[0];this.store.load(n.src).then(r=>{let o=i.navigate(r.document),s=r.getNodeOffset(o.node,o.offset,o.after);t.finish({spineIndex:n.spineIndex,offsetInItem:s,pageIndex:-1})})},(t,i)=>{Y.warn(i,"Cannot resolve fragment:",e),t.finish(null)})}resolveEPage(e){return _n("resolveEPage",t=>{if(e<=0){t.finish({spineIndex:0,offsetInItem:0,pageIndex:-1});return}if(this.epageIsRenderedPage){let r=this.spine.findIndex(a=>a.epage==0&&a.epageCount==0||a.epage<=e&&a.epage+a.epageCount>e);r==-1&&(r=this.spine.length-1);let o=this.spine[r];(!o||o.epageCount==0)&&(o=this.spine[--r]);let s=Math.floor(e-o.epage);t.finish({spineIndex:r,offsetInItem:-1,pageIndex:s});return}let i=mi(this.spine.length,r=>{let o=this.spine[r];return o.epage+o.epageCount>e});i==this.spine.length&&i--;let n=this.spine[i];this.store.load(n.src).then(r=>{e-=n.epage,e>n.epageCount&&(e=n.epageCount);let o=0;if(e>0){let s=r.getTotalOffset();o=Math.round(s*e/n.epageCount),o==s&&o--}t.finish({spineIndex:i,offsetInItem:o,pageIndex:-1})})},(t,i)=>{Y.warn(i,"Cannot resolve epage:",e),t.finish(null)})}getEPageFromPosition(e){let t=this.spine[e.spineIndex];if(this.epageIsRenderedPage){let n=t.epage+e.pageIndex;return T(n)}if(e.offsetInItem<=0)return T(t.epage);let i=M("getEPage");return this.store.load(t.src).then(n=>{let r=n.getTotalOffset(),o=Math.min(r,e.offsetInItem);i.finish(t.epage+o*t.epageCount/r)}),i.result()}},Fo=(e,t)=>({page:e,position:{spineIndex:e.spineIndex,pageIndex:t,offsetInItem:e.offset}}),YS=class{constructor(e,t,i,n,r,o){u(this,"opf",e),u(this,"viewport",t),u(this,"fontMapper",i),u(this,"pageSheetSizeReporter",r),u(this,"spineItems",[]),u(this,"spineItemLoadingContinuations",[]),u(this,"pref"),u(this,"clientLayout"),u(this,"counterStore"),u(this,"cmykStore"),u(this,"tocAutohide",!1),u(this,"tocVisible",!1),u(this,"tocView"),u(this,"paginationProgress",{totalOffsetsBySpine:[],renderedOffsetsBySpine:[],totalOffsetsReady:!1,lastReportedPages:0,lastReportedFraction:0,lastReportedSpineIndex:-1,lastReportedHref:""}),this.pref=Pc(n),this.clientLayout=new Wx(t),this.counterStore=new Km(e.documentURLTransformer),this.cmykStore=new ed,o!=null&&o.length&&this.cmykStore.registerCmykReserveMap(o)}getPage(e){let t=this.spineItems[e.spineIndex];return t?t.pages[e.pageIndex]:null}waitForPreviousSpines(e,t){if(t||e===0)return T(!0);let i=M("waitForPreviousSpines");return i.loopWithFrame(n=>{let r=!0;for(let o=0;o<e;o++){let s=this.spineItems[o];if(!s||!s.complete){r=!1;break}}r?n.breakLoop():i.sleep(100).then(()=>{n.continueLoop()})}).then(()=>{i.finish(!0)}),i.result()}getCurrentPageProgression(e){if(this.opf.pageProgression)return this.opf.pageProgression;{let t=this.spineItems[e?e.spineIndex:0];return t?t.instance.pageProgression:null}}finishPageContainer(e,t,i){t.container.style.display="none",t.container.style.visibility="visible",t.container.style.position="",t.container.style.top="",t.container.style.left="",t.container.setAttribute("data-vivliostyle-page-side",t.side);let n=e.pages[i];if(t.isFirstPage=e.item.spineIndex==0&&i==0,e.pages[i]=t,this.opf.epageIsRenderedPage){if(i==0&&e.item.spineIndex>0){let r=this.opf.spine[e.item.spineIndex-1];e.item.epage=r.epage+r.epageCount}e.item.epageCount=e.pages.length,this.opf.epageCount=this.opf.spine.reduce((r,o)=>r+o.epageCount,0),this.opf.epageCountCallback&&this.opf.epageCountCallback(this.opf.epageCount)}if(n)e.instance.viewport.contentContainer.replaceChild(t.container,n.container),n.dispatchEvent({type:"replaced",target:null,currentTarget:null,preventDefault:null,newPage:t});else{let r=null;if(i>0)r=e.pages[i-1].container.nextElementSibling;else for(let o=e.item.spineIndex+1;o<this.spineItems.length;o++){let s=this.spineItems[o];if(s&&s.pages[0]){r=s.pages[0].container;break}}e.instance.viewport.contentContainer.insertBefore(t.container,r)}this.pageSheetSizeReporter({width:e.instance.pageSheetWidth,height:e.instance.pageSheetHeight},e.instance.pageSheetSize,e.item.spineIndex,e.instance.pageNumberOffset+i)}getRenderedPageCount(){let e=0;for(let t of this.spineItems)t&&(e+=t.pages.length);return e}markSpineItemCompleteIfReady(e){e.complete=e.layoutPositions.length===e.pages.length,e.complete&&e.instance.viewport.layoutBox.removeAttribute("style")}getTotalOffsetForViewItem(e){let t=e.item.spineIndex,i=this.paginationProgress.totalOffsetsBySpine[t];return i==null&&(i=e.xmldoc.getTotalOffset(),this.paginationProgress.totalOffsetsBySpine[t]=i),i}collectTotalOffsets(){if(this.paginationProgress.totalOffsetsReady)return T(!0);let e=this.paginationProgress.totalOffsetsBySpine,t=0,i=M("collectTotalOffsets");return i.loopWithFrame(n=>{if(t===this.opf.spine.length){n.breakLoop();return}let r=t++;if(e[r]!=null){n.continueLoop();return}let o=this.opf.spine[r];this.opf.store.load(o.src).then(s=>{s&&(e[r]=s.getTotalOffset()),n.continueLoop()})}).then(()=>{this.paginationProgress.totalOffsetsReady=!0,i.finish(!0)}),i.result()}getTotalOffsetAll(){let e=0;for(let t of this.paginationProgress.totalOffsetsBySpine)t&&(e+=t);return e}getRenderedOffsetAll(){var e;let t=0,i=this.paginationProgress.totalOffsetsBySpine,n=this.paginationProgress.renderedOffsetsBySpine;for(let r=0;r<i.length;r++){let o=i[r];if(!o)continue;let s=(e=n[r])!=null?e:0;t+=Math.min(o,s)}return t}reportPaginationProgress(e,t){var i,n;let r=_t("PAGINATION_PROGRESS");if(!r.length)return;let o=e.item.spineIndex,s=this.getTotalOffsetForViewItem(e),a=s;t&&(a=e.instance.getPosition(t,!0)),a<0&&(a=0),a>s&&(a=s);let h=this.paginationProgress.renderedOffsetsBySpine[o];h!=null&&a<h&&(a=h),this.paginationProgress.renderedOffsetsBySpine[o]=a;let l=this.getRenderedPageCount(),c=this.getTotalOffsetAll(),d=this.getRenderedOffsetAll(),p=c>0?d/c:0;p<this.paginationProgress.lastReportedFraction?p=this.paginationProgress.lastReportedFraction:this.paginationProgress.lastReportedFraction=p,l>this.paginationProgress.lastReportedPages&&(this.paginationProgress.lastReportedPages=l);let f=e.item.src;o>=((i=this.paginationProgress.lastReportedSpineIndex)!=null?i:-1)?(this.paginationProgress.lastReportedSpineIndex=o,this.paginationProgress.lastReportedHref=f):f=(n=this.paginationProgress.lastReportedHref)!=null?n:f;let g={fraction:p,pages:this.paginationProgress.lastReportedPages,href:f};for(let v of r)try{v(g)}catch(w){Y.warn(w)}}isInCounterResolveScope(){return this.counterStore.currentPageCountersStack.length>0}hasNonEmptyPageType(e){return!!(e!=null&&e.pageType)&&e.pageType!==""}hasPageTypeBoundaryBetween(e,t){return e?.pageType!=null&&t?.pageType!=null&&e.pageType!==t.pageType}resolvePageTypeForRenderSlot(e,t,i,n,r,o,s){let a=!1;if(n){let h=this.hasPageTypeBoundaryBetween(r,n),l=o?.pageType===n.pageType,c=n.offset!==t.offset,d=s&&!c&&i>0;if(a=n.pageType!=null&&(d||i===0||n.pageType===r?.pageType),t.pageType=a?n.pageType:null,s){let p=e.instance.getPageStartPageTypeOverride(t.position);p===""?t.pageType="":p&&(t.pageType=p)}if(!s&&!a){let p=i>1&&h&&l?r.pageType:null;e.instance.styler.cascade.currentPageType=p,e.instance.pageManager.pageCascadeInstance.currentPageType=p}}!s&&this.hasNonEmptyPageType(r)&&this.hasNonEmptyPageType(o)&&r.pageType!==o.pageType&&(!n||n.pageType==null)&&(t.pageType=r.pageType)}evaluateNextPageRelayout(e,t,i,n,r){if(!e||t&&!i)return{needsRelayout:!1,shouldCascade:!1};let o=!!t&&(e.pageType===t.pageType||!t.pageType);return t&&n&&(!r||o)&&(t.pageType==null||e.pageType==null||e.pageType!==t.pageType)&&(t.pageType=null),{needsRelayout:!0,shouldCascade:!!t||!r}}preparePageCountersForRender(e,t){let i=e.pages[t],n=e.pageCounterStarts[t];i&&n&&(this.counterStore.currentPageCounters=Io(n));let r=Io(this.counterStore.currentPageCounters);return(!n||!i)&&(e.pageCounterStarts[t]=r),i}maybeRelayoutFollowingPage(e,t,i,n){if(!t)return T(!0);let r=e.layoutPositions[t.page];e.layoutPositions[t.page]=t;let o=e.pages[t.page],s=!!i&&n.offset!==i.offset,a=e.instance.hasActiveRootPageFloatLayoutContext(),h=!r||!t.isSamePosition(r)||t.highestSeenOffset!==r.highestSeenOffset||s||a,l=this.isInCounterResolveScope(),c=this.evaluateNextPageRelayout(i,o,h,s,l);return c.needsRelayout?(e.complete=!1,c.shouldCascade?this.renderSinglePage(e,t):T(!0)):T(!0)}resolveUnresolvedReferencesForPage(e,t,i,n){let r=M("resolveUnresolvedReferencesForPage"),o=this.isInCounterResolveScope()?[]:this.counterStore.getUnresolvedRefsToPage(t),s=0,a=t;return r.loopWithFrame(h=>{if(s++,s>o.length){h.breakLoop();return}let l=o[s-1];if(l.refs=l.refs.filter(c=>!c.isResolved()),l.refs.length===0){h.continueLoop();return}this.getPageViewItem(l.spineIndex).then(c=>{var d;if(!c){h.continueLoop();return}let p=c.instance.styler.cascade,f=c.instance.pageManager.pageCascadeInstance,g={currentPageType:p.currentPageType,previousPageType:p.previousPageType},v={currentPageType:f.currentPageType,previousPageType:f.previousPageType},w=US(c.instance.pageGroupPageCounts),x=c.instance.currentPageGroupDocument,m=c.instance.scopes;c.instance.scopes={};let S=l.pageIndex<c.pages.length-1,b=!!c.pages[l.pageIndex],C=b&&S,P=C&&l.pageIndex>0?(d=c.pages[l.pageIndex-1])==null?void 0:d.pageFloatLayoutContext:null,L=C?c.instance.beginIsolatedRootPageFloatLayoutContext(P):null;this.counterStore.pushPageCounters(l.pageCounters),this.counterStore.pushReferencesToSolve(l.refs);let A=c.layoutPositions[l.pageIndex];b&&c.instance.preparePageGroupPageIndicesForRerender(c.layoutPositions,l.pageIndex),this.renderSinglePage(c,A).then(z=>{C&&c.instance.endIsolatedRootPageFloatLayoutContext(L);let U=p.currentPageType;p.currentPageType=g.currentPageType,p.previousPageType=g.previousPageType,f.currentPageType=v.currentPageType,f.previousPageType=v.previousPageType,c.instance.pageGroupPageCounts=w,c.instance.currentPageGroupDocument=x,c.instance.scopes=m;let X=Io(this.counterStore.currentPageCounters);this.counterStore.popPageCounters(),this.counterStore.popReferencesToSolve(),z.pageAndPosition.position.spineIndex===a.spineIndex&&z.pageAndPosition.position.pageIndex===i&&(a=z.pageAndPosition.page),a.pageType&&a.pageType!==g.currentPageType&&U!==z.pageAndPosition.page.pageType&&(p.currentPageType=a.pageType);let re=c!==e,k=c.pages.length,_=c.layoutPositions[k],F=c.instance.hasActiveRootPageFloatLayoutContext();if(_&&!F){let D=re?Io(this.counterStore.currentPageCounters):null;re&&(this.counterStore.currentPageCounters=X);let E=k;this.renderSinglePage(c,_).then(()=>{re&&this.markSpineItemCompleteIfReady(c);let N=c.pages.length-E;if(re&&N>0){this.counterStore.adjustPageCountersOfLaterSpines(c.item.spineIndex,N),this.counterStore.updateTargetCounterNodesInPages(c.pages);let R=c.item.spineIndex;for(let $=R+1;$<this.spineItems.length;$++){let V=this.spineItems[$];if(V){V.item.epage+=N;for(let q of V.pageCounterStarts)q!=null&&q.page&&(q.page=q.page.map(Q=>Q+N));this.counterStore.updatePageCounterNodesInPages(V.pages,V.pageCounterStarts)}}if(D){let $=D.page;$&&(D.page=$.map(V=>V+N))}}D&&(this.counterStore.currentPageCounters=D),h.continueLoop()});return}re&&this.markSpineItemCompleteIfReady(c),h.continueLoop()})})}).then(()=>{a.container.parentElement||(a=e.pages[i]),a.isLastPage=!n&&e.item.spineIndex===this.opf.spine.length-1,a.isLastPage&&(this.viewport,this.counterStore.finishLastPage(this.viewport)),a.container.setAttribute("data-vivliostyle-page-index",i),a.container.setAttribute("data-vivliostyle-spine-index",a.spineIndex),r.finish(a)}),r.result()}renderSinglePage(e,t){let i=M("renderSinglePage"),n=t?Math.max(t.page,0):0,r=e.instance.getPageNumberContextDepth();e.instance.pushPageNumberContext(n+1);let o=()=>{e.instance.restorePageNumberContextDepth(r)};i.handler=(d,p)=>{o(),d.task.raise(p,d.parent)};let s=this.isInCounterResolveScope(),a=this.preparePageCountersForRender(e,n),h=n>0?e.pages[n-1]:null,l=e.pages[n+1],c=this.makePage(e,t);return this.resolvePageTypeForRenderSlot(e,c,n,a,h,l,s),e.instance.layoutNextPage(c,t).then(d=>{t=d;let p=t?t.page-1:e.layoutPositions.length-1;this.finishPageContainer(e,c,p),this.counterStore.finishPage(c.spineIndex,p),(_t("PAGINATION_PROGRESS").length?this.collectTotalOffsets():T(!0)).then(()=>{this.reportPaginationProgress(e,t),this.maybeRelayoutFollowingPage(e,t,a,c).thenAsync(()=>this.resolveUnresolvedReferencesForPage(e,c,p,t)).then(f=>{o(),i.finish({pageAndPosition:Fo(f,p),nextLayoutPosition:t})})})}),i.result()}normalizeSeekPosition(e,t){let i=e.pageIndex,n=-1;if(i<0){n=e.offsetInItem;let r=mi(t.layoutPositions.length,o=>t.instance.getPosition(t.layoutPositions[o],!0)>n);r===t.layoutPositions.length?t.complete?i=t.pages.length-1:i=Number.POSITIVE_INFINITY:i=r-1}else i===Number.POSITIVE_INFINITY&&e.offsetInItem!==-1&&(n=e.offsetInItem);return{spineIndex:e.spineIndex,pageIndex:i,offsetInItem:n}}findPage(e,t){let i=M("findPage");return this.waitForPreviousSpines(e.spineIndex,t).then(()=>{this.getPageViewItem(e.spineIndex).then(n=>{if(!n){i.finish(null);return}let r=null,o;i.loopWithFrame(s=>{let a=this.normalizeSeekPosition(e,n);o=a.pageIndex,r=n.pages[o],r?s.breakLoop():n.complete?(o=n.pages.length-1,r=n.pages[o],s.breakLoop()):t?this.renderPage(a).then(h=>{h&&(r=h.page,o=h.position.pageIndex),s.breakLoop()}):o<n.layoutPositions.length&&!n.pages[o]?this.renderPage(a).then(h=>{h&&(r=h.page,o=h.position.pageIndex),s.breakLoop()}):i.sleep(100).then(()=>{s.continueLoop()})}).then(()=>{i.finish(Fo(r,o))})})}),i.result()}renderPage(e){let t=M("renderPage");return this.getPageViewItem(e.spineIndex).then(i=>{if(!i){t.finish(null);return}let n=this.normalizeSeekPosition(e,i),r=n.pageIndex,o=n.offsetInItem,s=i.pages[r];if(s){t.finish(Fo(s,r));return}t.loopWithFrame(a=>{if(r<i.layoutPositions.length){a.breakLoop();return}if(i.complete){r=i.pages.length-1,a.breakLoop();return}let h=i.layoutPositions[i.layoutPositions.length-1];this.renderSinglePage(i,h).then(l=>{let c=l.pageAndPosition.page;if(h=l.nextLayoutPosition,h){if(o>=0&&i.instance.getPosition(h)>o){s=c,r=i.layoutPositions.length-2,a.breakLoop();return}a.continueLoop()}else s=c,r=l.pageAndPosition.position.pageIndex,this.markSpineItemCompleteIfReady(i),a.breakLoop()})}).then(()=>{s=s||i.pages[r];let a=i.layoutPositions[r];if(s){t.finish(Fo(s,r));return}this.renderSinglePage(i,a).then(h=>{h.nextLayoutPosition||this.markSpineItemCompleteIfReady(i),t.finish(h.pageAndPosition)})})}),t.result()}renderAllPages(){let e=M("renderAllPages");return this.renderPagesUpto({spineIndex:this.opf.spine.length-1,pageIndex:Number.POSITIVE_INFINITY,offsetInItem:-1},!1).then(t=>{e.loopWithFrame(i=>{this.spineItems.some(n=>n?.pages.some(r=>r?.fetchers.some(o=>!o.arrived)))?e.sleep(100).then(()=>{i.continueLoop()}):i.breakLoop()}).then(()=>{e.finish(t)})}),e.result()}renderPagesUpto(e,t){let i=M("renderPagesUpto");e||(e={spineIndex:0,pageIndex:0,offsetInItem:0});let n=e.spineIndex,r=e.pageIndex,o=0;t&&(o=n);let s;return i.loopWithFrame(a=>{let h={spineIndex:o,pageIndex:o===n?r:Number.POSITIVE_INFINITY,offsetInItem:o===n?e.offsetInItem:-1};this.renderPage(h).then(l=>{s=l,++o>n?a.breakLoop():a.continueLoop()})}).then(()=>{i.finish(s)}),i.result()}firstPage(e,t){return this.findPage({spineIndex:0,pageIndex:0,offsetInItem:-1},t)}lastPage(e,t){return this.findPage({spineIndex:this.opf.spine.length-1,pageIndex:Number.POSITIVE_INFINITY,offsetInItem:-1},t)}nextPage(e,t){let i=e.spineIndex,n=e.pageIndex,r=M("nextPage");return this.getPageViewItem(i).then(o=>{if(!o){r.finish(null);return}if(o.complete&&n==o.pages.length-1){if(i>=this.opf.spine.length-1){r.finish(null);return}i++,n=0;let s=this.spineItems[i],a=s&&s.pages[0],h=o.pages[o.pages.length-1];a&&h&&a.side==h.side&&(s.pages.forEach(l=>{l.container&&l.container.remove()}),this.spineItems[i]=null,this.spineItemLoadingContinuations[i]=null)}else n++;this.findPage({spineIndex:i,pageIndex:n,offsetInItem:-1},t).thenFinish(r)}),r.result()}previousPage(e,t){let i=e.spineIndex,n=e.pageIndex;if(n==0){if(i==0)return T(null);i--,n=Number.POSITIVE_INFINITY}else n--;return this.findPage({spineIndex:i,pageIndex:n,offsetInItem:-1},t)}isRectoPage(e,t){let i=e.side==="left",n=this.getCurrentPageProgression(t)==="ltr";return!i&&n||i&&!n}getSpread(e,t){let i=this.getPage(e);if(!i)return T({left:null,right:null});let n=M("getSpread"),r=i.side==="left",o;return this.isRectoPage(i,e)?o=this.previousPage(e,t):o=this.nextPage(e,t),o.then(s=>{let a=this.getPage(e),h=s&&s.page;h&&h.side===a.side&&(h=null),r?n.finish({left:a,right:h}):n.finish({left:h,right:a})}),n.result()}nextSpread(e,t){let i=this.getPage(e);if(!i)return T(null);let n=this.isRectoPage(i,e),r=this.nextPage(e,t);return n?r:r.thenAsync(o=>{if(o){if(o.page.side===i.side)return r;let s=this.nextPage(o.position,t);return s.thenAsync(a=>a?s:r)}else return T(null)})}previousSpread(e,t){let i=this.getPage(e);if(!i)return T(null);let n=this.isRectoPage(i,e),r=this.previousPage(e,t),o=i.container.previousElementSibling;return n?r.thenAsync(s=>s?s.page.side===i.side||s.page.container!==o?r:this.previousPage(s.position,t):T(null)):r}navigateToEPage(e,t,i){let n=M("navigateToEPage");return this.opf.resolveEPage(e).then(r=>{r?this.findPage(r,i).thenFinish(n):n.finish(null)}),n.result()}navigateToFragment(e,t,i){let n=M("navigateToCFI");return this.opf.resolveFragment(e).then(r=>{r?this.findPage(r,i).thenFinish(n):n.finish(null)}),n.result()}resolveSemanticFootnoteNavigationOffset(e,t){if(!Pt(t))return null;let i=t.getAttribute("id");if(!i)return null;let n=Ae(`#${i}`,e.xmldoc.url),r=e.xmldoc.document.getElementsByTagName("a");for(let o=0;o<r.length;o++){let s=r.item(o);if(!Gt(s))continue;let a=s.getAttribute("href")||s.getAttributeNS("http://www.w3.org/1999/xlink","href");if(a&&Ae(a,e.xmldoc.url)===n)return e.xmldoc.getElementOffset(s)}return null}navigateTo(e,t,i){Y.debug("Navigate to",e);let n=this.opf.getPathFromURL(pt(e));if(!n){if(this.opf.opfXML&&e.match(/^#epubcfi\(/))n=this.opf.getPathFromURL(this.opf.opfXML.url);else if(e.charAt(0)==="#"){let s=this.opf.documentURLTransformer.restoreURL(e);this.opf.opfXML?(n=this.opf.getPathFromURL(s[0]),n==null&&(n=s[0])):n=s[0],e=s[0]+(s[1]?`#${s[1]}`:"")}if(n==null)return T(null)}let r=this.opf.itemMapByPath[n];if(!r){if(this.opf.opfXML&&n==this.opf.getPathFromURL(this.opf.opfXML.url)){let s=e.indexOf("#");if(s>=0)return this.navigateToFragment(e.substr(s+1),t,i)}return T(null)}let o=M("navigateTo");return this.waitForPreviousSpines(r.spineIndex,i).then(()=>{this.getPageViewItem(r.spineIndex).then(s=>{if(!s){o.finish(null);return}let a=s.xmldoc.getElement(e),h=a&&this.resolveSemanticFootnoteNavigationOffset(s,a),l=h??(a?s.xmldoc.getElementOffset(a):0);this.findPage({spineIndex:r.spineIndex,pageIndex:-1,offsetInItem:l},i).thenFinish(o)})}),o.result()}makePage(e,t){let i=e.instance.viewport,n=i.document.createElement("div");n.setAttribute("data-vivliostyle-page-container","true"),n.role="presentation",Ar||(n.style.visibility="hidden"),i.layoutBox.appendChild(n);let r=i.document.createElement("div");r.setAttribute("data-vivliostyle-bleed-box","true"),r.role="presentation",n.appendChild(r);let o=new Qd(n,r);if(o.spineIndex=e.item.spineIndex,o.position=t,o.offset=e.instance.getPosition(t),o.offset===0&&!(e.instance.blankPageAtStart&&e.pages.length===0)){let s=this.opf.documentURLTransformer.transformFragment("",e.item.src);r.setAttribute("id",s),o.registerElementWithId(r,s)}if(i!==this.viewport){let s=Nc(this.viewport.width,this.viewport.height,i.width,i.height),a=Ri(null,new xt(s,null),"");o.delayedItems.push(new Ul(n,"transform",a))}return o}makeObjectView(e,t,i,n){let r=t.getAttribute("data"),o=null;if(r){r=Ae(r,e.url);let s=t.getAttribute("media-type");if(!s){let a=this.opf.getPathFromURL(r);if(a){let h=this.opf.itemMapByPath[a];h&&(s=h.mediaType)}}if(s){let a=this.opf.bindings[s];if(a){o=this.viewport.document.createElement("iframe"),o.style.border="none";let h=Ah(r),l=Ah(s),c=new gi;c.append(a),c.append("?src="),c.append(h),c.append("&type="),c.append(l);for(let f=t.firstChild;f;f=f.nextSibling)if(f.nodeType==1){let g=f;if(g.localName=="param"&&g.namespaceURI=="http://www.w3.org/1999/xhtml"){let v=g.getAttribute("name"),w=g.getAttribute("value");v&&w&&(c.append("&"),c.append(encodeURIComponent(v)),c.append("="),c.append(encodeURIComponent(w)))}}o.setAttribute("src",c.toString());let d=t.getAttribute("width");d&&o.setAttribute("width",d);let p=t.getAttribute("height");p&&o.setAttribute("height",p)}}}return o||(o=this.viewport.document.createElement("object"),r&&o.setAttribute("data",Ir(r)),o.setAttribute("data-adapt-process-children","true")),T(o)}makeMathJaxView(e,t,i,n){let r=qS();if(r){let o=i.ownerDocument,s=o.createElement("span");i.appendChild(s);let a=o.importNode(t,!0);this.resolveURLsInMathML(a,e),s.appendChild(a);let h=r.queue;h.Push(["Typeset",r,s]);let l=M("makeMathJaxView"),c=l.suspend();return h.Push(()=>{c.schedule(s)}),l.result()}return T(null)}resolveURLsInMathML(e,t){if(e!=null){if(e.nodeType===1&&e.tagName==="mglyph"){let i=Array.from(e.attributes);for(let n of i){if(n.name!=="src")continue;let r=Ae(n.nodeValue,t.url);n.namespaceURI?e.setAttributeNS(n.namespaceURI,n.name,r):e.setAttribute(n.name,r)}}e.firstChild&&this.resolveURLsInMathML(e.firstChild,t),e.nextSibling&&this.resolveURLsInMathML(e.nextSibling,t)}}makeCustomRenderer(e){return(t,i,n)=>t.localName=="object"&&t.namespaceURI=="http://www.w3.org/1999/xhtml"?this.makeObjectView(e,t,i,n):t.namespaceURI=="http://www.w3.org/1998/Math/MathML"?this.makeMathJaxView(e,t,i,n):t.dataset&&t.dataset.mathTypeset=="true"?this.makeMathJaxView(e,t,i,n):T(null)}getPageViewItem(e){if(e===-1||e>=this.opf.spine.length)return T(null);let t=this.spineItems[e];if(t)return T(t);let i=M("getPageViewItem"),n=this.spineItemLoadingContinuations[e];if(n){let s=i.suspend();return n.push(s),i.result()}else n=this.spineItemLoadingContinuations[e]=[];let r=this.opf.spine[e],o=this.opf.store;return o.load(r.src).then(s=>{var a;let h=r.itemRefElement.getAttribute("properties");h&&s.root.setAttribute("data-vivliostyle-epub-spine-properties",h),r.title=s.document.title;let l=o.getStyleForDoc(s),c=this.makeCustomRenderer(s),d=this.viewport,p=l.sizeViewport(d.width,d.height,d.fontSize,this.pref);(p.width!=d.width||p.height!=d.height||p.fontSize!=d.fontSize)&&(d=new Es(d.window,p.fontSize,d.pixelRatio,d.root,p.width,p.height));let f=(a=this.spineItems[0])==null?void 0:a.instance.isVersoFirstPage,g=this.spineItems[e-1],v,w;if(r.startPage!==null)v=r.startPage-1,w=v;else{if(e>0&&(!g||!g.complete))v=r.epage||e,!this.opf.prePaginated&&v%2==(f?1:0)&&v++,w=v;else{v=g?g.instance.pageNumberOffset+g.pages.length:0;let S=g&&g.pageCounterStarts[g.pages.length-1],b=S&&S.page;if(b&&b.length)w=b[b.length-1]+1;else{let C=this.counterStore.currentPageCounters.page;w=!C||!C.length?v:C[C.length-1]}}r.skipPagesBefore!==null&&(v+=r.skipPagesBefore,w+=r.skipPagesBefore)}this.counterStore.forceSetPageCounter(w);let x=new wh(l,s,this.opf.lang,d,this.clientLayout,this.fontMapper,c,this.opf.fallbackMap,v,this.opf.documentURLTransformer,this.counterStore,this.cmykStore,this.opf.pageProgression,f);x.pref=this.pref;let m=this.opf.metadata&&this.opf.metadata[qe.title];x.pubTitle=m&&m[0]&&m[0].v||"",x.docTitle=r.title||"",x.init().then(()=>{!this.opf.pageProgression&&x.pageProgression&&(this.opf.pageProgression=x.pageProgression),t={item:r,xmldoc:s,instance:x,layoutPositions:[null],pages:[],complete:!1,pageCounterStarts:[]},this.spineItems[e]=t,i.finish(t),n.forEach(S=>{S.schedule(t)})})}),i.result()}removeRenderedPages(){let e=this.spineItems;for(let t of e)t&&t.pages.splice(0);this.viewport.clear()}hasAutoSizedPages(){let e=this.spineItems;for(let t of e)if(t){let i=t.pages;for(let n of i)if(n.isAutoPageWidth&&n.isAutoPageHeight)return!0}return!1}hasPages(){return this.spineItems.some(e=>e&&e.pages.length>0)}showTOC(e){let t=this.opf,i=t.toc;if(this.tocAutohide=e,!i)return T(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"),T(this.tocView.page);let n=M("showTOC");this.tocView||(this.tocView=new zS(t.store,i.src,t.lang,this.clientLayout,this.fontMapper,this.pref,this,t.fallbackMap,t.documentURLTransformer,this.counterStore,this.cmykStore));let r=this.viewport,o=Math.min(344,Math.round(.67*r.width)-16),s=r.height-6,a=r.document.createElement("div");return r.root.appendChild(a),Ar||(a.style.visibility="hidden"),a.style.width=`${o+16}px`,a.style.maxHeight=`${s}px`,a.setAttribute("data-vivliostyle-toc-box","true"),a.setAttribute("role","navigation"),this.tocView.showTOC(a,r,o,s,this.viewport.fontSize).then(h=>{a.style.visibility="visible",a.setAttribute("aria-hidden","false"),n.finish(h)}),n.result()}hideTOC(){this.tocVisible=!1,this.tocView&&this.tocView.hideTOC()}isTOCVisible(){return this.tocVisible&&!!this.tocView&&this.tocView.isTOCVisible()}},sc="data-vivliostyle-viewer-status",ZS="data-vivliostyle-spread-view",mg=(e=>(e.SINGLE_PAGE="singlePage",e.SPREAD="spread",e.AUTO_SPREAD="autoSpread",e))(mg||{}),KS=class{constructor(e,t,i,n){u(this,"window",e),u(this,"viewportElement",t),u(this,"instanceId",i),u(this,"callbackFn",n),u(this,"fontMapper"),u(this,"kick"),u(this,"sendCommand"),u(this,"resizeListener"),u(this,"hyperlinkListener"),u(this,"pageRuleStyleElement"),u(this,"pageSheetSizeAlreadySet",!1),u(this,"renderTask",null),u(this,"actions"),u(this,"readyState"),u(this,"packageURL"),u(this,"opf"),u(this,"touchActive"),u(this,"touchX"),u(this,"touchY"),u(this,"needResize"),u(this,"resized"),u(this,"needRefresh"),u(this,"viewportSize"),u(this,"currentPage"),u(this,"currentSpread"),u(this,"pagePosition"),u(this,"fontSize"),u(this,"zoom"),u(this,"fitToScreen"),u(this,"pageViewMode"),u(this,"waitForLoading"),u(this,"renderAllPages"),u(this,"pref"),u(this,"pageSizes"),u(this,"pixelRatio"),u(this,"pixelRatioLimit"),u(this,"viewport"),u(this,"opfView"),u(this,"cmykReserveMap"),u(this,"cmykReserveMapUrl"),u(this,"paginationProgressHook",null);let r=t.ownerDocument,o=(s,a)=>{let h=r.getElementById(s);return h||(h=r.createElement("style"),h.id=s,a&&(h.textContent=a),r.head.appendChild(h)),h};o("vivliostyle-viewport-screen-css",Sd),o("vivliostyle-viewport-css",Cd),o("vivliostyle-polyfill-css",Ad),t.setAttribute("data-vivliostyle-viewer-viewport",!0),Ar&&t.setAttribute("data-vivliostyle-debug",!0),t.setAttribute(sc,"loading"),this.fontMapper=new Nx(r.head,t),this.init(),this.kick=()=>{},this.sendCommand=()=>{},this.resizeListener=()=>{this.needResize=!0,this.resized=!0,this.kick()},this.pageReplacedListener=this.pageReplacedListener.bind(this),this.hyperlinkListener=s=>{},this.pageRuleStyleElement=o("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=Ec(),this.pageSizes=[],this.pixelRatioLimit=Gr==="chromium"&&"currentCSSZoom"in Element.prototype?16:0,this.pixelRatio=Math.min(8,this.pixelRatioLimit)}addLogListeners(){let e=vc;Y.addListener(e.DEBUG,t=>{this.callback({t:"debug",content:t})}),Y.addListener(e.INFO,t=>{this.callback({t:"info",content:t})}),Y.addListener(e.WARN,t=>{this.callback({t:"warn",content:t})}),Y.addListener(e.ERROR,t=>{this.callback({t:"error",content:t})})}ensurePaginationProgressListener(){if(this.paginationProgressHook)return;let e=t=>{this.callback({t:"paginationprogress",...t})};this.paginationProgressHook=e,Ft("PAGINATION_PROGRESS",e)}removePaginationProgressListener(){this.paginationProgressHook&&(Cl("PAGINATION_PROGRESS",this.paginationProgressHook),this.paginationProgressHook=null)}callback(e){e.i=this.instanceId,this.callbackFn(e)}setReadyState(e){if(this.readyState!==e){this.readyState=e,this.viewportElement.setAttribute(sc,e);let t=this.getCurrentPageProgression();t&&this.viewportElement.setAttribute("data-vivliostyle-page-progression",t),this.callback({t:"readystatechange"})}}loadPublication(e){Nt.registerStartTiming("beforeRender"),this.setReadyState("loading");let t=e.url,i=e.fragment,n=e.authorStyleSheet,r=e.userStyleSheet;this.cmykReserveMapUrl=e.cmykReserveMapUrl,this.viewport=null;let o=M("loadPublication");return this.configure(e).then(()=>{let s=new nc;s.init(n,r).then(()=>{let a=Ae(Fn(t),this.window.location.href);this.packageURL=[a],s.loadPubDoc(a).then(h=>{h?(this.opf=h,this.loadCmykReserveMap(s).then(()=>{this.render(i).then(()=>{o.finish(!0)})})):o.finish(!1)})})}),o.result()}loadXML(e){Nt.registerStartTiming("beforeRender"),this.setReadyState("loading");let t=e.url,i=e.document,n=e.fragment,r=e.authorStyleSheet,o=e.userStyleSheet;this.cmykReserveMapUrl=e.cmykReserveMapUrl,this.viewport=null;let s=M("loadXML");return this.configure(e).then(()=>{let a=new nc;a.init(r,o).then(()=>{let h=t.map((l,c)=>({url:Ae(Fn(l.url),this.window.location.href),index:c,startPage:l.startPage,skipPagesBefore:l.skipPagesBefore}));this.packageURL=h.map(l=>l.url),this.opf=new Zo(a,""),this.opf.initWithChapters(h,i).then(()=>{this.loadCmykReserveMap(a).then(()=>{this.render(n).then(()=>{s.finish(!0)})})})})}),s.result()}render(e){this.cancelRenderingTask();let t;return e?t=this.opf.resolveFragment(e).thenAsync(i=>(this.pagePosition=i,T(!0))):t=T(!0),t.thenAsync(()=>(Nt.registerEndTiming("beforeRender"),this.resize()))}resolveLength(e){let t=parseFloat(e),i=/[a-z]+$/,n;if(typeof e=="string"&&(n=e.match(i))){let r=n[0];if(r==="em"||r==="rem")return t*this.fontSize;let o=Zt[r];if(o)return t*o}return t}configure(e){if(typeof e.autoresize=="boolean"&&(e.autoresize?(this.viewportSize=null,this.window.addEventListener("resize",this.resizeListener,!1),this.needResize=!0):this.window.removeEventListener("resize",this.resizeListener,!1)),typeof e.fontSize=="number"){let t=e.fontSize;t>=5&&t<=72&&this.fontSize!=t&&(this.fontSize=t,this.needResize=!0)}if(typeof e.viewport=="object"&&e.viewport){let t=e.viewport,i={marginLeft:this.resolveLength(t["margin-left"])||0,marginRight:this.resolveLength(t["margin-right"])||0,marginTop:this.resolveLength(t["margin-top"])||0,marginBottom:this.resolveLength(t["margin-bottom"])||0,width:this.resolveLength(t.width)||0,height:this.resolveLength(t.height)||0};(i.width>=200||i.height>=200)&&(this.window.removeEventListener("resize",this.resizeListener,!1),this.viewportSize=i,this.needResize=!0)}if(typeof e.hyphenate=="boolean"&&(this.pref.hyphenate=e.hyphenate,this.needResize=!0),typeof e.horizontal=="boolean"&&(this.pref.horizontal=e.horizontal,this.needResize=!0),typeof e.nightMode=="boolean"&&(this.pref.nightMode=e.nightMode,this.needResize=!0),typeof e.lineHeight=="number"&&(this.pref.lineHeight=e.lineHeight,this.needResize=!0),typeof e.columnWidth=="number"&&(this.pref.columnWidth=e.columnWidth,this.needResize=!0),typeof e.fontFamily=="string"&&(this.pref.fontFamily=e.fontFamily,this.needResize=!0),typeof e.load=="boolean"&&(this.waitForLoading=e.load),typeof e.renderAllPages=="boolean"&&(this.renderAllPages=e.renderAllPages),typeof e.userAgentRootURL=="string"&&(Ph(e.userAgentRootURL.replace(/resources\/?$/,"")),Nh(e.userAgentRootURL)),typeof e.rootURL=="string"&&(Ph(e.rootURL),Nh(`${Ji}resources/`)),typeof e.pageViewMode=="string"&&e.pageViewMode!==this.pageViewMode&&(this.pageViewMode=e.pageViewMode,this.needResize=!0),typeof e.pageBorder=="number"&&e.pageBorder!==this.pref.pageBorder&&(this.viewport=null,this.pref.pageBorder=e.pageBorder,this.needResize=!0),typeof e.zoom=="number"&&e.zoom!==this.zoom&&(this.zoom=e.zoom,this.needRefresh=!0),typeof e.fitToScreen=="boolean"&&e.fitToScreen!==this.fitToScreen&&(this.fitToScreen=e.fitToScreen,this.needRefresh=!0),typeof e.defaultPaperSize=="object"&&typeof e.defaultPaperSize.width=="number"&&typeof e.defaultPaperSize.height=="number"&&(this.viewport=null,this.pref.defaultPaperSize=e.defaultPaperSize,this.needResize=!0),typeof e.allowScripts=="boolean"&&e.allowScripts!==vi&&(Tx(e.allowScripts),this.needResize=!0),typeof e.pixelRatio=="number"){let t=Math.min(e.pixelRatio,this.pixelRatioLimit);t!==this.pixelRatio&&(this.pixelRatio=t,this.needResize=!0)}return this.configurePlugins(e),T(!0)}configurePlugins(e){_t("CONFIGURATION").forEach(t=>{let i=t(e);this.needResize=i.needResize||this.needResize,this.needRefresh=i.needRefresh||this.needRefresh})}pageReplacedListener(e){let t=this.currentPage,i=this.currentSpread,n=e.target;i?(i.left===n||i.right===n)&&this.showCurrent(e.newPage):t===e.target&&this.showCurrent(e.newPage)}forCurrentPages(e){let t=[];this.currentPage&&t.push(this.currentPage),this.currentSpread&&(t.push(this.currentSpread.left),t.push(this.currentSpread.right)),t.forEach(i=>{i&&e(i)})}removePageListeners(){this.forCurrentPages(e=>{e.removeEventListener("hyperlink",this.hyperlinkListener,!1),e.removeEventListener("replaced",this.pageReplacedListener,!1)})}hidePages(){this.removePageListeners(),this.forCurrentPages(e=>{I(e.container,"display","none")}),this.currentPage=null,this.currentSpread=null}showSinglePage(e){e.addEventListener("hyperlink",this.hyperlinkListener,!1),e.addEventListener("replaced",this.pageReplacedListener,!1),I(e.container,"visibility","visible"),I(e.container,"display","block")}showPage(e){this.hidePages(),this.currentPage=e,e.container.style.marginLeft="",e.container.style.marginRight="",this.showSinglePage(e)}showSpread(e){if(this.hidePages(),this.currentSpread=e,e.left&&e.right){let t=parseFloat(e.left.container.style.width),i=parseFloat(e.right.container.style.width);t&&i&&t!==i&&(t<i?e.left.container.style.marginLeft=`${i-t}px`:e.right.container.style.marginRight=`${t-i}px`)}e.left&&(this.showSinglePage(e.left),e.right?e.left.container.removeAttribute("data-vivliostyle-unpaired-page"):e.left.container.setAttribute("data-vivliostyle-unpaired-page",!0)),e.right&&(this.showSinglePage(e.right),e.left?e.right.container.removeAttribute("data-vivliostyle-unpaired-page"):e.right.container.setAttribute("data-vivliostyle-unpaired-page",!0))}reportPosition(){let e=M("reportPosition");return this.pagePosition,this.opf.getCFI(this.pagePosition.spineIndex,this.pagePosition.offsetInItem).then(t=>{let i=this.currentPage;(this.waitForLoading&&i.fetchers.length>0?Dn(i.fetchers):T(!0)).then(()=>{this.sendLocationNotification(i,t).thenFinish(e)})}),e.result()}createViewport(){let e=this.viewportElement;if(this.viewportSize){let t=this.viewportSize;return e.style.marginLeft=`${t.marginLeft}px`,e.style.marginRight=`${t.marginRight}px`,e.style.marginTop=`${t.marginTop}px`,e.style.marginBottom=`${t.marginBottom}px`,new Es(this.window,this.fontSize,this.pixelRatio,e,t.width,t.height)}else return new Es(this.window,this.fontSize,this.pixelRatio,e)}resolveSpreadView(e,t){switch(this.pageViewMode){case"singlePage":return!1;case"spread":return!0;default:return e!=null&&(e.width-this.pref.pageBorder)/e.height>=(t?t.width*2/t.height:1.45)&&(!!t||e.width>800)}}updateSpreadView(e){this.pref.spreadView=e,this.viewportElement.setAttribute(ZS,e.toString())}sizeIsGood(){var e;let t=this.createViewport(),i=((e=this.opfView)==null?void 0:e.hasPages())&&!this.opfView.hasAutoSizedPages(),n=this.resolveSpreadView(t,this.resized&&i?this.pageSizes[0]:null);this.resized=!1;let r=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:!r&&t.width==this.viewport.width&&t.height==this.viewport.height||!r&&t.width==this.viewport.width&&t.height!=this.viewport.height&&/Android|iPhone|iPad|iPod/.test(navigator.userAgent)?!0:i?(this.viewport.width=t.width,this.viewport.height=t.height,this.needRefresh=!0,!0):!1}setPageSize(e,t,i,n){this.pageSizes[n]=e,this.setPageSizePageRules(t,i,n),n===0&&this.pageViewMode==="autoSpread"&&!this.opfView.hasAutoSizedPages()&&this.updateSpreadView(this.resolveSpreadView(this.viewport,e))}setPageSizePageRules(e,t,i){var n,r;if(this.pageRuleStyleElement&&(!this.pageSheetSizeAlreadySet||this.pageSizes[i].width!==((n=this.pageSizes[i-1])==null?void 0:n.width)||this.pageSizes[i].height!==((r=this.pageSizes[i-1])==null?void 0:r.height))){let s=function(g){let v=g*.75;return Math.ceil(v)};var o=s;let a=Math.max(...this.pageSizes.map(g=>g.width)),h=Math.max(...this.pageSizes.map(g=>g.height)),l=s(a),c=s(h),d=l*((this.pixelRatio||1)-1)+2,p=c*((this.pixelRatio||1)-1)+2,f=`@page {size: ${l}pt ${c}pt; margin: 0 ${-d}pt ${-p}pt 0;}`;this.pageRuleStyleElement.textContent=f,this.pageSheetSizeAlreadySet=!0}}removePageSizePageRules(){this.pageRuleStyleElement&&(this.pageRuleStyleElement.textContent="",this.pageSheetSizeAlreadySet=!1)}loadCmykReserveMap(e){if(!this.cmykReserveMapUrl)return this.cmykReserveMap=void 0,T(!0);let t=Ae(Fn(this.cmykReserveMapUrl),Ji),i=M("loadCmykReserveMap");return e.loadAsJSON(t).then(n=>{Pm(n)?this.cmykReserveMap=n:(Y.warn("Invalid cmykReserveMap data, ignoring"),this.cmykReserveMap=void 0),i.finish(!0)}),i.result()}reset(){let e=!1,t=!1;this.opfView&&(e=this.opfView.tocVisible,t=this.opfView.tocAutohide,this.opfView.removeRenderedPages()),this.pageSizes=[],this.removePageSizePageRules(),this.viewport=this.createViewport(),this.viewport.resetZoom(),this.opfView=new YS(this.opf,this.viewport,this.fontMapper,this.pref,this.setPageSize.bind(this),this.cmykReserveMap),e&&this.sendCommand({a:"toc",v:"show",autohide:t})}showCurrent(e,t){this.needRefresh=!1,this.removePageListeners();let i=this.resolveSpreadView(this.viewport,e.dimensions);return i!==this.pref.spreadView&&this.updateSpreadView(i),i?this.opfView.getSpread(this.pagePosition,t).thenAsync(n=>!n.left&&!n.right?T(null):n.left&&n.right&&(!this.resolveSpreadView(this.viewport,n.left.dimensions)||!this.resolveSpreadView(this.viewport,n.right.dimensions))?(this.updateSpreadView(!1),this.showPage(e),this.setPageZoom(e),this.currentPage=e,T(null)):(this.showSpread(n),this.setSpreadZoom(n),this.currentPage=e.side==="left"?n.left:n.right,T(null))):(this.showPage(e),this.setPageZoom(e),this.currentPage=e,T(null))}setPageZoom(e){var t;let i=this.getAdjustedZoomFactor(e.dimensions);(t=this.viewport)==null||t.zoom(e.dimensions.width,e.dimensions.height,i)}setSpreadZoom(e){var t;let i=this.getSpreadDimensions(e);(t=this.viewport)==null||t.zoom(i.width,i.height,this.getAdjustedZoomFactor(i))}getAdjustedZoomFactor(e){return this.fitToScreen?this.calculateZoomFactorToFitInsideViewPort(e):this.zoom}getSpreadDimensions(e){let t=0,i=0;return e.left&&(t+=e.left.dimensions.width,i=e.left.dimensions.height),e.right&&(t+=e.right.dimensions.width,i=Math.max(i,e.right.dimensions.height)),e.left&&e.right&&(t+=this.pref.pageBorder*2,t+=Math.abs(e.left.dimensions.width-e.right.dimensions.width)),{width:t,height:i}}queryZoomFactor(e){if(!this.currentPage)throw new Error("no page exists.");if(e==="fit inside viewport"){let t;return this.pref.spreadView?(this.currentSpread,t=this.getSpreadDimensions(this.currentSpread)):t=this.currentPage.dimensions,this.calculateZoomFactorToFitInsideViewPort(t)}else throw new Error(`unknown zoom type: ${e}`)}calculateZoomFactorToFitInsideViewPort(e){if(!this.viewport)return this.zoom;let t=this.viewport.width/e.width,i=this.viewport.height/e.height;return Math.min(t,i)}cancelRenderingTask(){this.renderTask&&this.renderTask.interrupt(new ac),this.renderTask=null}resize(){if(this.needResize=!1,this.needRefresh=!1,this.sizeIsGood())return T(!0);this.setReadyState("loading"),this.cancelRenderingTask();let e=La().getScheduler().run(()=>_n("resize",t=>{if(!this.opf){t.finish(!1);return}this.renderTask=e,Nt.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(i=>{if(!i){t.finish(!1);return}this.pagePosition=i.position,this.showCurrent(i.page,!0).then(()=>{this.setReadyState("interactive"),this.opf.countEPages(n=>{let r={t:"nav",epageCount:n,first:this.currentPage.isFirstPage,last:this.isLastPageForNotification(this.currentPage),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)&&(r.epage=this.opf.spine[this.pagePosition.spineIndex].epage),this.callback(r)}).then(()=>{this.reportPosition().then(n=>{(this.renderAllPages?this.opfView.renderAllPages():T(null)).then(()=>{this.renderTask===e&&(this.renderTask=null),Nt.registerEndTiming("render (resize)"),vi&&Kf(this.window)?Rx(this.window).then(()=>{this.renderAllPages&&this.setReadyState("complete"),this.callback({t:"loaded"}),t.finish(n)}):(this.renderAllPages&&this.setReadyState("complete"),this.callback({t:"loaded"}),t.finish(n))})})})})})},(t,i)=>{if(i instanceof ac)Nt.registerEndTiming("render (resize)"),Y.debug(i.message);else throw i}));return T(!0)}sendLocationNotification(e,t){let i=M("sendLocationNotification"),n={t:"nav",first:e.isFirstPage,last:this.isLastPageForNotification(e),metadata:this.opf.metadata,docTitle:this.opf.spine[e.spineIndex].title};return this.opf.getEPageFromPosition(this.pagePosition).then(r=>{n.epage=r,n.epageCount=this.opf.epageCount,t&&(n.cfi=t),this.callback(n),i.finish(!0)}),i.result()}isLastPageForNotification(e){if(!this.opfView||!this.pagePosition)return e.isLastPage;let t=this.opfView.spineItems[this.pagePosition.spineIndex];if(!t||!t.complete)return!1;let i=t.item.spineIndex===this.opf.spine.length-1,n=this.pagePosition.pageIndex===t.pages.length-1;return i&&n}getCurrentPageProgression(){return this.opfView?this.opfView.getCurrentPageProgression(this.pagePosition):null}moveTo(e){var t;let i;if(this.readyState!=="complete"&&e.where!=="next"&&this.setReadyState("loading"),typeof e.where=="string"){let r;switch(e.where){case"next":r=this.pref.spreadView?this.opfView.nextSpread:this.opfView.nextPage;break;case"previous":r=this.pref.spreadView?this.opfView.previousSpread:this.opfView.previousPage;break;case"last":r=this.opfView.lastPage;break;case"first":r=this.opfView.firstPage;break;default:return T(!0)}r&&(i=()=>r.call(this.opfView,this.pagePosition,!this.renderAllPages))}else if(typeof e.epage=="number"){let r=e.epage;i=()=>this.opfView.navigateToEPage(r,this.pagePosition,!this.renderAllPages)}else if(typeof e.url=="string"){let r=e.url;i=()=>this.opfView.navigateTo(r,this.pagePosition,!this.renderAllPages)}else if(typeof((t=e.position)==null?void 0:t.spineIndex)=="number"){let r=e.position;i=()=>this.opfView.findPage(r,!this.renderAllPages)}else return T(!0);if(!this.opfView)return T(!0);let n=M("moveTo");return i.call(this.opfView).then(r=>{let o;if(r){this.pagePosition=r.position;let s=M("moveTo.showCurrent");o=s.result(),this.showCurrent(r.page,!this.renderAllPages).then(()=>{this.reportPosition().thenFinish(s)})}else o=T(!0);o.then(s=>{this.readyState==="loading"&&this.setReadyState("interactive"),n.finish(s)})}),n.result()}showTOC(e){let t=!!e.autohide,i=e.v,n=this.opfView.isTOCVisible(),r=t!=this.opfView.tocAutohide&&i!="hide";if(n){if(i=="show"&&!r)return T(!0)}else if(i=="hide")return T(!0);if(n&&i!="show")return this.opfView.hideTOC(),T(!0);{let o=M("showTOC");return this.opfView.showTOC(t).then(s=>{if(s){if(r&&(s.listeners={}),t){let a=()=>{this.opfView.hideTOC()};s.addEventListener("hyperlink",a,!1)}s.addEventListener("hyperlink",this.hyperlinkListener,!1)}o.finish(!0)}),o.result()}}runCommand(e){let t=e.a||"";return _n("runCommand",i=>{let n=this.actions[t];n?n.call(this,e).then(()=>{this.callback({t:"done",a:t}),i.finish(!0)}):(Y.error("No such action:",t),i.finish(!0))},(i,n)=>{Y.error(n,"Error during action:",t),i.finish(!0)})}initEmbed(e){let t=lc(e),i=null,n=this;Wy(()=>{let r=M("commandLoop"),o=La().getScheduler();return n.hyperlinkListener=s=>{let a=s,h=a.href.charAt(0)==="#"||n.packageURL.some(l=>a.href.substr(0,l.length)==l);if(h){s.preventDefault();let l={t:"hyperlink",href:a.href,internal:h};o.run(()=>(n.callback(l),T(!0)))}},r.loopWithFrame(s=>{if(n.needResize)n.resize().then(()=>{s.continueLoop()});else if(n.needRefresh)n.currentPage&&n.showCurrent(n.currentPage,!this.renderAllPages).then(()=>{s.continueLoop()});else if(t){let a=t;t=null,n.runCommand(a).then(()=>{s.continueLoop()})}else{let a=M("waitForCommand");i=a.suspend(this),a.result().then(()=>{s.continueLoop()})}}).thenFinish(r),r.result()}),n.kick=()=>{let r=i;r&&(i=null,r.schedule(!0))},n.sendCommand=r=>t?!1:(t=lc(r),n.kick(),!0),this.window.adapt_command=n.sendCommand}},yg=(e=>(e.FIT_INSIDE_VIEWPORT="fit inside viewport",e))(yg||{}),ac=class vg extends Error{constructor(){super(),u(this,"name","RenderingCanceledError"),u(this,"message","Page rendering has been canceled"),u(this,"stack"),Object.setPrototypeOf(this,vg.prototype),this.stack=new Error().stack}};function lc(e){return typeof e=="string"?kl(e):e}var hc=Sl;function JS(){return{autoResize:!0,fontSize:16,pageBorderWidth:1,renderAllPages:!0,pageViewMode:"autoSpread",zoom:1,fitToScreen:!1,defaultPaperSize:void 0,allowScripts:!0,pixelRatio:8}}function uc(e){let t={};return Object.keys(e).forEach(i=>{let n=e[i];switch(i){case"autoResize":t.autoresize=n;break;case"pageBorderWidth":t.pageBorder=n;break;default:t[i]=n}}),t}var wg=class{constructor(e,t){u(this,"settings",e),u(this,"initialized",!1),u(this,"adaptViewer_"),u(this,"options"),u(this,"eventTarget"),u(this,"readyState"),fc(e.debug),this.adaptViewer_=new KS(e.window||window,e.viewportElement,"main",this.dispatcher.bind(this)),this.options=JS(),t&&this.setOptions(t),this.eventTarget=new Nl,Object.defineProperty(this,"readyState",{get(){return this.adaptViewer_.readyState}})}setOptions(e){let t=Object.assign({a:"configure"},uc(e));this.adaptViewer_.sendCommand(t),Object.assign(this.options,e)}dispatcher(e){let t={type:e.t},i=e;Object.keys(i).forEach(n=>{n!=="t"&&(t[n]=i[n])}),this.eventTarget.dispatchEvent(t)}addListener(e,t){e==="paginationprogress"&&this.adaptViewer_.ensurePaginationProgressListener(),this.eventTarget.addEventListener(e,t,!1)}removeListener(e,t){var i;this.eventTarget.removeEventListener(e,t,!1),e==="paginationprogress"&&!((i=this.eventTarget.listeners[e])!=null&&i.length)&&this.adaptViewer_.removePaginationProgressListener()}loadDocument(e,t,i){if(!e||(Array.isArray(e)?!e[0]||typeof e[0]!="string"&&!e[0].url:typeof e!="string"&&!e.url)){this.eventTarget.dispatchEvent({type:"error",content:{error:new Error("No URL specified")}});return}this.loadDocumentOrPublication(e,null,t,i)}loadPublication(e,t,i){if(!e){this.eventTarget.dispatchEvent({type:"error",content:{error:new Error("No URL specified")}});return}this.loadDocumentOrPublication(null,e,t,i)}loadDocumentOrPublication(e,t,i,n){let r=i||{};function o(l){if(l)return l.map(c=>({url:c.url||null,text:c.text||null}))}let s=o(r.authorStyleSheet),a=o(r.userStyleSheet);n&&Object.assign(this.options,n);let h=Object.assign({a:e?"loadXML":"loadPublication",userAgentRootURL:this.settings.userAgentRootURL,url:QS(e)||t,document:r.documentObject,fragment:r.fragment,authorStyleSheet:s,userStyleSheet:a,cmykReserveMapUrl:r.cmykReserveMapUrl},uc(this.options));this.initialized?this.adaptViewer_.sendCommand(h):(this.initialized=!0,this.adaptViewer_.initEmbed(h))}getCurrentPageProgression(){return this.adaptViewer_.getCurrentPageProgression()}resolveNavigation(e){switch(e){case"left":return this.getCurrentPageProgression()===hc.LTR?"previous":"next";case"right":return this.getCurrentPageProgression()===hc.LTR?"next":"previous";default:return e}}navigateToPage(e,t){e==="epage"?this.adaptViewer_.sendCommand({a:"moveTo",epage:t}):this.adaptViewer_.sendCommand({a:"moveTo",where:this.resolveNavigation(e)})}navigateToInternalUrl(e){this.adaptViewer_.sendCommand({a:"moveTo",url:e})}navigateToPosition(e){var t,i;this.adaptViewer_.sendCommand({a:"moveTo",position:{spineIndex:e.spineIndex,pageIndex:(t=e.pageIndex)!=null?t:-1,offsetInItem:(i=e.offsetInItem)!=null?i:-1}})}isTOCVisible(){return this.adaptViewer_.opfView&&this.adaptViewer_.opfView.opf&&this.adaptViewer_.opfView.opf.toc?!!this.adaptViewer_.opfView.isTOCVisible():null}showTOC(e,t){let i=e==null?"toggle":e?"show":"hide";this.adaptViewer_.sendCommand({a:"toc",v:i,autohide:t})}queryZoomFactor(e){return this.adaptViewer_.queryZoomFactor(e)}getPageSizes(){return this.adaptViewer_.pageSizes}getTOC(){var e,t;return(t=(e=this.adaptViewer_.opfView)==null?void 0:e.tocView)==null?void 0:t.getTOC()}getMetadata(){return this.adaptViewer_.opf.getMetadata()}getCover(){return this.adaptViewer_.opf.cover}getCmykMap(){var e;let t=(e=this.adaptViewer_)==null?void 0:e.opfView;return t!=null&&t.cmykStore?t.cmykStore.toJSON():{}}};function QS(e){function t(n){return typeof n=="number"?n:null}function i(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(e)?e.map(i):e?[i(e)]:null}var bg=(e=>(e.PREVIOUS="previous",e.NEXT="next",e.LEFT="left",e.RIGHT="right",e.FIRST="first",e.LAST="last",e.EPAGE="epage",e))(bg||{}),eC=yg,tC=mg;Nt.forceRegisterEndTiming("load_vivliostyle");var iC=class{constructor(e,{title:t="",printCallback:i=s=>s.print(),errorCallback:n=null,hideIframe:r=!0,removeIframe:o=!0}){u(this,"htmlDoc"),u(this,"title"),u(this,"printCallback"),u(this,"errorCallback"),u(this,"hideIframe"),u(this,"removeIframe"),u(this,"iframe"),u(this,"iframeWin"),u(this,"window"),this.htmlDoc=e,this.title=t,this.printCallback=i,this.errorCallback=n,this.hideIframe=r,this.removeIframe=o}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=`
1879
1879
  <!DOCTYPE html>
1880
1880
  <html data-vivliostyle-paginated="true">
1881
1881
  <head>
@@ -1903,6 +1903,6 @@ span[data-viv-leader] {
1903
1903
  <body onload='parent.printInstance.runInIframe(window)'>
1904
1904
  <div id="vivliostyle-viewer-viewport"></div>
1905
1905
  </body>
1906
- </html>`,document.body.appendChild(this.iframe)}runInIframe(e){return this.iframeWin=e,this.preparePrint().then(()=>this.browserPrint()).then(()=>this.cleanUp())}preparePrint(){this.iframeWin.document.title=this.title;let e=new Blob([this.htmlDoc],{type:"text/html"}),t=URL.createObjectURL(e),i=new wg({viewportElement:this.iframeWin.document.body.firstElementChild,window:this.iframeWin,debug:!0});return new Promise(n=>{i.addListener("readystatechange",()=>{i.readyState==="complete"&&n()}),this.errorCallback&&i.addListener("error",o=>{var r,s;let a=(s=(r=o.content.error)==null?void 0:r.toString())!=null?s:o.content.messages.join(`
1907
- `);this.errorCallback(a)}),i.loadDocument({url:t})})}browserPrint(){this.printCallback(this.iframeWin)}cleanUp(){delete this.window.printInstance,this.removeIframe&&this.iframe.parentElement.removeChild(this.iframe)}};function nC(e,t){new iC(e,t).init()}});var oC=Lg(Sg());var export_printHTML=oC.printHTML;export{export_printHTML as printHTML};
1906
+ </html>`,document.body.appendChild(this.iframe)}runInIframe(e){return this.iframeWin=e,this.preparePrint().then(()=>this.browserPrint()).then(()=>this.cleanUp())}preparePrint(){this.iframeWin.document.title=this.title;let e=new Blob([this.htmlDoc],{type:"text/html"}),t=URL.createObjectURL(e),i=new wg({viewportElement:this.iframeWin.document.body.firstElementChild,window:this.iframeWin,debug:!0});return new Promise(n=>{i.addListener("readystatechange",()=>{i.readyState==="complete"&&n()}),this.errorCallback&&i.addListener("error",r=>{var o,s;let a=(s=(o=r.content.error)==null?void 0:o.toString())!=null?s:r.content.messages.join(`
1907
+ `);this.errorCallback(a)}),i.loadDocument({url:t})})}browserPrint(){this.printCallback(this.iframeWin)}cleanUp(){delete this.window.printInstance,this.removeIframe&&this.iframe.parentElement.removeChild(this.iframe)}};function nC(e,t){new iC(e,t).init()}});var rC=Lg(Sg());var export_printHTML=rC.printHTML;export{export_printHTML as printHTML};
1908
1908
  //# sourceMappingURL=index.es6.js.map