UNPKG

550 kBJavaScriptView Raw
1/**
2 * @vivliostyle/core v2.0.0-pre.1
3 * Library for HTML+CSS typesetting and rich paged viewing with EPUB/Web publications support.
4 *
5 * @author Vivliostyle Foundation
6 * @license AGPL-3.0
7 * @preserve
8 */
9!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).Vivliostyle={})}(this,(function(t){"use strict";function e(e){t.isDebug=e}function n(e){switch(e){case"ltr":return t.PageProgression.LTR;case"rtl":return t.PageProgression.RTL;default:throw new Error(`unknown PageProgression: ${e}`)}}var i,o;t.isDebug=!1,function(t){t.LTR="ltr",t.RTL="rtl"}(t.PageProgression||(t.PageProgression={})),(i=t.PageSide||(t.PageSide={})).LEFT="left",i.RIGHT="right",(o=t.ReadyState||(t.ReadyState={})).LOADING="loading",o.INTERACTIVE="interactive",o.COMPLETE="complete";const s={PageProgression:t.PageProgression,PageSide:t.PageSide,ReadyState:t.ReadyState};var r;!function(t){t[t.DEBUG=1]="DEBUG",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR"}(r||(r={}));function a(t){const e=Array.from(t);let n=null;return e[0]instanceof Error&&(n=e.shift()),{error:n,messages:e}}function l(t){const e=t.error,n=e&&(e.frameTrace||e.stack);let i=[].concat(t.messages);return e&&(i.length>0&&(i=i.concat(["\n"])),i=i.concat([e.toString()]),n&&(i=i.concat(["\n"]).concat(n))),i}const h=new class{constructor(t){this.opt_console=t,this.listeners={}}consoleDebug(t){this.opt_console?this.opt_console.debug?this.opt_console.debug(...t):this.opt_console.log(...t):console.debug(...t)}consoleInfo(t){this.opt_console?this.opt_console.info?this.opt_console.info(...t):this.opt_console.log(...t):console.info(...t)}consoleWarn(t){this.opt_console?this.opt_console.warn?this.opt_console.warn(...t):this.opt_console.log(...t):console.warn(...t)}consoleError(t){this.opt_console?this.opt_console.error?this.opt_console.error(...t):this.opt_console.log(...t):console.error(...t)}triggerListeners(t,e){const n=this.listeners[t];n&&n.forEach(t=>{t(e)})}addListener(t,e){let n=this.listeners[t];n||(n=this.listeners[t]=[]),n.push(e)}debug(...t){const e=a(arguments);this.consoleDebug(l(e)),this.triggerListeners(r.DEBUG,e)}info(...t){const e=a(arguments);this.consoleInfo(l(e)),this.triggerListeners(r.INFO,e)}warn(...t){const e=a(arguments);this.consoleWarn(l(e)),this.triggerListeners(r.WARN,e)}error(...t){const e=a(arguments);this.consoleError(l(e)),this.triggerListeners(r.ERROR,e)}};var c;(c=t.HOOKS||(t.HOOKS={})).SIMPLE_PROPERTY="SIMPLE_PROPERTY",c.PREPROCESS_SINGLE_DOCUMENT="PREPROCESS_SINGLE_DOCUMENT",c.PREPROCESS_TEXT_CONTENT="PREPROCESS_TEXT_CONTENT",c.PREPROCESS_ELEMENT_STYLE="PREPROCESS_ELEMENT_STYLE",c.POLYFILLED_INHERITED_PROPS="POLYFILLED_INHERITED_PROPS",c.CONFIGURATION="CONFIGURATION",c.RESOLVE_TEXT_NODE_BREAKER="RESOLVE_TEXT_NODE_BREAKER",c.RESOLVE_FORMATTING_CONTEXT="RESOLVE_FORMATTING_CONTEXT",c.RESOLVE_LAYOUT_PROCESSOR="RESOLVE_LAYOUT_PROCESSOR",c.POST_LAYOUT_BLOCK="POST_LAYOUT_BLOCK";const u={};function d(e,n){if(t.HOOKS[e]){let t=u[e];t||(t=u[e]=[]),t.push(n)}else h.warn(new Error(`Skipping unknown plugin hook '${e}'.`))}function p(e,n){if(t.HOOKS[e]){const t=u[e];if(t){const e=t.indexOf(n);e>=0&&t.splice(e,1)}}else h.warn(new Error(`Ignoring unknown plugin hook '${e}'.`))}function f(t){return u[t]||[]}const g={registerHook:d,removeHook:p};class m{constructor(t){this.performanceInstance=t,this.timestamps={},this.registerTiming=E,this.registerStartTiming=this.registerStartTiming=E,this.registerEndTiming=this.registerEndTiming=E}forceRegisterStartTiming(t,e){w.call(this,t,"start",e)}forceRegisterEndTiming(t,e){w.call(this,t,"end",e)}printTimings(){const t=this.timestamps;let e="";Object.keys(t).forEach(n=>{const i=t[n],o=i.length;for(let t=0;t<o;t++){const s=i[t];e+=n,o>1&&(e+=`(${t})`),e+=` => start: ${s.start}, end: ${s.end}, duration: ${s.end-s.start}\n`}}),h.info(e)}disable(){this.registerTiming=E,this.registerStartTiming=this.registerStartTiming=E,this.registerEndTiming=this.registerEndTiming=E}enable(){this.registerTiming=w,this.registerStartTiming=this.registerStartTiming=N,this.registerEndTiming=this.registerEndTiming=b}isEnabled(){return this.registerStartTiming===N}}function E(){}function w(t,e,n){n||(n=this.performanceInstance.now());let i,o=this.timestamps[t];o||(o=this.timestamps[t]=[]);for(let t=o.length-1;t>=0&&(i=o[t],!i||i[e]);t--)i=null;i||(i={},o.push(i)),i[e]=n}function N(t,e){this.registerTiming(t,"start",e)}function b(t,e){this.registerTiming(t,"end",e)}const S={now:Date.now},y=new m(window&&window.performance||S);y.forceRegisterStartTiming("load_vivliostyle");const C={profiler:{registerStartTiming:y.registerStartTiming,registerEndTiming:y.registerEndTiming,printTimings:y.printTimings,disable:y.disable,enable:y.enable}};let T={};function x(t){return JSON.parse(t)}function I(t){const e=t.match(/^([^#]*)/);return e?e[1]:t}let v=window.location.href;function P(t){v=t}let R=window.location.href;function A(t){R=t}function L(t,e){if(e.startsWith("data:"))return t||e;if(!e||t.match(/^\w{2,}:/))return t.toLowerCase().match("^javascript:")?"#":(t.match(/^\w{2,}:\/\/[^\/]+$/)&&(t=`${t}/`),t);let n;if(e.match(/^\w{2,}:\/\/[^\/]+$/)&&(e=`${e}/`),t.match(/^\/\//))return n=e.match(/^(\w{2,}:)\/\//),n?n[1]+t:t;if(t.match(/^\//))return n=e.match(/^(\w{2,}:\/\/[^\/]+)\//),n?n[1]+t:t;if(t.match(/^\.(\/|$)/)&&(t=t.substr(2)),e=function(t){const e=t.match(/^([^#?]*)/);return e?e[1]:t}(e),t.match(/^#/))return e+t;let i=e.lastIndexOf("/");if(i<0)return t;if(i<e.length-1){if(e.lastIndexOf(".")<i){if(""==t)return e;i=(e+="/").length-1}}let o=e.substr(0,i+1)+t,s="";for(n=o.match(/^([^?#]*)([?#].*)$/),n&&(o=n[1],s=n[2]);i=o.indexOf("/../"),!(i<=0);){const t=o.lastIndexOf("/",i-1);if(t<=0)break;o=o.substr(0,t)+o.substr(i+3)}return o.replace(/\/(\.\/)+/g,"/")+s}function O(t){let e;return(e=/^(https?:)\/\/github\.com\/([^/]+\/[^/]+)\/(blob\/|tree\/|raw\/)?(.*)$/.exec(t))?t=`${e[1]}//raw.githubusercontent.com/${e[2]}/${e[3]?"":"master/"}${e[4]}`:(e=/^(https?:)\/\/www\.aozora\.gr\.jp\/(cards\/[^/]+\/files\/[^/.]+\.html)$/.exec(t))?t=`${e[1]}//raw.githubusercontent.com/aozorabunko/aozorabunko/master/${e[2]}`:(e=/^(https?:)\/\/gist\.github\.com\/([^/]+\/\w+)(\/|$)(raw(\/|$))?(.*)$/.exec(t))?t=`${e[1]}//gist.githubusercontent.com/${e[2]}/raw/${e[6]}`:(e=/^(https?:)\/\/(?:[^/.]+\.)?jsbin\.com\/(?!(?:blog|help)\b)(\w+)((\/\d+)?).*$/.exec(t))&&(t=`${e[1]}//output.jsbin.com/${e[2]}${e[3]}/`),t}var k;function F(t){return null==t?t:t.toString()}!function(t){t.FB2="http://www.gribuser.ru/xml/fictionbook/2.0",t.epub="http://www.idpf.org/2007/ops",t.EV="http://www.w3.org/2001/xml-events",t.MATHML="http://www.w3.org/1998/Math/MathML",t.XML="http://www.w3.org/XML/1998/namespace",t.XHTML="http://www.w3.org/1999/xhtml",t.XLINK="http://www.w3.org/1999/xlink",t.SHADOW="http://www.pyroxy.com/ns/shadow",t.SVG="http://www.w3.org/2000/svg",t.DC="http://purl.org/dc/elements/1.1/",t.NCX="http://www.daisy.org/z3986/2005/ncx/",t.SSE="http://example.com/sse"}(k||(k={}));class D{constructor(){this.queue=[null]}length(){return this.queue.length-1}add(t){let e=this.queue.length;for(;e>1;){const n=Math.floor(e/2),i=this.queue[n];if(i.compare(t)>0)return void(this.queue[e]=t);this.queue[e]=i,e=n}this.queue[1]=t}peek(){return this.queue[1]}remove(){const t=this.queue[1],e=this.queue.pop(),n=this.queue.length;if(n>1){let t=1;for(;;){let i=2*t;if(i>=n)break;if(this.queue[i].compare(e)>0)i+1<n&&this.queue[i+1].compare(this.queue[i])>0&&i++;else{if(!(i+1<n&&this.queue[i+1].compare(e)>0))break;i++}this.queue[t]=this.queue[i],t=i}this.queue[t]=e}return t}}const _=["","-webkit-","-moz-","-ms-","-o-","-epub-"],B={};function M(t,e){if("writing-mode"===e){const n=document.createElement("span");return"-ms-"===t?(n.style.setProperty(t+e,"tb-rl"),"tb-rl"===n.style["writing-mode"]):(n.style.setProperty(t+e,"vertical-rl"),"vertical-rl"===n.style[t+e])}return"string"==typeof document.documentElement.style[function(t,e){return t&&(e=`-${e}`,"moz"===(t=t.replace(/-/g,""))&&(t="Moz")),t+e.replace(/-[a-z]/g,t=>t.substr(1).toUpperCase())}(t,e)]}function U(t){let e=B[t];if(e||null===e)return e;switch(t){case"text-combine-upright":if(M("-webkit-","text-combine")&&!M("","text-combine-upright"))return B[t]=["-webkit-text-combine"],["-webkit-text-combine"];break;case"writing-mode":if(M("-ms-","writing-mode"))return B[t]=["-ms-writing-mode"],["-ms-writing-mode"];break;case"filter":if(M("-webkit-","filter"))return B[t]=["-webkit-filter"],["-webkit-filter"];break;case"clip-path":if(M("-webkit-","clip-path"))return B[t]=["-webkit-clip-path","clip-path"];break;case"margin-inline-start":if(M("-webkit-","margin-start"))return B[t]=["-webkit-margin-start"],["-webkit-margin-start"];break;case"margin-inline-end":if(M("-webkit-","margin-end"))return B[t]=["-webkit-margin-end"],["-webkit-margin-end"];break;case"padding-inline-start":if(M("-webkit-","padding-start"))return B[t]=["-webkit-padding-start"],["-webkit-padding-start"];break;case"padding-inline-end":if(M("-webkit-","padding-end"))return B[t]=["-webkit-padding-end"],["-webkit-padding-end"]}for(const n of _)if(M(n,t))return e=n+t,B[t]=[e],[e];return h.warn("Property not supported by the browser: ",t),B[t]=null,null}function V(t,e,n){try{const i=U(e);if(!i)return;i.forEach(e=>{if("-ms-writing-mode"===e)switch(n){case"horizontal-tb":n="lr-tb";break;case"vertical-rl":n="tb-rl";break;case"vertical-lr":n="tb-lr"}else if("-webkit-text-combine"===e)switch(n){case"all":n="horizontal"}t&&t.style&&t.style.setProperty(e,n)})}catch(t){h.warn(t)}}function H(t,e,n){try{const n=B[e];return t.style.getPropertyValue(n?n[0]:e)}catch(t){}return n||""}function z(t){let e=t.getAttributeNS(k.XML,"lang");return e||t.namespaceURI!=k.XHTML||(e=t.getAttribute("lang")),e}class G{constructor(){this.list=[]}append(t){return this.list.push(t),this}clear(){this.list=[]}toString(){const t=this.list.join("");return this.list=[t],t}}function $(t){return`\\${t.charCodeAt(0).toString(16)} `}function W(t){return t.replace(/[^-_a-zA-Z0-9\u0080-\uFFFF]/g,$)}function X(t){return t.replace(/[\u0000-\u001F"\\]/g,$)}function Y(t){return t.replace(/[\s+&?=#\u007F-\uFFFF]+/g,encodeURIComponent)}function K(t){return!!t.match(/^[a-zA-Z\u009E\u009F\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u024F\u037B-\u037D\u0386\u0388-\u0482\u048A-\u0527]$/)}function j(t,e){return t.replace(/[^-a-zA-Z0-9_]/g,(function(t){return function(t,e){return(e="string"==typeof e?e:"\\u")+(65536|t.charCodeAt(0)).toString(16).substr(1)}(t,e)}))}function q(t){return j(t)}function Q(t,e){e="string"==typeof e?e:"\\u";const n=new RegExp(`${q(e)}[0-9a-fA-F]{4}`,"g");return t.replace(n,(function(t){return function(t,e){return e="string"==typeof e?e:"\\u",0===t.indexOf(e)?String.fromCharCode(parseInt(t.substring(e.length),16)):t}(t,e)}))}function Z(t,e){let n=0,i=t;for(;;){if(0==n||e(n-1),i==t||e(i),n==i)return n;const o=n+i>>1;e(o)?i=o:n=o+1}}function J(t,e){return t-e}function tt(t,e){const n={};for(const i of t){const t=e(i);t&&!n[t]&&(n[t]=i)}return n}function et(t,e){const n={};for(const i of t){const t=e(i);t&&(n[t]?n[t].push(i):n[t]=[i])}return n}class nt{constructor(){this.listeners={}}dispatchEvent(t){const e=this.listeners[t.type];if(e){t.target=this,t.currentTarget=this;for(let n=0;n<e.length;n++)e[n](t)}}addEventListener(t,e,n){if(n)return;const i=this.listeners[t];i?i.push(e):this.listeners[t]=[e]}removeEventListener(t,e,n){if(n)return;const i=this.listeners[t];if(i){const t=i.indexOf(e);t>=0&&i.splice(t,1)}}}let it=null;let ot=null;let st=null;let rt=null;function at(t){if(1==t.nodeType){const e=t.getAttribute("id");if(e&&e.match(/^[-a-zA-Z_0-9.\u007F-\uFFFF]+$/))return e}return null}function lt(t){return`^${t}`}function ht(t){return t.replace(/[\[\]\(\),=;^]/g,lt)}function ct(t){return t.substr(1)}function ut(t){return t?t.replace(/\^[\[\]\(\),=;^]/g,ct):t}function dt(t){const e=[];do{const n=t.match(/^(\^,|[^,])*/),i=ut(n[0]);if(!(t=t.substr(n[0].length+1))&&!e.length)return i;e.push(i)}while(t);return e}function pt(t){const e={};for(;t;){const n=t.match(/^;([^;=]+)=(([^;]|\^;)*)/);if(!n)return e;e[n[1]]=dt(n[2]),t=t.substr(n[0].length)}return e}class ft{appendTo(t){t.append("!")}applyTo(t){return!1}}class gt{constructor(t,e,n){this.index=t,this.id=e,this.sideBias=n}appendTo(t){t.append("/"),t.append(this.index.toString()),(this.id||this.sideBias)&&(t.append("["),this.id&&t.append(this.id),this.sideBias&&(t.append(";s="),t.append(this.sideBias)),t.append("]"))}applyTo(t){if(1!=t.node.nodeType)throw new Error("E_CFI_NOT_ELEMENT");const e=t.node,n=e.children,i=n.length;let o;const s=Math.floor(this.index/2)-1;if(s<0||0==i)o=e.firstChild,t.node=o||e;else{if(o=n[Math.min(s,i-1)],1&this.index){const e=o.nextSibling;e&&1!=e.nodeType?o=e:t.after=!0}t.node=o}if(this.id&&(t.after||this.id!=at(t.node)))throw new Error("E_CFI_ID_MISMATCH");return t.sideBias=this.sideBias,!0}}class mt{constructor(t,e,n,i){this.offset=t,this.textBefore=e,this.textAfter=n,this.sideBias=i}applyTo(t){if(this.offset>0&&!t.after){let e=this.offset,n=t.node;for(;;){const t=n.nodeType;if(1==t)break;const i=n.nextSibling;if(3<=t&&t<=5){const t=n.textContent.length;if(e<=t)break;if(!i){e=t;break}e-=t}if(!i){e=0;break}n=i}t.node=n,t.offset=e}return t.sideBias=this.sideBias,!0}appendTo(t){t.append(":"),t.append(this.offset.toString()),(this.textBefore||this.textAfter||this.sideBias)&&(t.append("["),(this.textBefore||this.textAfter)&&(this.textBefore&&t.append(ht(this.textBefore)),t.append(","),this.textAfter&&t.append(ht(this.textAfter))),this.sideBias&&(t.append(";s="),t.append(this.sideBias)),t.append("]"))}}class Et{constructor(){this.steps=null}fromString(t){let e=t.match(/^#?epubcfi\((.*)\)$/);if(!e)throw new Error("E_CFI_NOT_CFI");const n=e[1];let i=0;const o=[];for(;;){let t;switch(n.charAt(i)){case"/":{if(i++,e=n.substr(i).match(/^(0|[1-9][0-9]*)(\[([-a-zA-Z_0-9.\u007F-\uFFFF]+)(;([^\]]|\^\])*)?\])?/),!e)throw new Error("E_CFI_NUMBER_EXPECTED");i+=e[0].length;const s=parseInt(e[1],10),r=e[3];t=pt(e[4]),o.push(new gt(s,r,F(t.s)));break}case":":{if(i++,e=n.substr(i).match(/^(0|[1-9][0-9]*)(\[((([^\];,]|\^[\];,])*)(,(([^\];,]|\^[\];,])*))?)(;([^]]|\^\])*)?\])?/),!e)throw new Error("E_CFI_NUMBER_EXPECTED");i+=e[0].length;const s=parseInt(e[1],10);let r=e[4];r&&(r=ut(r));let a=e[7];a&&(a=ut(a)),t=pt(e[10]),o.push(new mt(s,r,a,F(t.s)));break}case"!":i++,o.push(new ft);break;case"~":case"@":case"":return void(this.steps=o);default:throw new Error("E_CFI_PARSE_ERROR")}}}navigate(t){const e={node:t.documentElement,offset:0,after:!1,sideBias:null,ref:null};for(let t=0;t<this.steps.length;t++)if(!this.steps[t].applyTo(e)){e.ref=new Et,e.ref.steps=this.steps.slice(t+1);break}return e}trim(t,e){return t.replace(/\s+/g," ").match(e?/^[ -\uD7FF\uE000-\uFFFF]{0,8}/:/[ -\uD7FF\uE000-\uFFFF]{0,8}$/)[0].replace(/^\s/,"").replace(/\s$/,"")}prependPathFromNode(t,e,n,i){const o=[];let s=t.parentNode,r="",a="";for(;t;){switch(t.nodeType){case 3:case 4:case 5:{const i=t.textContent,o=i.length;n?(e+=o,r||(r=i)):(e>o&&(e=o),n=!0,r=i.substr(0,e),a=i.substr(e)),t=t.previousSibling;continue}case 8:t=t.previousSibling;continue}break}for((e>0||r||a)&&(r=this.trim(r,!1),a=this.trim(a,!0),o.push(new mt(e,r,a,i)),i=null);s&&s&&9!=s.nodeType;){const e=n?null:at(t);let r=n?1:0;for(;t;)1==t.nodeType&&(r+=2),t=t.previousSibling;o.push(new gt(r,e,i)),i=null,t=s,s=s.parentNode,n=!1}o.reverse(),this.steps?(o.push(new ft),this.steps=o.concat(this.steps)):this.steps=o}toString(){if(!this.steps)return"";const t=new G;t.append("epubcfi(");for(let e=0;e<this.steps.length;e++)this.steps[e].appendTo(t);return t.append(")"),t.toString()}}function wt(t){return{fontFamily:t.fontFamily,lineHeight:t.lineHeight,margin:t.margin,hyphenate:t.hyphenate,columnWidth:t.columnWidth,horizontal:t.horizontal,nightMode:t.nightMode,spreadView:t.spreadView,pageBorder:t.pageBorder,enabledMediaTypes:Object.assign({},t.enabledMediaTypes),defaultPaperSize:t.defaultPaperSize?Object.assign({},t.defaultPaperSize):void 0}}const Nt={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},bt={PENDING:{}};function St(t,e,n,i){const o=Math.min((t-0)/n,(e-0)/i);return`matrix(${o},0,0,${o},0,0)`}function yt(t){return`"${X(`${t}`)}"`}function Ct(t){return W(`${t}`)}function Tt(t,e){return t?`${W(t)}.${W(e)}`:W(e)}let xt=0;class It{constructor(t,e){if(this.parent=t,this.resolver=e,this.children=[],this.values={},this.funcs={},this.builtIns={},this.scopeKey=`S${xt++}`,this.zero=new ae(this,0),this.one=new ae(this,1),this._true=new ae(this,!0),this._false=new ae(this,!1),t&&t.children.push(this),!t){const t=this.builtIns;t.floor=Math.floor,t.ceil=Math.ceil,t.round=Math.round,t.sqrt=Math.sqrt,t.min=Math.min,t.max=Math.max,t.letterbox=St,t["css-string"]=yt,t["css-name"]=Ct,t.typeof=t=>typeof t,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 yt(this.pubTitle?this.pubTitle:"")})),this.defineBuiltInName("doc-title",(function(){return yt(this.docTitle?this.docTitle:"")}))}}defineBuiltInName(t,e){this.values[t]=new oe(this,e,t)}defineName(t,e){this.values[t]=e}defineFunc(t,e){this.funcs[t]=e}defineBuiltIn(t,e){this.builtIns[t]=e}}function vt(t){switch(t.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}}const Pt={px:1,in:96,pt:4/3,pc:16,cm:96/2.54,mm:96/25.4,q:96/2.54/40,em:16,rem:16,ex:8,dppx:1,dpi:1/96,dpcm:2.54/96};function Rt(t){switch(t){case"q":case"rem":return!0;default:return!1}}class At{constructor(t,e,n,i){this.rootScope=t,this.viewportWidth=e,this.viewportHeight=n,this.actualPageWidth=null,this.actualPageHeight=null,this.rootFontSize=null,this.scopes={},this.pageAreaWidth=null,this.pageAreaHeight=null,this.pageVertical=null,this.pubTitle=null,this.docTitle=null,this.pageWidth=function(){return this.actualPageWidth?this.actualPageWidth:this.pref.spreadView?Math.floor(e/2)-this.pref.pageBorder:e},this.pageHeight=function(){return this.actualPageHeight?this.actualPageHeight:n},this.initialFontSize=i,this.fontSize=function(){return this.rootFontSize?this.rootFontSize:i},this.pref=Nt}getScopeContext(t){let e=this.scopes[t.scopeKey];return e||(e={},this.scopes[t.scopeKey]=e),e}clearScope(t){this.scopes[t.scopeKey]={};for(let e=0;e<t.children.length;e++)this.clearScope(t.children[e])}queryUnitSize(t,e){if(vt(t)){const e=this.pageWidth()/100,n=this.pageHeight()/100,i=null!=this.pageAreaWidth?this.pageAreaWidth/100:e,o=null!=this.pageAreaHeight?this.pageAreaHeight/100:n;switch(t){case"vw":return i;case"vh":return o;case"vi":return this.pageVertical?o:i;case"vb":return this.pageVertical?i:o;case"vmin":return i<o?i:o;case"vmax":return i>o?i:o;case"pvw":return e;case"pvh":return n;case"pvi":return this.pageVertical?n:e;case"pvb":return this.pageVertical?e:n;case"pvmin":return e<n?e:n;case"pvmax":return e>n?e:n}}return"em"==t||"rem"==t?e?this.initialFontSize:this.fontSize():"ex"==t?Pt.ex*(e?this.initialFontSize:this.fontSize())/Pt.em:Pt[t]}evalName(t,e){do{let n=t.values[e];if(n)return n;if(t.resolver&&(n=t.resolver.call(this,e,!1),n))return n;t=t.parent}while(t);throw new Error(`Name '${e}' is undefined`)}evalCall(t,e,n,i){do{let o=t.funcs[e];if(o)return o;if(t.resolver&&(o=t.resolver.call(this,e,!0),o))return o;const s=t.builtIns[e];if(s){if(i)return t.zero;const e=Array(n.length);for(let t=0;t<n.length;t++)e[t]=n[t].evaluate(this);return new ae(t,s.apply(this,e))}t=t.parent}while(t);throw new Error(`Function '${e}' is undefined`)}evalMediaName(t,e){const n="all"===t||!!this.pref.enabledMediaTypes[t];return e?!n:n}evalMediaTest(t,e){let n="";const i=t.match(/^(min|max)-(.*)$/);i&&(n=i[1],t=i[2]);let o=null,s=null;switch(t){case"width":case"height":case"device-width":case"device-height":case"color":e&&(o=e.evaluate(this))}switch(t){case"width":s=this.pageWidth();break;case"height":s=this.pageHeight();break;case"device-width":s=window.screen.availWidth;break;case"device-height":s=window.screen.availHeight;break;case"color":s=window.screen.pixelDepth}if(null!=s&&null!=o)switch(n){case"min":return s>=o;case"max":return s<=o;default:return s==o}else if(null!=s&&null==e)return 0!==s;return!1}queryVal(t,e){const n=this.scopes[t.scopeKey];return n?n[e]:void 0}storeVal(t,e,n){this.getScopeContext(t)[e]=n}}class Lt{constructor(t){this.scope=t,this.scope=t,this.key=`_${xt++}`}toString(){const t=new G;return this.appendTo(t,0),t.toString()}appendTo(t,e){throw new Error("F_ABSTRACT")}evaluateCore(t){throw new Error("F_ABSTRACT")}expand(t,e){return this}dependCore(t,e,n){return t===this}dependOuter(t,e,n){const i=n[this.key];if(null!=i)return i!==bt.PENDING&&i;{n[this.key]=bt.PENDING;const i=this.dependCore(t,e,n);return n[this.key]=i,i}}depend(t,e){return this.dependOuter(t,e,{})}evaluate(t){let e=t.queryVal(this.scope,this.key);return void 0!==e?e:(e=this.evaluateCore(t),t.storeVal(this.scope,this.key,e),e)}isMediaName(){return!1}}class Ot extends Lt{constructor(t,e){super(t),this.val=e}getOp(){throw new Error("F_ABSTRACT")}evalPrefix(t){throw new Error("F_ABSTRACT")}evaluateCore(t){const e=this.val.evaluate(t);return this.evalPrefix(e)}dependCore(t,e,n){return t===this||this.val.dependOuter(t,e,n)}appendTo(t,e){10<e&&t.append("("),t.append(this.getOp()),this.val.appendTo(t,10),10<e&&t.append(")")}expand(t,e){const n=this.val.expand(t,e);return n===this.val?this:new this.constructor(this.scope,n)}}class kt extends Lt{constructor(t,e,n){super(t),this.lhs=e,this.rhs=n}getPriority(){throw new Error("F_ABSTRACT")}getOp(){throw new Error("F_ABSTRACT")}evalInfix(t,e){throw new Error("F_ABSTRACT")}evaluateCore(t){const e=this.lhs.evaluate(t),n=this.rhs.evaluate(t);return this.evalInfix(e,n)}dependCore(t,e,n){return t===this||this.lhs.dependOuter(t,e,n)||this.rhs.dependOuter(t,e,n)}appendTo(t,e){const n=this.getPriority();n<=e&&t.append("("),this.lhs.appendTo(t,n),t.append(this.getOp()),this.rhs.appendTo(t,n),n<=e&&t.append(")")}expand(t,e){const n=this.lhs.expand(t,e),i=this.rhs.expand(t,e);return n===this.lhs&&i===this.rhs?this:new this.constructor(this.scope,n,i)}}class Ft extends kt{constructor(t,e,n){super(t,e,n)}getPriority(){return 1}}class Dt extends kt{constructor(t,e,n){super(t,e,n)}getPriority(){return 2}}class _t extends kt{constructor(t,e,n){super(t,e,n)}getPriority(){return 3}}class Bt extends kt{constructor(t,e,n){super(t,e,n)}getPriority(){return 4}}class Mt extends Ot{constructor(t,e){super(t,e)}getOp(){return"!"}evalPrefix(t){return!t}}class Ut extends Ot{constructor(t,e){super(t,e)}getOp(){return"-"}evalPrefix(t){return-t}}class Vt extends Ft{constructor(t,e,n){super(t,e,n)}getOp(){return"&&"}evaluateCore(t){return this.lhs.evaluate(t)&&this.rhs.evaluate(t)}}class Ht extends Vt{constructor(t,e,n){super(t,e,n)}getOp(){return" and "}}class zt extends Ft{constructor(t,e,n){super(t,e,n)}getOp(){return"||"}evaluateCore(t){return this.lhs.evaluate(t)||this.rhs.evaluate(t)}}class Gt extends zt{constructor(t,e,n){super(t,e,n)}getOp(){return", "}}class $t extends Dt{constructor(t,e,n){super(t,e,n)}getOp(){return"<"}evalInfix(t,e){return t<e}}class Wt extends Dt{constructor(t,e,n){super(t,e,n)}getOp(){return"<="}evalInfix(t,e){return t<=e}}class Xt extends Dt{constructor(t,e,n){super(t,e,n)}getOp(){return">"}evalInfix(t,e){return t>e}}class Yt extends Dt{constructor(t,e,n){super(t,e,n)}getOp(){return">="}evalInfix(t,e){return t>=e}}class Kt extends Dt{constructor(t,e,n){super(t,e,n)}getOp(){return"=="}evalInfix(t,e){return t==e}}class jt extends Dt{constructor(t,e,n){super(t,e,n)}getOp(){return"!="}evalInfix(t,e){return t!=e}}class qt extends _t{constructor(t,e,n){super(t,e,n)}getOp(){return"+"}evalInfix(t,e){return t+e}}class Qt extends _t{constructor(t,e,n){super(t,e,n)}getOp(){return" - "}evalInfix(t,e){return t-e}}class Zt extends Bt{constructor(t,e,n){super(t,e,n)}getOp(){return"*"}evalInfix(t,e){return t*e}}class Jt extends Bt{constructor(t,e,n){super(t,e,n)}getOp(){return"/"}evalInfix(t,e){return t/e}}class te extends Bt{constructor(t,e,n){super(t,e,n)}getOp(){return"%"}evalInfix(t,e){return t%e}}class ee extends Lt{constructor(t,e,n){super(t),this.num=e,this.unit=n.toLowerCase()}appendTo(t,e){t.append(this.num.toString()),t.append(W(this.unit))}evaluateCore(t){return this.num*t.queryUnitSize(this.unit,!1)}}class ne extends Lt{constructor(t,e){super(t),this.qualifiedName=e}appendTo(t,e){t.append(this.qualifiedName)}evaluateCore(t){return t.evalName(this.scope,this.qualifiedName).evaluate(t)}dependCore(t,e,n){return t===this||e.evalName(this.scope,this.qualifiedName).dependOuter(t,e,n)}}class ie extends Lt{constructor(t,e,n){super(t),this.not=e,this.name=n}appendTo(t,e){this.not&&t.append("not "),t.append(W(this.name))}evaluateCore(t){return t.evalMediaName(this.name,this.not)}dependCore(t,e,n){return t===this||this.value.dependOuter(t,e,n)}isMediaName(){return!0}}class oe extends Lt{constructor(t,e,n){super(t),this.fn=e,this.str=n}appendTo(t,e){t.append(this.str)}evaluateCore(t){return this.fn.call(t)}}class se extends Lt{constructor(t,e,n){super(t),this.qualifiedName=e,this.params=n}appendTo(t,e){t.append(this.qualifiedName),function(t,e){t.append("(");for(let n=0;n<e.length;n++)n&&t.append(","),e[n].appendTo(t,0);t.append(")")}(t,this.params)}evaluateCore(t){return t.evalCall(this.scope,this.qualifiedName,this.params,!1).expand(t,this.params).evaluate(t)}dependCore(t,e,n){if(t===this)return!0;for(let i=0;i<this.params.length;i++)if(this.params[i].dependOuter(t,e,n))return!0;return e.evalCall(this.scope,this.qualifiedName,this.params,!0).dependOuter(t,e,n)}expand(t,e){const n=function(t,e,n){let i=e;for(let o=0;o<e.length;o++){const s=e[o].expand(t,n);if(e!==i)i[o]=s;else if(s!==e[o]){i=Array(e.length);for(let t=0;t<o;t++)i[t]=e[t];i[o]=s}}return i}(t,this.params,e);return n===this.params?this:new se(this.scope,this.qualifiedName,n)}}class re extends Lt{constructor(t,e,n,i){super(t),this.cond=e,this.ifTrue=n,this.ifFalse=i}appendTo(t,e){e>0&&t.append("("),this.cond.appendTo(t,0),t.append("?"),this.ifTrue.appendTo(t,0),t.append(":"),this.ifFalse.appendTo(t,0),e>0&&t.append(")")}evaluateCore(t){return this.cond.evaluate(t)?this.ifTrue.evaluate(t):this.ifFalse.evaluate(t)}dependCore(t,e,n){return t===this||this.cond.dependOuter(t,e,n)||this.ifTrue.dependOuter(t,e,n)||this.ifFalse.dependOuter(t,e,n)}expand(t,e){const n=this.cond.expand(t,e),i=this.ifTrue.expand(t,e),o=this.ifFalse.expand(t,e);return n===this.cond&&i===this.ifTrue&&o===this.ifFalse?this:new re(this.scope,n,i,o)}}class ae extends Lt{constructor(t,e){super(t),this.val=e}appendTo(t,e){switch(typeof this.val){case"number":case"boolean":t.append(this.val.toString());break;case"string":t.append('"'),t.append(X(this.val)),t.append('"');break;default:throw new Error("F_UNEXPECTED_STATE")}}evaluateCore(t){return this.val}}class le extends Lt{constructor(t,e,n){super(t),this.name=e,this.value=n}appendTo(t,e){t.append("("),t.append(X(this.name.name)),t.append(":"),this.value.appendTo(t,0),t.append(")")}evaluateCore(t){return t.evalMediaTest(this.name.name,this.value)}dependCore(t,e,n){return t===this||this.value.dependOuter(t,e,n)}expand(t,e){const n=this.value.expand(t,e);return n===this.value?this:new le(this.scope,this.name,n)}}class he extends Lt{constructor(t,e){super(t),this.index=e}appendTo(t,e){t.append("$"),t.append(this.index.toString())}expand(t,e){const n=e[this.index];if(!n)throw new Error(`Parameter missing: ${this.index}`);return n}}function ce(t,e,n){return e===t._false||e===t.zero||n==t._false||n==t.zero?t._false:e===t._true||e===t.one?n:n===t._true||n===t.one?e:new Vt(t,e,n)}function ue(t,e,n){return e===t.zero?n:n===t.zero?e:new qt(t,e,n)}function de(t,e,n){return e===t.zero?new Ut(t,n):n===t.zero?e:new Qt(t,e,n)}function pe(t,e,n){return e===t.zero||n===t.zero?t.zero:e===t.one?n:n===t.one?e:new Zt(t,e,n)}function fe(t,e,n){return e===t.zero?t.zero:n===t.one?e:new Jt(t,e,n)}class ge{visitValues(t){for(let e=0;e<t.length;e++)t[e].visit(this)}visitEmpty(t){throw new Error("E_CSS_EMPTY_NOT_ALLOWED")}visitSlash(t){throw new Error("E_CSS_SLASH_NOT_ALLOWED")}visitStr(t){throw new Error("E_CSS_STR_NOT_ALLOWED")}visitIdent(t){throw new Error("E_CSS_IDENT_NOT_ALLOWED")}visitNumeric(t){throw new Error("E_CSS_NUMERIC_NOT_ALLOWED")}visitNum(t){throw new Error("E_CSS_NUM_NOT_ALLOWED")}visitInt(t){return this.visitNum(t)}visitColor(t){throw new Error("E_CSS_COLOR_NOT_ALLOWED")}visitURL(t){throw new Error("E_CSS_URL_NOT_ALLOWED")}visitSpaceList(t){throw new Error("E_CSS_LIST_NOT_ALLOWED")}visitCommaList(t){throw new Error("E_CSS_COMMA_NOT_ALLOWED")}visitFunc(t){throw new Error("E_CSS_FUNC_NOT_ALLOWED")}visitExpr(t){throw new Error("E_CSS_EXPR_NOT_ALLOWED")}}class me extends ge{constructor(){super()}visitValues(t){let e=null;for(let n=0;n<t.length;n++){const i=t[n],o=i.visit(this);if(e)e[n]=o;else if(i!==o){e=new Array(t.length);for(let i=0;i<n;i++)e[i]=t[i];e[n]=o}}return e||t}visitStr(t){return t}visitIdent(t){return t}visitSlash(t){return t}visitNumeric(t){return t}visitNum(t){return t}visitInt(t){return t}visitColor(t){return t}visitURL(t){return t}visitSpaceList(t){const e=this.visitValues(t.values);return e===t.values?t:new Oe(e)}visitCommaList(t){const e=this.visitValues(t.values);return e===t.values?t:new ke(e)}visitFunc(t){const e=this.visitValues(t.values);return e===t.values?t:new Fe(t.name,e)}visitExpr(t){return t}}class Ee{toString(){const t=new G;return this.appendTo(t,!0),t.toString()}stringValue(){const t=new G;return this.appendTo(t,!1),t.toString()}toExpr(t,e){throw new Error("F_ABSTRACT")}appendTo(t,e){t.append("[error]")}isExpr(){return!1}isNumeric(){return!1}isNum(){return!1}isIdent(){return!1}isSpaceList(){return!1}visit(t){throw new Error("F_ABSTRACT")}}class we extends Ee{constructor(){super()}static get instance(){return this.empty||(this.empty=new we),this.empty}toExpr(t,e){return new ae(t,"")}appendTo(t,e){}visit(t){return t.visitEmpty(this)}}const Ne=we.instance;class be extends Ee{constructor(){super()}static get instance(){return this.slash||(this.slash=new be),this.slash}toExpr(t,e){return new ae(t,"/")}appendTo(t,e){t.append("/")}visit(t){return t.visitSlash(this)}}const Se=be.instance;class ye extends Ee{constructor(t){super(),this.str=t}toExpr(t,e){return new ae(t,this.str)}appendTo(t,e){e?(t.append('"'),t.append(X(this.str)),t.append('"')):t.append(this.str)}visit(t){return t.visitStr(this)}}const Ce={};class Te extends Ee{constructor(t){if(super(),this.name=t,Ce[t])throw new Error("E_INVALID_CALL");Ce[t]=this}toExpr(t,e){return new ae(t,this.name)}appendTo(t,e){e?t.append(W(this.name)):t.append(this.name)}visit(t){return t.visitIdent(this)}isIdent(){return!0}}function xe(t){let e=Ce[t];return e||(e=new Te(t)),e}class Ie extends Ee{constructor(t,e){super(),this.num=t,this.unit=e.toLowerCase()}toExpr(t,e){return 0==this.num?t.zero:e&&"%"==this.unit?100==this.num?e:new Zt(t,e,new ae(t,this.num/100)):new ee(t,this.num,this.unit)}appendTo(t,e){t.append(this.num.toString()),t.append(this.unit)}visit(t){return t.visitNumeric(this)}isNumeric(){return!0}}class ve extends Ee{constructor(t){super(),this.num=t}toExpr(t,e){return 0==this.num?t.zero:1==this.num?t.one:new ae(t,this.num)}appendTo(t,e){t.append(this.num.toString())}visit(t){return t.visitNum(this)}isNum(){return!0}}class Pe extends ve{constructor(t){super(t)}visit(t){return t.visitInt(this)}}class Re extends Ee{constructor(t){super(),this.rgb=t}appendTo(t,e){t.append("#");const n=this.rgb.toString(16);t.append("000000".substr(n.length)),t.append(n)}visit(t){return t.visitColor(this)}}class Ae extends Ee{constructor(t){super(),this.url=t}appendTo(t,e){t.append('url("'),t.append(X(this.url)),t.append('")')}visit(t){return t.visitURL(this)}}function Le(t,e,n,i){const o=e.length;e[0].appendTo(t,i);for(let s=1;s<o;s++)t.append(n),e[s].appendTo(t,i)}class Oe extends Ee{constructor(t){super(),this.values=t}appendTo(t,e){Le(t,this.values," ",e)}visit(t){return t.visitSpaceList(this)}isSpaceList(){return!0}}class ke extends Ee{constructor(t){super(),this.values=t}appendTo(t,e){Le(t,this.values,",",e)}visit(t){return t.visitCommaList(this)}}class Fe extends Ee{constructor(t,e){super(),this.name=t,this.values=e}appendTo(t,e){t.append(W(this.name)),t.append("("),Le(t,this.values,",",e),t.append(")")}visit(t){return t.visitFunc(this)}}class De extends Ee{constructor(t){super(),this.expr=t}toExpr(){return this.expr}appendTo(t,e){t.append("-epubx-expr("),this.expr.appendTo(t,0),t.append(")")}visit(t){return t.visitExpr(this)}isExpr(){return!0}}function _e(t,e){if(t){if(t.isNumeric()){const n=t;return e.queryUnitSize(n.unit,!1)*n.num}if(t.isNum())return t.num}return 0}function Be(t,e){return new Ie(_e(t,e),"px")}const Me={absolute:xe("absolute"),all:xe("all"),always:xe("always"),auto:xe("auto"),avoid:xe("avoid"),balance:xe("balance"),balance_all:xe("balance-all"),block:xe("block"),block_end:xe("block-end"),block_start:xe("block-start"),both:xe("both"),bottom:xe("bottom"),border_box:xe("border-box"),break_all:xe("break-all"),break_word:xe("break-word"),crop:xe("crop"),cross:xe("cross"),column:xe("column"),exclusive:xe("exclusive"),_false:xe("false"),fixed:xe("fixed"),flex:xe("flex"),footnote:xe("footnote"),footer:xe("footer"),header:xe("header"),hidden:xe("hidden"),horizontal_tb:xe("horizontal-tb"),inherit:xe("inherit"),inline:xe("inline"),inline_block:xe("inline-block"),inline_end:xe("inline-end"),inline_start:xe("inline-start"),landscape:xe("landscape"),left:xe("left"),line:xe("line"),list_item:xe("list-item"),ltr:xe("ltr"),manual:xe("manual"),none:xe("none"),normal:xe("normal"),oeb_page_foot:xe("oeb-page-foot"),oeb_page_head:xe("oeb-page-head"),page:xe("page"),relative:xe("relative"),right:xe("right"),same:xe("same"),scale:xe("scale"),snap_block:xe("snap-block"),spread:xe("spread"),_static:xe("static"),rtl:xe("rtl"),table:xe("table"),table_caption:xe("table-caption"),table_cell:xe("table-cell"),table_footer_group:xe("table-footer-group"),table_header_group:xe("table-header-group"),table_row:xe("table-row"),top:xe("top"),transparent:xe("transparent"),vertical_lr:xe("vertical-lr"),vertical_rl:xe("vertical-rl"),visible:xe("visible"),_true:xe("true")},Ue=new Ie(100,"%"),Ve=new Ie(100,"pvw"),He=new Ie(100,"pvh"),ze=new Ie(0,"px"),Ge={"font-size":1,color:2};function $e(t,e){return(Ge[t]||Number.MAX_VALUE)-(Ge[e]||Number.MAX_VALUE)}class We{constructor(t,e,n,i){this.x1=t,this.y1=e,this.x2=n,this.y2=i}}class Xe{constructor(t,e){this.x=t,this.y=e}}class Ye{constructor(t,e,n,i){this.left=t,this.top=e,this.right=n,this.bottom=i}}class Ke{constructor(t,e,n,i){this.low=t,this.high=e,this.winding=n,this.shapeId=i}}class je{constructor(t,e,n,i){this.y1=t,this.y2=e,this.x1=n,this.x2=i,this.left=null,this.right=null}}function qe(t,e){return t.low.y-e.low.y||t.low.x-e.low.x}class Qe{constructor(t){this.points=t}addSegments(t,e){const n=this.points,i=n.length;let o=n[i-1];for(let s=0;s<i;s++){const i=n[s];let r;r=o.y<i.y?new Ke(o,i,1,e):new Ke(i,o,-1,e),t.push(r),o=i}}withOffset(t,e){const n=[];for(const i of this.points)n.push(new Xe(i.x+t,i.y+e));return new Qe(n)}}function Ze(t,e,n,i){const o=[];for(let s=0;s<20;s++){const r=2*s*Math.PI/20;o.push(new Xe(t+n*Math.sin(r),e+i*Math.cos(r)))}return new Qe(o)}function Je(t,e,n,i){return new Qe([new Xe(t,e),new Xe(n,e),new Xe(n,i),new Xe(t,i)])}class tn{constructor(t,e,n,i){this.x=t,this.winding=e,this.shapeId=n,this.lowOrHigh=i}}function en(t,e){const n=t.low.x+(t.high.x-t.low.x)*(e-t.low.y)/(t.high.y-t.low.y);if(isNaN(n))throw new Error("Bad intersection");return n}function nn(t,e,n,i){let o,s,r,a;e.high.y<n&&h.warn("Error: inconsistent segment (1)"),e.low.y<=n?(o=en(e,n),s=e.winding):(o=e.low.x,s=0),e.high.y>=i?(r=en(e,i),a=e.winding):(r=e.high.x,a=0),o<r?(t.push(new tn(o,s,e.shapeId,-1)),t.push(new tn(r,a,e.shapeId,1))):(t.push(new tn(r,a,e.shapeId,-1)),t.push(new tn(o,s,e.shapeId,1)))}function on(t,e,n){const i=e+n,o=Array(i),s=Array(i);let r;for(r=0;r<=i;r++)o[r]=0,s[r]=0;const a=[];let l=!1;const h=t.length;for(let n=0;n<h;n++){const h=t[n];o[h.shapeId]+=h.winding,s[h.shapeId]+=h.lowOrHigh;let c=!1;for(r=0;r<e;r++)if(o[r]&&!s[r]){c=!0;break}if(c)for(r=e;r<=i;r++)if(o[r]||s[r]){c=!1;break}l!=c&&(a.push(h.x),l=c)}return a}function sn(t,e){return e?Math.floor(t/e)*e:t}function rn(t){return new We(t.y1,-t.x2,t.y2,-t.x1)}function an(t){return new We(-t.y2,t.x1,-t.y1,t.x2)}function ln(t){return new Qe(t.points.map(t=>(function(t){return new Xe(t.y,-t.x)})(t)))}function hn(t,e){let n=e.length-1,i=new je(t.y2,t.y2,t.x1,t.x2);for(;n>=0;){const t=i;i=e[n],(i.y2-i.y1<1||i.x1==t.x1&&i.x2==t.x2)&&(t.y1=i.y1,e.splice(n,1),i=t),n--}}function cn(t,e){let n=0,i=t.length;for(;n<i;){const o=Math.floor((n+i)/2);e>=t[o].y2?n=o+1:i=o}return n}function un(t,e){if(!t.length)return e;let n,i,o=e.y1;for(i=0;i<t.length&&(n=t[i],!(n.y2>e.y1&&n.x1-.1<=e.x1&&n.x2+.1>=e.x2));i++)o=Math.max(o,n.y2);let s=o;for(;i<t.length&&(n=t[i],!(n.y1>=e.y2||n.x1-.1>e.x1||n.x2+.1<e.x2));i++)s=n.y2;return s=i===t.length?e.y2:Math.min(s,e.y2),s<=o?null:new We(e.x1,o,e.x2,s)}function dn(t,e){if(!t.length)return e;let n,i,o=e.y2;for(i=t.length-1;i>=0&&(n=t[i],!(i===t.length-1&&n.y2<e.y2))&&!(n.y1<e.y2&&n.x1-.1<=e.x1&&n.x2+.1>=e.x2);i--)o=Math.min(o,n.y1);let s=Math.min(o,n.y2);for(;i>=0&&(n=t[i],!(n.y2<=e.y1||n.x1-.1>e.x1||n.x2+.1<e.x2));i--)s=n.y1;return s=Math.max(s,e.y1),o<=s?null:new We(e.x1,s,e.x2,o)}class pn extends ge{constructor(){super(),this.propSet={}}visitIdent(t){return this.propSet[t.name]=!0,t}visitSpaceList(t){return this.visitValues(t.values),t}}class fn extends ge{constructor(t){super(),this.value=t}visitInt(t){return this.value=t.num,t}}function gn(t,e){if(t){const n=new fn(e);try{return t.visit(n),n.value}catch(t){h.warn(t,"toInt: ")}}return e}class mn extends ge{constructor(){super(),this.collect=!1,this.coords=[],this.name=null}visitNumeric(t){return this.collect&&this.coords.push(t),null}visitNum(t){return this.collect&&0==t.num&&this.coords.push(new Ie(0,"px")),null}visitSpaceList(t){return this.visitValues(t.values),null}visitFunc(t){return this.collect||(this.collect=!0,this.visitValues(t.values),this.collect=!1,this.name=t.name.toLowerCase()),null}getShape(t,e,n,i,o){if(this.coords.length>0){const s=[];switch(this.coords.forEach((t,e)=>{if("%"==t.unit){let o=e%2==0?n:i;3==e&&"circle"==this.name&&(o=Math.sqrt((n*n+i*i)/2)),s.push(t.num*o/100)}else s.push(t.num*o.queryUnitSize(t.unit,!1))}),this.name){case"polygon":if(s.length%2==0){const n=[];for(let i=0;i<s.length;i+=2)n.push(new Xe(t+s[i],e+s[i+1]));return new Qe(n)}break;case"rectangle":if(4==s.length)return Je(t+s[0],e+s[1],t+s[0]+s[2],e+s[1]+s[3]);break;case"ellipse":if(4==s.length)return Ze(t+s[0],e+s[1],s[2],s[3]);break;case"circle":if(3==s.length)return Ze(t+s[0],e+s[1],s[2],s[2])}}return null}}function En(t,e,n,i,o,s){if(t){const r=new mn;try{return t.visit(r),r.getShape(e,n,i,o,s)}catch(t){h.warn(t,"toShape:")}}return Je(e,n,e+i,n+o)}class wn extends ge{constructor(t){super(),this.reset=t,this.counters={},this.name=null}visitIdent(t){return this.name=t.toString(),this.reset?this.counters[this.name]=0:this.counters[this.name]=(this.counters[this.name]||0)+1,t}visitInt(t){return this.name&&(this.counters[this.name]+=t.num-(this.reset?0:1)),t}visitSpaceList(t){return this.visitValues(t.values),t}}function Nn(t,e){const n=new wn(e);try{t.visit(n)}catch(t){h.warn(t,"toCounters:")}return n.counters}class bn extends me{constructor(t,e){super(),this.baseUrl=t,this.transformer=e}visitURL(t){return new Ae(this.transformer.transformURL(t.url,this.baseUrl))}}function Sn(t){const e={};return Object.keys(t).forEach(n=>{e[n]=Array.from(t[n])}),e}class yn{constructor(t,e){this.targetId=t,this.resolved=e,this.pageCounters=null,this.spineIndex=-1,this.pageIndex=-1}equals(t){return this===t||!!t&&(this.targetId===t.targetId&&this.resolved===t.resolved&&this.spineIndex===t.spineIndex&&this.pageIndex===t.pageIndex)}isResolved(){return this.resolved}resolve(){this.resolved=!0}unresolve(){this.resolved=!1}}class Cn{constructor(t,e){this.counterStore=t,this.baseURL=e}countersOfId(t,e){t=this.counterStore.documentURLTransformer.transformFragment(t,this.baseURL),this.counterStore.countersById[t]=e}getExprContentListener(){return this.counterStore.getExprContentListener()}}class Tn{constructor(t,e,n,i){this.counterStore=t,this.baseURL=e,this.rootScope=n,this.pageScope=i,this.styler=null}setStyler(t){this.styler=t}getFragment(t){const e=t.match(/^[^#]*#(.*)$/);return e?e[1]:null}getTransformedId(t){let e=this.counterStore.documentURLTransformer.transformURL(L(t,this.baseURL),this.baseURL);return"#"===e.charAt(0)&&(e=e.substring(1)),e}getPageCounterVal(t,e){const n=this;const i=new oe(this.pageScope,()=>e(function(){const e=n.counterStore.currentPageCounters[t];return e&&e.length?e[e.length-1]:null}()),`page-counter-${t}`);return this.counterStore.registerPageCounterExpr(t,(function(t){return e(t[0])}),i),i}getPageCountersVal(t,e){const n=this;const i=new oe(this.pageScope,()=>e(n.counterStore.currentPageCounters[t]||[]),`page-counters-${t}`);return this.counterStore.registerPageCounterExpr(t,e,i),i}getTargetCounters(t,e,n){let i=this.counterStore.countersById[e];return!i&&n&&t&&(this.styler.styleUntilIdIsReached(t),i=this.counterStore.countersById[e]),i||null}getTargetPageCounters(t){return this.counterStore.currentPage.elementsById[t]?this.counterStore.currentPageCounters:this.counterStore.pageCountersById[t]||null}getTargetCounterVal(t,e,n){const i=this.getFragment(t),o=this.getTransformedId(t);let s=this.getTargetCounters(i,o,!1);if(s&&s[e]){const t=s[e];return new ae(this.rootScope,n(t[t.length-1]||null))}const r=this;return new oe(this.pageScope,()=>{if(s=r.getTargetCounters(i,o,!0),s){if(s[e]){const t=s[e];return n(t[t.length-1]||null)}{const t=r.getTargetPageCounters(o);if(t){if(r.counterStore.resolveReference(o),t[e]){const i=t[e];return n(i[i.length-1]||null)}return n(0)}return r.counterStore.saveReferenceOfCurrentPage(o,!1),"??"}}return r.counterStore.saveReferenceOfCurrentPage(o,!1),"??"},`target-counter-${e}-of-${t}`)}getTargetCountersVal(t,e,n){const i=this.getFragment(t),o=this.getTransformedId(t),s=this;return new oe(this.pageScope,()=>{const t=s.getTargetPageCounters(o);if(t){s.counterStore.resolveReference(o);const r=t[e]||[],a=s.getTargetCounters(i,o,!0)[e]||[];return n(r.concat(a))}return s.counterStore.saveReferenceOfCurrentPage(o,!1),"??"},`target-counters-${e}-of-${t}`)}}class xn{constructor(t){this.documentURLTransformer=t,this.countersById={},this.pageCountersById={},this.currentPageCounters={},this.previousPageCounters={},this.currentPageCountersStack=[],this.pageIndicesById={},this.currentPage=null,this.newReferencesOfCurrentPage=[],this.referencesToSolve=[],this.referencesToSolveStack=[],this.unresolvedReferences={},this.resolvedReferences={},this.pagesCounterExprs=[],this.currentPageCounters.page=[0]}createCounterListener(t){return new Cn(this,t)}createCounterResolver(t,e,n){return new Tn(this,t,e,n)}setCurrentPage(t){this.currentPage=t}definePageCounter(t,e){this.currentPageCounters[t]?this.currentPageCounters[t].push(e):this.currentPageCounters[t]=[e]}forceSetPageCounter(t){const e=this.currentPageCounters.page;e&&e.length?e[e.length-1]=t:this.currentPageCounters.page=[t]}updatePageCounters(t,e){let n;this.previousPageCounters=Sn(this.currentPageCounters);const i=t["counter-reset"];if(i){const t=i.evaluate(e);t&&(n=Nn(t,!0))}if(n)for(const t in n)this.definePageCounter(t,n[t]);let o;const s=t["counter-increment"];if(s){const t=s.evaluate(e);t&&(o=Nn(t,!1))}o?"page"in o||(o.page=1):(o={},o.page=1);for(const t in o){this.currentPageCounters[t]||this.definePageCounter(t,0);const e=this.currentPageCounters[t];e[e.length-1]+=o[t]}}pushPageCounters(t){this.currentPageCountersStack.push(this.currentPageCounters),this.currentPageCounters=Sn(t)}popPageCounters(){this.currentPageCounters=this.currentPageCountersStack.pop()}resolveReference(t){const e=this.unresolvedReferences[t];let n=this.resolvedReferences[t];n||(n=this.resolvedReferences[t]=[]);let i=!1;for(let o=0;o<this.referencesToSolve.length;){const s=this.referencesToSolve[o];if(s.targetId===t){if(s.resolve(),this.referencesToSolve.splice(o,1),e){const t=e.indexOf(s);t>=0&&e.splice(t,1)}n.push(s),i=!0}else o++}i||this.saveReferenceOfCurrentPage(t,!0)}saveReferenceOfCurrentPage(t,e){if(!this.newReferencesOfCurrentPage.some(e=>e.targetId===t)){const n=new yn(t,e);this.newReferencesOfCurrentPage.push(n)}}finishPage(t,e){const n=Object.keys(this.currentPage.elementsById);if(n.length>0){const i=Sn(this.currentPageCounters);n.forEach(n=>{this.pageCountersById[n]=i;const o=this.pageIndicesById[n];if(o&&o.pageIndex<e){const t=this.resolvedReferences[n];if(t){let e,i=this.unresolvedReferences[n];for(i||(i=this.unresolvedReferences[n]=[]);e=t.shift();)e.unresolve(),i.push(e)}}this.pageIndicesById[n]={spineIndex:t,pageIndex:e}})}const i=this.previousPageCounters;let o;for(;o=this.newReferencesOfCurrentPage.shift();){let n;o.pageCounters=i,o.spineIndex=t,o.pageIndex=e,o.isResolved()?(n=this.resolvedReferences[o.targetId],n||(n=this.resolvedReferences[o.targetId]=[])):(n=this.unresolvedReferences[o.targetId],n||(n=this.unresolvedReferences[o.targetId]=[])),n.every(t=>!o.equals(t))&&n.push(o)}this.currentPage=null}getUnresolvedRefsToPage(t){let e=[];Object.keys(t.elementsById).forEach(t=>{const n=this.unresolvedReferences[t];n&&(e=e.concat(n))}),e.sort((t,e)=>t.spineIndex-e.spineIndex||t.pageIndex-e.pageIndex);const n=[];let i=null;return e.forEach(t=>{i&&i.spineIndex===t.spineIndex&&i.pageIndex===t.pageIndex?i.refs.push(t):(i={spineIndex:t.spineIndex,pageIndex:t.pageIndex,pageCounters:t.pageCounters,refs:[t]},n.push(i))}),n}pushReferencesToSolve(t){this.referencesToSolveStack.push(this.referencesToSolve),this.referencesToSolve=t}popReferencesToSolve(){this.referencesToSolve=this.referencesToSolveStack.pop()}registerPageCounterExpr(t,e,n){"pages"===t&&this.pagesCounterExprs.push({expr:n,format:e})}getExprContentListener(){return this.exprContentListener.bind(this)}exprContentListener(t,e,n){if(this.pagesCounterExprs.findIndex(e=>e.expr===t)>=0){const i=n.createElement("span");return i.textContent=e,i.setAttribute(In,t.key),i}return null}finishLastPage(t){const e=t.root.querySelectorAll(`[${In}]`),n=this.currentPageCounters.page[0];Array.from(e).forEach(t=>{const e=t.getAttribute(In),i=this.pagesCounterExprs.findIndex(t=>t.expr.key===e);t.textContent=this.pagesCounterExprs[i].format([n])})}createLayoutConstraint(t){return new vn(this,t)}}const In="data-vivliostyle-pages-counter";class vn{constructor(t,e){this.counterStore=t,this.pageIndex=e}allowLayout(t){if(!t||t.after)return!0;const e=t.viewNode;if(!e||1!==e.nodeType)return!0;const n=e.getAttribute("id")||e.getAttribute("name");if(!n)return!0;if(!this.counterStore.resolvedReferences[n]&&!this.counterStore.unresolvedReferences[n])return!0;const i=this.counterStore.pageIndicesById[n];return!i||this.pageIndex>=i.pageIndex}}function Pn(t){if((t=t.substr(1)).match(/^[^0-9a-fA-F\n\r]$/))return t;const e=parseInt(t,16);return isNaN(e)?"":e<=65535?String.fromCharCode(e):e<=1114111?String.fromCharCode(55296|e>>10&1023,56320|1023&e):"�"}function Rn(t){return t.replace(/\\([0-9a-fA-F]{0,6}(\r\n|[ \n\r\t\f])?|[^0-9a-fA-F\n\r])/g,Pn)}var An,Ln;!function(t){t[t.EOF=0]="EOF",t[t.IDENT=1]="IDENT",t[t.STR=2]="STR",t[t.NUMERIC=3]="NUMERIC",t[t.NUM=4]="NUM",t[t.INT=5]="INT",t[t.FUNC=6]="FUNC",t[t.HASH=7]="HASH",t[t.URL=8]="URL",t[t.CLASS=9]="CLASS",t[t.O_PAR=10]="O_PAR",t[t.C_PAR=11]="C_PAR",t[t.O_BRC=12]="O_BRC",t[t.C_BRC=13]="C_BRC",t[t.O_BRK=14]="O_BRK",t[t.C_BRK=15]="C_BRK",t[t.COMMA=16]="COMMA",t[t.SEMICOL=17]="SEMICOL",t[t.COLON=18]="COLON",t[t.SLASH=19]="SLASH",t[t.AT=20]="AT",t[t.PERCENT=21]="PERCENT",t[t.QMARK=22]="QMARK",t[t.PLUS=23]="PLUS",t[t.MINUS=24]="MINUS",t[t.BAR_BAR=25]="BAR_BAR",t[t.AMP_AMP=26]="AMP_AMP",t[t.BANG=31]="BANG",t[t.DOLLAR=32]="DOLLAR",t[t.HAT=33]="HAT",t[t.BAR=34]="BAR",t[t.TILDE=35]="TILDE",t[t.STAR=36]="STAR",t[t.GT=37]="GT",t[t.LT=38]="LT",t[t.EQ=39]="EQ",t[t.BANG_EQ=41]="BANG_EQ",t[t.DOLLAR_EQ=42]="DOLLAR_EQ",t[t.HAT_EQ=43]="HAT_EQ",t[t.BAR_EQ=44]="BAR_EQ",t[t.TILDE_EQ=45]="TILDE_EQ",t[t.STAR_EQ=46]="STAR_EQ",t[t.GT_EQ=47]="GT_EQ",t[t.LT_EQ=48]="LT_EQ",t[t.EQ_EQ=49]="EQ_EQ",t[t.COL_COL=50]="COL_COL",t[t.INVALID=51]="INVALID",t[t.LAST=51]="LAST"}(An||(An={}));class On{constructor(){this.precededBySpace=!1,this.num=0,this.text="",this.position=0,this.type=An.EOF}}function kn(t,e){const n=Array(128);let i;for(i=0;i<128;i++)n[i]=t;for(n.NaN=t==Ln.END?Ln.END:Ln.INVALID,i=0;i<e.length;i+=2)n[e[i]]=e[i+1];return n}!function(t){t[t.SPACE=1]="SPACE",t[t.INT=2]="INT",t[t.IDENT=3]="IDENT",t[t.BANG=4]="BANG",t[t.HASH=6]="HASH",t[t.DOLLAR=7]="DOLLAR",t[t.PERCENT=8]="PERCENT",t[t.AMP=9]="AMP",t[t.O_PAR=10]="O_PAR",t[t.C_PAR=11]="C_PAR",t[t.STAR=12]="STAR",t[t.PLUS=13]="PLUS",t[t.COMMA=14]="COMMA",t[t.MINUS=15]="MINUS",t[t.DOT=16]="DOT",t[t.SLASH=17]="SLASH",t[t.COLON=18]="COLON",t[t.SEMICOL=19]="SEMICOL",t[t.LT=20]="LT",t[t.EQ=21]="EQ",t[t.GT=22]="GT",t[t.QMARK=23]="QMARK",t[t.AT=24]="AT",t[t.O_BRK=25]="O_BRK",t[t.C_BRK=26]="C_BRK",t[t.O_BRC=27]="O_BRC",t[t.C_BRC=28]="C_BRC",t[t.BSLASH=29]="BSLASH",t[t.HAT=30]="HAT",t[t.BAR=31]="BAR",t[t.TILDE=32]="TILDE",t[t.STR1=33]="STR1",t[t.STR2=34]="STR2",t[t.END=35]="END",t[t.EQTAIL=36]="EQTAIL",t[t.ENDINT=37]="ENDINT",t[t.ENDNUM=38]="ENDNUM",t[t.CONT=39]="CONT",t[t.UNIT=40]="UNIT",t[t.PCUNIT=41]="PCUNIT",t[t.NUMBER=42]="NUMBER",t[t.ENDIDNT=43]="ENDIDNT",t[t.IDNTESC=44]="IDNTESC",t[t.ENDIDES=45]="ENDIDES",t[t.ENDSTR=46]="ENDSTR",t[t.ENDESTR=47]="ENDESTR",t[t.STR1ESC=48]="STR1ESC",t[t.STR2ESC=49]="STR2ESC",t[t.BAR_BAR=50]="BAR_BAR",t[t.AMP_AMP=51]="AMP_AMP",t[t.FUNC=52]="FUNC",t[t.FUNCES=53]="FUNCES",t[t.COMMENT=54]="COMMENT",t[t.COMMST=55]="COMMST",t[t.ENDNOTK=56]="ENDNOTK",t[t.MINMIN=57]="MINMIN",t[t.TOINT=58]="TOINT",t[t.TONUM=59]="TONUM",t[t.TOIDENT=60]="TOIDENT",t[t.TOIDES=61]="TOIDES",t[t.KILL1=62]="KILL1",t[t.KILL2=63]="KILL2",t[t.URL=64]="URL",t[t.URL1=65]="URL1",t[t.URL2=66]="URL2",t[t.ENDURL=67]="ENDURL",t[t.TERMURL=68]="TERMURL",t[t.FINURL=69]="FINURL",t[t.LT_BG=70]="LT_BG",t[t.LT_BG_M=71]="LT_BG_M",t[t.INVALID=72]="INVALID",t[t.CHKPOSS=73]="CHKPOSS",t[t.CHKPOSN=74]="CHKPOSN",t[t.URLESC=75]="URLESC",t[t.IDESCH=76]="IDESCH",t[t.COL_COL=77]="COL_COL",t[t.TOCLASS=78]="TOCLASS",t[t.CHKSP=79]="CHKSP",t[t.EOF=80]="EOF"}(Ln||(Ln={}));const Fn=[Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.SPACE,Ln.SPACE,Ln.INVALID,Ln.SPACE,Ln.SPACE,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.SPACE,Ln.BANG,Ln.STR2,Ln.HASH,Ln.DOLLAR,Ln.PERCENT,Ln.AMP,Ln.STR1,Ln.O_PAR,Ln.C_PAR,Ln.STAR,Ln.PLUS,Ln.COMMA,Ln.MINUS,Ln.DOT,Ln.SLASH,Ln.INT,Ln.INT,Ln.INT,Ln.INT,Ln.INT,Ln.INT,Ln.INT,Ln.INT,Ln.INT,Ln.INT,Ln.COLON,Ln.SEMICOL,Ln.LT,Ln.EQ,Ln.GT,Ln.QMARK,Ln.AT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.O_BRK,Ln.BSLASH,Ln.C_BRK,Ln.HAT,Ln.IDENT,Ln.INVALID,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.IDENT,Ln.O_BRC,Ln.BAR,Ln.C_BRC,Ln.TILDE,Ln.INVALID];Fn.NaN=Ln.EOF;const Dn=[Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.FUNC,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.CONT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.ENDIDNT,Ln.IDNTESC,Ln.ENDIDNT,Ln.ENDIDNT,Ln.CONT,Ln.ENDIDNT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT,Ln.ENDIDNT];Dn.NaN=Ln.ENDIDNT;const _n=[Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.TOCLASS,Ln.TONUM,Ln.INVALID,Ln.TONUM,Ln.TONUM,Ln.TONUM,Ln.TONUM,Ln.TONUM,Ln.TONUM,Ln.TONUM,Ln.TONUM,Ln.TONUM,Ln.TONUM,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.INVALID,Ln.TOIDES,Ln.INVALID,Ln.INVALID,Ln.TOCLASS,Ln.INVALID,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.TOCLASS,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID,Ln.INVALID];Dn.NaN=Ln.ENDIDNT;const Bn=[Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.MINMIN,Ln.TONUM,Ln.END,Ln.TOINT,Ln.TOINT,Ln.TOINT,Ln.TOINT,Ln.TOINT,Ln.TOINT,Ln.TOINT,Ln.TOINT,Ln.TOINT,Ln.TOINT,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.END,Ln.TOIDES,Ln.END,Ln.END,Ln.TOIDENT,Ln.END,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.TOIDENT,Ln.END,Ln.END,Ln.END,Ln.END,Ln.END];Bn.NaN=Ln.END;const Mn=[Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.CHKPOSS,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.CHKPOSS,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.FUNCES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.ENDIDES,Ln.IDNTESC,Ln.ENDIDES,Ln.ENDIDES,Ln.CONT,Ln.ENDIDES,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES,Ln.ENDIDES];Mn.NaN=Ln.ENDIDES;const Un=[Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.PCUNIT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.NUMBER,Ln.ENDINT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.UNIT,Ln.ENDINT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT,Ln.ENDINT];Un.NaN=Ln.ENDINT;const Vn=[Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.PCUNIT,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.CONT,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.UNIT,Ln.ENDNUM,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.UNIT,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM,Ln.ENDNUM];Vn.NaN=Ln.ENDNUM;const Hn=kn(Ln.END,[61,Ln.EQTAIL]),zn=kn(Ln.END,[58,Ln.COL_COL]),Gn=kn(Ln.END,[61,Ln.EQTAIL,124,Ln.BAR_BAR]),$n=kn(Ln.END,[38,Ln.AMP_AMP]),Wn=kn(Ln.END,[42,Ln.COMMENT]),Xn=kn(Ln.CONT,[42,Ln.COMMST]),Yn=kn(Ln.COMMENT,[42,Ln.COMMST,47,Ln.ENDNOTK]),Kn=kn(Ln.KILL1,[62,Ln.ENDNOTK]),jn=kn(Ln.END,[61,Ln.EQTAIL,33/*!*/,Ln.LT_BG]),qn=kn(Ln.KILL1,[45,Ln.LT_BG_M]),Qn=kn(Ln.KILL2,[45,Ln.ENDNOTK]),Zn=kn(Ln.IDESCH,[9,Ln.INVALID,10,Ln.INVALID,13,Ln.INVALID,32,Ln.INVALID]),Jn=kn(Ln.CONT,[39,Ln.ENDSTR,10,Ln.INVALID,13,Ln.INVALID,92,Ln.STR1ESC]),ti=kn(Ln.CONT,[34,Ln.ENDSTR,10,Ln.INVALID,13,Ln.INVALID,92,Ln.STR2ESC]),ei=kn(Ln.CONT,[39,Ln.ENDESTR,10,Ln.CHKPOSN,13,Ln.CHKPOSN,92,Ln.STR1ESC]),ni=kn(Ln.CONT,[34,Ln.ENDESTR,10,Ln.CHKPOSN,13,Ln.CHKPOSN,92,Ln.STR2ESC]),ii=kn(Ln.URL,[9,Ln.CONT,32,Ln.CONT,34,Ln.URL2,39,Ln.URL1,41,Ln.INVALID,10,Ln.CONT,13,Ln.CONT]),oi=kn(Ln.CONT,[41,Ln.ENDURL,9,Ln.CHKSP,10,Ln.CHKSP,13,Ln.CHKSP,32,Ln.CHKSP,92,Ln.URLESC,40,Ln.INVALID,91,Ln.INVALID,93,Ln.INVALID,123,Ln.INVALID,125,Ln.INVALID,NaN,Ln.ENDURL]),si=kn(Ln.CONT,[39,Ln.TERMURL,10,Ln.CHKPOSN,13,Ln.CHKPOSN,92,Ln.URLESC,NaN,Ln.ENDURL]),ri=kn(Ln.CONT,[34,Ln.TERMURL,10,Ln.CHKPOSN,13,Ln.CHKPOSN,92,Ln.URLESC,NaN,Ln.ENDURL]),ai=kn(Ln.INVALID,[9,Ln.CONT,10,Ln.CONT,13,Ln.CONT,32,Ln.CONT,41,Ln.FINURL]),li=15;class hi{constructor(t,e){this.input=t,this.handler=e,this.head=-1,this.tail=0,this.curr=0,this.position=0,this.indexMask=li,this.buffer=Array(this.indexMask+1);for(let t=0;t<=this.indexMask;t++)this.buffer[t]=new On}token(){return this.tail==this.curr&&this.fillBuffer(),this.buffer[this.curr]}nthToken(t){return(this.tail-this.curr&this.indexMask)<=t&&this.fillBuffer(),this.buffer[this.curr+t&this.indexMask]}consume(){this.curr=this.curr+1&this.indexMask}mark(){if(this.head>=0)throw new Error("F_CSSTOK_BAD_CALL mark");this.head=this.curr}reset(){if(this.head<0)throw new Error("F_CSSTOK_BAD_CALL reset");this.curr=this.head,this.head=-1}unmark(){this.head=-1}hasMark(){return this.head>=0}reallocate(){const t=2*(this.indexMask+1)-1,e=Array(t+1);let n=this.head,i=0;for(;n!=this.tail;)e[i]=this.buffer[n],n==this.curr&&(this.curr=i),n=n+1&this.indexMask,i++;for(this.head=0,this.tail=i,this.indexMask=t,this.buffer=e;i<=t;)e[i++]=new On}error(t,e,n){this.handler&&this.handler.error(n,e)}fillBuffer(){let t=this.tail,e=this.head>=0?this.head:this.curr,n=this.indexMask;if(t>=e?e+=n:e--,e==t){if(this.head<0)throw new Error("F_CSSTOK_INTERNAL");this.reallocate(),t=this.tail,n=this.indexMask,e=n}let i=Fn;const o=this.input;let s=this.position;const r=this.buffer;let a=An.EOF,l=0,h="",c=0,u=!1,d=r[t],p=-9;for(;;){const f=o.charCodeAt(s);switch(i[f]||i[65]){case Ln.INVALID:a=An.INVALID,h=isNaN(f)?"E_CSS_UNEXPECTED_EOF":"E_CSS_UNEXPECTED_CHAR",i=Fn,s++;break;case Ln.SPACE:s++,u=!0;continue;case Ln.INT:l=s++,i=Un;continue;case Ln.IDENT:a=An.IDENT,l=s++,i=Dn;continue;case Ln.BANG:l=s++,a=An.BANG,i=Hn;continue;case Ln.STR1:a=An.STR,l=++s,i=Jn;continue;case Ln.STR2:a=An.STR,l=++s,i=ti;continue;case Ln.HASH:l=++s,a=An.HASH,i=Dn;continue;case Ln.DOLLAR:l=s++,a=An.DOLLAR,i=Hn;continue;case Ln.PERCENT:l=s++,a=An.PERCENT;break;case Ln.AMP:l=s++,a=An.DOLLAR,i=$n;continue;case Ln.O_PAR:l=s++,a=An.O_PAR;break;case Ln.C_PAR:l=s++,a=An.C_PAR;break;case Ln.STAR:l=s++,a=An.STAR,i=Hn;continue;case Ln.PLUS:l=s++,a=An.PLUS;break;case Ln.COMMA:l=s++,a=An.COMMA;break;case Ln.MINUS:a=An.MINUS,l=s++,i=Bn;continue;case Ln.DOT:l=s++,i=_n;continue;case Ln.TOCLASS:l=s++,a=An.CLASS,i=Dn;continue;case Ln.SLASH:l=s++,a=An.SLASH,i=Wn;continue;case Ln.COLON:l=s++,a=An.COLON,i=zn;continue;case Ln.COL_COL:s++,a=An.COL_COL;break;case Ln.SEMICOL:l=s++,a=An.SEMICOL;break;case Ln.LT:l=s++,a=An.LT,i=jn;continue;case Ln.EQ:l=s++,a=An.EQ,i=Hn;continue;case Ln.GT:l=s++,a=An.GT,i=Hn;continue;case Ln.QMARK:l=s++,a=An.QMARK;break;case Ln.AT:l=++s,a=An.AT,i=Dn;continue;case Ln.O_BRK:l=s++,a=An.O_BRK;break;case Ln.C_BRK:l=s++,a=An.C_BRK;break;case Ln.O_BRC:l=s++,a=An.O_BRC;break;case Ln.C_BRC:l=s++,a=An.C_BRC;break;case Ln.BSLASH:l=s++,p=l,a=An.IDENT,i=Zn;continue;case Ln.HAT:l=s++,a=An.HAT,i=Hn;continue;case Ln.BAR:l=s++,a=An.BAR,i=Gn;continue;case Ln.TILDE:l=s++,a=An.TILDE,i=Hn;continue;case Ln.END:break;case Ln.EQTAIL:s++,a=a+An.BANG_EQ-An.BANG;break;case Ln.ENDINT:a=An.INT,c=parseInt(o.substring(l,s),10);break;case Ln.ENDNUM:a=An.NUM,c=parseFloat(o.substring(l,s));break;case Ln.CONT:s++;continue;case Ln.UNIT:a=An.NUMERIC,c=parseFloat(o.substring(l,s)),l=s++,i=Dn;continue;case Ln.PCUNIT:a=An.NUMERIC,c=parseFloat(o.substring(l,s)),h="%",l=s++;break;case Ln.NUMBER:s++,i=Vn;continue;case Ln.ENDIDNT:h=o.substring(l,s);break;case Ln.IDNTESC:p=s++,i=Zn;continue;case Ln.ENDIDES:h=Rn(o.substring(l,s));break;case Ln.ENDSTR:h=o.substring(l,s),s++;break;case Ln.ENDESTR:h=Rn(o.substring(l,s)),s++;break;case Ln.STR1ESC:p=s,s+=2,i=ei;continue;case Ln.STR2ESC:p=s,s+=2,i=ni;continue;case Ln.BAR_BAR:s++,a=An.BAR_BAR;break;case Ln.AMP_AMP:s++,a=An.AMP_AMP;break;case Ln.FUNC:if(h=o.substring(l,s),a==An.IDENT){if(s++,"url"==h.toLowerCase()){i=ii;continue}a=An.FUNC}break;case Ln.FUNCES:if(h=Rn(o.substring(l,s)),a==An.IDENT){if(s++,"url"==h.toLowerCase()){i=ii;continue}a=An.FUNC}break;case Ln.COMMENT:i=Xn,s++;continue;case Ln.COMMST:i=Yn,s++;continue;case Ln.ENDNOTK:i=Fn,s++;continue;case Ln.MINMIN:i=Kn,s++;continue;case Ln.TOINT:a=An.INT,i=Un,s++;continue;case Ln.TONUM:a=An.NUM,i=Vn,s++;continue;case Ln.TOIDENT:a=An.IDENT,i=Dn,s++;continue;case Ln.TOIDES:a=An.IDENT,i=Zn,p=s++;continue;case Ln.KILL1:s--;break;case Ln.KILL2:s-=2;break;case Ln.URL:l=s++,i=oi;continue;case Ln.URL1:l=++s,i=si;continue;case Ln.URL2:l=++s,i=ri;continue;case Ln.ENDURL:a=An.URL,h=Rn(o.substring(l,s)),s++;break;case Ln.FINURL:s++;break;case Ln.LT_BG:i=qn,s++;continue;case Ln.LT_BG_M:i=Qn,s++;continue;case Ln.CHKSP:if(s-p<8&&o.substring(p+1,s+1).match(/^[0-9a-fA-F]{0,6}(\r\n|[\n\r])|[ \t]$/)){s++;continue}case Ln.TERMURL:a=An.URL,h=Rn(o.substring(l,s)),s++,i=ai;continue;case Ln.CHKPOSN:if(s++,s-p<9&&o.substring(p+1,s).match(/^[0-9a-fA-F]{0,6}(\r\n|[\n\r])$/))continue;a=An.INVALID,h="E_CSS_UNEXPECTED_NEWLINE",i=Fn;break;case Ln.CHKPOSS:if(s-p<9&&o.substring(p+1,s+1).match(/^[0-9a-fA-F]{0,6}[ \t]$/)){s++;continue}h=Rn(o.substring(l,s));break;case Ln.URLESC:p=s++;continue;case Ln.IDESCH:s++,i=Mn;continue;default:if(i!==Fn){a=An.INVALID,h="E_CSS_UNEXPECTED_STATE";break}l=s,a=An.EOF}if(d.type=a,d.precededBySpace=u,d.num=c,d.text=h,d.position=l,t++,t>=e)break;i=Fn,u=!1,d=r[t&n]}this.position=s,this.tail=t&n}}let ci=null,ui=null;function di(){return ci}function pi(t){if(!ci)throw new Error("E_TASK_NO_CONTEXT");ci.name||(ci.name=t);const e=ci,n=new Ti(e,e.top,t);return e.top=n,n.state=Ei.ACTIVE,n}function fi(t){return new yi(t)}function gi(t,e,n){const i=pi(t);i.handler=n;try{e(i)}catch(t){i.task.raise(t,i)}return i.result()}function mi(t,e){var n;return(ci?ci.getScheduler():ui||new Ni(n||new wi)).run(t,e)}var Ei;!function(t){t[t.INIT=0]="INIT",t[t.ACTIVE=1]="ACTIVE",t[t.FINISHED=2]="FINISHED",t[t.DEAD=3]="DEAD"}(Ei||(Ei={}));class wi{currentTime(){return(new Date).valueOf()}setTimeout(t,e){return setTimeout(t,e)}clearTimeout(t){clearTimeout(t)}}class Ni{constructor(t){this.timer=t,this.timeout=1,this.slice=25,this.sliceOverTime=0,this.wakeupTime=null,this.timeoutToken=null,this.inTimeSlice=!1,this.order=0,this.queue=new D,ui||(ui=this)}setSlice(t){this.slice=t}setTimeout(t){this.timeout=t}isTimeSliceOver(){return this.timer.currentTime()>=this.sliceOverTime}arm(){if(this.inTimeSlice)return;const t=this.queue.peek().scheduledTime,e=this.timer.currentTime();if(null!=this.timeoutToken){if(e+this.timeout>this.wakeupTime)return;this.timer.clearTimeout(this.timeoutToken)}let n=t-e;n<=this.timeout&&(n=this.timeout),this.wakeupTime=e+n;const i=this;this.timeoutToken=this.timer.setTimeout(()=>{i.timeoutToken=null,i.doTimeSlice()},n)}schedule(t,e){const n=t,i=this.timer.currentTime();n.order=this.order++,n.scheduledTime=i+(e||0),this.queue.add(n),this.arm()}doTimeSlice(){null!=this.timeoutToken&&(this.timer.clearTimeout(this.timeoutToken),this.timeoutToken=null),this.inTimeSlice=!0;try{let t=this.timer.currentTime();for(this.sliceOverTime=t+this.slice;this.queue.length();){const e=this.queue.peek();if(e.scheduledTime>t)break;if(this.queue.remove(),e.canceled||e.resumeInternal(),t=this.timer.currentTime(),t>=this.sliceOverTime)break}}catch(t){h.error(t)}this.inTimeSlice=!1,this.queue.length()&&this.arm()}run(t,e){const n=new Si(this,e||"");n.top=new Ti(n,null,"bootstrap"),n.top.state=Ei.ACTIVE,n.top.then(()=>{const e=()=>{n.running=!1;for(const t of n.callbacks)try{t()}catch(t){h.error(t)}};try{t().then(t=>{n.result=t,e()})}catch(t){n.raise(t),e()}});const i=ci;return ci=n,this.schedule(n.top.suspend("bootstrap")),ci=i,n}}class bi{constructor(t){this.task=t,this.scheduledTime=0,this.order=0,this.result=null,this.canceled=!1}compare(t){const e=t;return e.scheduledTime-this.scheduledTime||e.order-this.order}getTask(){return this.task}schedule(t,e){this.result=t,this.task.scheduler.schedule(this,e)}resumeInternal(){const t=this.task;if(this.task=null,t&&t.continuation==this){t.continuation=null;const e=ci;return ci=t,t.top.finish(this.result),ci=e,!0}return!1}cancel(){this.canceled=!0}}class Si{constructor(t,e){this.scheduler=t,this.name=e,this.callbacks=[],this.exception=null,this.running=!0,this.result=null,this.waitTarget=null,this.top=null,this.continuation=null}getName(){return this.name}interrupt(t){if(this.raise(t||new Error("E_TASK_INTERRUPT")),this!==ci&&this.continuation){this.continuation.cancel();const t=new bi(this);this.waitTarget="interrupt",this.continuation=t,this.scheduler.schedule(t)}}getScheduler(){return this.scheduler}isRunning(){return this.running}whenDone(t){this.callbacks.push(t)}join(){const t=pi("Task.join");if(this.running){const e=t.suspend(this),n=this;this.whenDone(()=>{e.schedule(n.result)})}else t.finish(this.result);return t.result()}unwind(){for(;this.top&&!this.top.handler;)this.top=this.top.parent;if(this.top&&this.top.handler&&this.exception){const t=this.exception;this.exception=null,this.top.handler(this.top,t)}else this.exception&&h.error(this.exception,"Unhandled exception in task",this.name)}raise(t,e){if(this.fillStack(t),e){let t=this.top;for(;t&&t!=e;)t=t.parent;t==e&&(this.top=t)}this.exception=t,this.unwind()}fillStack(t){let e=t.frameTrace;if(!e){e=t.stack?`${t.stack}\n\t---- async ---\n`:"";for(let t=this.top;t;t=t.parent)e+="\t",e+=t.getName(),e+="\n";t.frameTrace=e}}}class yi{constructor(t){this.value=t}then(t){t(this.value)}thenAsync(t){return t(this.value)}thenReturn(t){return new yi(t)}thenFinish(t){t.finish(this.value)}isPending(){return!1}get(){return this.value}}class Ci{constructor(t){this.frame=t}then(t){this.frame.then(t)}thenAsync(t){if(this.isPending()){const e=new Ti(this.frame.task,this.frame.parent,"AsyncResult.thenAsync");return e.state=Ei.ACTIVE,this.frame.parent=e,this.frame.then(n=>{t(n).then(t=>{e.finish(t)})}),e.result()}return t(this.frame.res)}thenReturn(t){return this.isPending()?this.thenAsync(()=>new yi(t)):new yi(t)}thenFinish(t){this.isPending()?this.then(e=>{t.finish(e)}):t.finish(this.frame.res)}isPending(){return this.frame.state==Ei.ACTIVE}get(){if(this.isPending())throw new Error("Result is pending");return this.frame.res}}class Ti{constructor(t,e,n){this.task=t,this.parent=e,this.name=n,this.res=null,this.callback=null,this.handler=null,this.state=Ei.INIT}checkEnvironment(){if(!ci)throw new Error("F_TASK_NO_CONTEXT");if(this!==ci.top)throw new Error("F_TASK_NOT_TOP_FRAME")}result(){return new Ci(this)}finish(t){this.checkEnvironment(),ci&&!ci.exception&&(this.res=t),this.state=Ei.FINISHED;const e=this.parent;if(ci&&(ci.top=e),this.callback){try{this.callback(t)}catch(t){this.task.raise(t,e)}this.state=Ei.DEAD}}getTask(){return this.task}getName(){return this.name}getScheduler(){return this.task.scheduler}then(t){switch(this.state){case Ei.ACTIVE:if(this.callback)throw new Error("F_TASK_FRAME_ALREADY_HAS_CALLBACK");this.callback=t;break;case Ei.FINISHED:{const e=this.task,n=this.parent;try{t(this.res),this.state=Ei.DEAD}catch(t){this.state=Ei.DEAD,e.raise(t,n)}break}case Ei.DEAD:throw new Error("F_TASK_DEAD_FRAME");default:throw new Error(`F_TASK_UNEXPECTED_FRAME_STATE ${this.state}`)}}timeSlice(){const t=pi("Frame.timeSlice");return t.getScheduler().isTimeSliceOver()?(h.debug("-- time slice --"),t.suspend().schedule(!0)):t.finish(!0),t.result()}sleep(t){const e=pi("Frame.sleep");return e.suspend().schedule(!0,t),e.result()}loop(t){const e=pi("Frame.loop"),n=i=>{try{for(;i;){const e=t();if(e.isPending())return void e.then(n);e.then(t=>{i=t})}e.finish(!0)}catch(t){e.task.raise(t,e)}};return n(!0),e.result()}loopWithFrame(t){const e=ci;if(!e)throw new Error("E_TASK_NO_CONTEXT");return this.loop(()=>{let n;do{const i=new xi(e,e.top);e.top=i,i.state=Ei.ACTIVE,t(i),n=i.result()}while(!n.isPending()&&n.get());return n})}suspend(t){if(this.checkEnvironment(),this.task.continuation)throw new Error("E_TASK_ALREADY_SUSPENDED");const e=new bi(this.task);return this.task.continuation=e,ci=null,this.task.waitTarget=t||null,e}}class xi extends Ti{constructor(t,e){super(t,e,"loop")}continueLoop(){this.finish(!0)}breakLoop(){this.finish(!1)}}class Ii{constructor(t,e){this.fetch=t,this.arrived=!1,this.resource=null,this.task=null,this.piggybacks=[],this.name=e}start(){if(!this.task){const t=this;this.task=di().getScheduler().run(()=>{const e=pi("Fetcher.run");return t.fetch().then(n=>{const i=t.piggybacks;if(t.arrived=!0,t.resource=n,t.task=null,t.piggybacks=[],i)for(let t=0;t<i.length;t++)try{i[t](n)}catch(t){h.error(t,"Error:")}e.finish(n)}),e.result()},this.name)}}piggyback(t){this.arrived?t(this.resource):this.piggybacks.push(t)}get(){return this.arrived?fi(this.resource):(this.start(),this.task.join())}hasArrived(){return this.arrived}}const vi=t=>{if(0==t.length)return fi(!0);if(1==t.length)return t[0].get().thenReturn(!0);const e=pi("waitForFetches");let n=0;return e.loop(()=>{for(;n<t.length;){const e=t[n++];if(!e.hasArrived())return e.get().thenReturn(!0)}return fi(!1)}).then(()=>{e.finish(!0)}),e.result()};function Pi(t,e){let n=null,i=null;"img"==t.localName&&(n=t.getAttribute("width"),i=t.getAttribute("height"));const o=new Ii(()=>{const o=pi("loadImage"),s=o.suspend(t);let r=!1;const a=e=>{r||(r=!0,"img"==t.localName&&(n||t.removeAttribute("width"),i||t.removeAttribute("height")),s.schedule(e?e.type:"timeout"))};return t.addEventListener("load",a,!1),t.addEventListener("error",a,!1),t.addEventListener("abort",a,!1),t.namespaceURI==k.SVG?(t.setAttributeNS(k.XLINK,"xlink:href",e),setTimeout(a,300)):t.src=e,o.result()},`loadElement ${e}`);return o.start(),o}var Ri,Ai='<!DOCTYPE html>\n<html xmlns="http://www.w3.org/1999/xhtml" xmlns:s="http://www.pyroxy.com/ns/shadow">\n<head>\n<style><![CDATA[\n\n.footnote-content {\n float: footnote;\n}\n\n.table-cell-container {\n display: block;\n}\n\n]]></style>\n</head>\n<body>\n\n<s:template id="footnote"><s:content/><s:include class="footnote-content"/></s:template>\n\n<s:template id="table-cell"><div data-vivliostyle-flow-root="true" class="table-cell-container"><s:content/></div></s:template>\n\n</body>\n</html>\n';function Li(t,e,n,i,o){const s=pi("ajax"),r=new XMLHttpRequest,a=s.suspend(r),l={status:0,statusText:"",url:t,contentType:null,responseText:null,responseXML:null,responseBlob:null};r.open(n||"GET",t,!0),e&&(r.responseType=e),r.onreadystatechange=()=>{if(4===r.readyState){if(l.status=r.status,l.statusText=r.statusText||404==r.status&&"Not Found"||"",200==l.status||0==l.status)if(e&&e!==Ri.DOCUMENT||!r.responseXML||"parsererror"==r.responseXML.documentElement.localName)if((!e||e===Ri.DOCUMENT)&&r.response instanceof HTMLDocument)l.responseXML=r.response,l.contentType=r.response.contentType;else{const n=r.response;e&&e!==Ri.TEXT||"string"!=typeof n?n?l.responseBlob="string"==typeof n?Oi([n]):n:h.warn("Unexpected empty success response for",t):l.responseText=n;const i=r.getResponseHeader("Content-Type");i&&(l.contentType=i.replace(/(.*);.*$/,"$1"))}else l.responseXML=r.responseXML,l.contentType=r.responseXML.contentType;a.schedule(l)}};try{i?(r.setRequestHeader("Content-Type",o||"text/plain; charset=UTF-8"),r.send(i)):(/^file:|^https?:\/\/[^/]+\.githubusercontent\.com|\.opf$/.test(t)?/\/aozorabunko\/[^/]+\/cards\/[^/]+\/files\/[^/.]+\.html$/.test(t)?r.overrideMimeType("text/html; charset=Shift_JIS"):/\.(html|htm)$/.test(t)?r.overrideMimeType("text/html; charset=UTF-8"):/\.(xhtml|xht|xml|opf)$/.test(t)?r.overrideMimeType("application/xml; charset=UTF-8"):/\.(txt|css)$/.test(t)?r.overrideMimeType("text/plain; charset=UTF-8"):r.overrideMimeType("text/html; charset=UTF-8"):/^data:,(<|%3C|%3c)/.test(t)?r.overrideMimeType("text/html; charset=UTF-8"):/^data:,/.test(t)&&r.overrideMimeType("text/plain; charset=UTF-8"),r.send(null))}catch(e){h.warn(e,`Error fetching ${t}`),a.schedule(l)}return s.result()}function Oi(t,e){const n=e||"application/octet-stream",i=window.WebKitBlobBuilder||window.MSBlobBuilder;if(i){const e=new i;for(let n=0;n<t.length;n++)e.append(t[n]);return e.getBlob(n)}return new Blob(t,{type:n})}!function(t){t.DEFAULT="",t.ARRAYBUFFER="arraybuffer",t.BLOB="blob",t.DOCUMENT="document",t.JSON="json",t.TEXT="text"}(Ri||(Ri={}));class ki{constructor(t,e){this.parser=t,this.type=e,this.resources={},this.fetchers={}}load(t,e,n){t=I(t);const i=this.resources[t];return void 0!==i?fi(i):this.fetch(t,e,n).get()}fetchInner(t,e,n){const i=this,o=pi("fetch"),s=t.endsWith("?viv-toc-box");s&&(t=t.replace("?viv-toc-box",""));const r=L("user-agent.xml",R),a=!s&&t===r;return a&&(t=`data:application/xml,${encodeURIComponent(Ai)}`),Li(t,i.type).then(l=>{if(l.status>=400&&e)throw new Error((n||`Failed to fetch required resource: ${t}`)+` (${l.status}${l.statusText?" "+l.statusText:""})`);s?(t+="?viv-toc-box",l.url+="?viv-toc-box"):a&&(l.url=t=r),i.parser(l,i).then(e=>{delete i.fetchers[t],i.resources[t]=e,o.finish(e)})}),o.result()}fetch(t,e,n){if(t=I(t),this.resources[t])return null;let i=this.fetchers[t];if(!i){const o=this;i=new Ii(()=>o.fetchInner(t,e,n),`Fetch ${t}`),o.fetchers[t]=i,i.start()}return i}get(t){return this.resources[I(t)]}delete(t){delete this.resources[I(t)]}}function Fi(t,e){const n=t.responseText;return fi(n?x(n):null)}const Di=0,_i=16777216,Bi=33554432,Mi=50331648,Ui=67108864,Vi=83886080,Hi=100663296;var zi;function Gi(t){let e=parseInt(t,16);if(isNaN(e))throw new Error("E_CSS_COLOR");if(6==t.length)return new Re(e);if(3==t.length)return e=15&e|(15&e)<<4|(240&e)<<4|(240&e)<<8|(3840&e)<<8|(3840&e)<<12,new Re(e);throw new Error("E_CSS_COLOR")}!function(t){t.USER_AGENT="UA",t.USER="User",t.AUTHOR="Author"}(zi||(zi={}));class $i{constructor(t){this.scope=t,this.flavor=zi.AUTHOR}getCurrentToken(){return null}getScope(){return this.scope}error(t,e){}startStylesheet(t){this.flavor=t}tagSelector(t,e){}classSelector(t){}pseudoclassSelector(t,e){}pseudoelementSelector(t,e){}idSelector(t){}attributeSelector(t,e,n,i){}descendantSelector(){}childSelector(){}adjacentSiblingSelector(){}followingSiblingSelector(){}nextSelector(){}startSelectorRule(){}startFontFaceRule(){}startFootnoteRule(t){}startViewportRule(){}startDefineRule(){}startRegionRule(){}startPageRule(){}startPageMarginBoxRule(t){}startWhenRule(t){}startMediaRule(t){this.startWhenRule(t)}startFlowRule(t){}startPageTemplateRule(){}startPageMasterRule(t,e,n){}startPartitionRule(t,e,n){}startPartitionGroupRule(t,e,n){}startRuleBody(){}property(t,e,n){}endRule(){}startFuncWithSelector(t){}endFuncWithSelector(){}getImportantSpecificity(){switch(this.flavor){case zi.USER_AGENT:return Di;case zi.USER:return Hi;default:return Vi}}getBaseSpecificity(){switch(this.flavor){case zi.USER_AGENT:return Di;case zi.USER:return _i;default:return Bi}}}class Wi extends $i{constructor(){super(null),this.stack=[],this.tokenizer=null,this.slave=null}pushHandler(t){this.stack.push(this.slave),this.slave=t}popHandler(){this.slave=this.stack.pop()}getCurrentToken(){return this.tokenizer?this.tokenizer.token():null}getScope(){return this.slave.getScope()}error(t,e){this.slave.error(t,e)}errorMsg(t,e){h.warn(t)}startStylesheet(t){super.startStylesheet(t),this.stack.length>0&&(this.slave=this.stack[0],this.stack=[]),this.slave.startStylesheet(t)}tagSelector(t,e){this.slave.tagSelector(t,e)}classSelector(t){this.slave.classSelector(t)}pseudoclassSelector(t,e){this.slave.pseudoclassSelector(t,e)}pseudoelementSelector(t,e){this.slave.pseudoelementSelector(t,e)}idSelector(t){this.slave.idSelector(t)}attributeSelector(t,e,n,i){this.slave.attributeSelector(t,e,n,i)}descendantSelector(){this.slave.descendantSelector()}childSelector(){this.slave.childSelector()}adjacentSiblingSelector(){this.slave.adjacentSiblingSelector()}followingSiblingSelector(){this.slave.followingSiblingSelector()}nextSelector(){this.slave.nextSelector()}startSelectorRule(){this.slave.startSelectorRule()}startFontFaceRule(){this.slave.startFontFaceRule()}startFootnoteRule(t){this.slave.startFootnoteRule(t)}startViewportRule(){this.slave.startViewportRule()}startDefineRule(){this.slave.startDefineRule()}startRegionRule(){this.slave.startRegionRule()}startPageRule(){this.slave.startPageRule()}startPageMarginBoxRule(t){this.slave.startPageMarginBoxRule(t)}startWhenRule(t){this.slave.startWhenRule(t)}startFlowRule(t){this.slave.startFlowRule(t)}startPageTemplateRule(){this.slave.startPageTemplateRule()}startPageMasterRule(t,e,n){this.slave.startPageMasterRule(t,e,n)}startPartitionRule(t,e,n){this.slave.startPartitionRule(t,e,n)}startPartitionGroupRule(t,e,n){this.slave.startPartitionGroupRule(t,e,n)}startRuleBody(){this.slave.startRuleBody()}property(t,e,n){this.slave.property(t,e,n)}endRule(){this.slave.endRule()}startFuncWithSelector(t){this.slave.startFuncWithSelector(t)}endFuncWithSelector(){this.slave.endFuncWithSelector()}}class Xi extends $i{constructor(t,e,n){super(t),this.owner=e,this.topLevel=n,this.depth=0,e&&(this.flavor=e.flavor)}getCurrentToken(){return this.owner.getCurrentToken()}error(t,e){this.owner.errorMsg(t,e)}startRuleBody(){this.depth++}endRule(){0!=--this.depth||this.topLevel||this.owner.popHandler()}}class Yi extends Xi{constructor(t,e,n){super(t,e,n)}report(t){this.error(t,this.getCurrentToken())}reportAndSkip(t){this.report(t),this.owner.pushHandler(new Xi(this.scope,this.owner,!1))}startSelectorRule(){this.reportAndSkip("E_CSS_UNEXPECTED_SELECTOR")}startFontFaceRule(){this.reportAndSkip("E_CSS_UNEXPECTED_FONT_FACE")}startFootnoteRule(t){this.reportAndSkip("E_CSS_UNEXPECTED_FOOTNOTE")}startViewportRule(){this.reportAndSkip("E_CSS_UNEXPECTED_VIEWPORT")}startDefineRule(){this.reportAndSkip("E_CSS_UNEXPECTED_DEFINE")}startRegionRule(){this.reportAndSkip("E_CSS_UNEXPECTED_REGION")}startPageRule(){this.reportAndSkip("E_CSS_UNEXPECTED_PAGE")}startWhenRule(t){this.reportAndSkip("E_CSS_UNEXPECTED_WHEN")}startFlowRule(t){this.reportAndSkip("E_CSS_UNEXPECTED_FLOW")}startPageTemplateRule(){this.reportAndSkip("E_CSS_UNEXPECTED_PAGE_TEMPLATE")}startPageMasterRule(t,e,n){this.reportAndSkip("E_CSS_UNEXPECTED_PAGE_MASTER")}startPartitionRule(t,e,n){this.reportAndSkip("E_CSS_UNEXPECTED_PARTITION")}startPartitionGroupRule(t,e,n){this.reportAndSkip("E_CSS_UNEXPECTED_PARTITION_GROUP")}startFuncWithSelector(t){this.reportAndSkip("E_CSS_UNEXPECTED_SELECTOR_FUNC")}endFuncWithSelector(){this.reportAndSkip("E_CSS_UNEXPECTED_END_SELECTOR_FUNC")}property(t,e,n){this.error("E_CSS_UNEXPECTED_PROPERTY",this.getCurrentToken())}}const Ki=[],ji=[],qi=[],Qi=[],Zi=[],Ji=[],to=[],eo=[],no=[],io=[],oo=[],so=[],ro=[];var ao;!function(t){t[t.SELECTOR_NAME_1=1]="SELECTOR_NAME_1",t[t.SELECTOR_NAME=2]="SELECTOR_NAME",t[t.SELECTOR_ANY_1=3]="SELECTOR_ANY_1",t[t.SELECTOR_ANY=4]="SELECTOR_ANY",t[t.SELECTOR_ID_1=5]="SELECTOR_ID_1",t[t.SELECTOR_ID=6]="SELECTOR_ID",t[t.SELECTOR_CLASS_1=7]="SELECTOR_CLASS_1",t[t.SELECTOR_CLASS=8]="SELECTOR_CLASS",t[t.SELECTOR_ATTR_1=9]="SELECTOR_ATTR_1",t[t.SELECTOR_ATTR=10]="SELECTOR_ATTR",t[t.SELECTOR_CHILD=11]="SELECTOR_CHILD",t[t.SELECTOR_SIBLING=12]="SELECTOR_SIBLING",t[t.SELECTOR_BODY=13]="SELECTOR_BODY",t[t.SELECTOR_PSEUDOCLASS=14]="SELECTOR_PSEUDOCLASS",t[t.VAL_IDENT=15]="VAL_IDENT",t[t.VAL_HASH=16]="VAL_HASH",t[t.VAL_NUM=17]="VAL_NUM",t[t.VAL_INT=18]="VAL_INT",t[t.VAL_NUMERIC=19]="VAL_NUMERIC",t[t.VAL_STR=20]="VAL_STR",t[t.VAL_URL=21]="VAL_URL",t[t.VAL_COMMA=22]="VAL_COMMA",t[t.VAL_SLASH=23]="VAL_SLASH",t[t.VAL_FUNC=24]="VAL_FUNC",t[t.VAL_C_PAR=25]="VAL_C_PAR",t[t.VAL_END=26]="VAL_END",t[t.RULE_END=27]="RULE_END",t[t.IDENT=28]="IDENT",t[t.SELECTOR_START=29]="SELECTOR_START",t[t.AT=30]="AT",t[t.EXPR_IDENT=31]="EXPR_IDENT",t[t.EXPR_NUM=32]="EXPR_NUM",t[t.EXPR_NUMERIC=33]="EXPR_NUMERIC",t[t.EXPR_STR=34]="EXPR_STR",t[t.EXPR_PARAM=35]="EXPR_PARAM",t[t.EXPR_PREFIX=36]="EXPR_PREFIX",t[t.EXPR_INFIX=37]="EXPR_INFIX",t[t.EXPR_FUNC=38]="EXPR_FUNC",t[t.EXPR_C_PAR=39]="EXPR_C_PAR",t[t.EXPR_O_PAR=40]="EXPR_O_PAR",t[t.SELECTOR_NEXT=41]="SELECTOR_NEXT",t[t.SELECTOR_PSEUDOELEM=42]="SELECTOR_PSEUDOELEM",t[t.EXPR_O_BRC=43]="EXPR_O_BRC",t[t.VAL_FINISH=44]="VAL_FINISH",t[t.EXPR_INFIX_NAME=45]="EXPR_INFIX_NAME",t[t.PROP=46]="PROP",t[t.VAL_BANG=47]="VAL_BANG",t[t.VAL_BRC=48]="VAL_BRC",t[t.EXPR_SEMICOL=49]="EXPR_SEMICOL",t[t.ERROR_PUSH=50]="ERROR_PUSH",t[t.ERROR_POP=51]="ERROR_POP",t[t.ERROR_POP_DECL=52]="ERROR_POP_DECL",t[t.ERROR_SEMICOL=53]="ERROR_SEMICOL",t[t.VAL_PLUS=54]="VAL_PLUS",t[t.SELECTOR_PSEUDOCLASS_1=55]="SELECTOR_PSEUDOCLASS_1",t[t.SELECTOR_FOLLOWING_SIBLING=56]="SELECTOR_FOLLOWING_SIBLING",t[t.DONE=200]="DONE"}(ao||(ao={}));const lo=An.LAST+1;var ho;Ki[An.IDENT]=ao.IDENT,Ki[An.STAR]=ao.SELECTOR_START,Ki[An.HASH]=ao.SELECTOR_START,Ki[An.CLASS]=ao.SELECTOR_START,Ki[An.O_BRK]=ao.SELECTOR_START,Ki[An.COLON]=ao.SELECTOR_START,Ki[An.AT]=ao.AT,Ki[An.C_BRC]=ao.RULE_END,Ki[An.EOF]=ao.DONE,ji[An.IDENT]=ao.PROP,ji[An.EOF]=ao.DONE,Ji[An.IDENT]=ao.SELECTOR_NAME,Ji[An.STAR]=ao.SELECTOR_ANY,Ji[An.HASH]=ao.SELECTOR_ID,Ji[An.CLASS]=ao.SELECTOR_CLASS,Ji[An.O_BRK]=ao.SELECTOR_ATTR,Ji[An.COLON]=ao.SELECTOR_PSEUDOCLASS,qi[An.GT]=ao.SELECTOR_CHILD,qi[An.PLUS]=ao.SELECTOR_SIBLING,qi[An.TILDE]=ao.SELECTOR_FOLLOWING_SIBLING,qi[An.IDENT]=ao.SELECTOR_NAME_1,qi[An.STAR]=ao.SELECTOR_ANY_1,qi[An.HASH]=ao.SELECTOR_ID_1,qi[An.CLASS]=ao.SELECTOR_CLASS_1,qi[An.O_BRK]=ao.SELECTOR_ATTR_1,qi[An.O_BRC]=ao.SELECTOR_BODY,qi[An.COLON]=ao.SELECTOR_PSEUDOCLASS_1,qi[An.COL_COL]=ao.SELECTOR_PSEUDOELEM,qi[An.COMMA]=ao.SELECTOR_NEXT,Qi[An.IDENT]=ao.SELECTOR_NAME_1,Qi[An.STAR]=ao.SELECTOR_ANY_1,Qi[An.HASH]=ao.SELECTOR_ID_1,Qi[An.CLASS]=ao.SELECTOR_CLASS_1,Qi[An.O_BRK]=ao.SELECTOR_ATTR_1,Qi[An.C_PAR]=ao.DONE,Qi[An.COLON]=ao.SELECTOR_PSEUDOCLASS_1,Zi[An.IDENT]=ao.SELECTOR_NAME,Zi[An.STAR]=ao.SELECTOR_ANY,Zi[An.HASH]=ao.SELECTOR_ID,Zi[An.CLASS]=ao.SELECTOR_CLASS,Zi[An.COLON]=ao.SELECTOR_PSEUDOCLASS,Zi[An.COL_COL]=ao.SELECTOR_PSEUDOELEM,Zi[An.O_BRK]=ao.SELECTOR_ATTR,Zi[An.O_BRC]=ao.SELECTOR_BODY,to[An.IDENT]=ao.VAL_IDENT,to[An.HASH]=ao.VAL_HASH,to[An.NUM]=ao.VAL_NUM,to[An.INT]=ao.VAL_INT,to[An.NUMERIC]=ao.VAL_NUMERIC,to[An.STR]=ao.VAL_STR,to[An.URL]=ao.VAL_URL,to[An.COMMA]=ao.VAL_COMMA,to[An.SLASH]=ao.VAL_SLASH,to[An.FUNC]=ao.VAL_FUNC,to[An.C_PAR]=ao.VAL_C_PAR,to[An.SEMICOL]=ao.VAL_END,to[An.C_BRC]=ao.VAL_BRC,to[An.BANG]=ao.VAL_BANG,to[An.PLUS]=ao.VAL_PLUS,to[An.EOF]=ao.VAL_FINISH,eo[An.IDENT]=ao.EXPR_IDENT,eo[An.NUM]=ao.EXPR_NUM,eo[An.INT]=ao.EXPR_NUM,eo[An.NUMERIC]=ao.EXPR_NUMERIC,eo[An.STR]=ao.EXPR_STR,eo[An.O_PAR]=ao.EXPR_O_PAR,eo[An.FUNC]=ao.EXPR_FUNC,eo[An.BANG]=ao.EXPR_PREFIX,eo[An.MINUS]=ao.EXPR_PREFIX,eo[An.DOLLAR]=ao.EXPR_PARAM,no[An.IDENT]=ao.EXPR_INFIX_NAME,no[An.COMMA]=ao.EXPR_INFIX,no[An.GT]=ao.EXPR_INFIX,no[An.LT]=ao.EXPR_INFIX,no[An.GT_EQ]=ao.EXPR_INFIX,no[An.LT_EQ]=ao.EXPR_INFIX,no[An.EQ]=ao.EXPR_INFIX,no[An.EQ_EQ]=ao.EXPR_INFIX,no[An.BANG_EQ]=ao.EXPR_INFIX,no[An.AMP_AMP]=ao.EXPR_INFIX,no[An.BAR_BAR]=ao.EXPR_INFIX,no[An.PLUS]=ao.EXPR_INFIX,no[An.MINUS]=ao.EXPR_INFIX,no[An.SLASH]=ao.EXPR_INFIX,no[An.PERCENT]=ao.EXPR_INFIX,no[An.STAR]=ao.EXPR_INFIX,no[An.COLON]=ao.EXPR_INFIX,no[An.QMARK]=ao.EXPR_INFIX,no[An.C_PAR]=ao.EXPR_C_PAR,no[An.O_BRC]=ao.EXPR_O_BRC,no[An.SEMICOL]=ao.EXPR_SEMICOL,io[An.EOF]=ao.DONE,io[An.O_BRC]=ao.ERROR_PUSH,io[An.C_BRC]=ao.ERROR_POP,io[An.O_BRK]=ao.ERROR_PUSH,io[An.C_BRK]=ao.ERROR_POP,io[An.O_PAR]=ao.ERROR_PUSH,io[An.C_PAR]=ao.ERROR_POP,io[An.SEMICOL]=ao.ERROR_SEMICOL,oo[An.EOF]=ao.DONE,oo[An.O_BRC]=ao.ERROR_PUSH,oo[An.C_BRC]=ao.ERROR_POP_DECL,oo[An.O_BRK]=ao.ERROR_PUSH,oo[An.C_BRK]=ao.ERROR_POP,oo[An.O_PAR]=ao.ERROR_PUSH,oo[An.C_PAR]=ao.ERROR_POP,oo[An.SEMICOL]=ao.ERROR_SEMICOL,so[An.EOF]=ao.DONE,so[An.O_BRC]=ao.ERROR_PUSH,so[An.C_BRC]=ao.ERROR_POP,so[An.O_BRK]=ao.ERROR_PUSH,so[An.C_BRK]=ao.ERROR_POP,so[An.O_PAR]=ao.ERROR_PUSH,so[An.C_PAR]=ao.ERROR_POP,ro[An.C_PAR]=0,ro[An.COMMA]=0,ro[An.QMARK]=1,ro[An.COLON]=1,ro[An.AMP_AMP]=2,ro[An.BAR_BAR]=2,ro[An.LT]=3,ro[An.GT]=3,ro[An.LT_EQ]=3,ro[An.GT_EQ]=3,ro[An.EQ]=3,ro[An.EQ_EQ]=3,ro[An.BANG_EQ]=3,ro[An.PLUS]=4,ro[An.MINUS]=4,ro[An.STAR]=5,ro[An.SLASH]=5,ro[An.PERCENT]=5,ro[An.EOF]=6,ro[lo]=2,function(t){t[t.PROP=0]="PROP",t[t.WHEN=1]="WHEN",t[t.MEDIA=2]="MEDIA",t[t.IMPORT=3]="IMPORT"}(ho||(ho={}));class co{constructor(t,e,n,i){this.actions=t,this.tokenizer=e,this.handler=n,this.baseURL=i,this.valStack=[],this.namespacePrefixToURI={},this.defaultNamespaceURI=null,this.propName=null,this.propImportant=!1,this.result=null,this.importReady=!1,this.importURL=null,this.importCondition=null,this.errorBrackets=[],this.ruleStack=[],this.regionRule=!1,this.pageRule=!1,this.exprContext=ho.MEDIA}extractVals(t,e){const n=[],i=this.valStack;for(;n.push(i[e++]),e!=i.length;)if(i[e++]!=t)throw new Error("Unexpected state");return n}valStackReduce(t,e){const n=this.valStack;let i,o=n.length;do{i=n[--o]}while(void 0!==i&&"string"!=typeof i);let s=n.length-(o+1);if(s>1&&n.splice(o+1,s,new Oe(n.slice(o+1,n.length))),","==t)return null;o++;do{i=n[--o]}while(void 0!==i&&("string"!=typeof i||","==i));if(s=n.length-(o+1),"("==i){if(")"!=t)return this.handler.error("E_CSS_MISMATCHED_C_PAR",e),this.actions=oo,null;const i=new Fe(n[o-1],this.extractVals(",",o+1));return n.splice(o-1,s+2,i),null}return";"!=t||o>=0?(this.handler.error("E_CSS_UNEXPECTED_VAL_END",e),this.actions=oo,null):s>1?new ke(this.extractVals(",",o+1)):n[0]}exprError(t,e){this.actions=this.propName?oo:io,this.handler.error(t,e)}exprStackReduce(t,e){const n=this.valStack,i=this.handler;let o,s=n.pop();for(;;){let r=n.pop();if(t==An.C_PAR){const e=[s];for(;r==An.COMMA;)e.unshift(n.pop()),r=n.pop();if("string"==typeof r){if("{"==r){for(;e.length>=2;){const t=e.shift(),n=e.shift(),o=new Gt(i.getScope(),t,n);e.unshift(o)}return n.push(new De(e[0])),!0}if("("==r){const o=n.pop(),r=n.pop();s=new se(i.getScope(),Tt(r,o),e),t=An.EOF;continue}}if(r==An.O_PAR){s.isMediaName()&&(s=new le(i.getScope(),s,null)),t=An.EOF;continue}}else if("string"==typeof r){n.push(r);break}if(r<0)if(r==-An.BANG)s=new Mt(i.getScope(),s);else{if(r!=-An.MINUS)return this.exprError("F_UNEXPECTED_STATE",e),!1;s=new Ut(i.getScope(),s)}else{if(ro[t]>ro[r]){n.push(r);break}switch(o=n.pop(),r){case An.AMP_AMP:s=new Vt(i.getScope(),o,s);break;case lo:s=new Ht(i.getScope(),o,s);break;case An.BAR_BAR:s=new zt(i.getScope(),o,s);break;case An.LT:s=new $t(i.getScope(),o,s);break;case An.GT:s=new Xt(i.getScope(),o,s);break;case An.LT_EQ:s=new Wt(i.getScope(),o,s);break;case An.GT_EQ:s=new Yt(i.getScope(),o,s);break;case An.EQ:case An.EQ_EQ:s=new Kt(i.getScope(),o,s);break;case An.BANG_EQ:s=new jt(i.getScope(),o,s);break;case An.PLUS:s=new qt(i.getScope(),o,s);break;case An.MINUS:s=new Qt(i.getScope(),o,s);break;case An.STAR:s=new Zt(i.getScope(),o,s);break;case An.SLASH:s=new Jt(i.getScope(),o,s);break;case An.PERCENT:s=new te(i.getScope(),o,s);break;case An.COLON:if(!(n.length>1))return this.exprError("E_CSS_EXPR_COND",e),!1;switch(n[n.length-1]){case An.QMARK:n.pop(),s=new re(i.getScope(),n.pop(),o,s);break;case An.O_PAR:if(!o.isMediaName())return this.exprError("E_CSS_MEDIA_TEST",e),!1;s=new le(i.getScope(),o,s)}break;case An.QMARK:if(t!=An.COLON)return this.exprError("E_CSS_EXPR_COND",e),!1;case An.O_PAR:return n.push(o),n.push(r),n.push(s),!1;default:return this.exprError("F_UNEXPECTED_STATE",e),!1}}}return n.push(s),!1}readPseudoParams(){const t=[];for(;;){const e=this.tokenizer.token();switch(e.type){case An.IDENT:t.push(e.text);break;case An.PLUS:t.push("+");break;case An.NUM:case An.INT:t.push(e.num);break;default:return t}this.tokenizer.consume()}}readNthPseudoParams(){let t=!1,e=this.tokenizer.token();if(e.type===An.PLUS)t=!0,this.tokenizer.consume(),e=this.tokenizer.token();else if(e.type===An.IDENT&&("even"===e.text||"odd"===e.text))return this.tokenizer.consume(),[2,"odd"===e.text?1:0];switch(e.type){case An.NUMERIC:if(t&&e.num<0)return null;case An.IDENT:if(t&&"-"===e.text.charAt(0))return null;if("n"===e.text||"-n"===e.text){if(t&&e.precededBySpace)return null;let n="-n"===e.text?-1:1;e.type===An.NUMERIC&&(n=e.num);let i=0;this.tokenizer.consume(),e=this.tokenizer.token();const o=e.type===An.MINUS,s=e.type===An.PLUS||o;if(s&&(this.tokenizer.consume(),e=this.tokenizer.token()),e.type===An.INT){if(i=e.num,1/i==-1/0){if(i=0,s)return null}else if(i<0){if(s)return null}else if(i>=0&&!s)return null;this.tokenizer.consume()}else if(s)return null;return[n,o&&i>0?-i:i]}if("n-"===e.text||"-n-"===e.text){if(t&&e.precededBySpace)return null;let n="-n-"===e.text?-1:1;if(e.type===An.NUMERIC&&(n=e.num),this.tokenizer.consume(),e=this.tokenizer.token(),e.type===An.INT)return e.num<0||1/e.num==-1/0?null:(this.tokenizer.consume(),[n,e.num])}else{let n=e.text.match(/^n(-[0-9]+)$/);if(n)return t&&e.precededBySpace?null:(this.tokenizer.consume(),[e.type===An.NUMERIC?e.num:1,parseInt(n[1],10)]);if(n=e.text.match(/^-n(-[0-9]+)$/),n)return this.tokenizer.consume(),[-1,parseInt(n[1],10)]}return null;case An.INT:return t&&(e.precededBySpace||e.num<0)?null:(this.tokenizer.consume(),[0,e.num])}return null}makeCondition(t,e){const n=this.handler.getScope();if(!n)return null;if(e=e||n._true,t){const i=t.split(/\s+/);for(const t of i)switch(t){case"vertical":e=ce(n,e,new Mt(n,new ne(n,"pref-horizontal")));break;case"horizontal":e=ce(n,e,new ne(n,"pref-horizontal"));break;case"day":e=ce(n,e,new Mt(n,new ne(n,"pref-night-mode")));break;case"night":e=ce(n,e,new ne(n,"pref-night-mode"));break;default:e=n._false}}return e===n._true?null:new De(e)}isInsidePropertyOnlyRule(){switch(this.ruleStack[this.ruleStack.length-1]){case"[selector]":case"font-face":case"-epubx-flow":case"-epubx-viewport":case"-epubx-define":case"-adapt-footnote-area":return!0}return!1}runParser(t,e,n,i,o){const s=this.handler,r=this.tokenizer,a=this.valStack;let l,h,c,u,d,p,f;i&&(this.exprContext=ho.MEDIA,this.valStack.push("{"));t:for(;t>0;--t)switch(l=r.token(),this.actions[l.type]){case ao.IDENT:if(r.nthToken(1).type!=An.COLON){this.isInsidePropertyOnlyRule()?(s.error("E_CSS_COLON_EXPECTED",r.nthToken(1)),this.actions=oo):(this.actions=Ji,s.startSelectorRule());continue}h=r.nthToken(2),h.precededBySpace||h.type!=An.IDENT&&h.type!=An.FUNC||r.mark(),this.propName=l.text,this.propImportant=!1,r.consume(),r.consume(),this.actions=to,a.splice(0,a.length);continue;case ao.PROP:if(r.nthToken(1).type!=An.COLON){this.actions=oo,s.error("E_CSS_COLON_EXPECTED",r.nthToken(1));continue}this.propName=l.text,this.propImportant=!1,r.consume(),r.consume(),this.actions=to,a.splice(0,a.length);continue;case ao.SELECTOR_START:this.actions=Ji,s.startSelectorRule();continue;case ao.SELECTOR_NAME_1:if(!l.precededBySpace){this.actions=so,s.error("E_CSS_SPACE_EXPECTED",l);continue}s.descendantSelector();case ao.SELECTOR_NAME:if(r.nthToken(1).type==An.BAR)if(r.consume(),r.consume(),c=this.namespacePrefixToURI[l.text],null!=c)switch(l=r.token(),l.type){case An.IDENT:s.tagSelector(c,l.text),this.actions=o?Qi:qi,r.consume();break;case An.STAR:s.tagSelector(c,null),this.actions=o?Qi:qi,r.consume();break;default:this.actions=io,s.error("E_CSS_NAMESPACE",l)}else this.actions=io,s.error("E_CSS_UNDECLARED_PREFIX",l);else s.tagSelector(this.defaultNamespaceURI,l.text),this.actions=o?Qi:qi,r.consume();continue;case ao.SELECTOR_ANY_1:if(!l.precededBySpace){this.actions=so,s.error("E_CSS_SPACE_EXPECTED",l);continue}s.descendantSelector();case ao.SELECTOR_ANY:if(r.nthToken(1).type==An.BAR)switch(r.consume(),r.consume(),l=r.token(),l.type){case An.IDENT:s.tagSelector(null,l.text),this.actions=o?Qi:qi,r.consume();break;case An.STAR:s.tagSelector(null,null),this.actions=o?Qi:qi,r.consume();break;default:this.actions=io,s.error("E_CSS_NAMESPACE",l)}else s.tagSelector(this.defaultNamespaceURI,null),this.actions=o?Qi:qi,r.consume();continue;case ao.SELECTOR_ID_1:l.precededBySpace&&s.descendantSelector();case ao.SELECTOR_ID:s.idSelector(l.text),this.actions=o?Qi:qi,r.consume();continue;case ao.SELECTOR_CLASS_1:l.precededBySpace&&s.descendantSelector();case ao.SELECTOR_CLASS:s.classSelector(l.text),this.actions=o?Qi:qi,r.consume();continue;case ao.SELECTOR_PSEUDOCLASS_1:l.precededBySpace&&s.descendantSelector();case ao.SELECTOR_PSEUDOCLASS:r.consume(),l=r.token();e:switch(l.type){case An.IDENT:s.pseudoclassSelector(l.text,null),r.consume(),this.actions=o?Qi:qi;continue;case An.FUNC:switch(u=l.text,r.consume(),u){case"not":this.actions=Ji,s.startFuncWithSelector("not"),this.runParser(Number.POSITIVE_INFINITY,!1,!1,!1,!0)?this.actions=qi:this.actions=so;break t;case"lang":case"href-epub-type":if(l=r.token(),l.type===An.IDENT){f=[l.text],r.consume();break}break e;case"nth-child":case"nth-of-type":case"nth-last-child":case"nth-last-of-type":if(f=this.readNthPseudoParams(),f)break;break e;default:f=this.readPseudoParams()}if(l=r.token(),l.type==An.C_PAR){s.pseudoclassSelector(u,f),r.consume(),this.actions=o?Qi:qi;continue}}s.error("E_CSS_PSEUDOCLASS_SYNTAX",l),this.actions=io;continue;case ao.SELECTOR_PSEUDOELEM:switch(r.consume(),l=r.token(),l.type){case An.IDENT:s.pseudoelementSelector(l.text,null),this.actions=o?Qi:qi,r.consume();continue;case An.FUNC:if(u=l.text,r.consume(),"nth-fragment"==u){if(f=this.readNthPseudoParams(),null===f)break}else f=this.readPseudoParams();if(l=r.token(),l.type==An.C_PAR){s.pseudoelementSelector(u,f),this.actions=o?Qi:qi,r.consume();continue}}s.error("E_CSS_PSEUDOELEM_SYNTAX",l),this.actions=io;continue;case ao.SELECTOR_ATTR_1:l.precededBySpace&&s.descendantSelector();case ao.SELECTOR_ATTR:if(r.consume(),l=r.token(),l.type==An.IDENT)u=l.text,r.consume();else if(l.type==An.STAR)u=null,r.consume();else{if(l.type!=An.BAR){this.actions=so,s.error("E_CSS_ATTR",l),r.consume();continue}u=""}if(l=r.token(),l.type==An.BAR){if(c=u?this.namespacePrefixToURI[u]:u,null==c){this.actions=so,s.error("E_CSS_UNDECLARED_PREFIX",l),r.consume();continue}if(r.consume(),l=r.token(),l.type!=An.IDENT){this.actions=so,s.error("E_CSS_ATTR_NAME_EXPECTED",l);continue}u=l.text,r.consume(),l=r.token()}else c="";switch(l.type){case An.EQ:case An.TILDE_EQ:case An.BAR_EQ:case An.HAT_EQ:case An.DOLLAR_EQ:case An.STAR_EQ:case An.COL_COL:d=l.type,r.consume(),l=r.token();break;case An.C_BRK:s.attributeSelector(c,u,An.EOF,null),this.actions=o?Qi:qi,r.consume();continue;default:this.actions=so,s.error("E_CSS_ATTR_OP_EXPECTED",l);continue}switch(l.type){case An.IDENT:case An.STR:s.attributeSelector(c,u,d,l.text),r.consume(),l=r.token();break;default:this.actions=so,s.error("E_CSS_ATTR_VAL_EXPECTED",l);continue}if(l.type!=An.C_BRK){this.actions=so,s.error("E_CSS_ATTR",l);continue}this.actions=o?Qi:qi,r.consume();continue;case ao.SELECTOR_CHILD:s.childSelector(),this.actions=Zi,r.consume();continue;case ao.SELECTOR_SIBLING:s.adjacentSiblingSelector(),this.actions=Zi,r.consume();continue;case ao.SELECTOR_FOLLOWING_SIBLING:s.followingSiblingSelector(),this.actions=Zi,r.consume();continue;case ao.SELECTOR_BODY:this.regionRule?(this.ruleStack.push("-epubx-region"),this.regionRule=!1):this.pageRule?(this.ruleStack.push("page"),this.pageRule=!1):this.ruleStack.push("[selector]"),s.startRuleBody(),this.actions=Ki,r.consume();continue;case ao.SELECTOR_NEXT:s.nextSelector(),this.actions=Ji,r.consume();continue;case ao.VAL_IDENT:a.push(xe(l.text)),r.consume();continue;case ao.VAL_HASH:d=parseInt(l.text,16);try{a.push(Gi(l.text))}catch(t){s.error("E_CSS_COLOR",l),this.actions=io}r.consume();continue;case ao.VAL_NUM:a.push(new ve(l.num)),r.consume();continue;case ao.VAL_INT:a.push(new Pe(l.num)),r.consume();continue;case ao.VAL_NUMERIC:vt(l.text)?a.push(new De(new ee(s.getScope(),l.num,l.text))):a.push(new Ie(l.num,l.text)),r.consume();continue;case ao.VAL_STR:a.push(new ye(l.text)),r.consume();continue;case ao.VAL_URL:a.push(new Ae(L(l.text,this.baseURL))),r.consume();continue;case ao.VAL_COMMA:this.valStackReduce(",",l),a.push(","),r.consume();continue;case ao.VAL_SLASH:a.push(Se),r.consume();continue;case ao.VAL_FUNC:u=l.text.toLowerCase(),"-epubx-expr"==u||"calc"==u||"env"==u?(this.actions=eo,this.exprContext=ho.PROP,a.push("{")):(a.push(u),a.push("(")),r.consume();continue;case ao.VAL_C_PAR:this.valStackReduce(")",l),r.consume();continue;case ao.VAL_BANG:if(r.consume(),l=r.token(),h=r.nthToken(1),l.type==An.IDENT&&"important"==l.text.toLowerCase()&&(h.type==An.SEMICOL||h.type==An.EOF||h.type==An.C_BRC)){r.consume(),this.propImportant=!0;continue}this.exprError("E_CSS_SYNTAX",l);continue;case ao.VAL_PLUS:switch(h=r.nthToken(1),h.type){case An.NUM:case An.NUMERIC:case An.INT:if(!h.precededBySpace){r.consume();continue}}if(this.actions===to&&r.hasMark()){r.reset(),this.actions=Ji,s.startSelectorRule();continue}this.exprError("E_CSS_UNEXPECTED_PLUS",l);continue;case ao.VAL_END:r.consume();case ao.VAL_BRC:r.unmark(),p=this.valStackReduce(";",l),p&&this.propName&&s.property(this.propName,p,this.propImportant),this.actions=n?ji:Ki;continue;case ao.VAL_FINISH:if(r.consume(),r.unmark(),p=this.valStackReduce(";",l),e)return this.result=p,!0;if(this.propName&&p&&s.property(this.propName,p,this.propImportant),n)return!0;this.exprError("E_CSS_SYNTAX",l);continue;case ao.EXPR_IDENT:h=r.nthToken(1),h.type==An.CLASS?(r.nthToken(2).type!=An.O_PAR||r.nthToken(2).precededBySpace?(a.push(new ne(s.getScope(),Tt(l.text,h.text))),this.actions=no):(a.push(l.text,h.text,"("),r.consume()),r.consume()):(this.exprContext==ho.MEDIA||this.exprContext==ho.IMPORT?"not"==l.text.toLowerCase()?(r.consume(),a.push(new ie(s.getScope(),!0,h.text))):("only"==l.text.toLowerCase()&&(r.consume(),l=h),a.push(new ie(s.getScope(),!1,l.text))):a.push(new ne(s.getScope(),l.text)),this.actions=no),r.consume();continue;case ao.EXPR_FUNC:a.push(null,l.text,"("),r.consume();continue;case ao.EXPR_NUM:a.push(new ae(s.getScope(),l.num)),r.consume(),this.actions=no;continue;case ao.EXPR_NUMERIC:u=l.text,"%"==u&&(u=this.propName&&this.propName.match(/height|^(top|bottom)$/)?"vh":"vw"),a.push(new ee(s.getScope(),l.num,u)),r.consume(),this.actions=no;continue;case ao.EXPR_STR:a.push(new ae(s.getScope(),l.text)),r.consume(),this.actions=no;continue;case ao.EXPR_PARAM:r.consume(),l=r.token(),l.type!=An.INT||l.precededBySpace?this.exprError("E_CSS_SYNTAX",l):(a.push(new he(s.getScope(),l.num)),r.consume(),this.actions=no);continue;case ao.EXPR_PREFIX:a.push(-l.type),r.consume();continue;case ao.EXPR_INFIX:this.actions=eo,this.exprStackReduce(l.type,l),a.push(l.type),r.consume();continue;case ao.EXPR_INFIX_NAME:"and"==l.text.toLowerCase()?(this.actions=eo,this.exprStackReduce(lo,l),a.push(lo),r.consume()):this.exprError("E_CSS_SYNTAX",l);continue;case ao.EXPR_C_PAR:this.exprStackReduce(l.type,l)&&(this.propName?this.actions=to:this.exprError("E_CSS_UNBALANCED_PAR",l)),r.consume();continue;case ao.EXPR_O_BRC:this.exprStackReduce(An.C_PAR,l)&&(this.propName||this.exprContext==ho.IMPORT?this.exprError("E_CSS_UNEXPECTED_BRC",l):(this.exprContext==ho.WHEN?s.startWhenRule(a.pop()):s.startMediaRule(a.pop()),this.ruleStack.push("media"),s.startRuleBody(),this.actions=Ki)),r.consume();continue;case ao.EXPR_SEMICOL:if(this.exprStackReduce(An.C_PAR,l)){if(!this.propName&&this.exprContext==ho.IMPORT)return this.importCondition=a.pop(),this.importReady=!0,this.actions=Ki,r.consume(),!1;this.exprError("E_CSS_UNEXPECTED_SEMICOL",l)}r.consume();continue;case ao.EXPR_O_PAR:a.push(l.type),r.consume();continue;case ao.RULE_END:this.actions=Ki,r.consume(),s.endRule(),this.ruleStack.length&&this.ruleStack.pop();continue;case ao.AT:switch(u=l.text.toLowerCase(),u){case"import":if(r.consume(),l=r.token(),l.type==An.STR||l.type==An.URL){if(this.importURL=l.text,r.consume(),l=r.token(),l.type==An.SEMICOL||l.type==An.EOF)return this.importReady=!0,r.consume(),!1;this.propName=null,this.exprContext=ho.IMPORT,this.actions=eo,a.push("{");continue}s.error("E_CSS_IMPORT_SYNTAX",l),this.actions=io;continue;case"namespace":switch(r.consume(),l=r.token(),l.type){case An.IDENT:if(u=l.text,r.consume(),l=r.token(),(l.type==An.STR||l.type==An.URL)&&r.nthToken(1).type==An.SEMICOL){this.namespacePrefixToURI[u]=l.text,r.consume(),r.consume();continue}break;case An.STR:case An.URL:if(r.nthToken(1).type==An.SEMICOL){this.defaultNamespaceURI=l.text,r.consume(),r.consume();continue}}s.error("E_CSS_NAMESPACE_SYNTAX",l),this.actions=io;continue;case"charset":if(r.consume(),l=r.token(),l.type==An.STR&&r.nthToken(1).type==An.SEMICOL){u=l.text.toLowerCase(),"utf-8"!=u&&"utf-16"!=u&&s.error(`E_CSS_UNEXPECTED_CHARSET ${u}`,l),r.consume(),r.consume();continue}s.error("E_CSS_CHARSET_SYNTAX",l),this.actions=io;continue;case"font-face":case"-epubx-page-template":case"-epubx-define":case"-epubx-viewport":if(r.nthToken(1).type==An.O_BRC){switch(r.consume(),r.consume(),u){case"font-face":s.startFontFaceRule();break;case"-epubx-page-template":s.startPageTemplateRule();break;case"-epubx-define":s.startDefineRule();break;case"-epubx-viewport":s.startViewportRule()}this.ruleStack.push(u),s.startRuleBody();continue}break;case"-adapt-footnote-area":switch(r.consume(),l=r.token(),l.type){case An.O_BRC:r.consume(),s.startFootnoteRule(null),this.ruleStack.push(u),s.startRuleBody();continue;case An.COL_COL:if(r.consume(),l=r.token(),l.type==An.IDENT&&r.nthToken(1).type==An.O_BRC){u=l.text,r.consume(),r.consume(),s.startFootnoteRule(u),this.ruleStack.push("-adapt-footnote-area"),s.startRuleBody();continue}}break;case"-epubx-region":r.consume(),s.startRegionRule(),this.regionRule=!0,this.actions=Ji;continue;case"page":r.consume(),s.startPageRule(),this.pageRule=!0,this.actions=Zi;continue;case"top-left-corner":case"top-left":case"top-center":case"top-right":case"top-right-corner":case"right-top":case"right-middle":case"right-bottom":case"bottom-right-corner":case"bottom-right":case"bottom-center":case"bottom-left":case"bottom-left-corner":case"left-bottom":case"left-middle":case"left-top":if(r.consume(),l=r.token(),l.type==An.O_BRC){r.consume(),s.startPageMarginBoxRule(u),this.ruleStack.push(u),s.startRuleBody();continue}break;case"-epubx-when":r.consume(),this.propName=null,this.exprContext=ho.WHEN,this.actions=eo,a.push("{");continue;case"media":r.consume(),this.propName=null,this.exprContext=ho.MEDIA,this.actions=eo,a.push("{");continue;case"-epubx-flow":if(r.nthToken(1).type==An.IDENT&&r.nthToken(2).type==An.O_BRC){s.startFlowRule(r.nthToken(1).text),r.consume(),r.consume(),r.consume(),this.ruleStack.push(u),s.startRuleBody();continue}break;case"-epubx-page-master":case"-epubx-partition":case"-epubx-partition-group":{r.consume(),l=r.token();let t=null,e=null;const n=[];for(l.type==An.IDENT&&(t=l.text,r.consume(),l=r.token()),l.type==An.COLON&&r.nthToken(1).type==An.IDENT&&(e=r.nthToken(1).text,r.consume(),r.consume(),l=r.token());l.type==An.FUNC&&"class"==l.text.toLowerCase()&&r.nthToken(1).type==An.IDENT&&r.nthToken(2).type==An.C_PAR;)n.push(r.nthToken(1).text),r.consume(),r.consume(),r.consume(),l=r.token();if(l.type==An.O_BRC){switch(r.consume(),u){case"-epubx-page-master":s.startPageMasterRule(t,e,n);break;case"-epubx-partition":s.startPartitionRule(t,e,n);break;case"-epubx-partition-group":s.startPartitionGroupRule(t,e,n)}this.ruleStack.push(u),s.startRuleBody();continue}break}case"":s.error(`E_CSS_UNEXPECTED_AT${u}`,l),this.actions=so;continue;default:s.error(`E_CSS_AT_UNKNOWN ${u}`,l),this.actions=io;continue}s.error(`E_CSS_AT_SYNTAX ${u}`,l),this.actions=io;continue;case ao.ERROR_PUSH:if(e||n)return!0;this.errorBrackets.push(l.type+1),r.consume();continue;case ao.ERROR_POP_DECL:if(e||n)return!0;if(0==this.errorBrackets.length){this.actions=Ki;continue}case ao.ERROR_POP:this.errorBrackets.length>0&&this.errorBrackets[this.errorBrackets.length-1]==l.type&&this.errorBrackets.pop(),0==this.errorBrackets.length&&l.type==An.C_BRC&&(this.actions=Ki),r.consume();continue;case ao.ERROR_SEMICOL:if(e||n)return!0;0==this.errorBrackets.length&&(this.actions=Ki),r.consume();continue;case ao.DONE:return o&&(r.consume(),s.endFuncWithSelector()),!0;default:if(e||n)return!0;if(i)return!!this.exprStackReduce(An.C_PAR,l)&&(this.result=a.pop(),!0);if(o)return l.type==An.INVALID?s.error(l.text,l):s.error("E_CSS_SYNTAX",l),!1;if(this.actions===to&&r.hasMark()){r.reset(),this.actions=Ji,s.startSelectorRule();continue}if(this.actions!==io&&this.actions!==so&&this.actions!==oo){l.type==An.INVALID?s.error(l.text,l):s.error("E_CSS_SYNTAX",l),this.isInsidePropertyOnlyRule()?this.actions=oo:this.actions=so;continue}r.consume();continue}return!1}}class uo extends $i{constructor(t){super(null),this.scope=t}error(t,e){throw new Error(t)}getScope(){return this.scope}}function po(t,e,n,i,o){const s=pi("parseStylesheet"),r=new co(Ki,t,e,n);let a=null;return o&&(a=function(t,e,n){const i=new co(eo,t,e,n);return i.runParser(Number.POSITIVE_INFINITY,!1,!1,!0,!1),i.result}(new hi(o,e),e,n)),a=r.makeCondition(i,a&&a.toExpr()),a&&(e.startMediaRule(a),e.startRuleBody()),s.loop(()=>{for(;!r.runParser(100,!1,!1,!1,!1);){if(r.importReady){const t=L(r.importURL,n);r.importCondition&&(e.startMediaRule(r.importCondition),e.startRuleBody());const i=pi("parseStylesheet.import");return go(t,e,null,null).then(()=>{r.importCondition&&e.endRule(),r.importReady=!1,r.importURL=null,r.importCondition=null,i.finish(!0)}),i.result()}const t=s.timeSlice();if(t.isPending)return t}return fi(!1)}).then(()=>{a&&e.endRule(),s.finish(!0)}),s.result()}function fo(t,e,n,i,o){return gi("parseStylesheetFromText",s=>{po(new hi(t,e),e,n,i,o).thenFinish(s)},(e,n)=>{h.warn(n,`Failed to parse stylesheet text: ${t}`),e.finish(!1)})}function go(t,e,n,i){return gi("parseStylesheetFromURL",o=>{Li(t).then(s=>{s.responseText?fo(s.responseText,e,t,n,i).then(e=>{e||h.warn(`Failed to parse stylesheet from ${t}`),o.finish(!0)}):o.finish(!0)})},(e,n)=>{h.warn(n,"Exception while fetching and parsing:",t),e.finish(!0)})}function mo(t,e,n){const i=new co(to,e,new uo(t),n);return i.runParser(Number.POSITIVE_INFINITY,!0,!1,!1,!1),i.result}const Eo={"z-index":!0,"column-count":!0,"flow-linger":!0,opacity:!0,page:!0,"flow-priority":!0,utilization:!0};function wo(t,e,n){const i=e.evaluate(t);switch(typeof i){case"number":return function(t){return!!Eo[t]}(n)?i==Math.round(i)?new Pe(i):new ve(i):new Ie(i,"px");case"string":return i?mo(e.scope,new hi(i,null),""):Ne;case"boolean":return i?Me._true:Me._false;case"undefined":return Ne}throw new Error("E_UNEXPECTED")}function No(t,e,n){return e.isExpr()?wo(t,e.expr,n):e}function bo(t,e,n){return t-=n,0===e?0===t:t%e==0&&t/e>=0}class So{constructor(t){this.matchers=t}matches(){return this.matchers.some(t=>t.matches())}}class yo{constructor(t){this.matchers=t}matches(){return this.matchers.every(t=>t.matches())}}class Co{constructor(t,e,n){this.elementOffset=t,this.a=e,this.b=n}static registerFragmentIndex(t,e,n){const i=Co.fragmentIndices;(!i[t]||i[t].priority<=n)&&(i[t]={fragmentIndex:e,priority:n})}static clearFragmentIndices(){Co.fragmentIndices={}}matches(){const t=Co.fragmentIndices[this.elementOffset];return null!=t&&null!=t.fragmentIndex&&bo(t.fragmentIndex,this.a,this.b)}}Co.fragmentIndices={};class To{static buildViewConditionMatcher(t,e){const n=e.split("_");return"NFS"==n[0]?new Co(t,parseInt(n[1],10),parseInt(n[2],10)):null}static buildAllMatcher(t){return new yo(t)}static buildAnyMatcher(t){return new So(t)}}const xo={azimuth:!0,"border-collapse":!0,"border-spacing":!0,"caption-side":!0,"clip-rule":!0,color:!0,"color-interpolation":!0,"color-rendering":!0,cursor:!0,direction:!0,elevation:!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":!0,"font-weight":!0,"glyph-orientation-vertical":!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,"pitch-range":!0,quotes:!0,richness:!0,"ruby-align":!0,"ruby-position":!0,"speak-header":!0,"speak-numeral":!0,"speak-punctuation":!0,"speech-rate":!0,"shape-rendering":!0,stress:!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-decoration-skip":!0,"text-emphasis-color":!0,"text-emphasis-position":!0,"text-emphasis-style":!0,"text-combine-upright":!0,"text-indent":!0,"text-justify":!0,"text-rendering":!0,"text-size-adjust":!0,"text-transform":!0,"text-underline-position":!0,visibility:!0,"voice-family":!0,volume:!0,"white-space":!0,widows:!0,"word-break":!0,"word-spacing":!0,"word-wrap":!0,"writing-mode":!0},Io=["box-decoration-break","image-resolution","orphans","widows"];function vo(){return f(t.HOOKS.POLYFILLED_INHERITED_PROPS).reduce((t,e)=>t.concat(e()),[].concat(Io))}const Po={"http://www.idpf.org/2007/ops":!0,"http://www.w3.org/1999/xhtml":!0,"http://www.w3.org/2000/svg":!0},Ro=["margin-%","padding-%","border-%-width","border-%-style","border-%-color","%"],Ao=["max-%","min-%","%"],Lo=(()=>{const t=["left","right","top","bottom"],e={width:!0,height:!0,"max-width":!0,"max-height":!0,"min-width":!0,"min-height":!0};for(let n=0;n<Ro.length;n++)for(let i=0;i<t.length;i++){e[Ro[n].replace("%",t[i])]=!0}return e})();function Oo(t,e){const n={};for(const e of Ro)for(const i in t){const o=e.replace("%",i),s=e.replace("%",t[i]);n[o]=s,n[s]=o}for(const t of Ao)for(const i in e){const o=t.replace("%",i),s=t.replace("%",e[i]);n[o]=s,n[s]=o}return n}const ko=Oo({"block-start":"right","block-end":"left","inline-start":"top","inline-end":"bottom"},{"block-size":"width","inline-size":"height"}),Fo=Oo({"block-start":"top","block-end":"bottom","inline-start":"left","inline-end":"right"},{"block-size":"height","inline-size":"width"}),Do=Oo({"block-start":"right","block-end":"left","inline-start":"bottom","inline-end":"top"},{"block-size":"width","inline-size":"height"}),_o=Oo({"block-start":"top","block-end":"bottom","inline-start":"right","inline-end":"left"},{"block-size":"height","inline-size":"width"});class Bo{constructor(t,e){this.value=t,this.priority=e}getBaseValue(){return this}filterValue(t){const e=this.value.visit(t);return e===this.value?this:new Bo(e,this.priority)}increaseSpecificity(t){return 0==t?this:new Bo(this.value,this.priority+t)}evaluate(t,e){return No(t,this.value,e)}isEnabled(t){return!0}}class Mo extends Bo{constructor(t,e,n){super(t,e),this.condition=n}getBaseValue(){return new Bo(this.value,this.priority)}filterValue(t){const e=this.value.visit(t);return e===this.value?this:new Mo(e,this.priority,this.condition)}increaseSpecificity(t){return 0==t?this:new Mo(this.value,this.priority+t,this.condition)}isEnabled(t){return!!this.condition.evaluate(t)}}function Uo(t,e,n){return(null==e||n.priority>e.priority)&&n.isEnabled(t)?n.getBaseValue():e}const Vo={"region-id":!0,"fragment-selector-id":!0};function Ho(t){return!!Vo[t]}function zo(t){return"_"!=t.charAt(0)&&!Vo[t]}function Go(t){return!!xo[t]}function $o(t,e){return t[e]}function Wo(t,e,n){n?t[e]=n:delete t[e]}function Xo(t,e){return t[e]}function Yo(t,e){let n=t[e];return n||(n={},t[e]=n),n}const Ko=t=>{let e=t._viewConditionalStyles;return e||(e=[],t._viewConditionalStyles=e),e};function jo(t,e){return t[e]}function qo(t,e){let n=t[e];return n||(n=[],t[e]=n),n}function Qo(t,e,n,i,o,s,r){if([{id:o,styleKey:"_pseudos"},{id:s,styleKey:"_regions"}].forEach(t=>{if(t.id){const n=Yo(e,t.styleKey);(e=n[t.id])||(e={},n[t.id]=e)}}),r){const t=Ko(e);e={},t.push({styles:e,matcher:r})}for(const o in n)if("_"!=o.charAt(0))if(Ho(o)){const t=jo(n,o),i=qo(e,o);Array.prototype.push.apply(i,t)}else{const s=$o(n,o).increaseSpecificity(i),r=$o(e,o);Wo(e,o,Uo(t,r,s))}}function Zo(t,e){if(t.length>0){t.sort((t,e)=>e.getPriority()-t.getPriority());let n=null;for(let i=t.length-1;i>=0;i--)n=t[i],n.chained=e,e=n;return n}return e}class Jo extends me{constructor(t,e){super(),this.props=t,this.context=e,this.propName=""}setPropName(t){this.propName=t}getFontSize(){const t=$o(this.props,"font-size").value;if(!function(t){switch(t.toLowerCase()){case"px":case"in":case"pt":case"pc":case"cm":case"mm":case"q":return!0;default:return!1}}(t.unit))throw new Error("Unexpected state");return t.num*Pt[t.unit]}visitNumeric(t){if(this.context,"font-size"===this.propName)return function(t,e,n){const i=(t=ts(t,e,n)).unit,o=t.num;return"px"===i?t:new Ie("%"===i?o/100*e:o*n.queryUnitSize(i,!1),"px")}(t,this.getFontSize(),this.context);if("em"==t.unit||"ex"==t.unit||"rem"==t.unit)return ts(t,this.getFontSize(),this.context);if("%"==t.unit){if("line-height"===this.propName)return t;const e=this.propName.match(/height|^(top|bottom)$/)?"vh":"vw";return new Ie(t.num,e)}return t}visitExpr(t){if("font-size"==this.propName){return No(this.context,t,this.propName).visit(this)}return t}}function ts(t,e,n){const i=t.unit,o=t.num;if("em"===i||"ex"===i){const t=Pt[i]/Pt.em;return new Ie(o*t*e,"px")}return"rem"===i?new Ie(o*n.fontSize(),"px"):t}class es{apply(t){}mergeWith(t){return new is([this,t])}clone(){return this}}class ns extends es{constructor(t){super(),this.conditionItem=t}apply(t){t.pushConditionItem(this.conditionItem.fresh(t))}}class is extends es{constructor(t){super(),this.list=t}apply(t){for(let e=0;e<this.list.length;e++)this.list[e].apply(t)}mergeWith(t){return this.list.push(t),this}clone(){return new is([].concat(this.list))}}class os extends es{constructor(t,e,n,i,o){super(),this.style=t,this.specificity=e,this.pseudoelement=n,this.regionId=i,this.viewConditionId=o}apply(t){Qo(t.context,t.currentStyle,this.style,this.specificity,this.pseudoelement,this.regionId,t.buildViewConditionMatcher(this.viewConditionId))}}class ss extends es{constructor(){super(),this.chained=null}apply(t){this.chained.apply(t)}getPriority(){return 0}makePrimary(t){return!1}}class rs extends ss{constructor(t){super(),this.className=t}apply(t){t.currentClassNames.includes(this.className)&&this.chained.apply(t)}getPriority(){return 10}makePrimary(t){return this.chained&&t.insertInTable(t.classes,this.className,this.chained),!0}}class as extends ss{constructor(t){super(),this.id=t}apply(t){t.currentId!=this.id&&t.currentXmlId!=this.id||this.chained.apply(t)}getPriority(){return 11}makePrimary(t){return this.chained&&t.insertInTable(t.ids,this.id,this.chained),!0}}class ls extends ss{constructor(t){super(),this.localName=t}apply(t){t.currentLocalName==this.localName&&this.chained.apply(t)}getPriority(){return 8}makePrimary(t){return this.chained&&t.insertInTable(t.tags,this.localName,this.chained),!0}}class hs extends ss{constructor(t,e){super(),this.ns=t,this.localName=e}apply(t){t.currentLocalName==this.localName&&t.currentNamespace==this.ns&&this.chained.apply(t)}getPriority(){return 8}makePrimary(t){if(this.chained){let e=t.nsPrefix[this.ns];e||(e=`ns${t.nsCount++}:`,t.nsPrefix[this.ns]=e);const n=e+this.localName;t.insertInTable(t.nstags,n,this.chained)}return!0}}class cs extends ss{constructor(t){super(),this.epubTypePatt=t}apply(t){const e=t.currentElement;if(e&&"a"==t.currentLocalName){const n=e.getAttribute("href");if(n&&n.match(/^#/)){const i=n.substring(1),o=e.ownerDocument.getElementById(i);if(o){const e=o.getAttributeNS(k.epub,"type");e&&e.match(this.epubTypePatt)&&this.chained.apply(t)}}}}}class us extends ss{constructor(t){super(),this.ns=t}apply(t){t.currentNamespace==this.ns&&this.chained.apply(t)}}class ds extends ss{constructor(t,e){super(),this.ns=t,this.name=e}apply(t){t.currentElement&&t.currentElement.hasAttributeNS(this.ns,this.name)&&this.chained.apply(t)}}class ps extends ss{constructor(t,e,n){super(),this.ns=t,this.name=e,this.value=n}apply(t){t.currentElement&&t.currentElement.getAttributeNS(this.ns,this.name)==this.value&&this.chained.apply(t)}getPriority(){return"type"==this.name&&this.ns==k.epub?9:0}makePrimary(t){return"type"==this.name&&this.ns==k.epub&&(this.chained&&t.insertInTable(t.epubtypes,this.value,this.chained),!0)}}class fs extends ss{constructor(t,e){super(),this.ns=t,this.name=e}apply(t){if(t.currentElement){const e=t.currentElement.getAttributeNS(this.ns,this.name);e&&Po[e]&&this.chained.apply(t)}}getPriority(){return 0}makePrimary(t){return!1}}class gs extends ss{constructor(t,e,n){super(),this.ns=t,this.name=e,this.regexp=n}apply(t){if(t.currentElement){const e=t.currentElement.getAttributeNS(this.ns,this.name);e&&e.match(this.regexp)&&this.chained.apply(t)}}}class ms extends ss{constructor(t){super(),this.langRegExp=t}apply(t){t.lang.match(this.langRegExp)&&this.chained.apply(t)}}class Es extends ss{constructor(){super()}apply(t){t.isFirst&&this.chained.apply(t)}getPriority(){return 6}}class ws extends ss{constructor(){super()}apply(t){t.isRoot&&this.chained.apply(t)}getPriority(){return 12}}class Ns extends ss{constructor(t,e){super(),this.a=t,this.b=e}matchANPlusB(t){return bo(t,this.a,this.b)}}class bs extends Ns{constructor(t,e){super(t,e)}apply(t){const e=t.currentSiblingTypeCounts[t.currentNamespace][t.currentLocalName];this.matchANPlusB(e)&&this.chained.apply(t)}getPriority(){return 5}}class Ss extends Ns{constructor(t,e){super(t,e)}apply(t){let e=t.currentFollowingSiblingOrder;null===e&&(e=t.currentFollowingSiblingOrder=t.currentElement.parentNode.childElementCount-t.currentSiblingOrder+1),this.matchANPlusB(e)&&this.chained.apply(t)}getPriority(){return 4}}class ys extends Ns{constructor(t,e){super(t,e)}apply(t){const e=t.currentFollowingSiblingTypeCounts;if(!e[t.currentNamespace]){let n=t.currentElement;do{const t=n.namespaceURI,i=n.localName;let o=e[t];o||(o=e[t]={}),o[i]=(o[i]||0)+1}while(n=n.nextElementSibling)}this.matchANPlusB(e[t.currentNamespace][t.currentLocalName])&&this.chained.apply(t)}getPriority(){return 4}}class Cs extends ss{constructor(){super()}apply(t){let e=t.currentElement.firstChild;for(;e;){switch(e.nodeType){case Node.ELEMENT_NODE:return;case Node.TEXT_NODE:if(e.length>0)return}e=e.nextSibling}this.chained.apply(t)}getPriority(){return 4}}class Ts extends ss{constructor(){super()}apply(t){!1===t.currentElement.disabled&&this.chained.apply(t)}getPriority(){return 5}}class xs extends ss{constructor(){super()}apply(t){!0===t.currentElement.disabled&&this.chained.apply(t)}getPriority(){return 5}}class Is extends ss{constructor(){super()}apply(t){const e=t.currentElement;!0!==e.selected&&!0!==e.checked||this.chained.apply(t)}getPriority(){return 5}}class vs extends ss{constructor(t){super(),this.condition=t}apply(t){if(t.conditions[this.condition])try{t.dependentConditions.push(this.condition),this.chained.apply(t)}finally{t.dependentConditions.pop()}}getPriority(){return 5}}class Ps extends es{constructor(){super(),this.applied=!1}apply(t){this.applied=!0}clone(){const t=new Ps;return t.applied=this.applied,t}}class Rs extends ss{constructor(t){super(),this.checkAppliedAction=new Ps,this.firstAction=Zo(t,this.checkAppliedAction)}apply(t){this.firstAction.apply(t),this.checkAppliedAction.applied||this.chained.apply(t),this.checkAppliedAction.applied=!1}getPriority(){return this.firstAction.getPriority()}}class As{constructor(t,e,n){this.condition=t,this.viewConditionId=e,this.viewCondition=n}increment(t){t.increment(this.condition,this.viewCondition)}decrement(t){t.decrement(this.condition,this.viewCondition)}buildViewConditionMatcher(t){return t.buildViewConditionMatcher(this.viewConditionId)}}class Ls extends As{constructor(t,e,n){super(t,e,n)}fresh(t){return new Ls(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,e){return 0==e&&this.increment(t),!1}pop(t,e){return 0==e&&(this.decrement(t),!0)}}class Os extends As{constructor(t,e,n){super(t,e,n)}fresh(t){return new Os(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,e){return 0==e?this.increment(t):1==e&&this.decrement(t),!1}pop(t,e){return 0==e?(this.decrement(t),!0):(1==e&&this.increment(t),!1)}}class ks extends As{constructor(t,e,n){super(t,e,n),this.fired=!1}fresh(t){return new ks(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,e){return!!this.fired&&(this.decrement(t),!0)}pop(t,e){return this.fired?(this.decrement(t),!0):(0==e&&(this.fired=!0,this.increment(t)),!1)}}class Fs extends As{constructor(t,e,n){super(t,e,n),this.fired=!1}fresh(t){return new Fs(this.condition,this.viewConditionId,this.buildViewConditionMatcher(t))}push(t,e){return this.fired&&(-1==e?this.increment(t):0==e&&this.decrement(t)),!1}pop(t,e){if(this.fired){if(-1==e)return this.decrement(t),!0;0==e&&this.increment(t)}else 0==e&&(this.fired=!0,this.increment(t));return!1}}class Ds{constructor(t,e){this.afterprop=t,this.element=e}fresh(t){return this}push(t,e){return!1}pop(t,e){return 0==e&&(t.processPseudoelementProps(this.afterprop,this.element),!0)}}class _s{constructor(t){this.lang=t}fresh(t){return this}push(t,e){return!1}pop(t,e){return 0==e&&(t.lang=this.lang,!0)}}class Bs{constructor(t){this.oldQuotes=t}fresh(t){return this}push(t,e){return!1}pop(t,e){return 0==e&&(t.quotes=this.oldQuotes,!0)}}class Ms extends me{constructor(t){super(),this.element=t}createValueFromString(t,e){switch(e){case"url":return new Ae(t?t:"about:invalid");case"string":default:return new ye(t?t:"")}}visitFunc(t){if("attr"!==t.name)return super.visitFunc(t);let e="string",n=null,i=null;if(t.values[0]instanceof Oe){const i=t.values[0].values;i.length>=2&&(e=i[1].stringValue()),n=i[0].stringValue()}else n=t.values[0].stringValue();return i=t.values.length>1?this.createValueFromString(t.values[1].stringValue(),e):this.createValueFromString(null,e),this.element&&this.element.hasAttribute(n)?this.createValueFromString(this.element.getAttribute(n),e):i}}class Us extends me{constructor(t,e,n){super(),this.cascade=t,this.element=e,this.counterResolver=n}visitIdent(t){const e=this.cascade,n=e.quotes,i=Math.floor(n.length/2)-1;switch(t.name){case"open-quote":{const t=n[2*Math.min(i,e.quoteDepth)];return e.quoteDepth++,t}case"close-quote":return e.quoteDepth>0&&e.quoteDepth--,n[2*Math.min(i,e.quoteDepth)+1];case"no-open-quote":return e.quoteDepth++,new ye("");case"no-close-quote":return e.quoteDepth>0&&e.quoteDepth--,new ye("")}return t}format(t,e){let n,i=!1,o=!1;null!=(n=e.match(/^upper-(.*)/))?(i=!0,e=n[1]):null!=(n=e.match(/^lower-(.*)/))&&(o=!0,e=n[1]);let s="";return Vs[e]?s=function(t,e){const n=t[0];if(e>n||e<=0||e!=Math.round(e))return"";let i="";for(let n=1;n<t.length;n+=2){const o=t[n];let s=Math.floor(e/o);if(s>20)return"";for(e-=s*o;s>0;)i+=t[n+1],s--}return i}(Vs[e],t):Hs[e]?s=function(t,e){if(e<=0||e!=Math.round(e))return"";const n=function(t){const e=[];let n=0;for(;n<t.length;)if("-"==t.substr(n+1,1)){const i=t.charCodeAt(n),o=t.charCodeAt(n+2);n+=3;for(let t=i;t<=o;t++)e.push(String.fromCharCode(t))}else e.push(t.substr(n++,1));return e}(t);let i="";do{const t=--e%n.length;i=n[t]+i,e=(e-t)/n.length}while(e>0);return i}(Hs[e],t):null!=zs[e]?s=zs[e]:"decimal-leading-zero"==e?(s=`${t}`,1==s.length&&(s=`0${s}`)):s="cjk-ideographic"==e||"trad-chinese-informal"==e?function(t,e){if(t>9999||t<-9999)return`${t}`;if(0==t)return e.digits.charAt(0);const n=new G;t<0&&(n.append(e.negative),t=-t);if(t<10)n.append(e.digits.charAt(t));else if(!e.formal&&t<=19)n.append(e.markers.charAt(0)),0!=t&&n.append(e.digits.charAt(t-10));else{const i=Math.floor(t/1e3);i&&(n.append(e.digits.charAt(i)),n.append(e.markers.charAt(2)));const o=Math.floor(t/100)%10;o&&(n.append(e.digits.charAt(o)),n.append(e.markers.charAt(1)));const s=Math.floor(t/10)%10;s&&(n.append(e.digits.charAt(s)),n.append(e.markers.charAt(0)));const r=t%10;r&&n.append(e.digits.charAt(r))}return n.toString()}(t,Gs):`${t}`,i?s.toUpperCase():o?s.toLowerCase():s}visitFuncCounter(t){const e=t[0].toString(),n=t.length>1?t[1].stringValue():"decimal",i=this.cascade.counters[e];if(i&&i.length){const t=i&&i.length&&i[i.length-1]||0;return new ye(this.format(t,n))}{const t=this,i=new De(this.counterResolver.getPageCounterVal(e,e=>t.format(e||0,n)));return new Oe([i])}}visitFuncCounters(t){const e=t[0].toString(),n=t[1].stringValue(),i=t.length>2?t[2].stringValue():"decimal",o=this.cascade.counters[e],s=new G;if(o&&o.length)for(let t=0;t<o.length;t++)t>0&&s.append(n),s.append(this.format(o[t],i));const r=this,a=new De(this.counterResolver.getPageCountersVal(e,t=>{const e=[];if(t.length)for(let n=0;n<t.length;n++)e.push(r.format(t[n],i));const o=s.toString();return o.length&&e.push(o),e.length?e.join(n):r.format(0,i)}));return new Oe([a])}visitFuncTargetCounter(t){const e=t[0];let n;n=e instanceof Ae?e.url:e.stringValue();const i=t[1].toString(),o=t.length>2?t[2].stringValue():"decimal",s=this,r=new De(this.counterResolver.getTargetCounterVal(n,i,t=>s.format(t||0,o)));return new Oe([r])}visitFuncTargetCounters(t){const e=t[0];let n;n=e instanceof Ae?e.url:e.stringValue();const i=t[1].toString(),o=t[2].stringValue(),s=t.length>3?t[3].stringValue():"decimal",r=this,a=new De(this.counterResolver.getTargetCountersVal(n,i,t=>{const e=t.map(t=>r.format(t,s));return e.length?e.join(o):r.format(0,s)}));return new Oe([a])}visitFunc(t){switch(t.name){case"counter":if(t.values.length<=2)return this.visitFuncCounter(t.values);break;case"counters":if(t.values.length<=3)return this.visitFuncCounters(t.values);break;case"target-counter":if(t.values.length<=3)return this.visitFuncTargetCounter(t.values);break;case"target-counters":if(t.values.length<=4)return this.visitFuncTargetCounters(t.values)}return h.warn("E_CSS_CONTENT_PROP:",t.toString()),new ye("")}}const Vs={roman:[4999,1e3,"M",900,"CM",500,"D",400,"CD",100,"C",90,"XC",50,"L",40,"XL",10,"X",9,"IX",5,"V",4,"IV",1,"I"],armenian:[9999,9e3,"ք",8e3,"փ",7e3,"ւ",6e3,"ց",5e3,"ր",4e3,"տ",3e3,"վ",2e3,"ս",1e3,"ռ",900,"ջ",800,"պ",700,"չ",600,"ո",500,"շ",400,"ն",300,"յ",200,"մ",100,"ճ",90,"ղ",80,"ձ",70,"հ",60,"կ",50,"ծ",40,"խ",30,"լ",20,"ի",10,"ժ",9,"թ",8,"ը",7,"է",6,"զ",5,"ե",4,"դ",3,"գ",2,"բ",1,"ա"],georgian:[19999,1e4,"ჵ",9e3,"ჰ",8e3,"ჯ",7e3,"ჴ",6e3,"ხ",5e3,"ჭ",4e3,"წ",3e3,"ძ",2e3,"ც",1e3,"ჩ",900,"შ",800,"ყ",700,"ღ",600,"ქ",500,"ფ",400,"ჳ",300,"ტ",200,"ს",100,"რ",90,"ჟ",80,"პ",70,"ო",60,"ჲ",50,"ნ",40,"მ",30,"ლ",20,"კ",10,"ი",9,"თ",8,"ჱ",7,"ზ",6,"ვ",5,"ე",4,"დ",3,"გ",2,"ბ",1,"ა"],hebrew:[999,400,"ת",300,"ש",200,"ר",100,"ק",90,"צ",80,"פ",70,"ע",60,"ס",50,"נ",40,"מ",30,"ל",20,"כ",19,"יט",18,"יח",17,"יז",16,"טז",15,"טו",10,"י",9,"ט",8,"ח",7,"ז",6,"ו",5,"ה",4,"ד",3,"ג",2,"ב",1,"א"]},Hs={latin:"a-z",alpha:"a-z",greek:"α-ρσ-ω",russian:"а-ик-щэ-я"},zs={square:"■",disc:"•",circle:"◦",none:""};const Gs={formal:!1,digits:"零一二三四五六七八九",markers:"十百千",negative:"負"};const $s=1/1048576;function Ws(t,e){for(const n in t)e[n]=t[n].clone()}class Xs{constructor(){this.nsCount=0,this.nsPrefix={},this.tags={},this.nstags={},this.epubtypes={},this.classes={},this.ids={},this.pagetypes={},this.order=0}clone(){const t=new Xs;t.nsCount=this.nsCount;for(const e in this.nsPrefix)t.nsPrefix[e]=this.nsPrefix[e];return Ws(this.tags,t.tags),Ws(this.nstags,t.nstags),Ws(this.epubtypes,t.epubtypes),Ws(this.classes,t.classes),Ws(this.ids,t.ids),Ws(this.pagetypes,t.pagetypes),t.order=this.order,t}insertInTable(t,e,n){const i=t[e];i&&(n=i.mergeWith(n)),t[e]=n}createInstance(t,e,n,i){return new Ys(this,t,e,n,i)}nextOrder(){return this.order+=$s}}class Ys{constructor(t,e,n,i,o){this.context=e,this.counterListener=n,this.counterResolver=i,this.stack=[[],[]],this.conditions={},this.currentElement=null,this.currentElementOffset=null,this.currentStyle=null,this.currentClassNames=null,this.currentLocalName="",this.currentNamespace="",this.currentId="",this.currentXmlId="",this.currentNSTag="",this.currentEpubTypes=null,this.currentPageType=null,this.isFirst=!0,this.isRoot=!0,this.counters={},this.counterScoping=[{}],this.quoteDepth=0,this.lang="",this.siblingOrderStack=[0],this.currentSiblingOrder=0,this.siblingTypeCountsStack=[{}],this.currentFollowingSiblingOrder=null,this.followingSiblingTypeCountsStack=[{}],this.viewConditions={},this.dependentConditions=[],this.code=t,this.quotes=[new ye("“"),new ye("”"),new ye("‘"),new ye("’")],this.currentSiblingTypeCounts=this.siblingTypeCountsStack[0],this.followingSiblingOrderStack=[this.currentFollowingSiblingOrder],this.currentFollowingSiblingTypeCounts=this.siblingTypeCountsStack[0]}pushConditionItem(t){this.stack[this.stack.length-1].push(t)}increment(t,e){this.conditions[t]=(this.conditions[t]||0)+1,e&&(this.viewConditions[t]?this.viewConditions[t].push(e):this.viewConditions[t]=[e])}decrement(t,e){this.conditions[t]--,this.viewConditions[t]&&(this.viewConditions[t]=this.viewConditions[t].filter(t=>t!==e),0===this.viewConditions[t].length&&delete this.viewConditions[t])}buildViewConditionMatcher(t){let e=null;t&&(this.currentElementOffset,e=To.buildViewConditionMatcher(this.currentElementOffset,t));const n=this.dependentConditions.map(t=>{const e=this.viewConditions[t];return e&&e.length>0?1===e.length?e[0]:To.buildAnyMatcher([].concat(e)):null}).filter(t=>t);return n.length<=0?e:null===e?1===n.length?n[0]:To.buildAllMatcher(n):To.buildAllMatcher([e].concat(n))}applyAction(t,e){const n=t[e];n&&n.apply(this)}pushRule(t,e,n){this.currentElement=null,this.currentElementOffset=null,this.currentStyle=n,this.currentNamespace="",this.currentLocalName="",this.currentId="",this.currentXmlId="",this.currentClassNames=t,this.currentNSTag="",this.currentEpubTypes=Ks,this.currentPageType=e,this.applyActions()}defineCounter(t,e){this.counters[t]?this.counters[t].push(e):this.counters[t]=[e];let n=this.counterScoping[this.counterScoping.length-1];n||(n={},this.counterScoping[this.counterScoping.length-1]=n),n[t]=!0}pushCounters(t){let e=Me.inline;const n=t.display;n&&(e=n.evaluate(this.context));let i=null,o=null,s=null;const r=t["counter-reset"];if(r){const t=r.evaluate(this.context);t&&(i=Nn(t,!0))}const a=t["counter-set"];if(a){const t=a.evaluate(this.context);t&&(s=Nn(t,!1))}const l=t["counter-increment"];if(l){const t=l.evaluate(this.context);t&&(o=Nn(t,!1))}if("ol"!=this.currentLocalName&&"ul"!=this.currentLocalName||this.currentNamespace!=k.XHTML||(i||(i={}),i["ua-list-item"]=0),e===Me.list_item&&(o||(o={}),o["ua-list-item"]=1),i)for(const t in i)this.defineCounter(t,i[t]);if(s)for(const t in s)if(this.counters[t]){const e=this.counters[t];e[e.length-1]=s[t]}else this.defineCounter(t,s[t]);if(o)for(const t in o){this.counters[t]||this.defineCounter(t,0);const e=this.counters[t];e[e.length-1]+=o[t]}if(e===Me.list_item){const e=this.counters["ua-list-item"],n=e[e.length-1];t["ua-list-item-count"]=new Bo(new ve(n),0)}this.counterScoping.push(null)}popCounters(){const t=this.counterScoping.pop();if(t)for(const e in t){const t=this.counters[e];t&&(1==t.length?delete this.counters[e]:t.pop())}}processPseudoelementProps(t,e){this.pushCounters(t),t.content&&(t.content=t.content.filterValue(new Us(this,e,this.counterResolver))),this.popCounters()}pushElement(t,e,n){this.currentPageType=null,this.currentElement=t,this.currentElementOffset=n,this.currentStyle=e,this.currentNamespace=t.namespaceURI,this.currentLocalName=t.localName;const i=this.code.nsPrefix[this.currentNamespace];this.currentNSTag=i?i+this.currentLocalName:"",this.currentId=t.getAttribute("id"),this.currentXmlId=t.getAttributeNS(k.XML,"id");const o=t.getAttribute("class");this.currentClassNames=o?o.split(/\s+/):Ks;const s=t.getAttributeNS(k.epub,"type");if(this.currentEpubTypes=s?s.split(/\s+/):Ks,"style"==this.currentLocalName&&this.currentNamespace==k.FB2){const e=t.getAttribute("name")||"";this.currentClassNames=[e]}const r=z(t);r&&(this.stack[this.stack.length-1].push(new _s(this.lang)),this.lang=r.toLowerCase());const a=this.isRoot,l=this.siblingOrderStack;this.currentSiblingOrder=++l[l.length-1],l.push(0);const h=this.siblingTypeCountsStack,c=this.currentSiblingTypeCounts=h[h.length-1];let u=c[this.currentNamespace];u||(u=c[this.currentNamespace]={}),u[this.currentLocalName]=(u[this.currentLocalName]||0)+1,h.push({});const d=this.followingSiblingOrderStack;null!==d[d.length-1]?this.currentFollowingSiblingOrder=--d[d.length-1]:this.currentFollowingSiblingOrder=null,d.push(null);const p=this.followingSiblingTypeCountsStack,f=this.currentFollowingSiblingTypeCounts=p[p.length-1];f&&f[this.currentNamespace]&&f[this.currentNamespace][this.currentLocalName]--,p.push({}),this.applyActions(),this.applyAttrFilter(t);const g=e.quotes;let m=null;if(g){const t=g.evaluate(this.context);t&&(m=new Bs(this.quotes),t===Me.none?this.quotes=[new ye(""),new ye("")]:t instanceof Oe&&(this.quotes=t.values))}this.pushCounters(this.currentStyle);const E=this.currentId||this.currentXmlId||t.getAttribute("name")||"";if(a||E){const t={};Object.keys(this.counters).forEach(e=>{t[e]=Array.from(this.counters[e])}),this.counterListener.countersOfId(E,t)}const w=Xo(this.currentStyle,"_pseudos");if(w){let e=!0;for(const n of js){n||(e=!1);const i=w[n];i&&(e?this.processPseudoelementProps(i,t):this.stack[this.stack.length-2].push(new Ds(i,t)))}}m&&this.stack[this.stack.length-2].push(m)}applyAttrFilterInner(t,e){for(const n in e)zo(n)&&(e[n]=e[n].filterValue(t))}applyAttrFilter(t){const e=new Ms(t),n=this.currentStyle,i=Xo(n,"_pseudos");for(const t in i)this.applyAttrFilterInner(e,i[t]);this.applyAttrFilterInner(e,n)}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),null!==this.currentPageType&&(this.applyAction(this.code.pagetypes,this.currentPageType),this.applyAction(this.code.pagetypes,"*")),this.currentElement=null,this.currentDoc=null,this.stack.push([]);for(let e=1;e>=-1;--e){const n=this.stack[this.stack.length-e-2];for(t=0;t<n.length;)n[t].push(this,e)?n.splice(t,1):t++}this.isFirst=!0,this.isRoot=!1}pop(){for(let t=1;t>=-1;--t){const e=this.stack[this.stack.length-t-2];let n=0;for(;n<e.length;)e[n].pop(this,t)?e.splice(n,1):n++}this.stack.pop(),this.isFirst=!1}popRule(){this.pop()}popElement(t){this.siblingOrderStack.pop(),this.siblingTypeCountsStack.pop(),this.followingSiblingOrderStack.pop(),this.followingSiblingTypeCountsStack.pop(),this.pop(),this.popCounters()}}const Ks=[],js=["before","transclusion-before","footnote-call","footnote-marker","inner","first-letter","first-line","","transclusion-after","after"];var qs;!function(t){t[t.TOP=0]="TOP",t[t.SELECTOR=1]="SELECTOR",t[t.RULE=2]="RULE"}(qs||(qs={}));let Qs=null;class Zs extends Yi{constructor(t,e,n,i,o,s,r){super(t,e,r),this.condition=n,this.regionId=o,this.validatorSet=s,this.chain=null,this.specificity=0,this.elementStyle=null,this.conditionCount=0,this.pseudoelement=null,this.footnoteContent=!1,this.viewConditionId=null,this.cascade=i?i.cascade:Qs?Qs.clone():new Xs,this.state=qs.TOP}insertNonPrimary(t){this.cascade.insertInTable(this.cascade.tags,"*",t)}processChain(t){const e=Zo(this.chain,t);e!==t&&e.makePrimary(this.cascade)||this.insertNonPrimary(e)}isInsideSelectorRule(t){return this.state!=qs.TOP&&(this.reportAndSkip(t),!0)}tagSelector(t,e){(e||t)&&(this.specificity+=1,e&&t?this.chain.push(new hs(t,e.toLowerCase())):e?this.chain.push(new ls(e.toLowerCase())):this.chain.push(new us(t)))}classSelector(t){if(this.pseudoelement)return h.warn(`::${this.pseudoelement}`,`followed by .${t}`),void this.chain.push(new vs(""));this.specificity+=256,this.chain.push(new rs(t))}pseudoclassSelector(t,e){if(this.pseudoelement)return h.warn(`::${this.pseudoelement}`,`followed by :${t}`),void this.chain.push(new vs(""));switch(t.toLowerCase()){case"enabled":this.chain.push(new Ts);break;case"disabled":this.chain.push(new xs);break;case"checked":this.chain.push(new Is);break;case"root":this.chain.push(new ws);break;case"link":this.chain.push(new ls("a")),this.chain.push(new ds("","href"));break;case"-adapt-href-epub-type":case"href-epub-type":if(e&&1==e.length&&"string"==typeof e[0]){const t=e[0],n=new RegExp(`(^|s)${q(t)}($|s)`);this.chain.push(new cs(n))}else this.chain.push(new vs(""));break;case"-adapt-footnote-content":case"footnote-content":this.footnoteContent=!0;break;case"visited":case"active":case"hover":case"focus":this.chain.push(new vs(""));break;case"lang":if(e&&1==e.length&&"string"==typeof e[0]){const t=e[0];this.chain.push(new ms(new RegExp(`^${q(t.toLowerCase())}($|-)`)))}else this.chain.push(new vs(""));break;case"nth-child":case"nth-last-child":case"nth-of-type":case"nth-last-of-type":{const n=Js[t.toLowerCase()];e&&2==e.length?this.chain.push(new n(e[0],e[1])):this.chain.push(new vs(""));break}case"first-child":this.chain.push(new Es);break;case"last-child":this.chain.push(new Ss(0,1));break;case"first-of-type":this.chain.push(new bs(0,1));break;case"last-of-type":this.chain.push(new ys(0,1));break;case"only-child":this.chain.push(new Es),this.chain.push(new Ss(0,1));break;case"only-of-type":this.chain.push(new bs(0,1)),this.chain.push(new ys(0,1));break;case"empty":this.chain.push(new Cs);break;case"before":case"after":case"first-line":case"first-letter":return void this.pseudoelementSelector(t,e);default:h.warn(`unknown pseudo-class selector: ${t}`),this.chain.push(new vs(""))}this.specificity+=256}pseudoelementSelector(t,e){switch(t){case"before":case"after":case"first-line":case"first-letter":case"footnote-call":case"footnote-marker":case"inner":case"after-if-continues":this.pseudoelement?(h.warn(`Double pseudoelement ::${this.pseudoelement}::${t}`),this.chain.push(new vs(""))):this.pseudoelement=t;break;case"first-n-lines":if(e&&1==e.length&&"number"==typeof e[0]){const n=Math.round(e[0]);if(n>0&&n==e[0]){this.pseudoelement?(h.warn(`Double pseudoelement ::${this.pseudoelement}::${t}`),this.chain.push(new vs(""))):this.pseudoelement=`first-${n}-lines`;break}}this.chain.push(new vs(""));break;case"nth-fragment":e&&2==e.length?this.viewConditionId=`NFS_${e[0]}_${e[1]}`:this.chain.push(new vs(""));break;default:h.warn(`Unrecognized pseudoelement: ::${t}`),this.chain.push(new vs(""))}this.specificity+=1}idSelector(t){this.specificity+=65536,this.chain.push(new as(t))}attributeSelector(t,e,n,i){let o;switch(this.specificity+=256,e=e.toLowerCase(),i=i||"",n){case An.EOF:o=new ds(t,e);break;case An.EQ:o=new ps(t,e,i);break;case An.TILDE_EQ:o=!i||i.match(/\s/)?new vs(""):new gs(t,e,new RegExp(`(^|\\s)${q(i)}($|\\s)`));break;case An.BAR_EQ:o=new gs(t,e,new RegExp(`^${q(i)}($|-)`));break;case An.HAT_EQ:o=i?new gs(t,e,new RegExp(`^${q(i)}`)):new vs("");break;case An.DOLLAR_EQ:o=i?new gs(t,e,new RegExp(`${q(i)}$`)):new vs("");break;case An.STAR_EQ:o=i?new gs(t,e,new RegExp(q(i))):new vs("");break;case An.COL_COL:"supported"==i?o=new fs(t,e):(h.warn("Unsupported :: attr selector op:",i),o=new vs(""));break;default:h.warn("Unsupported attr selector:",n),o=new vs("")}this.chain.push(o)}descendantSelector(){const t=`d${tr++}`;this.processChain(new ns(new Ls(t,this.viewConditionId,null))),this.chain=[new vs(t)],this.viewConditionId=null}childSelector(){const t=`c${tr++}`;this.processChain(new ns(new Os(t,this.viewConditionId,null))),this.chain=[new vs(t)],this.viewConditionId=null}adjacentSiblingSelector(){const t=`a${tr++}`;this.processChain(new ns(new ks(t,this.viewConditionId,null))),this.chain=[new vs(t)],this.viewConditionId=null}followingSiblingSelector(){const t=`f${tr++}`;this.processChain(new ns(new Fs(t,this.viewConditionId,null))),this.chain=[new vs(t)],this.viewConditionId=null}nextSelector(){this.finishChain(),this.pseudoelement=null,this.footnoteContent=!1,this.specificity=0,this.chain=[]}startSelectorRule(){this.isInsideSelectorRule("E_CSS_UNEXPECTED_SELECTOR")||(this.state=qs.SELECTOR,this.elementStyle={},this.pseudoelement=null,this.specificity=0,this.footnoteContent=!1,this.chain=[])}error(t,e){super.error(t,e),this.state==qs.SELECTOR&&(this.state=qs.TOP)}startStylesheet(t){super.startStylesheet(t),this.state=qs.TOP}startRuleBody(){this.finishChain(),super.startRuleBody(),this.state==qs.SELECTOR&&(this.state=qs.TOP)}endRule(){super.endRule(),this.insideSelectorRule=qs.TOP}finishChain(){if(this.chain){const t=this.specificity+this.cascade.nextOrder();this.processChain(this.makeApplyRuleAction(t)),this.chain=null,this.pseudoelement=null,this.viewConditionId=null,this.footnoteContent=!1,this.specificity=0}}makeApplyRuleAction(t){let e=this.regionId;return this.footnoteContent&&(e=e?"xxx-bogus-xxx":"footnote"),new os(this.elementStyle,t,this.pseudoelement,e,this.viewConditionId)}special(t,e){let n;n=this.condition?new Mo(e,0,this.condition):new Bo(e,0),qo(this.elementStyle,t).push(n)}property(t,e,n){this.validatorSet.validatePropertyAndHandleShorthand(t,e,n,this)}invalidPropertyValue(t,e){this.report(`E_INVALID_PROPERTY_VALUE ${t}: ${e.toString()}`)}unknownProperty(t,e){this.report(`E_INVALID_PROPERTY ${t}: ${e.toString()}`)}simpleProperty(t,e,n){"display"!=t||e!==Me.oeb_page_head&&e!==Me.oeb_page_foot||(this.simpleProperty("flow-options",new Oe([Me.exclusive,Me._static]),n),this.simpleProperty("flow-into",e,n),e=Me.block),f("SIMPLE_PROPERTY").forEach(i=>{const o=i({name:t,value:e,important:n});t=o.name,e=o.value,n=o.important});const i=n?this.getImportantSpecificity():this.getBaseSpecificity(),o=this.condition?new Mo(e,i,this.condition):new Bo(e,i);Wo(this.elementStyle,t,o)}finish(){return this.cascade}startFuncWithSelector(t){switch(t){case"not":{const t=new er(this);t.startSelectorRule(),this.owner.pushHandler(t);break}}}}const Js={"nth-child":class extends Ns{constructor(t,e){super(t,e)}apply(t){this.matchANPlusB(t.currentSiblingOrder)&&this.chained.apply(t)}getPriority(){return 5}},"nth-of-type":bs,"nth-last-child":Ss,"nth-last-of-type":ys};let tr=0;class er extends Zs{constructor(t){super(t.scope,t.owner,t.condition,t,t.regionId,t.validatorSet,!1),this.parent=t,this.parentChain=t.chain}startFuncWithSelector(t){"not"==t&&this.reportAndSkip("E_CSS_UNEXPECTED_NOT")}startRuleBody(){this.reportAndSkip("E_CSS_UNEXPECTED_RULE_BODY")}nextSelector(){this.reportAndSkip("E_CSS_UNEXPECTED_NEXT_SELECTOR")}endFuncWithSelector(){this.chain&&this.chain.length>0&&this.parentChain.push(new Rs(this.chain)),this.parent.specificity+=this.specificity,this.owner.popHandler()}error(t,e){super.error(t,e),this.owner.popHandler()}}class nr extends Yi{constructor(t,e){super(t,e,!1)}property(t,e,n){if(this.scope.values[t])this.error(`E_CSS_NAME_REDEFINED ${t}`,this.getCurrentToken());else{const n=t.match(/height|^(top|bottom)$/)?"vh":"vw",i=new ee(this.scope,100,n);this.scope.defineName(t,e.toExpr(this.scope,i))}}}class ir extends Yi{constructor(t,e,n,i,o){super(t,e,!1),this.condition=n,this.elementStyle=i,this.validatorSet=o,this.order=0}property(t,e,n){n?h.warn("E_IMPORTANT_NOT_ALLOWED"):this.validatorSet.validatePropertyAndHandleShorthand(t,e,n,this)}invalidPropertyValue(t,e){h.warn("E_INVALID_PROPERTY_VALUE",`${t}:`,e.toString())}unknownProperty(t,e){h.warn("E_INVALID_PROPERTY",`${t}:`,e.toString())}simpleProperty(t,e,n){let i=n?this.getImportantSpecificity():this.getBaseSpecificity();i+=this.order,this.order+=$s;const o=this.condition?new Mo(e,i,this.condition):new Bo(e,i);Wo(this.elementStyle,t,o)}}class or extends uo{constructor(t,e){super(t),this.validatorSet=e,this.elementStyle={},this.order=0}property(t,e,n){this.validatorSet.validatePropertyAndHandleShorthand(t,e,n,this)}invalidPropertyValue(t,e){h.warn("E_INVALID_PROPERTY_VALUE",`${t}:`,e.toString())}unknownProperty(t,e){h.warn("E_INVALID_PROPERTY",`${t}:`,e.toString())}simpleProperty(t,e,n){let i=n?Ui:Mi;i+=this.order,this.order+=$s;const o=new Bo(e,i);Wo(this.elementStyle,t,o)}}function sr(t,e){const n=Ko(t);n&&n.forEach(t=>{t.matcher.matches()&&e(t.styles)})}function rr(t,e,n){sr(n,n=>{dr(t,n,e)})}function ar(t,e,n,i){const o=new or(t,e),s=new hi(i,o);try{!function(t,e,n){new co(ji,t,e,n).runParser(Number.POSITIVE_INFINITY,!1,!0,!1,!1)}(s,o,n)}catch(t){h.warn(t,"Style attribute parse error:")}return o.elementStyle}function lr(t,e,n){const i=t["writing-mode"];if(i){const t=i.evaluate(e,"writing-mode");if(t&&t!==Me.inherit)return t===Me.vertical_rl}return n}function hr(t,e,n){const i=t.direction;if(i){const t=i.evaluate(e,"direction");if(t&&t!==Me.inherit)return t===Me.rtl}return n}function cr(t,e,n,i,o){const s={};for(const e in t)zo(e)&&(s[e]=$o(t,e));return rr(s,e,t),ur(t,n,i,(t,n)=>{dr(s,n,e),rr(s,e,n)}),s}function ur(t,e,n,i){const o=Xo(t,"_regions");if((e||n)&&o){if(n){const t=["footnote"];e=e?e.concat(t):t}for(const t of e){const e=o[t];e&&i(t,e)}}}function dr(t,e,n){for(const i in e)if(zo(i)){const o=$o(e,i),s=t[i];t[i]=Uo(n,s,o)}}const pr=(t,e,n,i,o)=>{const s=n?i?Do:ko:i?_o:Fo;for(const n in t)if(t.hasOwnProperty(n)){const i=t[n];if(!i)continue;const r=s[n];let a;if(r){const e=t[r];if(e&&e.priority>i.priority)continue;a=Lo[r]?r:n}else a=n;e[a]=o(n,i)}};function fr(t,e){const n={};return Object.keys(t).forEach(i=>{const o=n[i]={},s=t[i];Object.keys(s).forEach(t=>{o[t]=s[t].map(t=>{const n=e?t.logical:t.physical,i=e?t.physical:t.logical;return{regexp:new RegExp(`(-?)${n}(-?)`),to:`$1${i}$2`}})})}),n}function gr(t,e,n,i){const o=i[e];if(!o)throw new Error(`unknown writing-mode: ${e}`);const s=o[n||"ltr"];if(!s)throw new Error(`unknown direction: ${n}`);for(const e of s){const n=t.replace(e.regexp,e.to);if(n!==t)return n}return t}const mr={"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"}]}},Er=fr(mr,!0);const wr=fr(mr,!1);var Nr;function br(t,e,n){const i={display:e.style.display,position:e.style.position,width:e.style.width,maxWidth:e.style.maxWidth,minWidth:e.style.minWidth,height:e.style.height,maxHeight:e.style.maxHeight,minHeight:e.style.minHeight},o=e.ownerDocument,s=e.parentNode,r=o.createElement("div");function a(n){return t.getElementComputedStyle(e).getPropertyValue(n)}V(r,"position",i.position),s.insertBefore(r,e),r.appendChild(e),V(e,"width","auto"),V(e,"max-width","none"),V(e,"min-width","0"),V(e,"height","auto"),V(e,"max-height","none"),V(e,"min-height","0");const l=U("writing-mode"),h=(l?a(l[0]):null)||a("writing-mode"),c="vertical-rl"===h||"tb-rl"===h||"vertical-lr"===h||"tb-lr"===h,u=c?"height":"width",d=c?"width":"height";function p(){return V(e,"display","block"),V(e,"position","static"),a(u)}function f(){V(e,"display","inline-block"),V(r,u,"99999999px");const t=a(u);return V(r,u,""),t}function g(){V(e,"display","inline-block"),V(r,u,"0");const t=a(u);return V(r,u,""),t}function m(){const t=p(),e=g(),n=parseFloat(t);if(n<=parseFloat(e))return e;{const e=f();return n<=parseFloat(e)?t:e}}function E(){return a(d)}function w(){throw new Error("Getting fill-available block size is not implemented")}const N={};return n.forEach(t=>{let n;switch(t){case Nr.FILL_AVAILABLE_INLINE_SIZE:n=p();break;case Nr.MAX_CONTENT_INLINE_SIZE:n=f();break;case Nr.MIN_CONTENT_INLINE_SIZE:n=g();break;case Nr.FIT_CONTENT_INLINE_SIZE:n=m();break;case Nr.FILL_AVAILABLE_BLOCK_SIZE:n=w();break;case Nr.MAX_CONTENT_BLOCK_SIZE:case Nr.MIN_CONTENT_BLOCK_SIZE:case Nr.FIT_CONTENT_BLOCK_SIZE:n=E();break;case Nr.FILL_AVAILABLE_WIDTH:n=c?w():p();break;case Nr.FILL_AVAILABLE_HEIGHT:n=c?p():w();break;case Nr.MAX_CONTENT_WIDTH:n=c?E():f();break;case Nr.MAX_CONTENT_HEIGHT:n=c?f():E();break;case Nr.MIN_CONTENT_WIDTH:n=c?E():g();break;case Nr.MIN_CONTENT_HEIGHT:n=c?g():E();break;case Nr.FIT_CONTENT_WIDTH:n=c?E():m();break;case Nr.FIT_CONTENT_HEIGHT:n=c?m():E()}N[t]=parseFloat(n),V(e,"position",i.position),V(e,"display",i.display)}),V(e,"width",i.width),V(e,"max-width",i.maxWidth),V(e,"min-width",i.minWidth),V(e,"height",i.height),V(e,"max-height",i.maxHeight),V(e,"min-height",i.minHeight),s.insertBefore(e,r),s.removeChild(r),N}!function(t){t.FILL_AVAILABLE_INLINE_SIZE="fill-available inline size",t.FILL_AVAILABLE_BLOCK_SIZE="fill-available block size",t.FILL_AVAILABLE_WIDTH="fill-available width",t.FILL_AVAILABLE_HEIGHT="fill-available height",t.MAX_CONTENT_INLINE_SIZE="max-content inline size",t.MAX_CONTENT_BLOCK_SIZE="max-content block size",t.MAX_CONTENT_WIDTH="max-content width",t.MAX_CONTENT_HEIGHT="max-content height",t.MIN_CONTENT_INLINE_SIZE="min-content inline size",t.MIN_CONTENT_BLOCK_SIZE="min-content block size",t.MIN_CONTENT_WIDTH="min-content width",t.MIN_CONTENT_HEIGHT="min-content height",t.FIT_CONTENT_INLINE_SIZE="fit-content inline size",t.FIT_CONTENT_BLOCK_SIZE="fit-content block size",t.FIT_CONTENT_WIDTH="fit-content width",t.FIT_CONTENT_HEIGHT="fit-content height"}(Nr||(Nr={}));var Sr=-1,yr=1,Cr=0;function Tr(t,e,n,i){if(t===e)return t?[[Cr,t]]:[];if(null!=n){var o=function(t,e,n){var i="number"==typeof n?{index:n,length:0}:n.oldRange,o="number"==typeof n?null:n.newRange,s=t.length,r=e.length;if(0===i.length&&(null===o||0===o.length)){var a=i.index,l=t.slice(0,a),h=t.slice(a),c=o?o.index:null,u=a+r-s;if((null===c||c===u)&&!(u<0||u>r)){var d=e.slice(0,u);if((N=e.slice(u))===h){var p=Math.min(a,u),f=l.slice(0,p),g=d.slice(0,p);if(f===g){var m=l.slice(p),E=d.slice(p);return Or(f,m,E,h)}}}if(null===c||c===a){var w=a,N=(d=e.slice(0,w),e.slice(w));if(d===l){var b=Math.min(s-w,r-w),S=h.slice(h.length-b),y=N.slice(N.length-b);if(S===y){m=h.slice(0,h.length-b),E=N.slice(0,N.length-b);return Or(l,m,E,S)}}}}if(i.length>0&&o&&0===o.length){f=t.slice(0,i.index),S=t.slice(i.index+i.length),p=f.length,b=S.length;if(!(r<p+b)){g=e.slice(0,p),y=e.slice(r-b);if(f===g&&S===y){m=t.slice(p,s-b),E=e.slice(p,r-b);return Or(f,m,E,S)}}}return null}(t,e,n);if(o)return o}var s=Ir(t,e),r=t.substring(0,s);s=vr(t=t.substring(s),e=e.substring(s));var a=t.substring(t.length-s),l=function(t,e){var n;if(!t)return[[yr,e]];if(!e)return[[Sr,t]];var i=t.length>e.length?t:e,o=t.length>e.length?e:t,s=i.indexOf(o);if(-1!==s)return n=[[yr,i.substring(0,s)],[Cr,o],[yr,i.substring(s+o.length)]],t.length>e.length&&(n[0][0]=n[2][0]=Sr),n;if(1===o.length)return[[Sr,t],[yr,e]];var r=function(t,e){var n=t.length>e.length?t:e,i=t.length>e.length?e:t;if(n.length<4||2*i.length<n.length)return null;function o(t,e,n){for(var i,o,s,r,a=t.substring(n,n+Math.floor(t.length/4)),l=-1,h="";-1!==(l=e.indexOf(a,l+1));){var c=Ir(t.substring(n),e.substring(l)),u=vr(t.substring(0,n),e.substring(0,l));h.length<u+c&&(h=e.substring(l-u,l)+e.substring(l,l+c),i=t.substring(0,n-u),o=t.substring(n+c),s=e.substring(0,l-u),r=e.substring(l+c))}return 2*h.length>=t.length?[i,o,s,r,h]:null}var s,r,a,l,h,c=o(n,i,Math.ceil(n.length/4)),u=o(n,i,Math.ceil(n.length/2));if(!c&&!u)return null;s=u?c&&c[4].length>u[4].length?c:u:c;t.length>e.length?(r=s[0],a=s[1],l=s[2],h=s[3]):(l=s[0],h=s[1],r=s[2],a=s[3]);var d=s[4];return[r,a,l,h,d]}(t,e);if(r){var a=r[0],l=r[1],h=r[2],c=r[3],u=r[4],d=Tr(a,h),p=Tr(l,c);return d.concat([[Cr,u]],p)}return function(t,e){for(var n=t.length,i=e.length,o=Math.ceil((n+i)/2),s=o,r=2*o,a=new Array(r),l=new Array(r),h=0;h<r;h++)a[h]=-1,l[h]=-1;a[s+1]=0,l[s+1]=0;for(var c=n-i,u=c%2!=0,d=0,p=0,f=0,g=0,m=0;m<o;m++){for(var E=-m+d;E<=m-p;E+=2){for(var w=s+E,N=(T=E===-m||E!==m&&a[w-1]<a[w+1]?a[w+1]:a[w-1]+1)-E;T<n&&N<i&&t.charAt(T)===e.charAt(N);)T++,N++;if(a[w]=T,T>n)p+=2;else if(N>i)d+=2;else if(u){if((y=s+c-E)>=0&&y<r&&-1!==l[y]){var b=n-l[y];if(T>=b)return xr(t,e,T,N)}}}for(var S=-m+f;S<=m-g;S+=2){for(var y=s+S,C=(b=S===-m||S!==m&&l[y-1]<l[y+1]?l[y+1]:l[y-1]+1)-S;b<n&&C<i&&t.charAt(n-b-1)===e.charAt(i-C-1);)b++,C++;if(l[y]=b,b>n)g+=2;else if(C>i)f+=2;else if(!u){if((w=s+c-S)>=0&&w<r&&-1!==a[w]){var T=a[w];N=s+T-w;if(T>=(b=n-b))return xr(t,e,T,N)}}}}return[[Sr,t],[yr,e]]}(t,e)}(t=t.substring(0,t.length-s),e=e.substring(0,e.length-s));return r&&l.unshift([Cr,r]),a&&l.push([Cr,a]),function t(e,n){e.push([Cr,""]);var i,o=0,s=0,r=0,a="",l="";for(;o<e.length;)if(o<e.length-1&&!e[o][1])e.splice(o,1);else switch(e[o][0]){case yr:r++,l+=e[o][1],o++;break;case Sr:s++,a+=e[o][1],o++;break;case Cr:var h=o-r-s-1;if(n){if(h>=0&&Lr(e[h][1])){var c=e[h][1].slice(-1);if(e[h][1]=e[h][1].slice(0,-1),a=c+a,l=c+l,!e[h][1]){e.splice(h,1),o--;var u=h-1;e[u]&&e[u][0]===yr&&(r++,l=e[u][1]+l,u--),e[u]&&e[u][0]===Sr&&(s++,a=e[u][1]+a,u--),h=u}}if(Ar(e[o][1])){c=e[o][1].charAt(0);e[o][1]=e[o][1].slice(1),a+=c,l+=c}}if(o<e.length-1&&!e[o][1]){e.splice(o,1);break}if(a.length>0||l.length>0){a.length>0&&l.length>0&&(0!==(i=Ir(l,a))&&(h>=0?e[h][1]+=l.substring(0,i):(e.splice(0,0,[Cr,l.substring(0,i)]),o++),l=l.substring(i),a=a.substring(i)),0!==(i=vr(l,a))&&(e[o][1]=l.substring(l.length-i)+e[o][1],l=l.substring(0,l.length-i),a=a.substring(0,a.length-i)));var d=r+s;0===a.length&&0===l.length?(e.splice(o-d,d),o-=d):0===a.length?(e.splice(o-d,d,[yr,l]),o=o-d+1):0===l.length?(e.splice(o-d,d,[Sr,a]),o=o-d+1):(e.splice(o-d,d,[Sr,a],[yr,l]),o=o-d+2)}0!==o&&e[o-1][0]===Cr?(e[o-1][1]+=e[o][1],e.splice(o,1)):o++,r=0,s=0,a="",l=""}""===e[e.length-1][1]&&e.pop();var p=!1;o=1;for(;o<e.length-1;)e[o-1][0]===Cr&&e[o+1][0]===Cr&&(e[o][1].substring(e[o][1].length-e[o-1][1].length)===e[o-1][1]?(e[o][1]=e[o-1][1]+e[o][1].substring(0,e[o][1].length-e[o-1][1].length),e[o+1][1]=e[o-1][1]+e[o+1][1],e.splice(o-1,1),p=!0):e[o][1].substring(0,e[o+1][1].length)==e[o+1][1]&&(e[o-1][1]+=e[o+1][1],e[o][1]=e[o][1].substring(e[o+1][1].length)+e[o+1][1],e.splice(o+1,1),p=!0)),o++;p&&t(e,n)}(l,i),l}function xr(t,e,n,i){var o=t.substring(0,n),s=e.substring(0,i),r=t.substring(n),a=e.substring(i),l=Tr(o,s),h=Tr(r,a);return l.concat(h)}function Ir(t,e){if(!t||!e||t.charAt(0)!==e.charAt(0))return 0;for(var n=0,i=Math.min(t.length,e.length),o=i,s=0;n<o;)t.substring(s,o)==e.substring(s,o)?s=n=o:i=o,o=Math.floor((i-n)/2+n);return Pr(t.charCodeAt(o-1))&&o--,o}function vr(t,e){if(!t||!e||t.slice(-1)!==e.slice(-1))return 0;for(var n=0,i=Math.min(t.length,e.length),o=i,s=0;n<o;)t.substring(t.length-o,t.length-s)==e.substring(e.length-o,e.length-s)?s=n=o:i=o,o=Math.floor((i-n)/2+n);return Rr(t.charCodeAt(t.length-o))&&o--,o}function Pr(t){return t>=55296&&t<=56319}function Rr(t){return t>=56320&&t<=57343}function Ar(t){return Rr(t.charCodeAt(0))}function Lr(t){return Pr(t.charCodeAt(t.length-1))}function Or(t,e,n,i){return Lr(t)||Ar(i)?null:function(t){for(var e=[],n=0;n<t.length;n++)t[n][1].length>0&&e.push(t[n]);return e}([[Cr,t],[Sr,e],[yr,n],[Cr,i]])}function kr(t,e,n){return Tr(t,e,n,!0)}kr.INSERT=yr,kr.DELETE=Sr,kr.EQUAL=Cr;var Fr,Dr,_r,Br,Mr,Ur,Vr=kr;function Hr(t){return t.reduce((t,e)=>e[0]===Vr.DELETE?t:t+e[1],"")}function zr(t,e,n){let i=0,o=0;return t.some(t=>{for(let s=0;s<t[1].length;s++){switch(t[0]*n){case Vr.INSERT:i++;break;case Vr.DELETE:i--,o++;break;case Vr.EQUAL:o++}if(o>e)return!0}return!1}),Math.max(Math.min(e,o-1)+i,0)}!function(t){t.isInstanceOfBlockFormattingContext=function(t){return t&&"Block"===t.formattingContextType}}(Fr||(Fr={})),function(t){let e;!function(t){t.INLINE="inline",t.COLUMN="column",t.REGION="region",t.PAGE="page"}(e=t.FloatReference||(t.FloatReference={}))}(Dr||(Dr={})),function(t){t.isInstanceOfAfterIfContinuesLayoutConstraint=function(t){return t&&"AfterIfContinue"==t.flagmentLayoutConstraintType}}(_r||(_r={})),function(t){t.isInstanceOfRepetitiveElementsOwnerFormattingContext=function(t){return!!t&&("RepetitiveElementsOwner"===t.formattingContextType||Mr.isInstanceOfTableFormattingContext(t))},t.isInstanceOfRepetitiveElementsOwnerLayoutConstraint=function(t){return!!t&&("RepetitiveElementsOwner"===t.flagmentLayoutConstraintType||Mr.isInstanceOfTableRowLayoutConstraint(t))}}(Br||(Br={})),function(t){t.isInstanceOfTableFormattingContext=function(t){return t&&"Table"===t.formattingContextType},t.isInstanceOfTableRowLayoutConstraint=function(t){return t&&"TableRow"===t.flagmentLayoutConstraintType}}(Mr||(Mr={})),function(t){let e,n;!function(t){t[t.IGNORE=0]="IGNORE",t[t.NEWLINE=1]="NEWLINE",t[t.PRESERVE=2]="PRESERVE"}(e=t.Whitespace||(t.Whitespace={})),function(t){t[t.NONE=0]="NONE",t[t.CONTENT=1]="CONTENT",t[t.ROOTLESS=2]="ROOTLESS",t[t.ROOTED=3]="ROOTED"}(n=t.ShadowType||(t.ShadowType={}))}(Ur||(Ur={}));const Gr={transform:!0,"transform-origin":!0},$r={top:!0,bottom:!0,left:!0,right:!0};class Wr{constructor(t,e,n){this.target=t,this.name=e,this.value=n}}const Xr={show:function(t){t.style.visibility="visible"},hide:function(t){t.style.visibility="hidden"},play:function(t){t.currentTime=0,t.play()},pause:function(t){t.pause()},resume:function(t){t.play()},mute:function(t){t.muted=!0},unmute:function(t){t.muted=!1}};function Yr(t,e){const n=Xr[e];return n?()=>{for(let e=0;e<t.length;e++)try{n(t[e])}catch(t){}}:null}class Kr extends nt{constructor(t,e){super(),this.container=t,this.bleedBox=e,this.pageAreaElement=null,this.delayedItems=[],this.elementsById={},this.dimensions={width:0,height:0},this.isFirstPage=!1,this.isLastPage=!1,this.isAutoPageWidth=!0,this.isAutoPageHeight=!0,this.spineIndex=0,this.position=null,this.offset=-1,this.side=null,this.fetchers=[],this.marginBoxes={top:{},bottom:{},left:{},right:{}};const n=this;this.hrefHandler=t=>{const e=t.currentTarget,i=e.getAttribute("href")||e.getAttributeNS(k.XLINK,"href");if(i){const o={type:"hyperlink",target:null,currentTarget:null,anchorElement:e,href:i,preventDefault(){t.preventDefault()}};n.dispatchEvent(o)}}}setAutoPageWidth(t){this.isAutoPageWidth=t,t?this.container.setAttribute(Kr.AUTO_PAGE_WIDTH_ATTRIBUTE,"true"):this.container.removeAttribute(Kr.AUTO_PAGE_WIDTH_ATTRIBUTE)}setAutoPageHeight(t){this.isAutoPageHeight=t,t?this.container.setAttribute(Kr.AUTO_PAGE_HEIGHT_ATTRIBUTE,"true"):this.container.removeAttribute(Kr.AUTO_PAGE_HEIGHT_ATTRIBUTE)}registerElementWithId(t,e){const n=this.elementsById[e];n?n.push(t):this.elementsById[e]=[t]}finish(t,e){Object.keys(this.elementsById).forEach(t=>{const e=this.elementsById[t];for(let t=0;t<e.length;)this.container.contains(e[t])?t++:e.splice(t,1);0===e.length&&delete this.elementsById[t]});const n=this.delayedItems;for(let t=0;t<n.length;t++){const e=n[t];(e.target!==this.container||"transform"!==e.name||this.isAutoPageWidth||this.isAutoPageHeight)&&V(e.target,e.name,e.value.toString())}const i=e.getElementClientRect(this.container);this.dimensions.width=i.width,this.dimensions.height=i.height;for(let e=0;e<t.length;e++){const n=t[e],i=this.elementsById[n.ref],o=this.elementsById[n.observer];if(i&&o){const t=Yr(i,n.action);if(t)for(let e=0;e<o.length;e++)o[e].addEventListener(n.event,t,!1)}}}zoom(t){V(this.container,"transform",`scale(${t})`)}getPageAreaElement(){return this.pageAreaElement||this.container}}Kr.AUTO_PAGE_WIDTH_ATTRIBUTE="data-vivliostyle-auto-page-width",Kr.AUTO_PAGE_HEIGHT_ATTRIBUTE="data-vivliostyle-auto-page-height";const jr="data-adapt-spec",qr=Ur.Whitespace;function Qr(t){switch(t){case"normal":case"nowrap":return qr.IGNORE;case"pre-line":return qr.NEWLINE;case"pre":case"pre-wrap":return qr.PRESERVE;default:return null}}function Zr(t,e){if(1==t.nodeType)return!1;const n=t.textContent;switch(e){case qr.IGNORE:return!!n.match(/^\s*$/);case qr.NEWLINE:return!!n.match(/^[ \t\f]*$/);case qr.PRESERVE:return 0==n.length}throw new Error(`Unexpected whitespace: ${e}`)}class Jr{constructor(t,e){this.flowName=t,this.parentFlowName=e,this.forcedBreakOffsets=[],this.formattingContext=null}}class ta{constructor(t,e,n,i,o,s,r,a,l){this.flowName=t,this.element=e,this.startOffset=n,this.priority=i,this.linger=o,this.exclusive=s,this.repeated=r,this.last=a,this.breakBefore=l,this.startPage=-1}isBetter(t){return!!this.exclusive&&(!t.exclusive||(this.priority>t.priority||this.last))}}function ea(t,e){return t.top-e.top}function na(t,e){return e.right-t.right}function ia(t,e){return t===e||!(!t||!e)&&(t.node===e.node&&t.shadowType===e.shadowType&&ha(t.shadowContext,e.shadowContext)&&ha(t.nodeShadow,e.nodeShadow)&&ia(t.shadowSibling,e.shadowSibling))}function oa(t,e){if(t===e)return!0;if(!t||!e)return!1;if(t.offsetInNode!==e.offsetInNode||t.after!==e.after||t.steps.length!==e.steps.length)return!1;for(let n=0;n<t.steps.length;n++)if(!ia(t.steps[n],e.steps[n]))return!1;return!0}function sa(t,e){return{steps:[{node:t.sourceNode,shadowType:aa.NONE,shadowContext:t.shadowContext,nodeShadow:null,shadowSibling:null,formattingContext:null,fragmentIndex:null!=e?e:t.fragmentIndex}],offsetInNode:0,after:!1,preprocessedTextContent:t.preprocessedTextContent}}function ra(t,e){const n=new ua(t.node,e,0);return n.shadowType=t.shadowType,n.shadowContext=t.shadowContext,n.nodeShadow=t.nodeShadow,n.shadowSibling=t.shadowSibling?ra(t.shadowSibling,e.copy()):null,n.formattingContext=t.formattingContext,n.fragmentIndex=t.fragmentIndex+1,n}const aa=Ur.ShadowType;class la{constructor(t,e,n,i,o,s,r){this.owner=t,this.root=e,this.xmldoc=n,this.parentShadow=i,this.type=s,this.styler=r,this.subShadow=null,o&&(o.subShadow=this)}equals(t){return!!t&&(this.owner===t.owner&&this.xmldoc===t.xmldoc&&this.type===t.type&&ha(this.parentShadow,t.parentShadow))}}function ha(t,e){return t===e||!!t&&!!e&&t.equals(e)}class ca{constructor(t,e){this.outer=t,this.count=e}}class ua{constructor(t,e,n){this.sourceNode=t,this.parent=e,this.boxOffset=n,this.offsetInNode=0,this.after=!1,this.nodeShadow=null,this.shadowSibling=null,this.shared=!1,this.inline=!0,this.overflow=!1,this.display=null,this.floatSide=null,this.clearSide=null,this.floatMinWrapBlock=null,this.columnSpan=null,this.verticalAlign="baseline",this.captionSide="top",this.inlineBorderSpacing=0,this.blockBorderSpacing=0,this.flexContainer=!1,this.establishesBFC=!1,this.containingBlockForAbsolute=!1,this.breakBefore=null,this.breakAfter=null,this.viewNode=null,this.clearSpacer=null,this.lang=null,this.preprocessedTextContent=null,this.repeatOnBreak=null,this.pluginProps={},this.fragmentIndex=1,this.afterIfContinues=null,this.footnotePolicy=null,this.shadowType=aa.NONE,this.shadowContext=e?e.shadowContext:null,this.breakPenalty=e?e.breakPenalty:0,this.floatReference=Dr.FloatReference.INLINE,this.whitespace=e?e.whitespace:qr.IGNORE,this.hyphenateCharacter=e?e.hyphenateCharacter:null,this.breakWord=!!e&&e.breakWord,this.inheritedProps=e?e.inheritedProps:{},this.vertical=!!e&&e.vertical,this.direction=e?e.direction:"ltr",this.firstPseudo=e?e.firstPseudo:null,this.formattingContext=e?e.formattingContext: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=Dr.FloatReference.INLINE,this.floatSide=null,this.clearSide=null,this.floatMinWrapBlock=null,this.columnSpan=null,this.verticalAlign="baseline",this.flexContainer=!1,this.whitespace=this.parent?this.parent.whitespace:qr.IGNORE,this.hyphenateCharacter=this.parent?this.parent.hyphenateCharacter:null,this.breakWord=!!this.parent&&this.parent.breakWord,this.breakBefore=null,this.breakAfter=null,this.nodeShadow=null,this.establishesBFC=!1,this.containingBlockForAbsolute=!1,this.vertical=!!this.parent&&this.parent.vertical,this.nodeShadow=null,this.preprocessedTextContent=null,this.formattingContext=this.parent?this.parent.formattingContext:null,this.repeatOnBreak=null,this.pluginProps={},this.fragmentIndex=1,this.afterIfContinues=null,this.footnotePolicy=null}cloneItem(){const t=new ua(this.sourceNode,this.parent,this.boxOffset);return t.offsetInNode=this.offsetInNode,t.after=this.after,t.nodeShadow=this.nodeShadow,t.shadowType=this.shadowType,t.shadowContext=this.shadowContext,t.shadowSibling=this.shadowSibling,t.inline=this.inline,t.breakPenalty=this.breakPenalty,t.display=this.display,t.floatReference=this.floatReference,t.floatSide=this.floatSide,t.clearSide=this.clearSide,t.floatMinWrapBlock=this.floatMinWrapBlock,t.columnSpan=this.columnSpan,t.verticalAlign=this.verticalAlign,t.captionSide=this.captionSide,t.inlineBorderSpacing=this.inlineBorderSpacing,t.blockBorderSpacing=this.blockBorderSpacing,t.establishesBFC=this.establishesBFC,t.containingBlockForAbsolute=this.containingBlockForAbsolute,t.flexContainer=this.flexContainer,t.whitespace=this.whitespace,t.hyphenateCharacter=this.hyphenateCharacter,t.breakWord=this.breakWord,t.breakBefore=this.breakBefore,t.breakAfter=this.breakAfter,t.viewNode=this.viewNode,t.clearSpacer=this.clearSpacer,t.firstPseudo=this.firstPseudo,t.vertical=this.vertical,t.overflow=this.overflow,t.preprocessedTextContent=this.preprocessedTextContent,t.formattingContext=this.formattingContext,t.repeatOnBreak=this.repeatOnBreak,t.pluginProps=Object.create(this.pluginProps),t.fragmentIndex=this.fragmentIndex,t.afterIfContinues=this.afterIfContinues,t.footnotePolicy=this.footnotePolicy,t}modify(){return this.shared?this.cloneItem():this}copy(){let t=this;do{if(t.shared)break;t.shared=!0,t=t.parent}while(t);return this}clone(){const t=this.cloneItem();let e,n=t;for(;null!=(e=n.parent);)e=e.cloneItem(),n.parent=e,n=e;return t}toNodePositionStep(){return{node:this.sourceNode,shadowType:this.shadowType,shadowContext:this.shadowContext,nodeShadow:this.nodeShadow,shadowSibling:this.shadowSibling?this.shadowSibling.toNodePositionStep():null,formattingContext:this.formattingContext,fragmentIndex:this.fragmentIndex}}toNodePosition(){let t=this;const e=[];do{t.firstPseudo&&t.parent&&t.parent.firstPseudo!==t.firstPseudo||e.push(t.toNodePositionStep()),t=t.parent}while(t);var n,i;return{steps:e,offsetInNode:this.preprocessedTextContent?(n=this.preprocessedTextContent,i=this.offsetInNode,zr(n,i,-1)):this.offsetInNode,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}walkUpBlocks(t){let e=this;for(;e;)e.inline||t(e),e=e.parent}belongsTo(t){return this.formattingContext===t&&!!this.parent&&this.parent.formattingContext===t}}class da{constructor(t){this.primary=t,this.floats=null}clone(){const t=new da(this.primary);if(this.floats){t.floats=[];for(let e=0;e<this.floats.length;++e)t.floats[e]=this.floats[e]}return t}isSamePosition(t){if(!t)return!1;if(this===t)return!0;if(!oa(this.primary,t.primary))return!1;if(this.floats){if(!t.floats||this.floats.length!==t.floats.length)return!1;for(let e=0;e<this.floats.length;e++)if(!oa(this.floats[e],t.floats[e]))return!1}else if(t.floats)return!1;return!0}}class pa{constructor(t,e){this.chunkPosition=t,this.flowChunk=e}clone(){return new pa(this.chunkPosition.clone(),this.flowChunk)}isSamePosition(t){return!!t&&(this===t||this.chunkPosition.isSamePosition(t.chunkPosition))}}class fa{constructor(){this.positions=[],this.startSide="any",this.breakAfter=null}clone(){const t=new fa,e=this.positions,n=t.positions;for(let t=0;t<e.length;t++)n[t]=e[t].clone();return t.startSide=this.startSide,t.breakAfter=this.breakAfter,t}isSamePosition(t){if(this===t)return!0;if(!t||this.positions.length!==t.positions.length)return!1;for(let e=0;e<this.positions.length;e++)if(!this.positions[e].isSamePosition(t.positions[e]))return!1;return!0}hasContent(t){return this.positions.length>0&&this.positions[0].flowChunk.startOffset<=t}}class ga{constructor(){this.page=0,this.flows={},this.flowPositions={},this.highestSeenOffset=0}clone(){const t=new ga;t.page=this.page,t.highestSeenNode=this.highestSeenNode,t.highestSeenOffset=this.highestSeenOffset,t.lookupPositionOffset=this.lookupPositionOffset,t.flows=this.flows;for(const e in this.flowPositions)t.flowPositions[e]=this.flowPositions[e].clone();return t}isSamePosition(t){if(this===t)return!0;if(!t||this.page!==t.page||this.highestSeenOffset!==t.highestSeenOffset)return!1;const e=Object.keys(this.flowPositions),n=Object.keys(t.flowPositions);if(e.length!==n.length)return!1;for(const n of e)if(!this.flowPositions[n].isSamePosition(t.flowPositions[n]))return!1;return!0}hasContent(t,e){const n=this.flowPositions[t];return!!n&&n.hasContent(e)}startSideOfFlow(t){const e=this.flowPositions[t];return e?e.startSide:"any"}firstFlowChunkOfFlow(t){const e=this.flowPositions[t];if(!e)return null;const n=e.positions[0];return n?n.flowChunk:null}}class ma{constructor(t){this.element=t,this.left=0,this.top=0,this.marginLeft=0,this.marginRight=0,this.marginTop=0,this.marginBottom=0,this.borderLeft=0,this.borderRight=0,this.borderTop=0,this.borderBottom=0,this.paddingLeft=0,this.paddingRight=0,this.paddingTop=0,this.paddingBottom=0,this.width=0,this.height=0,this.originX=0,this.originY=0,this.exclusions=null,this.innerShape=null,this.computedBlockSize=0,this.snapWidth=0,this.snapHeight=0,this.snapOffsetX=0,this.snapOffsetY=0,this.vertical=!1}getInsetTop(){return this.marginTop+this.borderTop+this.paddingTop}getInsetBottom(){return this.marginBottom+this.borderBottom+this.paddingBottom}getInsetLeft(){return this.marginLeft+this.borderLeft+this.paddingLeft}getInsetRight(){return this.marginRight+this.borderRight+this.paddingRight}getInsetBefore(){return this.vertical?this.getInsetRight():this.getInsetTop()}getInsetAfter(){return this.vertical?this.getInsetLeft():this.getInsetBottom()}getInsetStart(){return this.vertical?this.getInsetTop():this.getInsetLeft()}getInsetEnd(){return this.vertical?this.getInsetBottom():this.getInsetRight()}getBeforeEdge(t){return this.vertical?t.right:t.top}getAfterEdge(t){return this.vertical?t.left:t.bottom}getStartEdge(t){return this.vertical?t.top:t.left}getEndEdge(t){return this.vertical?t.bottom:t.right}getInlineSize(t){return this.vertical?t.bottom-t.top:t.right-t.left}getBoxSize(t){return this.vertical?t.right-t.left:t.bottom-t.top}getBoxDir(){return this.vertical?-1:1}getInlineDir(){return 1}copyFrom(t){this.element=t.element,this.left=t.left,this.top=t.top,this.marginLeft=t.marginLeft,this.marginRight=t.marginRight,this.marginTop=t.marginTop,this.marginBottom=t.marginBottom,this.borderLeft=t.borderLeft,this.borderRight=t.borderRight,this.borderTop=t.borderTop,this.borderBottom=t.borderBottom,this.paddingLeft=t.paddingLeft,this.paddingRight=t.paddingRight,this.paddingTop=t.paddingTop,this.paddingBottom=t.paddingBottom,this.width=t.width,this.height=t.height,this.originX=t.originX,this.originY=t.originY,this.innerShape=t.innerShape,this.exclusions=t.exclusions,this.computedBlockSize=t.computedBlockSize,this.snapWidth=t.snapWidth,this.snapHeight=t.snapHeight,this.vertical=t.vertical}setVerticalPosition(t,e){this.top=t,this.height=e,V(this.element,"top",`${t}px`),V(this.element,"height",`${e}px`)}setHorizontalPosition(t,e){this.left=t,this.width=e,V(this.element,"left",`${t}px`),V(this.element,"width",`${e}px`)}setBlockPosition(t,e){this.vertical?this.setHorizontalPosition(t+e*this.getBoxDir(),e):this.setVerticalPosition(t,e)}setInlinePosition(t,e){this.vertical?this.setVerticalPosition(t,e):this.setHorizontalPosition(t,e)}clear(){const t=this.element;let e;for(;e=t.lastChild;)t.removeChild(e)}getInnerShape(){const t=this.getInnerRect();return this.innerShape?this.innerShape.withOffset(t.x1,t.y1):Je(t.x1,t.y1,t.x2,t.y2)}getInnerRect(){const t=this.originX+this.left+this.getInsetLeft(),e=this.originY+this.top+this.getInsetTop();return new We(t,e,t+this.width,e+this.height)}getPaddingRect(){const t=this.originX+this.left+this.marginLeft+this.borderLeft,e=this.originY+this.top+this.marginTop+this.borderTop,n=this.paddingLeft+this.width+this.paddingRight,i=this.paddingTop+this.height+this.paddingBottom;return new We(t,e,t+n,e+i)}getOuterShape(t,e){const n=this.getOuterRect();return En(t,n.x1,n.y1,n.x2-n.x1,n.y2-n.y1,e)}getOuterRect(){const t=this.originX+this.left,e=this.originY+this.top,n=this.getInsetLeft()+this.width+this.getInsetRight(),i=this.getInsetTop()+this.height+this.getInsetBottom();return new We(t,e,t+n,e+i)}}class Ea extends ge{constructor(t,e,n,i){super(),this.elem=t,this.context=e,this.rootContentValue=n,this.exprContentListener=i}visitStrInner(t,e){e||(e=this.elem.ownerDocument.createTextNode(t)),this.elem.appendChild(e)}visitStr(t){return this.visitStrInner(t.str),null}visitURL(t){if(this.rootContentValue.url)this.elem.setAttribute("src",t.url);else{const e=this.elem.ownerDocument.createElementNS(k.XHTML,"img");e.setAttribute("src",t.url),this.elem.appendChild(e)}return null}visitSpaceList(t){return this.visitValues(t.values),null}visitExpr(t){const e=t.toExpr();let n=e.evaluate(this.context);if("string"==typeof n){e instanceof ne&&(n=mo(e.scope,new hi(n,null),"").stringValue()),this.elem.ownerDocument;const t=this.exprContentListener(e,n,this.elem.ownerDocument);this.visitStrInner(n,t)}return null}}function wa(t){return null!=t&&t!==Me.normal&&t!==Me.none&&t!==Me.inherit}const Na=Dr.FloatReference;function ba(t){switch(t){case Na.INLINE:return!1;case Na.COLUMN:case Na.REGION:case Na.PAGE:return!0;default:throw new Error(`Unknown float-reference: ${t}`)}}class Sa{constructor(t,e,n,i,o,s){this.nodePosition=t,this.floatReference=e,this.floatSide=n,this.clearSide=i,this.flowName=o,this.floatMinWrapBlock=s,this.order=null,this.id=null}getOrder(){if(null===this.order)throw new Error("The page float is not yet added");return this.order}getId(){if(!this.id)throw new Error("The page float is not yet added");return this.id}isAllowedOnContext(t){return t.isAnchorAlreadyAppeared(this.getId())}isAllowedToPrecede(t){return!1}}class ya{constructor(){this.floats=[],this.nextPageFloatIndex=0}nextOrder(){return this.nextPageFloatIndex++}createPageFloatId(t){return`pf${t}`}addPageFloat(t){if(this.floats.findIndex(e=>oa(e.nodePosition,t.nodePosition))>=0)throw new Error("A page float with the same source node is already registered");{const e=t.order=this.nextOrder();t.id=this.createPageFloatId(e),this.floats.push(t)}}findPageFloatByNodePosition(t){const e=this.floats.findIndex(e=>oa(e.nodePosition,t));return e>=0?this.floats[e]:null}findPageFloatById(t){const e=this.floats.findIndex(e=>e.id===t);return e>=0?this.floats[e]:null}}class Ca{constructor(t,e,n,i,o){this.floatReference=t,this.floatSide=e,this.continuations=n,this.area=i,this.continues=o}hasFloat(t){return this.continuations.some(e=>e.float===t)}findNotAllowedFloat(t){for(let e=this.continuations.length-1;e>=0;e--){const n=this.continuations[e].float;if(!n.isAllowedOnContext(t))return n}return null}getOuterShape(){return this.area.getOuterShape(null,null)}getOuterRect(){return this.area.getOuterRect()}getOrder(){const t=this.continuations.map(t=>t.float);return Math.min.apply(null,t.map(t=>t.getOrder()))}shouldBeStashedBefore(t){return this.getOrder()<t.getOrder()}addContinuations(t){t.forEach(t=>{this.continuations.push(t)})}getFlowName(){const t=this.continuations[0].float.flowName;return this.continuations.every(e=>e.float.flowName===t),t}}class Ta{constructor(t,e){this.float=t,this.nodePosition=e}equals(t){return!!t&&(this===t||this.float===t.float&&oa(this.nodePosition,t.nodePosition))}}class xa{constructor(t,e,n,i,o,s,r){this.parent=t,this.floatReference=e,this.container=n,this.flowName=i,this.generatingNodePosition=o,this.children=[],this.invalidated=!1,this.forbiddenFloats=[],this.floatFragments=[],this.stashedFloatFragments=[],this.floatAnchors={},this.floatsDeferredToNext=[],this.layoutConstraints=[],this.locked=!1,t&&t.children.push(this),this.writingMode=s||t&&t.writingMode||Me.horizontal_tb,this.direction=r||t&&t.direction||Me.ltr,this.floatStore=t?t.floatStore:new ya;const a=this.getPreviousSibling();this.floatsDeferredFromPrevious=a?[].concat(a.floatsDeferredToNext):[]}getParent(t){if(!this.parent)throw new Error(`No PageFloatLayoutContext for ${t}`);return this.parent}getPreviousSiblingOf(t,e,n,i){let o=this.children.indexOf(t);o<0&&(o=this.children.length);for(let t=o-1;t>=0;t--){let o=this.children[t];if(o.floatReference===e&&o.flowName===n&&oa(o.generatingNodePosition,i))return o;if(o=o.getPreviousSiblingOf(null,e,n,i),o)return o}return null}getPreviousSibling(){let t,e=this,n=this.parent;for(;n;){if(t=n.getPreviousSiblingOf(e,this.floatReference,this.flowName,this.generatingNodePosition),t)return t;e=n,n=n.parent}return null}getContainer(t){return t&&t!==this.floatReference?this.getParent(t).getContainer(t):this.container}setContainer(t){this.container=t,this.reattachFloatFragments()}addPageFloat(t){this.floatStore.addPageFloat(t)}getPageFloatLayoutContext(t){return t===this.floatReference?this:this.getParent(t).getPageFloatLayoutContext(t)}findPageFloatByNodePosition(t){return this.floatStore.findPageFloatByNodePosition(t)}forbid(t){const e=t.getId(),n=t.floatReference;if(n===this.floatReference){if(!this.forbiddenFloats.includes(e)){this.forbiddenFloats.push(e),(new va).findByFloat(t).forbid(t,this)}}else{this.getParent(n).forbid(t)}}isForbidden(t){const e=t.getId(),n=t.floatReference;if(n===this.floatReference)return this.forbiddenFloats.includes(e);return this.getParent(n).isForbidden(t)}addPageFloatFragment(t,e){const n=t.floatReference;if(n!==this.floatReference){this.getParent(n).addPageFloatFragment(t,e)}else this.floatFragments.includes(t)||(this.floatFragments.push(t),this.floatFragments.sort((t,e)=>t.getOrder()-e.getOrder()));e||this.invalidate()}removePageFloatFragment(t,e){const n=t.floatReference;if(n!==this.floatReference){this.getParent(n).removePageFloatFragment(t,e)}else{const n=this.floatFragments.indexOf(t);if(n>=0){const t=this.floatFragments.splice(n,1)[0],i=t.area&&t.area.element;i&&i.parentNode&&i.parentNode.removeChild(i),e||this.invalidate()}}}findPageFloatFragment(t){if(t.floatReference!==this.floatReference){return this.getParent(t.floatReference).findPageFloatFragment(t)}const e=this.floatFragments.findIndex(e=>e.hasFloat(t));return e>=0?this.floatFragments[e]:null}hasFloatFragments(t){return!(!(this.floatFragments.length>0)||t&&!this.floatFragments.some(t))||!!this.parent&&this.parent.hasFloatFragments(t)}hasContinuingFloatFragmentsInFlow(t){return this.hasFloatFragments(e=>e.continues&&e.getFlowName()===t)}registerPageFloatAnchor(t,e){this.floatAnchors[t.getId()]=e}collectPageFloatAnchors(){const t=Object.assign({},this.floatAnchors);return this.children.reduce((t,e)=>Object.assign(t,e.collectPageFloatAnchors()),t)}isAnchorAlreadyAppeared(t){if(this.getDeferredPageFloatContinuations().some(e=>e.float.getId()===t))return!0;const e=this.collectPageFloatAnchors()[t];return!!e&&(!(!this.container||!this.container.element)&&this.container.element.contains(e))}deferPageFloat(t){const e=t.float;if(e.floatReference===this.floatReference){const n=this.floatsDeferredToNext.findIndex(t=>t.float===e);n>=0?this.floatsDeferredToNext.splice(n,1,t):this.floatsDeferredToNext.push(t)}else{this.getParent(e.floatReference).deferPageFloat(t)}}hasPrecedingFloatsDeferredToNext(t,e){if(!e&&t.floatReference!==this.floatReference)return this.getParent(t.floatReference).hasPrecedingFloatsDeferredToNext(t,!1);const n=t.getOrder();return!!this.floatsDeferredToNext.some(e=>e.float.getOrder()<n&&!t.isAllowedToPrecede(e.float))||!!this.parent&&this.parent.hasPrecedingFloatsDeferredToNext(t,!0)}getLastFollowingFloatInFragments(t){const e=t.getOrder();let n=null;if(this.floatFragments.forEach(t=>{t.continuations.forEach(t=>{const i=t.float,o=i.getOrder();o>e&&(!n||o>n.getOrder())&&(n=i)})}),this.parent){const e=this.parent.getLastFollowingFloatInFragments(t);e&&(!n||e.getOrder()>n.getOrder())&&(n=e)}return n}getDeferredPageFloatContinuations(t){t=t||this.flowName;let e=this.floatsDeferredFromPrevious.filter(e=>!t||e.float.flowName===t);return this.parent&&(e=this.parent.getDeferredPageFloatContinuations(t).concat(e)),e.sort((t,e)=>t.float.getOrder()-e.float.getOrder())}getPageFloatContinuationsDeferredToNext(t){t=t||this.flowName;const e=this.floatsDeferredToNext.filter(e=>!t||e.float.flowName===t);return this.parent?this.parent.getPageFloatContinuationsDeferredToNext(t).concat(e):e}getFloatsDeferredToNextInChildContexts(){let t=[];const e=[];for(let n=this.children.length-1;n>=0;n--){const i=this.children[n];e.includes(i.flowName)||(e.push(i.flowName),t=t.concat(i.floatsDeferredToNext.map(t=>t.float)),t=t.concat(i.getFloatsDeferredToNextInChildContexts()))}return t}checkAndForbidNotAllowedFloat(){if(this.checkAndForbidFloatFollowingDeferredFloat())return!0;for(let t=this.floatFragments.length-1;t>=0;t--){const e=this.floatFragments[t],n=e.findNotAllowedFloat(this);if(n)return this.locked?this.invalidate():(this.removePageFloatFragment(e),this.forbid(n),this.removeEndFloatFragments(e.floatSide)),!0}return!(this.floatReference!==Na.REGION||!this.parent.locked)&&this.parent.checkAndForbidNotAllowedFloat()}checkAndForbidFloatFollowingDeferredFloat(){const t=this.getFloatsDeferredToNextInChildContexts(),e=this.floatFragments.reduce((t,e)=>t.concat(e.continuations.map(t=>t.float)),[]);e.sort((t,e)=>e.getOrder()-t.getOrder());for(const n of e){const e=n.getOrder();if(t.some(t=>!n.isAllowedToPrecede(t)&&e>t.getOrder())){if(this.locked)this.invalidate();else{this.forbid(n);const t=this.findPageFloatFragment(n);this.removePageFloatFragment(t)}return!0}}return!1}finish(){if(!this.checkAndForbidNotAllowedFloat()){for(let t=this.floatsDeferredToNext.length-1;t>=0;t--){if(!this.floatsDeferredToNext[t].float.isAllowedOnContext(this)){if(this.locked)return void this.invalidate();this.floatsDeferredToNext.splice(t,1)}}this.floatsDeferredFromPrevious.forEach(t=>{this.floatsDeferredToNext.findIndex(e=>t.equals(e))>=0||this.floatFragments.some(e=>e.hasFloat(t.float))||this.floatsDeferredToNext.push(t)})}}hasSameContainerAs(t){return!!this.container&&!!t.container&&this.container.element===t.container.element}invalidate(){this.invalidated=!0,this.locked||(this.container&&(this.children.forEach(t=>{this.hasSameContainerAs(t)&&t.floatFragments.forEach(t=>{const e=t.area.element;e&&e.parentNode&&e.parentNode.removeChild(e)})}),this.container.clear()),this.children.forEach(t=>{t.layoutConstraints.splice(0)}),this.children.splice(0),Object.keys(this.floatAnchors).forEach(t=>{delete this.floatAnchors[t]}))}detachChildren(){const t=this.children.splice(0);return t.forEach(t=>{t.floatFragments.forEach(t=>{const e=t.area.element;e&&e.parentNode&&e.parentNode.removeChild(e)})}),t}attachChildren(t){t.forEach(t=>{this.children.push(t),t.reattachFloatFragments()})}isInvalidated(){return this.invalidated||!!this.parent&&this.parent.isInvalidated()}validate(){this.invalidated=!1}toLogical(t){return function(t,e,n){return gr(t,e,n||null,wr)}(t,this.writingMode.toString(),this.direction.toString())}toPhysical(t){return function(t,e,n){return gr(t,e,n||null,Er)}(t,this.writingMode.toString(),this.direction.toString())}removeEndFloatFragments(t){const e=this.toLogical(t);if("block-end"===e||"inline-end"===e){let t=0;for(;t<this.floatFragments.length;){const n=this.floatFragments[t];this.toLogical(n.floatSide)===e?this.removePageFloatFragment(n):t++}}}stashEndFloatFragments(t){const e=t.floatReference;if(e!==this.floatReference)return void this.getParent(e).stashEndFloatFragments(t);const n=this.toLogical(t.floatSide);if("block-end"===n||"snap-block"===n||"inline-end"===n){let e=0;for(;e<this.floatFragments.length;){const i=this.floatFragments[e],o=this.toLogical(i.floatSide);(o===n||"snap-block"===n&&"block-end"===o)&&i.shouldBeStashedBefore(t)?(this.stashedFloatFragments.push(i),this.floatFragments.splice(e,1)):e++}}}restoreStashedFragments(t){t===this.floatReference?(this.stashedFloatFragments.forEach(t=>{this.addPageFloatFragment(t,!0)}),this.stashedFloatFragments.splice(0)):this.getParent(t).restoreStashedFragments(t)}discardStashedFragments(t){t===this.floatReference?this.stashedFloatFragments.splice(0):this.getParent(t).discardStashedFragments(t)}getStashedFloatFragments(t){return t===this.floatReference?this.stashedFloatFragments.concat().sort((t,e)=>e.getOrder()-t.getOrder()):this.getParent(t).getStashedFloatFragments(t)}getLimitValue(t,e,n,i){this.container;const o=this.toLogical(t),s=this.toPhysical(t),r=this.getLimitValueInner(o,e,n,i);if(this.parent&&this.parent.container){const t=this.parent.getLimitValue(s,e,n,i);switch(s){case"top":case"left":return Math.max(r,t);case"bottom":case"right":return Math.min(r,t)}}return r}getLimitValueInner(t,e,n,i){this.container;const o=this.getLimitValuesInner(e,n,i);switch(t){case"block-start":return this.container.vertical?o.right:o.top;case"block-end":return this.container.vertical?o.left:o.bottom;case"inline-start":return this.container.vertical?o.top:o.left;case"inline-end":return this.container.vertical?o.bottom:o.right;default:throw new Error(`Unknown logical side: ${t}`)}}getLimitValuesInner(t,e,n){this.container;const i=this.container.originX,o=this.container.originY,s=this.container.getPaddingRect();let r={top:s.y1-o,left:s.x1-i,bottom:s.y2-o,right:s.x2-i,floatMinWrapBlockStart:0,floatMinWrapBlockEnd:0};function a(n,i,o){return"%"===n.unit?o*n.num/100:t.convertLengthToPx(n,i,e)}const l=this.floatFragments;return l.length>0&&(r=l.reduce((t,e)=>{if(n&&!n(e,this))return t;const i=this.toLogical(e.floatSide),o=e.area,r=e.continuations[0].float.floatMinWrapBlock;let l=t.top,h=t.left,c=t.bottom,u=t.right,d=t.floatMinWrapBlockStart,p=t.floatMinWrapBlockEnd;switch(i){case"inline-start":o.vertical?l=Math.max(l,o.top+o.height):h=Math.max(h,o.left+o.width);break;case"block-start":o.vertical?(r&&o.left<u&&(d=a(r,o.rootViewNodes[0],s.x2-s.x1)),u=Math.min(u,o.left)):(r&&o.top+o.height>l&&(d=a(r,o.rootViewNodes[0],s.y2-s.y1)),l=Math.max(l,o.top+o.height));break;case"inline-end":o.vertical?c=Math.min(c,o.top):u=Math.min(u,o.left);break;case"block-end":o.vertical?(r&&o.left+o.width>h&&(p=a(r,o.rootViewNodes[0],s.x2-s.x1)),h=Math.max(h,o.left+o.width)):(r&&o.top<c&&(p=a(r,o.rootViewNodes[0],s.y2-s.y1)),c=Math.min(c,o.top));break;default:throw new Error(`Unknown logical float side: ${i}`)}return{top:l,left:h,bottom:c,right:u,floatMinWrapBlockStart:d,floatMinWrapBlockEnd:p}},r)),r.left+=i,r.right+=i,r.top+=o,r.bottom+=o,r}setFloatAreaDimensions(t,e,n,i,o,s,r){if(e!==this.floatReference){return this.getParent(e).setFloatAreaDimensions(t,e,n,i,o,s,r)}let a=this.toLogical(n);if("snap-block"===a){if(!r["block-start"]&&!r["block-end"])return null}else if(!r[a])return null;t.clientLayout;let l=this.getLimitValue("block-start",t.layoutContext,t.clientLayout),h=this.getLimitValue("block-end",t.layoutContext,t.clientLayout),c=this.getLimitValue("inline-start",t.layoutContext,t.clientLayout),u=this.getLimitValue("inline-end",t.layoutContext,t.clientLayout);const d=t.vertical?t.originX:t.originY,p=t.vertical?t.originY:t.originX;function f(e,n){let i=e(t.bands,n);return i?(t.vertical&&(i=an(i)),l=t.vertical?Math.min(l,i.x2):Math.max(l,i.y1),h=t.vertical?Math.max(h,i.x1):Math.min(h,i.y2),!0):s}let g,m,E,w;if(l=t.vertical?Math.min(l,t.left+t.getInsetLeft()+t.width+t.getInsetRight()+d):Math.max(l,t.top+d),h=t.vertical?Math.max(h,t.left+d):Math.min(h,t.top+t.getInsetTop()+t.height+t.getInsetBottom()+d),o){const e=t.vertical?rn(new We(h,c,l,u)):new We(c,l,u,h);if(("block-start"===a||"snap-block"===a||"inline-start"===a)&&!f(un,e))return null;if(("block-end"===a||"snap-block"===a||"inline-end"===a)&&!f(dn,e))return null;if(E=(h-l)*t.getBoxDir(),g=E-t.getInsetBefore()-t.getInsetAfter(),w=u-c,m=w-t.getInsetStart()-t.getInsetEnd(),!s&&(g<=0||m<=0))return null}else{g=t.computedBlockSize,E=g+t.getInsetBefore()+t.getInsetAfter();const e=(h-l)*t.getBoxDir();if("snap-block"===a){if(null===i)a="block-start";else{const t=this.container.getPaddingRect();a=this.container.getBoxDir()*(i-(this.container.vertical?t.x2:t.y1))<=this.container.getBoxDir()*((this.container.vertical?t.x1:t.y2)-i-E)?"block-start":"block-end"}if(!r[a]){if(!r["block-end"])return null;a="block-end"}}if(!s&&e<E)return null;m="inline-start"===a||"inline-end"===a?br(t.clientLayout,t.element,[Nr.FIT_CONTENT_INLINE_SIZE])[Nr.FIT_CONTENT_INLINE_SIZE]:t.adjustContentRelativeSize?t.getContentInlineSize():t.vertical?t.height:t.width,w=m+t.getInsetStart()+t.getInsetEnd();const n=u-c;if(!s&&n<w)return null}switch(l-=d,h-=d,c-=p,u-=p,a){case"inline-start":case"block-start":case"snap-block":t.setInlinePosition(c,m),t.setBlockPosition(l,g);break;case"inline-end":case"block-end":t.setInlinePosition(u-w,m),t.setBlockPosition(h-E*t.getBoxDir(),g);break;default:throw new Error(`unknown float direction: ${n}`)}return a}getFloatFragmentExclusions(){const t=this.floatFragments.map(t=>t.getOuterShape());return this.parent?this.parent.getFloatFragmentExclusions().concat(t):t}reattachFloatFragments(){const t=this.container.element&&this.container.element.parentNode;t&&this.floatFragments.forEach(e=>{t.appendChild(e.area.element)})}getMaxReachedAfterEdge(){const t=this.getContainer().vertical;return this.floatFragments.reduce((e,n)=>{const i=n.getOuterRect();return t?Math.min(e,i.x1):Math.max(e,i.y2)},t?1/0:0)}getBlockStartEdgeOfBlockEndFloats(){const t=this.getContainer().vertical;return this.floatFragments.filter(t=>"block-end"===t.floatSide).reduce((e,n)=>{const i=n.getOuterRect();return t?Math.max(e,i.x2):Math.min(e,i.y1)},t?0:1/0)}getPageFloatClearEdge(t,e){function n(t){return e=>t.isAnchorAlreadyAppeared(e.float.getId())}function i(t,e){return t.continuations.some(n(e))}const o=e.getPaddingRect(),s=e.vertical?o.x1:o.y2;let r=this;for(;r;){if(r.floatsDeferredToNext.some(n(r)))return s;r=r.parent}e.clientLayout;const a=this.getLimitValue("block-start",e.layoutContext,e.clientLayout,i);return this.getLimitValue("block-end",e.layoutContext,e.clientLayout,i)*e.getBoxDir()<s*e.getBoxDir()?s:a}getPageFloatPlacementCondition(t,e,n){if(t.floatReference!==this.floatReference){return this.getParent(t.floatReference).getPageFloatPlacementCondition(t,e,n)}const i={"block-start":!0,"block-end":!0,"inline-start":!0,"inline-end":!0};if(!n)return i;const o=this.toLogical(e),s=this.toLogical(n);let r;r="all"===s?["block-start","block-end","inline-start","inline-end"]:"both"===s?["inline-start","inline-end"]:"same"===s?"snap-block"===o?["block-start","block-end"]:[o]:[s];const a=t.getOrder();function l(t){return e=>e.floatSide===t&&e.getOrder()<a}return r.forEach(t=>{switch(t){case"block-start":case"inline-start":i[t]=!function t(e,n){return e.children.some(e=>e.floatFragments.some(l(n))||t(e,n))}(this,t);break;case"block-end":case"inline-end":i[t]=!function t(e,n){const i=e.parent;return!!i&&(i.floatFragments.some(l(n))||t(i,n))}(this,t);break;default:throw new Error(`Unexpected side: ${t}`)}}),i}getLayoutConstraints(){return(this.parent?this.parent.getLayoutConstraints():[]).concat(this.layoutConstraints)}addLayoutConstraint(t,e){e===this.floatReference?this.layoutConstraints.push(t):this.getParent(e).addLayoutConstraint(t,e)}isColumnFullWithPageFloats(t){const e=t.layoutContext,n=t.clientLayout;let i=this,o=null;for(;i&&i.container;){const s=i.getLimitValuesInner(e,n);o?t.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,i=i.parent}const s=Math.max(o.floatMinWrapBlockStart,o.floatMinWrapBlockEnd);return(t.vertical?o.right-o.left:o.bottom-o.top)<=s}getMaxBlockSizeOfPageFloats(){const t=this.getContainer().vertical;return this.floatFragments.length?Math.max.apply(null,this.floatFragments.map(e=>{const n=e.area;return t?n.width:n.height})):0}lock(){this.locked=!0}unlock(){this.locked=!1}isLocked(){return this.locked}}const Ia=[];class va{static register(t){Ia.push(t)}findByNodeContext(t){for(let e=Ia.length-1;e>=0;e--){const n=Ia[e];if(n.appliesToNodeContext(t))return n}throw new Error(`No PageFloatLayoutStrategy found for ${t}`)}findByFloat(t){for(let e=Ia.length-1;e>=0;e--){const n=Ia[e];if(n.appliesToFloat(t))return n}throw new Error(`No PageFloatLayoutStrategy found for ${t}`)}}va.register(new class{appliesToNodeContext(t){return ba(t.floatReference)}appliesToFloat(t){return!0}createPageFloat(t,e,n){let i=t.floatReference;t.floatSide;const o=t.floatSide,s=t.toNodePosition();return n.resolveFloatReferenceFromColumnSpan(i,t.columnSpan,t).thenAsync(n=>{i=n,e.flowName;const r=new Sa(s,i,o,t.clearSide,e.flowName,t.floatMinWrapBlock);return e.addPageFloat(r),fi(r)})}createPageFloatFragment(t,e,n,i){const o=t[0].float;return new Ca(o.floatReference,e,t,n,i)}findPageFloatFragment(t,e){return e.findPageFloatFragment(t)}adjustPageFloatArea(t,e,n){}forbid(t,e){}});const Pa=Ca;class Ra extends Sa{constructor(t,e,n,i,o){super(t,e,"block-end",null,n,o),this.footnotePolicy=i}isAllowedToPrecede(t){return!(t instanceof Ra)}}class Aa extends Pa{constructor(t,e,n,i){super(t,"block-end",e,n,i)}getOrder(){return 1/0}shouldBeStashedBefore(t){return t instanceof Ra||this.getOrder()<t.getOrder()}}class La{constructor(t){this.footnote=t}allowLayout(t){return!oa(t.toNodePosition(),this.footnote.nodePosition)}}va.register(new class{appliesToNodeContext(t){return"footnote"===t.floatSide}appliesToFloat(t){return t instanceof Ra}createPageFloat(t,e,n){let i=Na.REGION;const o=e.getPageFloatLayoutContext(i);e.getPageFloatLayoutContext(Na.PAGE).hasSameContainerAs(o)&&(i=Na.PAGE);const s=t.toNodePosition();e.flowName;const r=new Ra(s,i,e.flowName,t.footnotePolicy,t.floatMinWrapBlock);return e.addPageFloat(r),fi(r)}createPageFloatFragment(t,e,n,i){const o=t[0].float;return new Aa(o.floatReference,t,n,i)}findPageFloatFragment(t,e){const n=e.getPageFloatLayoutContext(t.floatReference).floatFragments.filter(t=>t instanceof Aa);return n.length,n[0]||null}adjustPageFloatArea(t,e,n){t.isFootnote=!0,t.adjustContentRelativeSize=!1;const i=t.element;t.vertical=n.layoutContext.applyFootnoteStyle(e.vertical,n.layoutContext.nodeContext&&"rtl"===n.layoutContext.nodeContext.direction,i),t.convertPercentageSizesToPx(i),n.setComputedInsets(i,t),n.setComputedWidthAndHeight(i,t)}forbid(t,e){const n=t;switch(n.footnotePolicy){case Me.line:{const t=new La(n);e.addLayoutConstraint(t,n.floatReference);break}}}});const Oa={page:!0,left:!0,right:!0,recto:!0,verso:!0,column:!0,region:!0};function ka(t){return!!Oa[t]}const Fa={avoid:!0,"avoid-page":!0,"avoid-column":!0,"avoid-region":!0};function Da(t){return!!Fa[t]}function _a(t,e){if(!t)return e;if(!e)return t;{const n=ka(t),i=ka(e);if(!n||!i)return i?e:n?t:Da(e)?e:Da(t)?t:e;switch(e){case"column":return t;case"region":return"column"===t?e:t;default:return e}}}function Ba(t){switch(t){case"left":case"right":case"recto":case"verso":return t;default:return"any"}}function Ma(t){switch(t){case"left":case"right":case"recto":case"verso":return t;default:return null}}function Ua(t,e,n,i){const o=t.viewNode;if(!o)return NaN;if(1==o.nodeType){if(t.after||!t.inline){const n=e.getElementClientRect(o);if(n.right>=n.left&&n.bottom>=n.top)return t.after?i?n.left:n.bottom:i?n.right:n.top}return NaN}{let s=NaN;const r=o.ownerDocument.createRange(),a=o.textContent.length;if(!a)return NaN;t.after&&(n+=a),n>=a&&(n=a-1),r.setStart(o,n),r.setEnd(o,n+1);let l=e.getRangeClientRects(r);i&&function(t){if(null==it){const e=t.ownerDocument,n=e.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.width="100px",n.style.height="100px",n.style.overflow="hidden",n.style.lineHeight="16px",n.style.fontSize="16px",V(n,"writing-mode","vertical-rl"),t.appendChild(n);const i=e.createTextNode("a a a a a a a a a a a a a a a a");n.appendChild(i);const o=e.createRange();o.setStart(i,0),o.setEnd(i,1);const s=o.getBoundingClientRect();it=s.right-s.left<10,t.removeChild(n)}return it}(document.body)&&(l=function(t,e,n){const i=n.ownerDocument.createRange();i.setStart(n,0),i.setEnd(n,n.textContent.length);const o=t.getRangeClientRects(i),s=[];for(const t of e){let e;for(e=0;e<o.length;e++){const n=o[e];if(t.top>=n.top&&t.bottom<=n.bottom&&Math.abs(t.left-n.left)<1){s.push({top:t.top,left:n.left,bottom:t.bottom,right:n.right});break}}e==o.length&&(h.warn("Could not fix character box"),s.push(t))}return s}(e,l,o));let c=0;for(const t of l){const e=i?t.bottom-t.top:t.right-t.left;t.right>t.left&&t.bottom>t.top&&(isNaN(s)||e>c)&&(s=i?t.left:t.bottom,c=e)}return s}}function Va(t,e,n){const i=e.clientLayout.getElementClientRect(t),o=e.getComputedMargin(t);return n?i.width+o.left+o.right:i.height+o.top+o.bottom}function Ha(t){for(;t;){if(t.parentNode===t.ownerDocument)return!1;t=t.parentNode}return!0}function za(t,e){if(!t)return;let n;for(;(n=t.lastChild)!=e;)t.removeChild(n)}function Ga(t){return!!t.getAttribute(jr)}function $a(t){if(!t)return!1;const e=t.viewNode;return!(!e||1!==e.nodeType)&&Ga(e)}d("SIMPLE_PROPERTY",(function(t){const e=t.name,n=t.value;switch(e){case"page-break-before":case"page-break-after":case"page-break-inside":return{name:e.replace(/^page-/,""),value:n===Me.always?Me.page:n,important:t.important};default:return t}}));class Wa{calculateOffset(t){return Xa(this.getNodeContext(),t.collectElementsOffset())}breakPositionChosen(t){}getNodeContext(){return null}}function Xa(t,e){return{current:e.reduce((e,n)=>e+n.calculateOffset(t),0),minimum:e.reduce((e,n)=>e+n.calculateMinimumOffset(t),0)}}class Ya extends Wa{constructor(t,e,n,i){super(),this.position=t,this.breakOnEdge=e,this.overflows=n,this.computedBlockSize=i,this.isEdgeUpdated=!1,this.edge=0,this.overflowIfRepetitiveElementsDropped=n}findAcceptableBreak(t,e){return this.updateOverflows(t),e<this.getMinBreakPenalty()?null:t.findEdgeBreakPosition(this)}getMinBreakPenalty(){if(!this.isEdgeUpdated)throw new Error("EdgeBreakPosition.prototype.updateEdge not called");const t=this.isFirstContentOfRepetitiveElementsOwner()&&!this.overflowIfRepetitiveElementsDropped;return(Da(this.breakOnEdge)?1:0)+(this.overflows&&!t?3:0)+(this.position.parent?this.position.parent.breakPenalty:0)}updateEdge(t){const e=t.calculateClonedPaddingBorder(this.position);this.edge=Ua(this.position,t.clientLayout,0,t.vertical)+e,this.isEdgeUpdated=!0}updateOverflows(t){this.isEdgeUpdated||this.updateEdge(t);const e=this.edge,n=this.calculateOffset(t);this.overflowIfRepetitiveElementsDropped=t.isOverflown(e+(t.vertical?-1:1)*n.minimum),this.overflows=this.position.overflow=t.isOverflown(e+(t.vertical?-1:1)*n.current)}getNodeContext(){return this.position}isFirstContentOfRepetitiveElementsOwner(){const t=this.getNodeContext();if(!t||!t.parent)return!1;const{formattingContext:e}=t.parent;if(!Br.isInstanceOfRepetitiveElementsOwnerFormattingContext(e))return!1;const n=e.getRepetitiveElements();return!!n&&n.isFirstContentNode(t)}}const Ka="data-vivliostyle-flow-root";function ja(t){const e=t.toString();let n;switch(e){case"inline-flex":n="flex";break;case"inline-grid":n="grid";break;case"inline-table":n="table";break;case"inline":case"table-row-group":case"table-column":case"table-column-group":case"table-header-group":case"table-footer-group":case"table-row":case"table-cell":case"table-caption":case"inline-block":n="block";break;default:n=e}return xe(n)}function qa(t){return t===Me.absolute||t===Me.fixed}function Qa(t,e,n,i){return t===Me.none||(qa(e)?(n=Me.none,t=ja(t)):(n&&n!==Me.none||i)&&(t=ja(t))),{display:t,position:e,float:n}}function Za(t,e,n,i){return Qa(t,e,n,i).display===Me.block}function Ja(t){switch(t.toString()){case"inline":case"inline-block":case"inline-list-item":case"inline-flex":case"inline-grid":case"ruby":case"inline-table":return!0;default:return!1}}class tl{find(e){const n=f(t.HOOKS.RESOLVE_LAYOUT_PROCESSOR);for(let t=0;t<n.length;t++){const i=n[t](e);if(i)return i}throw new Error(`No processor found for a formatting context: ${e.getName()}`)}}class el{layout(t,e,n){return e.isFloatNodeContext(t)?e.layoutFloatOrFootnote(t):e.isBreakable(t)?e.layoutBreakableBlock(t):e.layoutUnbreakable(t)}createEdgeBreakPosition(t,e,n,i){return new Ya(t.copy(),e,n,i)}startNonInlineElementNode(t){return!1}afterNonInlineElementNode(t,e){return!1}clearOverflownViewNodes(t,e,n,i){if(!n.viewNode)return;if(!n.viewNode.parentNode)return;const o=n.viewNode.parentNode;za(o,n.viewNode),i&&o.removeChild(n.viewNode)}finishBreak(t,e,n,i){const o=n||null!=e.viewNode&&1==e.viewNode.nodeType&&!e.after;return t.clearOverflownViewNodes(e,o),i&&(t.fixJustificationIfNeeded(e,!0),t.layoutContext.processFragmentedBlockEdge(o?e:e.parent)),fi(!0)}}class nl{constructor(t){this.parent=t,this.formattingContextType="Block"}getName(){return"Block formatting context (BlockFormattingContext)"}isFirstTime(t,e){return e}getParent(){return this.parent}saveState(){}restoreState(t){}}const il=new el,ol=Fr.isInstanceOfBlockFormattingContext;d(t.HOOKS.RESOLVE_FORMATTING_CONTEXT,(t,e,n,i,o,s)=>{const r=t.parent;return!r&&t.formattingContext?null:r&&t.formattingContext!==r.formattingContext?null:t.establishesBFC||!t.formattingContext&&Za(n,i,o,s)?new nl(r?r.formattingContext:null):null}),d(t.HOOKS.RESOLVE_LAYOUT_PROCESSOR,t=>t instanceof nl?il:null);class sl{constructor(){this.initialBreakPositions=null,this.initialStateOfFormattingContext=null}layout(t,e){return this.prepareLayout(t,e),this.tryLayout(t,e)}tryLayout(t,e){const n=pi("AbstractLayoutRetryer.tryLayout");this.saveState(t,e);const i=this.resolveLayoutMode(t);return i.doLayout(t,e).then(o=>{let s=i.accept(o,e);s=i.postLayout(o,this.initialPosition,e,s),s?n.finish(o):(this.initialPosition,this.clearNodes(this.initialPosition),this.restoreState(t,e),this.tryLayout(this.initialPosition,e).thenFinish(n))}),n.result()}prepareLayout(t,e){}clearNodes(t){const e=t.viewNode||t.parent.viewNode;let n,i;for(;n=e.lastChild;)e.removeChild(n);for(;i=e.nextSibling;)i.parentNode.removeChild(i)}saveState(t,e){this.initialPosition=t.copy(),this.initialBreakPositions=[].concat(e.breakPositions),this.initialFragmentLayoutConstraints=[].concat(e.fragmentLayoutConstraints),t.formattingContext&&(this.initialStateOfFormattingContext=t.formattingContext.saveState())}restoreState(t,e){e.breakPositions=this.initialBreakPositions,e.fragmentLayoutConstraints=this.initialFragmentLayoutConstraints,t.formattingContext&&t.formattingContext.restoreState(this.initialStateOfFormattingContext)}}class rl{initialState(t){return{nodeContext:t,atUnforcedBreak:!1,break:!1}}startNonDisplayableNode(t){}afterNonDisplayableNode(t){}startIgnoredTextNode(t){}afterIgnoredTextNode(t){}startNonElementNode(t){}afterNonElementNode(t){}startInlineElementNode(t){}afterInlineElementNode(t){}startNonInlineElementNode(t){}afterNonInlineElementNode(t){}finish(t){}}class al{constructor(t,e){this.strategy=t,this.layoutContext=e}iterate(t){const e=this.strategy,n=e.initialState(t),i=pi("LayoutIterator");return i.loopWithFrame(t=>{let i;for(;n.nodeContext;){i=n.nodeContext.viewNode?1!==n.nodeContext.viewNode.nodeType?Zr(n.nodeContext.viewNode,n.nodeContext.whitespace)?n.nodeContext.after?e.afterIgnoredTextNode(n):e.startIgnoredTextNode(n):n.nodeContext.after?e.afterNonElementNode(n):e.startNonElementNode(n):n.nodeContext.inline?n.nodeContext.after?e.afterInlineElementNode(n):e.startInlineElementNode(n):n.nodeContext.after?e.afterNonInlineElementNode(n):e.startNonInlineElementNode(n):n.nodeContext.after?e.afterNonDisplayableNode(n):e.startNonDisplayableNode(n);const o=(i&&i.isPending()?i:fi(!0)).thenAsync(()=>n.break?fi(null):this.layoutContext.nextInTree(n.nodeContext,n.atUnforcedBreak));if(o.isPending())return void o.then(e=>{n.break?t.breakLoop():(n.nodeContext=e,t.continueLoop())});if(n.break)return void t.breakLoop();n.nodeContext=o.get()}e.finish(n),t.breakLoop()}).then(()=>{i.finish(n.nodeContext)}),i.result()}}class ll extends rl{constructor(t){super(),this.leadingEdge=t}startNonInlineBox(t){}endEmptyNonInlineBox(t){}endNonInlineBox(t){}initialState(t){return{nodeContext:t,atUnforcedBreak:!!this.leadingEdge&&t.after,break:!1,leadingEdge:this.leadingEdge,breakAtTheEdge:null,onStartEdges:!1,leadingEdgeContexts:[],lastAfterNodeContext:null}}processForcedBreak(t,e){const n=!t.leadingEdge&&ka(t.breakAtTheEdge);if(n){const n=t.nodeContext=t.leadingEdgeContexts[0]||t.nodeContext;n.viewNode.parentNode.removeChild(n.viewNode),e.pageBreakType=t.breakAtTheEdge}return n}saveEdgeAndProcessOverflow(t,e){const n=e.checkOverflowAndSaveEdgeAndBreakPosition(t.lastAfterNodeContext,null,!0,t.breakAtTheEdge);return n&&(t.nodeContext=(t.lastAfterNodeContext||t.nodeContext).modify(),t.nodeContext.overflow=!0),n}processLayoutConstraint(t,e,n){let i=t.nodeContext;const o=!e.allowLayout(i);return o&&(n.checkOverflowAndSaveEdgeAndBreakPosition(t.lastAfterNodeContext,null,!1,t.breakAtTheEdge),i=t.nodeContext=i.modify(),i.overflow=!0),o}startNonElementNode(t){t.onStartEdges=!1}startNonInlineElementNode(t){return t.leadingEdgeContexts.push(t.nodeContext.copy()),t.breakAtTheEdge=_a(t.breakAtTheEdge,t.nodeContext.breakBefore),t.onStartEdges=!0,this.startNonInlineBox(t)}afterNonInlineElementNode(t){let e,n;return t.onStartEdges?(e=this.endEmptyNonInlineBox(t),n=e&&e.isPending()?e:fi(!0),n=n.thenAsync(()=>(t.break||(t.leadingEdgeContexts=[],t.leadingEdge=!1,t.atUnforcedBreak=!1,t.breakAtTheEdge=null),fi(!0)))):(e=this.endNonInlineBox(t),n=e&&e.isPending()?e:fi(!0)),n.thenAsync(()=>(t.break||(t.onStartEdges=!1,t.lastAfterNodeContext=t.nodeContext.copy(),t.breakAtTheEdge=_a(t.breakAtTheEdge,t.nodeContext.breakAfter)),fi(!0)))}}let hl=[];const cl=(new DOMParser).parseFromString(`<root xmlns="${k.SHADOW}"/>`,"text/xml"),ul=["footnote-marker","first-5-lines","first-4-lines","first-3-lines","first-2-lines","first-line","first-letter","before","","after"],dl="data-adapt-pseudo";function pl(t){return t.getAttribute(dl)||""}function fl(t,e){t.setAttribute(dl,e)}class gl{constructor(t,e,n,i,o){this.element=t,this.style=e,this.styler=n,this.context=i,this.exprContentListener=o,this.contentProcessed={}}getStyle(t,e){const n=pl(t);this.styler&&n&&n.match(/after$/)&&(this.style=this.styler.getStyle(this.element,!0),this.styler=null);const i=Xo(this.style,"_pseudos")[n]||{};if(n.match(/^first-/)&&!i["x-first-pseudo"]){let t,e=1;"first-letter"==n?e=0:null!=(t=n.match(/^first-([0-9]+)-lines$/))&&(e=t[1]-0),i["x-first-pseudo"]=new Bo(new Pe(e),0)}return i}processContent(t,e){const n=pl(t);if(!this.contentProcessed[n]){this.contentProcessed[n]=!0;const i=e.content;i&&wa(i)&&i.visit(new Ea(t,this.context,i,this.exprContentListener))}}}_r.isInstanceOfAfterIfContinuesLayoutConstraint;const ml=Co.registerFragmentIndex;class El{constructor(t,e){this.sourceNode=t,this.styler=e}createElement(t,e){const n=e.viewNode.ownerDocument.createElement("div"),i=new vl(t,n,e),o=i.getColumn().pageBreakType;return i.getColumn().pageBreakType=null,i.layout(this.createNodePositionForPseudoElement(),!0).thenAsync(()=>{this.styler.contentProcessed["after-if-continues"]=!1,i.getColumn().pageBreakType=o;const t=n.firstChild;return V(t,"display","block"),fi(t)})}createNodePositionForPseudoElement(){const t=cl.createElementNS(k.XHTML,"div");fl(t,"after-if-continues");const e=this.createShadowContext(t),n={node:t,shadowType:e.type,shadowContext:e,nodeShadow:null,shadowSibling:null};return new da({steps:[n],offsetInNode:0,after:!1,preprocessedTextContent:null})}createShadowContext(t){return new la(this.sourceNode,t,null,null,null,Ur.ShadowType.ROOTED,this.styler)}}class wl{constructor(t,e,n){this.nodeContext=t,this.afterIfContinues=e,this.pseudoElementHeight=n,this.flagmentLayoutConstraintType="AfterIfContinue"}allowLayout(t,e,n){return!(e&&!t||t&&t.overflow)}nextCandidate(t){return!1}postLayout(t,e,n,i){}finishBreak(t,e){return this.getRepetitiveElements().affectTo(t)?this.afterIfContinues.createElement(e,this.nodeContext).thenAsync(t=>(this.nodeContext.viewNode.appendChild(t),fi(!0))):fi(!0)}getRepetitiveElements(){return new Nl(this.nodeContext,this.pseudoElementHeight)}equalsTo(t){return t instanceof wl&&this.afterIfContinues==t.afterIfContinues}getPriorityOfFinishBreak(){return 9}}class Nl{constructor(t,e){this.nodeContext=t,this.pseudoElementHeight=e}calculateOffset(t){return this.affectTo(t)?this.pseudoElementHeight:0}calculateMinimumOffset(t){return this.calculateOffset(t)}affectTo(t){if(!t)return!1;const e=t.shadowContext?t.shadowContext.owner:t.sourceNode;if(e===this.nodeContext.sourceNode)return!!t.after;for(let t=e.parentNode;t;t=t.parentNode)if(t===this.nodeContext.sourceNode)return!0;return!1}}function bl(t,e){if(!t||!t.afterIfContinues||t.after||e.isFloatNodeContext(t))return fi(t);const n=t.afterIfContinues;return n.createElement(e,t).thenAsync(i=>{const o=function(t,e,n){const i=t.viewNode;i.appendChild(n);const o=Va(n,e,t.vertical);return i.removeChild(n),o}(t,e,i);return e.fragmentLayoutConstraints.push(new wl(t,n,o)),fi(t)})}function Sl(t,e){return t.thenAsync(t=>bl(t,e))}const yl={img:!0,svg:!0,audio:!0,video:!0};class Cl{constructor(t){this.constraints=t}allowLayout(t){return this.constraints.every(e=>e.allowLayout(t))}}class Tl extends Wa{constructor(t,e){super(),this.checkPoints=t,this.penalty=e,this.alreadyEvaluated=!1,this.breakNodeContext=null}findAcceptableBreak(t,e){return e<this.getMinBreakPenalty()?null:(this.alreadyEvaluated||(this.breakNodeContext=t.findBoxBreakPosition(this,e>0),this.alreadyEvaluated=!0),this.breakNodeContext)}getMinBreakPenalty(){return this.penalty}getNodeContext(){return this.alreadyEvaluated?this.breakNodeContext:this.checkPoints[this.checkPoints.length-1]}}function xl(t){switch(t){case"ruby":case"inline-block":case"inline-flex":case"inline-grid":case"inline-list-item":case"inline-table":return!0}return!1}class Il extends ma{constructor(t,e,n,i,o){super(t),this.layoutContext=e,this.clientLayout=n,this.layoutConstraint=i,this.pageFloatLayoutContext=o,this.flowRootFormattingContext=null,this.isFloat=!1,this.isFootnote=!1,this.startEdge=0,this.endEdge=0,this.beforeEdge=0,this.afterEdge=0,this.footnoteEdge=0,this.box=null,this.chunkPositions=null,this.bands=null,this.overflown=!1,this.breakPositions=null,this.pageBreakType=null,this.forceNonfitting=!0,this.leftFloatEdge=0,this.rightFloatEdge=0,this.bottommostFloatTop=0,this.stopAtOverflow=!0,this.lastAfterPosition=null,this.fragmentLayoutConstraints=[],this.pseudoParent=null,this.nodeContextOverflowingDueToRepetitiveElements=null,this.blockDistanceToBlockEndFloats=NaN,this.last=t.lastChild,this.viewDocument=t.ownerDocument,o.setContainer(this)}getTopEdge(){return this.vertical?this.startEdge:this.beforeEdge}getBottomEdge(){return this.vertical?this.endEdge:this.afterEdge}getLeftEdge(){return this.vertical?this.afterEdge:this.startEdge}getRightEdge(){return this.vertical?this.beforeEdge:this.endEdge}isFloatNodeContext(t){return!(!t.floatSide||this.isFloat&&!t.parent)}stopByOverflow(t){return this.stopAtOverflow&&!!t&&t.overflow}isOverflown(t){return this.vertical?t<this.footnoteEdge:t>this.footnoteEdge}getExclusions(){const t=this.pageFloatLayoutContext.getFloatFragmentExclusions();return this.exclusions.concat(t)}openAllViews(t){const e=this,n=pi("openAllViews"),i=t.steps;e.layoutContext.setViewRoot(e.element,e.isFootnote);let o=i.length-1,s=null;return n.loop(()=>{for(;o>=0;){const n=s,r=i[o];if(s=ra(r,n),o!==i.length-1||s.formattingContext||(s.formattingContext=e.flowRootFormattingContext),0==o&&(s.offsetInNode=e.calculateOffsetInNodeForNodeContext(t),s.after=t.after,s.preprocessedTextContent=t.preprocessedTextContent,s.after))break;const a=e.layoutContext.setCurrent(s,0==o&&0==s.offsetInNode);if(o--,a.isPending())return a}return fi(!1)}).then(()=>{n.finish(s)}),n.result()}calculateOffsetInNodeForNodeContext(t){return t.preprocessedTextContent?(e=t.preprocessedTextContent,n=t.offsetInNode,zr(e,n,1)):t.offsetInNode;var e,n}maybePeelOff(t,e){if(t.firstPseudo&&t.inline&&!t.after&&0==t.firstPseudo.count&&1!=t.viewNode.nodeType){const e=t.viewNode.textContent.match(Pl);return this.layoutContext.peelOff(t,e[0].length)}return fi(t)}buildViewToNextBlockEdge(t,e){const n=this;let i=!1;const o=pi("buildViewToNextBlockEdge");return o.loopWithFrame(o=>{t.viewNode&&!$a(t)&&e.push(t.copy()),n.maybePeelOff(t,0).then(s=>{s!==t&&($a(t=s)||e.push(t.copy())),n.nextInTree(t).then(e=>{(t=e)?(!i&&n.layoutConstraint.allowLayout(t)||(i=!0,(t=t.modify()).overflow=!0),n.isFloatNodeContext(t)&&!n.vertical?n.layoutFloatOrFootnote(t).then(e=>{t=e,n.pageFloatLayoutContext.isInvalidated()&&(t=null),t?o.continueLoop():o.breakLoop()}):t.inline?o.continueLoop():o.breakLoop()):o.breakLoop()})})}).then(()=>{o.finish(t)}),o.result()}nextInTree(t,e){return Sl(this.layoutContext.nextInTree(t,e),this)}buildDeepElementView(t){if(!t.viewNode)return fi(t);let e=[];const n=t.sourceNode,i=this,o=pi("buildDeepElementView");return o.loopWithFrame(o=>{t.viewNode&&t.inline&&!$a(t)?e.push(t.copy()):(e.length>0&&i.postLayoutBlock(t,e),e=[]),i.maybePeelOff(t,0).then(s=>{const r=s;if(r!==t){let i=r;for(;i&&i.sourceNode!=n;)i=i.parent;if(null==i)return t=r,void o.breakLoop();$a(r)||e.push(r.copy())}i.nextInTree(r).then(e=>{(t=e)&&t.sourceNode!=n?i.layoutConstraint.allowLayout(t)?o.continueLoop():((t=t.modify()).overflow=!0,i.stopAtOverflow?o.breakLoop():o.continueLoop()):o.breakLoop()})})}).then(()=>{e.length>0&&i.postLayoutBlock(t,e),o.finish(t)}),o.result()}createFloat(t,e,n,i){const o=this.viewDocument.createElement("div");return this.vertical?(i>=this.height&&(i-=.1),V(o,"height",`${n}px`),V(o,"width",`${i}px`)):(n>=this.width&&(n-=.1),V(o,"width",`${n}px`),V(o,"height",`${i}px`)),V(o,"float",e),V(o,"clear",e),this.element.insertBefore(o,t),o}killFloats(){let t=this.element.firstChild;for(;t;){const e=t.nextSibling;if(1==t.nodeType){const e=t,n=e.style.cssFloat;if("left"!=n&&"right"!=n)break;this.element.removeChild(e)}t=e}}createFloats(){const t=this.element.firstChild,e=this.bands,n=this.vertical?this.getTopEdge():this.getLeftEdge(),i=this.vertical?this.getBottomEdge():this.getRightEdge();for(const o of e){const e=o.y2-o.y1;o.left=this.createFloat(t,"left",o.x1-n,e),o.right=this.createFloat(t,"right",i-o.x2,e)}}calculateEdge(t,e,n,i){let o;if(t&&Ha(t.viewNode))return NaN;if(t&&t.after&&!t.inline&&(o=Ua(t,this.clientLayout,0,this.vertical),!isNaN(o)))return o;let s=i-(t=e[n]).boxOffset;for(;;){if(o=Ua(t,this.clientLayout,s,this.vertical),!isNaN(o))return o;if(s>0)s--;else{if(--n<0)return this.beforeEdge;1!=(t=e[n]).viewNode.nodeType&&(s=t.viewNode.textContent.length)}}}parseComputedLength(t){if("number"==typeof t)return t;const e=t.match(/^(-?[0-9]*(\.[0-9]*)?)px$/);return e?parseFloat(e[0]):0}getComputedMargin(t){const e=this.clientLayout.getElementComputedStyle(t),n=new Ye(0,0,0,0);return e&&(n.left=this.parseComputedLength(e.marginLeft),n.top=this.parseComputedLength(e.marginTop),n.right=this.parseComputedLength(e.marginRight),n.bottom=this.parseComputedLength(e.marginBottom)),n}getComputedPaddingBorder(t){const e=this.clientLayout.getElementComputedStyle(t),n=new Ye(0,0,0,0);return e&&(n.left=this.parseComputedLength(e.borderLeftWidth)+this.parseComputedLength(e.paddingLeft),n.top=this.parseComputedLength(e.borderTopWidth)+this.parseComputedLength(e.paddingTop),n.right=this.parseComputedLength(e.borderRightWidth)+this.parseComputedLength(e.paddingRight),n.bottom=this.parseComputedLength(e.borderBottomWidth)+this.parseComputedLength(e.paddingBottom)),n}getComputedInsets(t){const e=this.clientLayout.getElementComputedStyle(t),n=new Ye(0,0,0,0);if(e){if("border-box"==e.boxSizing)return this.getComputedMargin(t);n.left=this.parseComputedLength(e.marginLeft)+this.parseComputedLength(e.borderLeftWidth)+this.parseComputedLength(e.paddingLeft),n.top=this.parseComputedLength(e.marginTop)+this.parseComputedLength(e.borderTopWidth)+this.parseComputedLength(e.paddingTop),n.right=this.parseComputedLength(e.marginRight)+this.parseComputedLength(e.borderRightWidth)+this.parseComputedLength(e.paddingRight),n.bottom=this.parseComputedLength(e.marginBottom)+this.parseComputedLength(e.borderBottomWidth)+this.parseComputedLength(e.paddingBottom)}return n}setComputedInsets(t,e){const n=this.clientLayout.getElementComputedStyle(t);n&&(e.marginLeft=this.parseComputedLength(n.marginLeft),e.borderLeft=this.parseComputedLength(n.borderLeftWidth),e.paddingLeft=this.parseComputedLength(n.paddingLeft),e.marginTop=this.parseComputedLength(n.marginTop),e.borderTop=this.parseComputedLength(n.borderTopWidth),e.paddingTop=this.parseComputedLength(n.paddingTop),e.marginRight=this.parseComputedLength(n.marginRight),e.borderRight=this.parseComputedLength(n.borderRightWidth),e.paddingRight=this.parseComputedLength(n.paddingRight),e.marginBottom=this.parseComputedLength(n.marginBottom),e.borderBottom=this.parseComputedLength(n.borderBottomWidth),e.paddingBottom=this.parseComputedLength(n.paddingBottom))}setComputedWidthAndHeight(t,e){const n=this.clientLayout.getElementComputedStyle(t);n&&(e.width=this.parseComputedLength(n.width),e.height=this.parseComputedLength(n.height))}layoutUnbreakable(t){return this.buildDeepElementView(t)}layoutFloat(t){const e=this,n=pi("layoutFloat"),i=t.viewNode,o=t.floatSide;return V(i,"float","none"),V(i,"display","inline-block"),V(i,"vertical-align","top"),e.buildDeepElementView(t).then(s=>{const r=e.clientLayout.getElementClientRect(i),a=e.getComputedMargin(i);let l=new We(r.left-a.left,r.top-a.top,r.right+a.right,r.bottom+a.bottom),h=e.startEdge,c=e.endEdge,u=t.parent;for(;u&&u.inline;)u=u.parent;if(u){const n=u.viewNode.ownerDocument.createElement("div");n.style.left="0px",n.style.top="0px",e.vertical?(n.style.bottom="0px",n.style.width="1px"):(n.style.right="0px",n.style.height="1px"),u.viewNode.appendChild(n);const i=e.clientLayout.getElementClientRect(n);h=Math.max(e.getStartEdge(i),h),c=Math.min(e.getEndEdge(i),c),u.viewNode.removeChild(n);const s=e.vertical?l.y2-l.y1:l.x2-l.x1;"left"==o?c=Math.max(c,h+s):h=Math.min(h,c-s),u.viewNode.appendChild(t.viewNode)}let d=new We(h,e.getBoxDir()*e.beforeEdge,c,e.getBoxDir()*e.afterEdge),p=l;e.vertical&&(p=rn(l));const f=e.getBoxDir();if(p.y1<e.bottommostFloatTop*f){const t=p.y2-p.y1;p.y1=e.bottommostFloatTop*f,p.y2=p.y1+t}!function(t,e,n,i){let o=n.y1;const s=n.x2-n.x1,r=n.y2-n.y1;let a=cn(e,o);for(;;){const l=o+r;if(l>t.y2)return!1;let h=t.x1,c=t.x2;for(let t=a;t<e.length&&e[t].y1<l;t++){const n=e[t];n.x1>h&&(h=n.x1),n.x2<c&&(c=n.x2)}if(h+s<=c||a>=e.length)return"left"==i?(n.x1=h,n.x2=h+s):(n.x1=c-s,n.x2=c),n.y2+=o-n.y1,n.y1=o,!0;o=e[a].y2,a++}}(d,e.bands,p,o),e.vertical&&(l=an(p));const g=e.getComputedInsets(i);let m;V(i,"width",`${l.x2-l.x1-g.left-g.right}px`),V(i,"height",`${l.y2-l.y1-g.top-g.bottom}px`),V(i,"position","absolute"),t.display,V(i,"display",t.display);let E=null;if(u&&(E=u.containingBlockForAbsolute?u:u.getContainingBlockForAbsolute()),E){const t=E.viewNode.ownerDocument.createElement("div");t.style.position="absolute",E.vertical?t.style.right="0":t.style.left="0",t.style.top="0",E.viewNode.appendChild(t),m=e.clientLayout.getElementClientRect(t),E.viewNode.removeChild(t)}else m={left:e.getLeftEdge()-e.paddingLeft,right:e.getRightEdge()+e.paddingRight,top:e.getTopEdge()-e.paddingTop};(E?E.vertical:e.vertical)?V(i,"right",`${m.right-l.x2}px`):V(i,"left",`${l.x1-m.left}px`),V(i,"top",`${l.y1-m.top}px`),t.clearSpacer&&(t.clearSpacer.parentNode.removeChild(t.clearSpacer),t.clearSpacer=null);const w=e.vertical?l.x1:l.y2,N=e.vertical?l.x2:l.y1;e.isOverflown(w)&&0!=e.breakPositions.length?((t=t.modify()).overflow=!0,n.finish(t)):(e.killFloats(),d=new We(e.getLeftEdge(),e.getTopEdge(),e.getRightEdge(),e.getBottomEdge()),e.vertical&&(d=rn(d)),function(t,e,n,i,o){for(i||(i=[new je(n.y1,n.y2,n.x1,n.x2)]);i.length>0&&i[0].y2<=t.y1;)i.shift();if(0==i.length)return;let s;i[0].y1<t.y1&&(i[0].y1=t.y1);const r=0==e.length?t.y1:e[e.length-1].y2;r<t.y2&&e.push(new je(r,t.y2,t.x1,t.x2));let a=cn(e,i[0].y1);for(const n of i){if(a==e.length)break;for(e[a].y1<n.y1&&(s=e[a],a++,e.splice(a,0,new je(n.y1,s.y2,s.x1,s.x2)),s.y2=n.y1);a<e.length&&(s=e[a++],s.y2>n.y2&&(e.splice(a,0,new je(n.y2,s.y2,s.x1,s.x2)),s.y2=n.y2),n.x1!=n.x2&&("left"==o?s.x1=Math.min(n.x2,t.x2):s.x2=Math.max(n.x1,t.x1)),s.y2!=n.y2););}hn(t,e)}(d,e.bands,p,null,o),e.createFloats(),"left"==o?e.leftFloatEdge=w:e.rightFloatEdge=w,e.bottommostFloatTop=N,e.updateMaxReachedAfterEdge(w),n.finish(s))}),n.result()}setupFloatArea(t,e,n,i,o,s){const r=this.pageFloatLayoutContext,a=r.getContainer(e),l=t.element;a.element.parentNode.appendChild(l),t.isFloat=!0,t.originX=a.originX,t.originY=a.originY,t.vertical=a.vertical,t.marginLeft=t.marginRight=t.marginTop=t.marginBottom=0,t.borderLeft=t.borderRight=t.borderTop=t.borderBottom=0,t.paddingLeft=t.paddingRight=t.paddingTop=t.paddingBottom=0,t.exclusions=(a.exclusions||[]).concat(),t.forceNonfitting=!r.hasFloatFragments(),t.innerShape=null;const h=a.getPaddingRect();t.setHorizontalPosition(h.x1-a.originX,h.x2-h.x1),t.setVerticalPosition(h.y1-a.originY,h.y2-h.y1),o.adjustPageFloatArea(t,a,this),t.init();const c=!!r.setFloatAreaDimensions(t,e,n,i,!0,!r.hasFloatFragments(),s);return c?(t.killFloats(),t.init()):a.element.parentNode.removeChild(l),c}createPageFloatArea(t,e,n,i,o){const s=this.element.ownerDocument.createElement("div");V(s,"position","absolute");const r=this.pageFloatLayoutContext.getPageFloatLayoutContext(t.floatReference),a=new xa(null,Na.COLUMN,null,this.pageFloatLayoutContext.flowName,t.nodePosition,null,null),l=r.getContainer(),h=new kl(e,s,this.layoutContext.clone(),this.clientLayout,this.layoutConstraint,a,l);return a.setContainer(h),this.setupFloatArea(h,t.floatReference,e,n,i,o)?h:null}layoutSinglePageFloatFragment(t,e,n,i,o,s,r){const a=this.pageFloatLayoutContext,l=r?r.continuations:[],h=(t=l.concat(t))[0].float,c=a.getPageFloatPlacementCondition(h,e,n),u=this.createPageFloatArea(h,e,s,o,c),d={floatArea:u,pageFloatFragment:null,newPosition:null};if(!u)return fi(d);const p=pi("layoutSinglePageFloatFragment");let f=!1,g=0;return p.loopWithFrame(e=>{if(g>=t.length)return void e.breakLoop();const n=t[g],o=new da(n.nodePosition);u.layout(o,!0).then(t=>{d.newPosition=t,!t||i?(g++,e.continueLoop()):(f=!0,e.breakLoop())})}).then(()=>{if(!f){const n=a.setFloatAreaDimensions(u,h.floatReference,e,s,!1,i,c);if(n){const e=o.createPageFloatFragment(t,n,u,!!d.newPosition);a.addPageFloatFragment(e,!0),d.pageFloatFragment=e}else f=!0}p.finish(d)}),p.result()}layoutPageFloatInner(t,e,n,i){const o=this.pageFloatLayoutContext,s=t.float;function r(e,n){n?o.removePageFloatFragment(n,!0):e&&e.element.parentNode.removeChild(e.element),o.restoreStashedFragments(s.floatReference),o.deferPageFloat(t)}o.stashEndFloatFragments(s);const a=pi("layoutPageFloatInner"),l=this;return this.layoutSinglePageFloatFragment([t],s.floatSide,s.clearSide,!o.hasFloatFragments(),e,n,i).then(t=>{const e=t.floatArea,n=t.pageFloatFragment,h=t.newPosition;n?l.layoutStashedPageFloats(s.floatReference,[i]).then(t=>{if(t){if(o.addPageFloatFragment(n),o.discardStashedFragments(s.floatReference),h){const t=new Ta(s,h.primary);o.deferPageFloat(t)}a.finish(!0)}else r(e,n),a.finish(!1)}):(r(e,n),a.finish(!1))}),a.result()}layoutStashedPageFloats(t,e){const n=this.pageFloatLayoutContext,i=n.getStashedFloatFragments(t),o=[],s=[];let r=!1;const a=pi("layoutStashedPageFloats"),l=this;let h=0;return a.loopWithFrame(t=>{if(h>=i.length)return void t.breakLoop();const n=i[h];if(e.includes(n))return h++,void t.continueLoop();const a=(new va).findByFloat(n.continuations[0].float);l.layoutSinglePageFloatFragment(n.continuations,n.floatSide,null,!1,a,null).then(e=>{const n=e.floatArea;n&&o.push(n);const i=e.pageFloatFragment;i?(s.push(i),h++,t.continueLoop()):(r=!0,t.breakLoop())})}).then(()=>{r?(s.forEach(t=>{n.removePageFloatFragment(t,!0)}),o.forEach(t=>{const e=t.element;e&&e.parentNode&&e.parentNode.removeChild(e)})):i.forEach(t=>{const e=t.area.element;e&&e.parentNode&&e.parentNode.removeChild(e)}),a.finish(!r)}),a.result()}setFloatAnchorViewNode(t){const e=t.viewNode.parentNode,n=e.ownerDocument.createElement("span");n.setAttribute(jr,"1"),"footnote"===t.floatSide&&this.layoutContext.applyPseudoelementStyle(t,"footnote-call",n),e.appendChild(n),e.removeChild(t.viewNode);const i=t.modify();return i.after=!0,i.viewNode=n,i}resolveFloatReferenceFromColumnSpan(t,e,n){const i=this,o=pi("resolveFloatReferenceFromColumnSpan"),s=this.pageFloatLayoutContext,r=s.getPageFloatLayoutContext(Na.REGION);return s.getContainer().width<r.getContainer().width&&t===Na.COLUMN?e===Me.auto?this.buildDeepElementView(n.copy()).then(e=>{const n=e.viewNode;let s=br(i.clientLayout,n,[Nr.MIN_CONTENT_INLINE_SIZE])[Nr.MIN_CONTENT_INLINE_SIZE];const r=i.getComputedMargin(n);i.vertical?s+=r.top+r.bottom:s+=r.left+r.right,s>i.width?o.finish(Na.REGION):o.finish(t)}):e===Me.all?o.finish(Na.REGION):o.finish(t):o.finish(t),o.result()}layoutPageFloat(t){const e=this,n=this.pageFloatLayoutContext,i=(new va).findByNodeContext(t);let o;const s=n.findPageFloatByNodePosition(t.toNodePosition());return o=s?fi(s):i.createPageFloat(t,n,this),o.thenAsync(o=>{const s=sa(t,0),r=e.setFloatAnchorViewNode(t),a=i.findPageFloatFragment(o,n),l=new Ta(o,s);if(a&&a.hasFloat(o))return n.registerPageFloatAnchor(o,r.viewNode),fi(r);if(n.isForbidden(o)||n.hasPrecedingFloatsDeferredToNext(o))return n.deferPageFloat(l),n.registerPageFloatAnchor(o,r.viewNode),fi(r);if(e.nodeContextOverflowingDueToRepetitiveElements)return fi(null);{const t=Ua(r,e.clientLayout,0,e.vertical);return e.isOverflown(t)?fi(r):e.layoutPageFloatInner(l,i,t,a).thenAsync(t=>t?fi(null):(n.registerPageFloatAnchor(o,r.viewNode),fi(r)))}})}createJustificationAdjustmentElement(t,e,n,i){const o=e.createElement("span");o.style.visibility="hidden",o.style.verticalAlign="top",o.setAttribute(jr,"1");const s=e.createElement("span");s.style.fontSize="0",s.style.lineHeight="0",s.textContent=" #",o.appendChild(s),o.style.display="block",o.style.textIndent="0",o.style.textAlign="left",n.insertBefore(o,t);const r=this.clientLayout.getElementClientRect(s);o.style.textAlign="right";const a=this.clientLayout.getElementClientRect(s);o.style.textAlign="",!function(t){if(null===ot){const e=t.ownerDocument,n=e.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.width="30px",n.style.height="100px",n.style.lineHeight="16px",n.style.fontSize="16px",n.style.textAlign="justify",t.appendChild(n);const i=e.createTextNode("a | ");n.appendChild(i);const o=e.createElement("span");o.style.display="inline-block",o.style.width="30px",n.appendChild(o);const s=e.createRange();s.setStart(i,0),s.setEnd(i,3);const r=s.getBoundingClientRect();ot=r.right<27,t.removeChild(n)}return ot}(document.body)?o.style.display="inline-block":o.style.display="inline";const l=i?a.top-r.top:a.left-r.left,h=l>=1?`${l-1}px`:"100%";return i?o.style.paddingTop=h:o.style.paddingLeft=h,o}addAndAdjustJustificationElement(t,e,n,i,o,s){return function(t,e,n,i){if(function(t){if(null===st){const e=t.ownerDocument,n=e.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.width="40px",n.style.height="100px",n.style.lineHeight="16px",n.style.fontSize="16px",n.style.textAlign="justify",t.appendChild(n);const i=e.createTextNode("a a-");n.appendChild(i);const o=e.createElement("span");o.style.display="inline-block",o.style.width="40px",n.appendChild(o);const s=e.createRange();s.setStart(i,2),s.setEnd(i,4);const r=s.getBoundingClientRect();st=r.right<37,t.removeChild(n)}return st}(document.body)){const o=Al(t),s=e?n:n.previousSibling,r=s?s.textContent:"";if(r.charAt(r.length-1)===o){const t=n.ownerDocument,e=n.parentNode;!function(t){if(null===rt){const e=t.ownerDocument,n=e.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.width="40px",n.style.height="100px",n.style.lineHeight="16px",n.style.fontSize="16px",n.style.textAlign="justify",t.appendChild(n);const i=e.createTextNode("a a-");n.appendChild(i),n.appendChild(e.createElement("wbr"));const o=e.createElement("span");o.style.display="inline-block",o.style.width="40px",n.appendChild(o);const s=e.createRange();s.setStart(i,2),s.setEnd(i,4);const r=s.getBoundingClientRect();rt=r.right<37,t.removeChild(n)}return rt}(document.body)?e.insertBefore(t.createElement("wbr"),i):e.insertBefore(t.createTextNode(" "),i)}}}(t,e,n,i),this.createJustificationAdjustmentElement(i,o,s,t.vertical)}compensateJustificationLineHeight(t,e,n){const i=this.clientLayout.getElementClientRect(t),o=this.clientLayout.getElementClientRect(e);n.vertical?(e.style.marginRight=`${o.right-i.right}px`,e.style.width="0px"):(e.style.marginTop=`${i.top-o.top}px`,e.style.height="0px"),e.setAttribute(jr,"1")}fixJustificationIfNeeded(t,e){if(t.after&&!t.inline)return;if(e){let e="";for(let n=t.parent;n&&!e;n=n.parent)!n.inline&&n.viewNode&&(e=n.viewNode.style.textAlign);if("justify"!==e)return}const n=t.viewNode,i=n.ownerDocument,o=e&&(t.after||1!=n.nodeType);let s=o?n.nextSibling:n;s&&!s.parentNode&&(s=null);const r=n.parentNode||t.parent&&t.parent.viewNode;if(!r)return;const a=this.addAndAdjustJustificationElement(t,o,n,s,i,r);if(!e){const e=i.createElement("div");r.insertBefore(e,s),this.compensateJustificationLineHeight(a,e,t)}}processLineStyling(t,e,n){const i=this,o=pi("processLineStyling");let s=n.concat([]);n.splice(0,n.length);let r=0,a=t.firstPseudo;return 0==a.count&&(a=a.outer),o.loopWithFrame(n=>{if(!a)return void n.breakLoop();const o=i.findLinePositions(s),l=a.count-r;if(o.length<=l)return void n.breakLoop();const h=i.findAcceptableBreakInside(s,o[l-1],!0);null!=h?i.finishBreak(h,!1,!1).then(()=>{r+=l,i.layoutContext.peelOff(h,0).then(o=>{t=o,i.fixJustificationIfNeeded(t,!1),a=t.firstPseudo,s=[],i.buildViewToNextBlockEdge(t,s).then(t=>{e=t,n.continueLoop()})})}):n.breakLoop()}).then(()=>{Array.prototype.push.apply(n,s),o.finish(e)}),o.result()}isLoneImage(t){return!(2!=t.length&&this.breakPositions.length>0)&&(t[0].sourceNode==t[1].sourceNode&&yl[t[0].sourceNode.localName])}getTrailingMarginEdgeAdjustment(t){let e=0,n=0;for(let i=t.length-1;i>=0;i--){const o=t[i];if(!o.after||!o.viewNode||1!=o.viewNode.nodeType)break;const s=this.getComputedMargin(o.viewNode),r=this.vertical?-s.left:s.bottom;r>0?e=Math.max(e,r):n=Math.min(n,r)}return e-n}layoutBreakableBlock(t){const e=this,n=pi("layoutBreakableBlock"),i=[];return e.buildViewToNextBlockEdge(t,i).then(o=>{const s=i.length-1;if(s<0)return void n.finish(o);let r,a=e.calculateEdge(o,i,s,i[s].boxOffset),l=!1;if(!o||!Ha(o.viewNode)){const t=Xa(o,e.collectElementsOffset());l=e.isOverflown(a+(e.vertical?-1:1)*t.minimum),e.isOverflown(a+(e.vertical?-1:1)*t.current)&&!e.nodeContextOverflowingDueToRepetitiveElements&&(e.nodeContextOverflowingDueToRepetitiveElements=o)}null==o&&(a+=e.getTrailingMarginEdgeAdjustment(i)),e.updateMaxReachedAfterEdge(a),r=t.firstPseudo?e.processLineStyling(t,o,i):fi(o),r.then(t=>{e.postLayoutBlock(t,i),i.length>0&&(e.saveBoxBreakPosition(i),l&&!e.isLoneImage(i)&&t&&((t=t.modify()).overflow=!0)),n.finish(t)})}),n.result()}postLayoutBlock(e,n){f(t.HOOKS.POST_LAYOUT_BLOCK).forEach(t=>{t(e,n,this)})}findEndOfLine(t,e,n){const i=this.vertical?t-1:t+1;let o,s=0,r=e[0].boxOffset,a=s,l=e.length-1,h=e[l].boxOffset;for(;r<h;){o=r+Math.ceil((h-r)/2),a=s;let t=l;for(;a<t;){const n=a+Math.ceil((t-a)/2);e[n].boxOffset>o?t=n-1:a=n}const c=this.calculateEdge(null,e,a,o);if(this.vertical?c<=i:c>=i){for(h=o-1;e[a].boxOffset==o;)a--;l=a}else n&&this.updateMaxReachedAfterEdge(c),r=o,s=a}return{nodeContext:e[a],index:r,checkPointIndex:a}}findAcceptableBreakInside(t,e,n){const i=this.findEndOfLine(e,t,!0);let o=i.nodeContext;const s=o.viewNode;if(1!=s.nodeType){const e=s;o=this.resolveTextNodeBreaker(o).breakTextNode(e,o,i.index,t,i.checkPointIndex,n)}return this.clearOverflownViewNodes(o,!1),o}resolveTextNodeBreaker(e){return f(t.HOOKS.RESOLVE_TEXT_NODE_BREAKER).reduce((t,n)=>n(e)||t,Rl.instance)}getRangeBoxes(t,e){const n=[],i=t.ownerDocument.createRange();let o=!1,s=t,r=null,a=!1,l=!0;for(;l;){let t=!0;do{let n=null;s==e&&(l=1===e.nodeType&&!(!e.firstChild||o)),1!=s.nodeType?(a||(i.setStartBefore(s),a=!0),r=s):o?o=!1:Ga(s)?t=!a:"ruby"==s.localName||xl(this.clientLayout.getElementComputedStyle(s).display)?(t=!a,t&&(i.setStartBefore(s),a=!0,r=s),s.contains(e)&&(l=!1)):n=s.firstChild,n||(n=s.nextSibling,n||(o=!0,n=s.parentNode)),s=n}while(t&&l);if(a){i.setEndAfter(r);const t=this.clientLayout.getRangeClientRects(i);for(let e=0;e<t.length;e++)n.push(t[e]);a=!1}}return n}findLinePositions(t){const e=[],n=this.getRangeBoxes(t[0].viewNode,t[t.length-1].viewNode);n.sort(this.vertical?na:ea);let i=0,o=0,s=0,r=0,a=0;const l=this.getBoxDir();for(;;){if(a<n.length){const t=n[a];let e=1;if(r>0){const n=Math.max(this.getBoxSize(t),1);e=l*this.getBeforeEdge(t)<l*i?l*(this.getAfterEdge(t)-i)/n:l*this.getAfterEdge(t)>l*o?l*(o-this.getBeforeEdge(t))/n:1}if(0==r||e>=.6||e>=.2&&this.getStartEdge(t)>=s-1){s=this.getEndEdge(t),this.vertical?(i=0==r?t.right:Math.max(i,t.right),o=0==r?t.left:Math.min(o,t.left)):(i=0==r?t.top:Math.min(i,t.top),o=0==r?t.bottom:Math.max(o,t.bottom)),r++,a++;continue}}if(r>0&&(e.push(o),r=0),a>=n.length)break}return e.sort(J),this.vertical&&e.reverse(),e}calculateClonedPaddingBorder(t){let e=0;return t.walkUpBlocks(t=>{if("clone"===t.inheritedProps["box-decoration-break"]){t.viewNode,Element;const n=this.getComputedPaddingBorder(t.viewNode);e+=t.vertical?-n.left:n.bottom,"table"===t.display&&(e+=t.blockBorderSpacing)}}),e}getOffsetByRepetitiveElements(t){let e;return e=t?t.calculateOffset(this):Xa(null,this.collectElementsOffset()),e.current}findBoxBreakPosition(t,e){const n=this,i=t.checkPoints;let o,s,r=i[0];for(;r.parent&&r.inline;)r=r.parent;e?(o=1,s=1):(o=Math.max((r.inheritedProps.widows||2)-0,1),s=Math.max((r.inheritedProps.orphans||2)-0,1));const a=n.calculateClonedPaddingBorder(r),l=this.findLinePositions(i);let h=this.footnoteEdge-a;const c=this.getBoxDir(),u=this.getOffsetByRepetitiveElements(t);h-=c*u;const d=this.findFirstOverflowingEdgeAndCheckPoint(i);isNaN(d.edge)&&(d.edge=c*(1/0));let p=Z(l.length,t=>{const e=l[t];return n.vertical?e<h||e<=d.edge:e>h||e>=d.edge});const f=p<=0;if(f&&(p=Z(l.length,t=>n.vertical?l[t]<h:l[t]>h)),p=Math.min(l.length-o,p),p<s)return null;let g;if(h=l[p-1],g=f?d.checkPoint:this.findAcceptableBreakInside(t.checkPoints,h,e),g){const t=this.getAfterEdgeOfBlockContainer(g);!isNaN(t)&&t<h&&(h=t),this.computedBlockSize=c*(h-this.beforeEdge)+u}return g}getAfterEdgeOfBlockContainer(t){let e=t;do{e=e.parent}while(e&&e.inline);return e?(e=e.copy().modify(),e.after=!0,Ua(e,this.clientLayout,0,this.vertical)):NaN}findFirstOverflowingEdgeAndCheckPoint(t){const e=t.findIndex(t=>t.overflow);if(e<0)return{edge:NaN,checkPoint:null};const n=t[e];return{edge:this.calculateEdge(null,t,e,n.boxOffset),checkPoint:n}}findEdgeBreakPosition(t){return this.computedBlockSize=t.computedBlockSize+this.getOffsetByRepetitiveElements(t),t.position}finishBreak(t,e,n){t.formattingContext;let i=(new tl).find(t.formattingContext).finishBreak(this,t,e,n);return i||(i=il.finishBreak(this,t,e,n)),i}findAcceptableBreakPosition(){let t=null,e=null,n=0,i=0;do{n=i,i=Number.MAX_VALUE;for(let o=this.breakPositions.length-1;o>=0&&!e;--o){t=this.breakPositions[o],e=t.findAcceptableBreak(this,n);const s=t.getMinBreakPenalty();s>n&&(i=Math.min(i,s))}}while(i>n&&!e&&this.forceNonfitting);return{breakPosition:e?t:null,nodeContext:e}}doFinishBreak(t,e,n,i){if(this.pageFloatLayoutContext.isInvalidated()||this.pageBreakType||!e)return fi(t);const o=this,s=pi("doFinishBreak");let r=!1;if(!t){if(this.forceNonfitting)return h.warn("Could not find any page breaks?!!"),o.skipTailEdges(e).then(t=>{t?((t=t.modify()).overflow=!1,o.finishBreak(t,r,!0).then(()=>{s.finish(t)})):s.finish(t)}),s.result();t=n,r=!0,o.computedBlockSize=i}return this.finishBreak(t,r,!0).then(()=>{s.finish(t)}),s.result()}isBreakable(t){if(t.after)return!0;switch(t.sourceNode.namespaceURI){case k.SVG:return!1}return!t.flexContainer}zeroIndent(t){const e=t.toString();return""==e||"auto"==e||!!e.match(/^0+(.0*)?[^0-9]/)}checkOverflowAndSaveEdge(t,e){if(!t)return!1;if(Ha(t.viewNode))return!1;let n=Ua(t,this.clientLayout,0,this.vertical);const i=Xa(t,this.collectElementsOffset()),o=this.isOverflown(n+(this.vertical?-1:1)*i.minimum);if(this.isOverflown(n+(this.vertical?-1:1)*i.current)&&!this.nodeContextOverflowingDueToRepetitiveElements)this.nodeContextOverflowingDueToRepetitiveElements=t;else if(e){const t=n+this.getTrailingMarginEdgeAdjustment(e),o=this.footnoteEdge-this.getBoxDir()*i.current;n=this.vertical?Math.min(n,Math.max(t,o)):Math.max(n,Math.min(t,o))}return this.updateMaxReachedAfterEdge(n),o}checkOverflowAndSaveEdgeAndBreakPosition(t,e,n,i){if(!t)return!1;if(Ha(t.viewNode))return!1;const o=this.checkOverflowAndSaveEdge(t,e);return!n&&o||this.saveEdgeBreakPosition(t,i,o),o}applyClearance(t){if(!t.viewNode.parentNode)return!1;const e=this.getComputedMargin(t.viewNode),n=t.viewNode.ownerDocument.createElement("div");this.vertical?(n.style.bottom="0px",n.style.width="1px",n.style.marginRight=`${e.right}px`):(n.style.right="0px",n.style.height="1px",n.style.marginTop=`${e.top}px`),t.viewNode.parentNode.insertBefore(n,t.viewNode);let i=this.clientLayout.getElementClientRect(n);const o=this.getBeforeEdge(i),s=this.getBoxDir(),r=t.clearSide;let a=-this.getBoxDir()*(1/0);switch("all"===r&&(a=this.pageFloatLayoutContext.getPageFloatClearEdge(r,this)),r){case"left":a=s*Math.max(a*s,this.leftFloatEdge*s);break;case"right":a=s*Math.max(a*s,this.rightFloatEdge*s);break;default:a=s*Math.max(a*s,Math.max(this.rightFloatEdge*s,this.leftFloatEdge*s))}if(o*s>=a*s)return t.viewNode.parentNode.removeChild(n),!1;{const r=Math.max(1,(a-o)*s);this.vertical?n.style.width=`${r}px`:n.style.height=`${r}px`,i=this.clientLayout.getElementClientRect(n);const l=this.getAfterEdge(i);if(this.vertical){let t=l+e.right-a;t>0==e.right>=0&&(t+=e.right),n.style.marginLeft=`${t}px`}else{let t=a-(l+e.top);t>0==e.top>=0&&(t+=e.top),n.style.marginBottom=`${t}px`}return t.clearSpacer=n,!0}}isBFC(t){return!!ol(t)||!!Br.isInstanceOfRepetitiveElementsOwnerFormattingContext(t)}skipEdges(t,e,n){const i=t.after?t.parent&&t.parent.formattingContext:t.formattingContext;if(i&&!this.isBFC(i))return fi(t);const o=this,s=pi("skipEdges");let r=!n&&e&&t&&t.after,a=n,l=null,h=[],c=[],u=!1;function d(){return!!n||!e&&ka(a)}function p(){(t=h[0]||t).viewNode.parentNode.removeChild(t.viewNode),o.pageBreakType=a}return s.loopWithFrame(n=>{for(;t;){t.formattingContext;const i=(new tl).find(t.formattingContext);do{if(!t.viewNode)break;if(t.inline&&1!=t.viewNode.nodeType){if(Zr(t.viewNode,t.whitespace))break;if(!t.after)return d()?p():o.checkOverflowAndSaveEdgeAndBreakPosition(l,null,!0,a)?(t=(o.stopAtOverflow&&l||t).modify()).overflow=!0:(t=t.modify()).breakBefore=a,void n.breakLoop()}if(!t.after){if(i&&i.startNonInlineElementNode(t))break;if(t.clearSide&&o.applyClearance(t)&&e&&0===o.breakPositions.length&&o.saveEdgeBreakPosition(t.copy(),a,!1),!o.isBFC(t.formattingContext)||Br.isInstanceOfRepetitiveElementsOwnerFormattingContext(t.formattingContext)||o.isFloatNodeContext(t)||t.flexContainer)return h.push(t.copy()),a=_a(a,t.breakBefore),d()?p():!o.checkOverflowAndSaveEdgeAndBreakPosition(l,null,!0,a)&&o.layoutConstraint.allowLayout(t)||((t=(o.stopAtOverflow&&l||t).modify()).overflow=!0),void n.breakLoop()}if(1!=t.viewNode.nodeType)break;const s=t.viewNode.style;if(t.after){if(t.inline)break;if(i&&i.afterNonInlineElementNode(t,o.stopAtOverflow))break;if(u){if(d())return p(),void n.breakLoop();h=[],e=!1,r=!1,a=null}u=!1,l=t.copy(),c.push(l),a=_a(a,t.breakAfter),!s||o.zeroIndent(s.paddingBottom)&&o.zeroIndent(s.borderBottomWidth)||(c=[l])}else{if(h.push(t.copy()),a=_a(a,t.breakBefore),!o.layoutConstraint.allowLayout(t)&&(o.checkOverflowAndSaveEdgeAndBreakPosition(l,null,!o.stopAtOverflow,a),(t=t.modify()).overflow=!0,o.stopAtOverflow))return void n.breakLoop();const e=t.viewNode.localName;if(yl[e])return d()?p():o.checkOverflowAndSaveEdgeAndBreakPosition(l,null,!0,a)&&((t=(o.stopAtOverflow&&l||t).modify()).overflow=!0),void n.breakLoop();!s||o.zeroIndent(s.paddingTop)&&o.zeroIndent(s.borderTopWidth)||(r=!1,c=[]),u=!0}}while(0);const s=o.nextInTree(t,r);if(s.isPending())return void s.then(e=>{t=e,n.continueLoop()});t=s.get()}o.checkOverflowAndSaveEdgeAndBreakPosition(l,c,!o.stopAtOverflow,a)?l&&o.stopAtOverflow&&((t=l.modify()).overflow=!0):ka(a)&&(o.pageBreakType=a),n.breakLoop()}).then(()=>{l&&(o.lastAfterPosition=l.toNodePosition()),s.finish(t)}),s.result()}skipTailEdges(t){let e=t.copy();const n=this,i=pi("skipEdges");let o=null,s=!1;return i.loopWithFrame(i=>{for(;t;){do{if(!t.viewNode)break;if(t.inline&&1!=t.viewNode.nodeType){if(Zr(t.viewNode,t.whitespace))break;if(!t.after)return ka(o)&&(n.pageBreakType=o),void i.breakLoop()}if(!t.after&&(n.isFloatNodeContext(t)||t.flexContainer))return o=_a(o,t.breakBefore),ka(o)&&(n.pageBreakType=o),void i.breakLoop();if(1!=t.viewNode.nodeType)break;const e=t.viewNode.style;if(t.after){if(s){if(ka(o))return n.pageBreakType=o,void i.breakLoop();o=null}s=!1,o=_a(o,t.breakAfter)}else{o=_a(o,t.breakBefore);const s=t.viewNode.localName;if(yl[s])return ka(o)&&(n.pageBreakType=o),void i.breakLoop();if(e&&(!n.zeroIndent(e.paddingTop)||!n.zeroIndent(e.borderTopWidth)))return void i.breakLoop()}s=!0}while(0);const e=n.layoutContext.nextInTree(t);if(e.isPending())return void e.then(e=>{t=e,i.continueLoop()});t=e.get()}e=null,i.breakLoop()}).then(()=>{i.finish(e)}),i.result()}layoutFloatOrFootnote(t){return ba(t.floatReference)||"footnote"===t.floatSide?this.layoutPageFloat(t):this.layoutFloat(t)}layoutNext(t,e,n){const i=this,o=pi("layoutNext");return this.skipEdges(t,e,n||null).then(n=>{if(!(t=n)||i.pageBreakType||i.stopByOverflow(t))o.finish(t);else{const n=t.formattingContext;(new tl).find(n).layout(t,i,e).thenFinish(o)}}),o.result()}clearOverflownViewNodes(t,e){if(t)for(let n=t.parent;t;t=n,n=n?n.parent:null){const i=(n||t).formattingContext;(new tl).find(i).clearOverflownViewNodes(this,n,t,e),e=!1}}initGeom(){const t=this.element.ownerDocument.createElement("div");t.style.position="absolute",t.style.top=`${this.paddingTop}px`,t.style.right=`${this.paddingRight}px`,t.style.bottom=`${this.paddingBottom}px`,t.style.left=`${this.paddingLeft}px`,this.element.appendChild(t);const e=this.clientLayout.getElementClientRect(t);this.element.removeChild(t);const n=this.originX+this.left+this.getInsetLeft(),i=this.originY+this.top+this.getInsetTop();this.box=new We(n,i,n+this.width,i+this.height),this.startEdge=e?this.vertical?e.top:e.left:0,this.endEdge=e?this.vertical?e.bottom:e.right:0,this.beforeEdge=e?this.vertical?e.right:e.top:0,this.afterEdge=e?this.vertical?e.left:e.bottom:0,this.leftFloatEdge=this.beforeEdge,this.rightFloatEdge=this.beforeEdge,this.bottommostFloatTop=this.beforeEdge,this.footnoteEdge=this.afterEdge,this.bands=function(t,e,n,i,o,s){s&&(t=rn(t),e=e.map(t=>ln(t)),n=n.map(t=>ln(t)));const r=e.length,a=n?n.length:0,l=[],h=[];let c,u,d;for(c=0;c<r;c++)e[c].addSegments(h,c);for(c=0;c<a;c++)n[c].addSegments(h,c+r);const p=h.length;h.sort(qe);let f=0;for(;h[f].shapeId>=r;)f++;let g=h[f].low.y;g>t.y1&&l.push(new je(t.y1,g,t.x2,t.x2));let m=0;const E=[];for(;m<p&&(d=h[m]).low.y<g;)d.high.y>g&&E.push(d),m++;for(;m<p||E.length>0;){let e=t.y2;const n=Math.min((w=Math.ceil(g+i),(N=o)?Math.ceil(w/N)*N:w),t.y2);for(u=0;u<E.length&&e>n;u++)d=E[u],d.low.x==d.high.x?d.high.y<e&&(e=Math.max(sn(d.high.y,o),n)):d.low.x!=d.high.x&&(e=n);for(e>t.y2&&(e=t.y2);m<p&&(d=h[m]).low.y<e;)if(d.high.y<g)m++;else{if(!(d.low.y<n)){const t=sn(d.low.y,o);t<e&&(e=t);break}d.low.y==d.high.y&&d.low.y==g||(E.push(d),e=n),m++}const s=[];for(u=0;u<E.length;u++)nn(s,E[u],g,e);s.sort((t,e)=>t.x-e.x||t.lowOrHigh-e.lowOrHigh);const c=on(s,r,a);if(0==c.length)l.push(new je(g,e,t.x2,t.x2));else{let n=0,i=t.x1;for(u=0;u<c.length;u+=2){const e=Math.max(t.x1,c[u]),o=Math.min(t.x2,c[u+1])-e;o>n&&(n=o,i=e)}0==n?l.push(new je(g,e,t.x2,t.x2)):l.push(new je(g,e,Math.max(i,t.x1),Math.min(i+n,t.x2)))}if(e==t.y2)break;for(g=e,u=E.length-1;u>=0;u--)E[u].high.y<=e&&E.splice(u,1)}var w,N;return hn(t,l),l}(this.box,[this.getInnerShape()],this.getExclusions(),8,this.snapHeight,this.vertical),this.createFloats()}init(){this.chunkPositions=[],V(this.element,"width",`${this.width}px`),V(this.element,"height",`${this.height}px`),this.initGeom(),this.computedBlockSize=0,this.overflown=!1,this.pageBreakType=null,this.lastAfterPosition=null}saveEdgeBreakPosition(t,e,n){t.formattingContext;const i=t.copy(),o=(new tl).find(t.formattingContext),s=this.calculateClonedPaddingBorder(i),r=o.createEdgeBreakPosition(i,e,n,this.computedBlockSize+s);this.breakPositions.push(r)}saveBoxBreakPosition(t){const e=t[0].breakPenalty,n=new Tl(t,e);this.breakPositions.push(n)}updateMaxReachedAfterEdge(t){if(!isNaN(t)){const e=this.getBoxDir()*(t-this.beforeEdge);this.computedBlockSize=Math.max(e,this.computedBlockSize)}}layout(t,e,n){if(this.chunkPositions.push(t),t.primary.after&&(this.lastAfterPosition=t.primary),this.stopAtOverflow&&this.overflown)return fi(t);if(this.isFullWithPageFloats())return t.primary.after&&1===t.primary.steps.length?fi(null):fi(t);const i=this,o=pi("layout");return i.openAllViews(t.primary).then(t=>{let s=null;if(t.viewNode)s=t.copy();else{const t=e=>{e.nodeContext.viewNode&&(s=e.nodeContext,i.layoutContext.removeEventListener("nextInTree",t))};i.layoutContext.addEventListener("nextInTree",t)}const r=new Ll(e,n);r.layout(t,i).then(t=>{i.doFinishBreak(t,r.context.overflownNodeContext,s,r.initialComputedBlockSize).then(t=>{let e=null;e=i.pseudoParent?fi(null):i.doFinishBreakOfFragmentLayoutConstraints(t),e.then(()=>{if(i.pageFloatLayoutContext.isInvalidated())o.finish(null);else if(t){i.overflown=!0;const e=new da(t.toNodePosition());o.finish(e)}else o.finish(null)})})})}),o.result()}isFullWithPageFloats(){return this.pageFloatLayoutContext.isColumnFullWithPageFloats(this)}getMaxBlockSizeOfPageFloats(){return this.pageFloatLayoutContext.getMaxBlockSizeOfPageFloats()}doFinishBreakOfFragmentLayoutConstraints(t){const e=pi("doFinishBreakOfFragmentLayoutConstraints"),n=[].concat(this.fragmentLayoutConstraints);n.sort((t,e)=>t.getPriorityOfFinishBreak()-e.getPriorityOfFinishBreak());let i=0;return e.loop(()=>{if(i<n.length){return n[i++].finishBreak(t,this).thenReturn(!0)}return fi(!1)}).then(()=>{e.finish(!0)}),e.result()}doLayout(t,e,n){const i=this,o=pi("doLayout");let s=null;return i.breakPositions=[],i.nodeContextOverflowingDueToRepetitiveElements=null,o.loopWithFrame(o=>{for(;t;){let r=!0;if(i.layoutNext(t,e,n||null).then(a=>{if(e=!1,n=null,i.nodeContextOverflowingDueToRepetitiveElements&&i.stopAtOverflow?(i.pageBreakType=null,(t=i.nodeContextOverflowingDueToRepetitiveElements).overflow=!0):t=a,i.pageFloatLayoutContext.isInvalidated())o.breakLoop();else if(i.pageBreakType)o.breakLoop();else if(t&&i.stopByOverflow(t)){s=t;const e=i.findAcceptableBreakPosition();t=e.nodeContext,e.breakPosition&&e.breakPosition.breakPositionChosen(i),o.breakLoop()}else r?r=!1:o.continueLoop()}),r)return void(r=!1)}i.computedBlockSize+=i.getOffsetByRepetitiveElements(),o.breakLoop()}).then(()=>{o.finish({nodeContext:t,overflownNodeContext:s})}),o.result()}redoLayout(){const t=this.chunkPositions;let e=this.element.lastChild;for(;e!=this.last;){const t=e.previousSibling;this.element===e.parentNode&&this.layoutContext.isPseudoelement(e)||this.element.removeChild(e),e=t}this.killFloats(),this.init();const n=this,i=pi("redoLayout");let o=0,s=null,r=!0;return i.loopWithFrame(e=>{if(o<t.length){const i=t[o++];n.layout(i,r).then(t=>{r=!1,t?(s=t,e.breakLoop()):e.continueLoop()})}else e.breakLoop()}).then(()=>{i.finish(s)}),i.result()}saveDistanceToBlockEndFloats(){const t=this.pageFloatLayoutContext.getBlockStartEdgeOfBlockEndFloats();t>0&&isFinite(t)&&(this.blockDistanceToBlockEndFloats=this.getBoxDir()*(t-this.beforeEdge-this.computedBlockSize))}collectElementsOffset(){const t=[];for(let e=this;e;e=e.pseudoParent)e.fragmentLayoutConstraints.forEach(e=>{if(Br.isInstanceOfRepetitiveElementsOwnerLayoutConstraint(e)){const n=e.getRepetitiveElements();t.push(n)}if(_r.isInstanceOfAfterIfContinuesLayoutConstraint(e)){const n=e.getRepetitiveElements();t.push(n)}Mr.isInstanceOfTableRowLayoutConstraint(e)&&e.getElementsOffsetsForTableCell(this).forEach(e=>{t.push(e)})});return t}}class vl{constructor(t,e,n){this.startNodeContexts=[],this.column=Object.create(t),this.column.element=e,this.column.layoutContext=t.layoutContext.clone(),this.column.stopAtOverflow=!1,this.column.flowRootFormattingContext=n.formattingContext,this.column.pseudoParent=t;const i=this.column.calculateClonedPaddingBorder(n);this.column.footnoteEdge=this.column.footnoteEdge-i;const o=this;this.column.openAllViews=function(t){return Il.prototype.openAllViews.call(this,t).thenAsync(t=>(o.startNodeContexts.push(t.copy()),fi(t)))}}layout(t,e){return this.column.layout(t,e)}findAcceptableBreakPosition(t){const e=this.column.findAcceptableBreakPosition();if(t){const t=this.startNodeContexts[0].copy(),n=new Ya(t,null,t.overflow,0);if(n.findAcceptableBreak(this.column,0),!e.nodeContext)return{breakPosition:n,nodeContext:t}}return e}finishBreak(t,e,n){return this.column.finishBreak(t,e,n)}doFinishBreakOfFragmentLayoutConstraints(t){this.column.doFinishBreakOfFragmentLayoutConstraints(t)}isStartNodeContext(t){const e=this.startNodeContexts[0];return e.viewNode===t.viewNode&&e.after===t.after&&e.offsetInNode===t.offsetInNode}isLastAfterNodeContext(t){return oa(t.toNodePosition(),this.column.lastAfterPosition)}getColumnElement(){return this.column.element}getColumn(){return this.column}}const Pl=/^[^A-Za-z0-9_\u009E\u009F\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02AF\u037B-\u037D\u0386\u0388-\u0482\u048A-\u0527]*([A-Za-z0-9_\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02AF\u037B-\u037D\u0386\u0388-\u0482\u048A-\u0527][^A-Za-z0-9_\u009E\u009F\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02AF\u037B-\u037D\u0386\u0388-\u0482\u048A-\u0527]*)?/;class Rl{breakTextNode(t,e,n,i,o,s){if(e.after)e.offsetInNode=t.length;else{let i=n-e.boxOffset;const o=t.data;i=173==o.charCodeAt(i)?this.breakAfterSoftHyphen(t,o,i,e):this.breakAfterOtherCharacter(t,o,i,e),i>0&&(e=this.updateNodeContext(e,i,t))}return e}breakAfterSoftHyphen(t,e,n,i){return t.replaceData(n,e.length-n,i.breakWord?"":Al(i)),n+1}breakAfterOtherCharacter(t,e,n,i){const o=e.charAt(n);n++;const s=e.charAt(n);return t.replaceData(n,e.length-n,!i.breakWord&&K(o)&&K(s)?Al(i):""),n}updateNodeContext(t,e,n){return(t=t.modify()).offsetInNode+=e,t.breakBefore=null,t}}function Al(t){return t.hyphenateCharacter||t.parent&&t.parent.hyphenateCharacter||"-"}Rl.instance=new Rl;class Ll extends sl{constructor(t,e){super(),this.leadingEdge=t,this.initialPageBreakType=null,this.initialComputedBlockSize=0,this.initialOverflown=!1,this.context={overflownNodeContext:null},this.breakAfter=e||null}resolveLayoutMode(t){return new Ol(this.leadingEdge,this.breakAfter,this.context)}prepareLayout(t,e){e.fragmentLayoutConstraints=[],e.pseudoParent||(hl=[])}clearNodes(t){super.clearNodes(t);let e=t;for(;e;){const t=e.viewNode;t&&za(t.parentNode,t),e=e.parent}}saveState(t,e){super.saveState(t,e),this.initialPageBreakType=e.pageBreakType,this.initialComputedBlockSize=e.computedBlockSize,this.initialOverflown=e.overflown}restoreState(t,e){super.restoreState(t,e),e.pageBreakType=this.initialPageBreakType,e.computedBlockSize=this.initialComputedBlockSize,e.overflown=this.initialOverflown}}class Ol{constructor(t,e,n){this.leadingEdge=t,this.breakAfter=e,this.context=n}doLayout(t,e){const n=pi("DefaultLayoutMode.doLayout");return function(t,e){const n=pi("processAfterIfContinuesOfAncestors");let i=t;return n.loop(()=>{if(null!==i){const t=bl(i,e);return i=i.parent,t.thenReturn(!0)}return fi(!1)}).then(()=>{n.finish(!0)}),n.result()}(t,e).then(()=>{e.doLayout(t,this.leadingEdge,this.breakAfter).then(t=>{this.context.overflownNodeContext=t.overflownNodeContext,n.finish(t.nodeContext)})}),n.result()}accept(t,e){return!(!e.pageFloatLayoutContext.isInvalidated()&&!e.pageBreakType)||(e.fragmentLayoutConstraints.length<=0||e.fragmentLayoutConstraints.every(n=>n.allowLayout(t,this.context.overflownNodeContext,e)))}postLayout(t,e,n,i){if(!i){const e=n.fragmentLayoutConstraints.some(e=>e.nextCandidate(t));i=!e}return n.fragmentLayoutConstraints.forEach(o=>{o.postLayout(i,t,e,n)}),i}}class kl extends Il{constructor(t,e,n,i,o,s,r){super(e,n,i,o,s),this.floatSide=t,this.parentContainer=r,this.rootViewNodes=[],this.floatMargins=[],this.adjustContentRelativeSize=!0}openAllViews(t){return super.openAllViews(t).thenAsync(t=>(t&&this.fixFloatSizeAndPosition(t),fi(t)))}convertPercentageSizesToPx(t){const e=this.parentContainer.getPaddingRect(),n=e.x2-e.x1,i=e.y2-e.y1;function o(e,n){e.forEach(e=>{const i=H(t,e);if(i&&"%"===i.charAt(i.length-1)){const o=parseFloat(i);V(t,e,`${n*o/100}px`)}})}o(["width","max-width","min-width"],n),o(["height","max-height","min-height"],i),o(["margin-top","margin-right","margin-bottom","margin-left","padding-top","padding-right","padding-bottom","padding-left"],this.vertical?i:n),["margin-top","margin-right","margin-bottom","margin-left"].forEach(e=>{"auto"===H(t,e)&&V(t,e,"0")})}fixFloatSizeAndPosition(t){for(;t.parent;)t=t.parent;t.viewNode.nodeType;const e=t.viewNode;if(this.rootViewNodes.push(e),this.adjustContentRelativeSize&&this.convertPercentageSizesToPx(e),this.floatMargins.push(this.getComputedMargin(e)),this.adjustContentRelativeSize){const t=this.floatSide;if(this.parentContainer.vertical){if("block-end"===t||"left"===t){const t=H(e,"height");""!==t&&"auto"!==t&&V(e,"margin-top","auto")}}else if("block-end"===t||"bottom"===t){const t=H(e,"width");""!==t&&"auto"!==t&&V(e,"margin-left","auto")}}}getContentInlineSize(){return Math.max.apply(null,this.rootViewNodes.map((t,e)=>{const n=this.clientLayout.getElementClientRect(t),i=this.floatMargins[e];return this.vertical?i.top+n.height+i.bottom:i.left+n.width+i.right}))}}class Fl{constructor(t,e){this.parent=t,this.rootSourceNode=e,this.formattingContextType="RepetitiveElementsOwner",this.isRoot=!1,this.repetitiveElements=null}getName(){return"Repetitive elements owner formatting context (RepetitiveElementsOwnerFormattingContext)"}isFirstTime(t,e){return e}getParent(){return this.parent}getRepetitiveElements(){return this.repetitiveElements}getRootViewNode(t){const e=this.getRootNodeContext(t);return e?e.viewNode:null}getRootNodeContext(t){do{if(!t.belongsTo(this)&&t.sourceNode===this.rootSourceNode)return t}while(t=t.parent);return null}initializeRepetitiveElements(t){if(this.repetitiveElements)return;hl.some(t=>t.root===this.rootSourceNode&&(this.repetitiveElements=t.elements,!0))||(this.repetitiveElements=new Dl(t,this.rootSourceNode),hl.push({root:this.rootSourceNode,elements:this.repetitiveElements}))}saveState(){}restoreState(t){}}class Dl{constructor(t,e){this.vertical=t,this.ownerSourceNode=e,this.headerSourceNode=null,this.footerSourceNode=null,this.headerViewNode=null,this.footerViewNode=null,this.headerNodePosition=null,this.footerNodePosition=null,this.headerHeight=0,this.footerHeight=0,this.isSkipHeader=!1,this.isSkipFooter=!1,this.enableSkippingFooter=!0,this.enableSkippingHeader=!0,this.doneInitialLayout=!1,this.firstContentSourceNode=null,this.lastContentSourceNode=null,this.affectedNodeCache=[],this.afterLastContentNodeCache=[],this.allowInsert=!1}setHeaderNodeContext(t){this.headerNodePosition||(this.headerNodePosition=sa(t,0),this.headerSourceNode=t.sourceNode,this.headerViewNode=t.viewNode)}setFooterNodeContext(t){this.footerNodePosition||(this.footerNodePosition=sa(t,0),this.footerSourceNode=t.sourceNode,this.footerViewNode=t.viewNode)}updateHeight(t){this.headerViewNode&&(this.headerHeight=Va(this.headerViewNode,t,this.vertical),this.headerViewNode=null),this.footerViewNode&&(this.footerHeight=Va(this.footerViewNode,t,this.vertical),this.footerViewNode=null)}prepareLayoutFragment(){this.isSkipHeader=this.isSkipFooter=!1,this.enableSkippingFooter=!0,this.enableSkippingHeader=!0}appendHeaderToFragment(t,e,n){return!this.headerNodePosition||this.isSkipHeader?fi(!0):this.appendElementToFragment(this.headerNodePosition,t,e,n)}appendFooterToFragment(t,e,n){return!this.footerNodePosition||this.isSkipFooter?fi(!0):this.appendElementToFragment(this.footerNodePosition,t,e,n)}appendElementToFragment(t,e,n,i){const o=e.viewNode.ownerDocument,s=e.viewNode,r=o.createElement("div");s.appendChild(r);const a=new vl(i,r,e),l=a.getColumn().pageBreakType;return a.getColumn().pageBreakType=null,this.allowInsertRepeatitiveElements=!0,a.layout(new da(t),!0).thenAsync(()=>(this.allowInsertRepeatitiveElements=!1,s.removeChild(r),this.moveChildren(r,s,n),a.getColumn().pageBreakType=l,fi(!0)))}moveChildren(t,e,n){if(e)for(;t.firstChild;){const i=t.firstChild;t.removeChild(i),i.setAttribute(jr,"1"),n?e.insertBefore(i,n):e.appendChild(i)}}calculateOffset(t){let e=0;return t&&!this.affectTo(t)?e:((!this.isSkipFooter||t&&this.isAfterLastContent(t))&&(e+=this.footerHeight),this.isSkipHeader||(e+=this.headerHeight),e)}calculateMinimumOffset(t){let e=0;return t&&!this.affectTo(t)?e:(t&&this.isAfterLastContent(t)&&(e+=this.footerHeight),this.enableSkippingHeader||(e+=this.headerHeight),e)}isAfterLastContent(t){return this.findResultFromCache(t,this.afterLastContentNodeCache,e=>this.isAfterNodeContextOf(this.lastContentSourceNode,t,!1))}affectTo(t){return this.findResultFromCache(t,this.affectedNodeCache,e=>this.isAfterNodeContextOf(this.ownerSourceNode,t,!0))}findResultFromCache(t,e,n){const i=e.filter(e=>e.nodeContext.sourceNode===t.sourceNode&&e.nodeContext.after===t.after);if(i.length>0)return i[0].result;{const i=n(t);return e.push({nodeContext:t,result:i}),i}}isAfterNodeContextOf(t,e,n){const i=[];for(let n=t;n;n=n.parentNode){if(e.sourceNode===n)return e.after;i.push(n)}for(let t=e.sourceNode;t;t=t.parentNode){const e=i.indexOf(t);if(e>=0)return!!n&&0===e;for(let e=t;e;e=e.previousElementSibling)if(i.includes(e))return!0}return e.after}isFirstContentNode(t){return t&&this.firstContentSourceNode===t.sourceNode}isEnableToUpdateState(){return!!(!this.isSkipFooter&&this.enableSkippingFooter&&this.footerNodePosition||!this.isSkipHeader&&this.enableSkippingHeader&&this.headerNodePosition)}updateState(){!this.isSkipFooter&&this.enableSkippingFooter&&this.footerNodePosition?this.isSkipFooter=!0:!this.isSkipHeader&&this.enableSkippingHeader&&this.headerNodePosition&&(this.isSkipHeader=!0)}preventSkippingHeader(){this.isSkipHeader=!1,this.enableSkippingHeader=!1}preventSkippingFooter(){this.isSkipFooter=!1,this.enableSkippingFooter=!1}isHeaderRegistered(){return!!this.headerNodePosition}isFooterRegistered(){return!!this.footerNodePosition}isHeaderSourceNode(t){return this.headerSourceNode===t}isFooterSourceNode(t){return this.footerSourceNode===t}}class _l{constructor(t){this.formattingContext=t}accept(t,e){return!!t}postLayout(t,e,n,i){const o=this.formattingContext.getRepetitiveElements();return o&&(n.clientLayout,o.doneInitialLayout||(o.updateHeight(n),o.doneInitialLayout=!0)),i}}class Bl{constructor(t){this.formattingContext=t}accept(t,e){return!0}postLayout(t,e,n,i){return i}}class Ml extends _l{constructor(t,e){super(t),this.processor=e}doLayout(t,e){return this.processor.doInitialLayout(t,e)}accept(t,e){return!1}}class Ul extends Bl{constructor(t,e){super(t),this.processor=e}doLayout(t,e){return t.belongsTo(this.formattingContext)||t.after||e.fragmentLayoutConstraints.unshift(new Vl(t)),this.processor.doLayout(t,e)}}class Vl{constructor(t){this.flagmentLayoutConstraintType="RepetitiveElementsOwner";const e=t.formattingContext;this.nodeContext=e.getRootNodeContext(t)}allowLayout(t,e,n){const i=this.getRepetitiveElements();return!i||(!!Ha(this.nodeContext.viewNode)||(!i.isEnableToUpdateState()||!(e&&!t||t&&t.overflow)))}nextCandidate(t){const e=this.getRepetitiveElements();return!!e&&(!!e.isEnableToUpdateState()&&(e.updateState(),!0))}postLayout(t,e,n,i){const o=this.getRepetitiveElements();o&&t&&i.stopAtOverflow&&(null==e||o.isAfterLastContent(e))&&o.preventSkippingFooter()}finishBreak(t,e){const n=this.nodeContext.formattingContext,i=this.getRepetitiveElements();if(!i)return fi(!0);const o=this.nodeContext;return function(t,e,n){const i=t.getRepetitiveElements();if(i){const o=t.getRootNodeContext(e);if(o.viewNode){const t=o.viewNode.firstChild;return i.appendHeaderToFragment(o,t,n)}}return fi(!0)}(n,o,e).thenAsync(()=>(function(t,e,n){const i=t.getRepetitiveElements();if(i&&!i.isSkipFooter){const o=t.getRootNodeContext(e);if(o.viewNode)return i.appendFooterToFragment(o,null,n)}return fi(!0)})(n,o,e).thenAsync(()=>(i.prepareLayoutFragment(),fi(!0))))}getRepetitiveElements(){return this.nodeContext.formattingContext.getRepetitiveElements()}equalsTo(t){return t instanceof Vl&&this.nodeContext.formattingContext===t.nodeContext.formattingContext}getPriorityOfFinishBreak(){return 10}}class Hl extends sl{constructor(t,e){super(),this.formattingContext=t,this.processor=e}resolveLayoutMode(t){const e=this.formattingContext.getRepetitiveElements();return t.belongsTo(this.formattingContext)||e.doneInitialLayout?(t.belongsTo(this.formattingContext)||t.after||e&&e.preventSkippingHeader(),new Ul(this.formattingContext,this.processor)):new Ml(this.formattingContext,this.processor)}}class zl extends ll{constructor(t,e){super(),this.formattingContext=t,this.column=e}startNonInlineElementNode(t){const e=this.formattingContext,n=t.nodeContext,i=e.getRepetitiveElements();if(n.parent&&e.rootSourceNode===n.parent.sourceNode){switch(n.repeatOnBreak){case"header":if(!i.isHeaderRegistered())return i.setHeaderNodeContext(n),fi(!0);n.repeatOnBreak="none";break;case"footer":if(!i.isFooterRegistered())return i.setFooterNodeContext(n),fi(!0);n.repeatOnBreak="none"}i.firstContentSourceNode||(i.firstContentSourceNode=n.sourceNode)}return ll.prototype.startNonInlineElementNode.call(this,t)}afterNonInlineElementNode(t){const e=this.formattingContext,n=t.nodeContext;return n.sourceNode===e.rootSourceNode&&(e.getRepetitiveElements().lastContentSourceNode=t.lastAfterNodeContext&&t.lastAfterNodeContext.sourceNode,t.break=!0),"header"===n.repeatOnBreak||"footer"===n.repeatOnBreak?fi(!0):ll.prototype.afterNonInlineElementNode.call(this,t)}}function Gl(t,e){t&&function(t,e){for(let n=t;n;n=n.parent){const t=n.formattingContext;t&&t instanceof Fl&&!n.belongsTo(t)&&e(t,n)}}(t.after?t.parent:t,(t,n)=>{Mr.isInstanceOfTableFormattingContext(t)||e.fragmentLayoutConstraints.push(new Vl(n))})}const $l=new class extends el{layout(t,e,n){if(e.isFloatNodeContext(t))return e.layoutFloatOrFootnote(t);const i=t.formattingContext;return i.getRootViewNode(t)?(n&&Gl(t.parent,e),t.belongsTo(i)?el.prototype.layout.call(this,t,e,n):new Hl(i,this).layout(t,e)):e.buildDeepElementView(t)}startNonInlineElementNode(t){const e=function(t){const e=t.formattingContext;if(!e)return null;if(!(e instanceof Fl))return null;return e}(t).getRepetitiveElements();return!!e&&(e.allowInsertRepeatitiveElements||!e.isHeaderSourceNode(t.sourceNode)&&!e.isFooterSourceNode(t.sourceNode)||t.viewNode.parentNode.removeChild(t.viewNode),!1)}doInitialLayout(t,e){t.formattingContext;const n=pi("BlockLayoutProcessor.doInitialLayout");return this.layoutEntireBlock(t,e).thenFinish(n),n.result()}layoutEntireBlock(t,e){const n=t.formattingContext,i=new zl(n,e);return new al(i,e.layoutContext).iterate(t)}doLayout(t,e){const n=t.formattingContext,i=pi("doLayout");return Sl(e.layoutContext.nextInTree(t,!1),e).then(t=>{let o=t;i.loopWithFrame(t=>{for(;o;){let i=!0;if(e.layoutNext(o,!1).then(s=>{o=s,e.pageFloatLayoutContext.isInvalidated()?t.breakLoop():e.pageBreakType?t.breakLoop():o&&e.stopByOverflow(o)?t.breakLoop():o&&o.after&&o.sourceNode==n.rootSourceNode?t.breakLoop():i?i=!1:t.continueLoop()}),i)return void(i=!1)}t.breakLoop()}).then(()=>{i.finish(o)})}),i.result()}finishBreak(t,e,n,i){return el.prototype.finishBreak.call(this,t,e,n,i)}clearOverflownViewNodes(t,e,n,i){el.prototype.clearOverflownViewNodes(t,e,n,i)}};d(t.HOOKS.RESOLVE_LAYOUT_PROCESSOR,t=>t instanceof Fl&&!Mr.isInstanceOfTableFormattingContext(t)?$l:null);class Wl{constructor(t,e){this.rowIndex=t,this.sourceNode=e,this.cells=[]}addCell(t){this.cells.push(t)}getMinimumHeight(){return Math.min.apply(null,this.cells.map(t=>t.height))}}class Xl{constructor(t,e,n){this.rowIndex=t,this.columnIndex=e,this.height=0,this.anchorSlot=null,this.viewElement=n,this.colSpan=n.colSpan||1,this.rowSpan=n.rowSpan||1}setHeight(t){this.height=t}setAnchorSlot(t){this.anchorSlot=t}}class Yl{constructor(t,e,n){this.rowIndex=t,this.columnIndex=e,this.cell=n}}class Kl{constructor(t,e,n){this.column=t,this.cellNodeContext=n,this.empty=!1,this.pseudoColumn=new vl(t,e,n)}findAcceptableBreakPosition(){const t=this.cellNodeContext.viewNode,e=this.cellNodeContext.verticalAlign;"middle"!==e&&"bottom"!==e||V(t,"vertical-align","top");const n=this.pseudoColumn.findAcceptableBreakPosition(!0);return V(t,"vertical-align",e),n}}class jl{constructor(t,e){this.viewNode=t,this.side=e}}class ql extends Ya{constructor(t,e,n,i){super(t,e,n,i),this.acceptableCellBreakPositions=null,this.rowIndex=null,this.formattingContext=t.formattingContext}findAcceptableBreak(t,e){const n=super.findAcceptableBreak(t,e);return e<this.getMinBreakPenalty()?null:this.getAcceptableCellBreakPositions().every(t=>!!t.nodeContext)?n:null}getMinBreakPenalty(){let t=super.getMinBreakPenalty();return this.getAcceptableCellBreakPositions().forEach(e=>{t+=e.breakPosition.getMinBreakPenalty()}),t}getAcceptableCellBreakPositions(){if(!this.acceptableCellBreakPositions){this.formattingContext;const t=this.getCellFragments();this.acceptableCellBreakPositions=t.map(t=>t.findAcceptableBreakPosition())}return this.acceptableCellBreakPositions}getRowIndex(){return null!=this.rowIndex?this.rowIndex:this.rowIndex=this.formattingContext.findRowIndexBySourceNode(this.position.sourceNode)}getCellFragments(){return this.formattingContext.getRowSpanningCellsOverflowingTheRow(this.getRowIndex()).map(this.formattingContext.getCellFragmentOfCell,this.formattingContext)}}class Ql extends Wa{constructor(t,e,n){super(),this.rowIndex=t,this.beforeNodeContext=e,this.formattingContext=n,this.acceptableCellBreakPositions=null}findAcceptableBreak(t,e){if(e<this.getMinBreakPenalty())return null;const n=this.getCellFragments(),i=this.getAcceptableCellBreakPositions(),o=i.every(t=>!!t.nodeContext)&&i.some((t,e)=>{const i=n[e].pseudoColumn,o=t.nodeContext;return!i.isStartNodeContext(o)&&!i.isLastAfterNodeContext(o)});return this.beforeNodeContext.overflow=i.some(t=>t.nodeContext&&t.nodeContext.overflow),o?this.beforeNodeContext:null}getMinBreakPenalty(){const t=this.formattingContext,e=t.getRowByIndex(this.rowIndex);let n=0;return t.isFreelyFragmentableRow(e)||(n+=10),this.getAcceptableCellBreakPositions().forEach(t=>{n+=t.breakPosition.getMinBreakPenalty()}),n}getAcceptableCellBreakPositions(){if(!this.acceptableCellBreakPositions){const t=this.getCellFragments();this.acceptableCellBreakPositions=t.map(t=>t.findAcceptableBreakPosition())}return this.acceptableCellBreakPositions}getCellFragments(){return this.formattingContext.getCellsFallingOnRow(this.rowIndex).map(this.formattingContext.getCellFragmentOfCell,this.formattingContext)}}class Zl extends Fl{constructor(t,e){super(t,e),this.tableSourceNode=e,this.formattingContextType="Table",this.vertical=!1,this.columnCount=-1,this.tableWidth=0,this.captions=[],this.colGroups=null,this.colWidths=null,this.inlineBorderSpacing=0,this.rows=[],this.slots=[],this.cellFragments=[],this.lastRowViewNode=null,this.cellBreakPositions=[],this.repetitiveElements=null}getName(){return"Table formatting context (Table.TableFormattingContext)"}isFirstTime(t,e){if(!e)return e;switch(t.display){case"table-row":return 0===this.cellBreakPositions.length;case"table-cell":return!this.cellBreakPositions.some(e=>e.cellNodePosition.steps[0].node===t.sourceNode);default:return e}}getParent(){return this.parent}finishFragment(){this.cellFragments=[]}addRow(t,e){this.rows[t]=e}getRowSlots(t){let e=this.slots[t];return e||(e=this.slots[t]=[]),e}addCell(t,e){let n=this.rows[t];n||(this.addRow(t,new Wl(t,null)),n=this.rows[t]),n.addCell(e);const i=t+e.rowSpan;let o=this.getRowSlots(t),s=0;for(;o[s];)s++;for(;t<i;t++){o=this.getRowSlots(t);for(let n=s;n<s+e.colSpan;n++){const i=o[n]=new Yl(t,n,e);e.anchorSlot||e.setAnchorSlot(i)}}}getRowByIndex(t){return this.rows[t]}findRowIndexBySourceNode(t){return this.rows.findIndex(e=>t===e.sourceNode)}addCellFragment(t,e,n){let i=this.cellFragments[t];i||(i=this.cellFragments[t]=[]),i[e]=n}getCellsFallingOnRow(t){return this.getRowSlots(t).reduce((t,e)=>e.cell!==t[t.length-1]?t.concat(e.cell):t,[])}getRowSpanningCellsOverflowingTheRow(t){return this.getCellsFallingOnRow(t).filter(e=>e.rowIndex+e.rowSpan-1>t)}getCellFragmentOfCell(t){return this.cellFragments[t.rowIndex]&&this.cellFragments[t.rowIndex][t.columnIndex]}isFreelyFragmentableRow(t){return t.getMinimumHeight()>this.tableWidth/2}getColumnCount(){return this.columnCount<0&&(this.columnCount=Math.max.apply(null,this.rows.map(t=>t.cells.reduce((t,e)=>t+e.colSpan,0)))),this.columnCount}updateCellSizes(t){this.rows.forEach(e=>{e.cells.forEach(e=>{const n=t.getElementClientRect(e.viewElement);e.viewElement=null,e.setHeight(this.vertical?n.width:n.height)})})}findCellFromColumn(t){if(!t)return null;let e=null,n=0,i=0;t:for(n=0;n<this.cellFragments.length;n++)if(this.cellFragments[n])for(i=0;i<this.cellFragments[n].length;i++)if(this.cellFragments[n][i]&&t===this.cellFragments[n][i].pseudoColumn.getColumn()){e=this.rows[n].cells[i];break t}if(!e)return null;for(;n<this.slots.length;n++)for(;i<this.slots[n].length;i++){const t=this.slots[n][i];if(t.cell===e)return{rowIndex:t.rowIndex,columnIndex:t.columnIndex}}return null}collectElementsOffsetOfUpperCells(t){const e=[];return this.slots.reduce((n,i,o)=>{if(o>=t.rowIndex)return n;const s=this.getCellFragmentOfCell(i[t.columnIndex].cell);return!s||e.includes(s)?n:(this.collectElementsOffsetFromColumn(s.pseudoColumn.getColumn(),n),e.push(s),n)},[])}collectElementsOffsetOfHighestColumn(){const t=[];return this.rows.forEach(e=>{e.cells.forEach((e,n)=>{t[n]||(t[n]={collected:[],elements:[]});const i=t[n],o=this.getCellFragmentOfCell(e);o&&!i.collected.includes(o)&&(this.collectElementsOffsetFromColumn(o.pseudoColumn.getColumn(),i.elements),i.collected.push(o))})}),[new Jl(t.map(t=>t.elements))]}collectElementsOffsetFromColumn(t,e){t.fragmentLayoutConstraints.forEach(t=>{if(Br.isInstanceOfRepetitiveElementsOwnerLayoutConstraint(t)){const n=t.getRepetitiveElements();e.push(n)}Mr.isInstanceOfTableRowLayoutConstraint(t)&&t.getElementsOffsetsForTableCell(null).forEach(t=>{e.push(t)})})}saveState(){return[].concat(this.cellBreakPositions)}restoreState(t){this.cellBreakPositions=t}}class Jl{constructor(t){this.repeatitiveElementsInColumns=t}calculateOffset(t){return this.calculateMaxOffsetOfColumn(t,t=>t.current)}calculateMinimumOffset(t){return this.calculateMaxOffsetOfColumn(t,t=>t.minimum)}calculateMaxOffsetOfColumn(t,e){let n=0;return this.repeatitiveElementsInColumns.forEach(i=>{const o=Xa(t,i);n=Math.max(n,e(o))}),n}}function th(t){return function(t){return"table-row-group"===t||"table-header-group"===t||"table-footer-group"===t}(t)||function(t){return"table"===t||"inline-table"===t}(t)}function eh(t,e,n){const i=t.nodeContext,o=i.display,s=i.parent?i.parent.display:null;let r=!1;if("inline-table"===s&&!(i.formattingContext instanceof Zl))for(let t=i.parent;t;t=t.parent)if(t.formattingContext instanceof Zl){r=t.formattingContext===e;break}return r||"table-row"===o&&!th(s)||"table-cell"===o&&"table-row"!==s&&!th(s)||i.formattingContext instanceof Zl&&i.formattingContext!==e?n.buildDeepElementView(i).thenAsync(e=>(t.nodeContext=e,fi(!0))):null}class nh extends ll{constructor(t,e){super(),this.formattingContext=t,this.column=e,this.rowIndex=-1,this.columnIndex=0,this.inRow=!1,this.checkPoints=[],this.inHeaderOrFooter=!1}startNonInlineElementNode(t){const e=this.formattingContext,n=eh(t,e,this.column);if(n)return n;this.postLayoutBlockContents(t);const i=t.nodeContext,o=i.display,s=e.getRepetitiveElements();switch(o){case"table":e.inlineBorderSpacing=i.inlineBorderSpacing;break;case"table-caption":{const t=new jl(i.viewNode,i.captionSide);e.captions.push(t);break}case"table-header-group":return s.isHeaderRegistered()||(this.inHeaderOrFooter=!0,s.setHeaderNodeContext(i)),fi(!0);case"table-footer-group":return s.isFooterRegistered()||(this.inHeaderOrFooter=!0,s.setFooterNodeContext(i)),fi(!0);case"table-row":this.inHeaderOrFooter||(this.inRow=!0,this.rowIndex++,i.sourceNode,this.columnIndex=0,e.addRow(this.rowIndex,new Wl(this.rowIndex,i.sourceNode)),s.firstContentSourceNode||(s.firstContentSourceNode=i.sourceNode))}return super.startNonInlineElementNode(t)}afterNonInlineElementNode(t){const e=this.formattingContext,n=t.nodeContext,i=n.display,o=this.column.clientLayout;if(this.postLayoutBlockContents(t),n.sourceNode===e.tableSourceNode){const i=o.getElementComputedStyle(e.getRootViewNode(n));e.tableWidth=parseFloat(i[e.vertical?"height":"width"]),e.getRepetitiveElements().lastContentSourceNode=t.lastAfterNodeContext&&t.lastAfterNodeContext.sourceNode,t.break=!0}else switch(i){case"table-header-group":case"table-footer-group":if(this.inHeaderOrFooter)return this.inHeaderOrFooter=!1,fi(!0);break;case"table-row":this.inHeaderOrFooter||(e.lastRowViewNode=n.viewNode,this.inRow=!1);break;case"table-cell":if(!this.inHeaderOrFooter){this.inRow||(this.rowIndex++,this.columnIndex=0,this.inRow=!0);const t=n.viewNode;e.addCell(this.rowIndex,new Xl(this.rowIndex,this.columnIndex,t)),this.columnIndex++}}return super.afterNonInlineElementNode(t)}startNonElementNode(t){this.registerCheckPoint(t)}afterNonElementNode(t){this.registerCheckPoint(t)}startInlineElementNode(t){this.registerCheckPoint(t)}afterInlineElementNode(t){this.registerCheckPoint(t)}registerCheckPoint(t){const e=t.nodeContext;e&&e.viewNode&&!$a(e)&&this.checkPoints.push(e.clone())}postLayoutBlockContents(t){this.checkPoints.length>0&&this.column.postLayoutBlock(t.nodeContext,this.checkPoints),this.checkPoints=[]}}class ih extends ll{constructor(t,e){super(!0),this.formattingContext=t,this.column=e,this.inRow=!1,this.currentRowIndex=-1,this.currentColumnIndex=0,this.originalStopAtOverflow=e.stopAtOverflow,e.stopAtOverflow=!1}resetColumn(){this.column.stopAtOverflow=this.originalStopAtOverflow}getColSpanningCellWidth(t){const e=this.formattingContext.colWidths;let n=0;for(let i=0;i<t.colSpan;i++)n+=e[t.anchorSlot.columnIndex+i];return n+=this.formattingContext.inlineBorderSpacing*(t.colSpan-1),n}layoutCell(t,e,n){const i=t.rowIndex,o=t.columnIndex,s=t.colSpan,r=e.viewNode;e.verticalAlign;s>1&&(V(r,"box-sizing","border-box"),V(r,this.formattingContext.vertical?"height":"width",`${this.getColSpanningCellWidth(t)}px`));const a=r.ownerDocument.createElement("div");r.appendChild(a);const l=new Kl(this.column,a,e);return this.formattingContext.addCellFragment(i,o,l),1===n.primary.steps.length&&n.primary.after&&(l.empty=!0),l.pseudoColumn.layout(n,!0).thenReturn(!0)}hasBrokenCellAtSlot(t){const e=this.formattingContext.cellBreakPositions[0];return!!e&&e.cell.anchorSlot.columnIndex===t}extractRowSpanningCellBreakPositions(){const t=this.formattingContext.cellBreakPositions;if(0===t.length)return[];const e=[];let n=0;do{const i=t[n],o=i.cell.rowIndex;if(o<this.currentRowIndex){let s=e[o];s||(s=e[o]=[]),s.push(i),t.splice(n,1)}else n++}while(n<t.length);return e}layoutRowSpanningCellsFromPreviousFragment(t){const e=this.formattingContext,n=this.extractRowSpanningCellBreakPositions(),i=n.reduce(t=>t+1,0);if(0===i)return fi(!0);const o=this.column.layoutContext,s=t.nodeContext;s.viewNode.parentNode.removeChild(s.viewNode);const r=pi("layoutRowSpanningCellsFromPreviousFragment");let a=fi(!0),l=0;const h=[];return n.forEach(t=>{a=a.thenAsync(()=>{const n=ra(t[0].cellNodePosition.steps[1],s.parent);return o.setCurrent(n,!1).thenAsync(()=>{let s=fi(!0),r=0;function a(t){for(;r<t;){if(!h.includes(r)){const t=n.viewNode.ownerDocument.createElement("td");V(t,"padding","0"),n.viewNode.appendChild(t)}r++}}return t.forEach(t=>{s=s.thenAsync(()=>{const e=t.cell;a(e.anchorSlot.columnIndex);const s=t.cellNodePosition,c=ra(s.steps[0],n);return c.offsetInNode=s.offsetInNode,c.after=s.after,c.fragmentIndex=s.steps[0].fragmentIndex+1,o.setCurrent(c,!1).thenAsync(()=>{const n=t.breakChunkPosition;for(let t=0;t<e.colSpan;t++)h.push(r+t);return r+=e.colSpan,this.layoutCell(e,c,n).thenAsync(()=>(c.viewNode.rowSpan=e.rowIndex+e.rowSpan-this.currentRowIndex+i-l,fi(!0)))})})}),s.thenAsync(()=>(a(e.getColumnCount()),l++,fi(!0)))})})}),a.then(()=>{o.setCurrent(s,!0,t.atUnforcedBreak).then(()=>{r.finish(!0)})}),r.result()}startTableRow(t){if(this.inHeader||this.inFooter)return fi(!0);const e=t.nodeContext,n=this.formattingContext;return this.currentRowIndex<0?(e.sourceNode,this.currentRowIndex=n.findRowIndexBySourceNode(e.sourceNode)):this.currentRowIndex++,this.currentColumnIndex=0,this.inRow=!0,this.layoutRowSpanningCellsFromPreviousFragment(t).thenAsync(()=>{return this.registerCellFragmentIndex(),this.column.checkOverflowAndSaveEdgeAndBreakPosition(t.lastAfterNodeContext,null,!0,t.breakAtTheEdge)&&0===n.getRowSpanningCellsOverflowingTheRow(this.currentRowIndex-1).length&&(this.resetColumn(),e.overflow=!0,t.break=!0),fi(!0)})}registerCellFragmentIndex(){this.formattingContext.getRowByIndex(this.currentRowIndex).cells.forEach(t=>{const e=this.formattingContext.cellBreakPositions[t.columnIndex];if(e&&e.cell.anchorSlot.columnIndex==t.anchorSlot.columnIndex){const t=e.cellNodePosition.steps[0],n=this.column.layoutContext.xmldoc.getElementOffset(t.node);ml(n,t.fragmentIndex+1,1)}})}startTableCell(t){if(this.inHeader||this.inFooter)return fi(!0);const e=t.nodeContext;this.inRow||(this.currentRowIndex<0?this.currentRowIndex=0:this.currentRowIndex++,this.currentColumnIndex=0,this.inRow=!0);const n=this.formattingContext.getRowByIndex(this.currentRowIndex).cells[this.currentColumnIndex],i=e.copy().modify();i.after=!0,t.nodeContext=i;const o=pi("startTableCell");let s;if(this.hasBrokenCellAtSlot(n.anchorSlot.columnIndex)){const t=this.formattingContext.cellBreakPositions.shift();e.fragmentIndex=t.cellNodePosition.steps[0].fragmentIndex+1,s=fi(t.breakChunkPosition)}else s=this.column.nextInTree(e,t.atUnforcedBreak).thenAsync(t=>{t.viewNode&&e.viewNode.removeChild(t.viewNode);const n=sa(t,0);return fi(new da(n))});return s.then(i=>{this.layoutCell(n,e,i).then(()=>{this.afterNonInlineElementNode(t),this.currentColumnIndex++,o.finish(!0)})}),o.result()}startNonInlineBox(t){const e=eh(t,this.formattingContext,this.column);if(e)return e;const n=t.nodeContext,i=this.formattingContext.getRepetitiveElements(),o=n.display;return"table-header-group"===o&&i&&i.isHeaderSourceNode(n.sourceNode)?(this.inHeader=!0,fi(!0)):"table-footer-group"===o&&i&&i.isFooterSourceNode(n.sourceNode)?(this.inFooter=!0,fi(!0)):"table-row"===o?this.startTableRow(t):"table-cell"===o?this.startTableCell(t):fi(!0)}endNonInlineBox(t){const e=t.nodeContext;if("table-row"===e.display&&(this.inRow=!1,!this.inHeader&&!this.inFooter)){const t=e.copy().modify();t.after=!1;const n=new Ql(this.currentRowIndex,t,this.formattingContext);this.column.breakPositions.push(n)}return fi(!0)}afterNonInlineElementNode(t){const e=t.nodeContext,n=this.formattingContext.getRepetitiveElements(),i=e.display;if("table-header-group"===i?n&&!n.allowInsertRepeatitiveElements&&n.isHeaderSourceNode(e.sourceNode)?(this.inHeader=!1,e.viewNode.parentNode.removeChild(e.viewNode)):V(e.viewNode,"display","table-row-group"):"table-footer-group"===i&&(n&&!n.allowInsertRepeatitiveElements&&n.isFooterSourceNode(e.sourceNode)?(this.inFooter=!1,e.viewNode.parentNode.removeChild(e.viewNode)):V(e.viewNode,"display","table-row-group")),i&&ih.ignoreList[i])e.viewNode.parentNode.removeChild(e.viewNode);else{if(e.sourceNode!==this.formattingContext.tableSourceNode)return super.afterNonInlineElementNode(t);e.overflow=this.column.checkOverflowAndSaveEdge(e,null),this.resetColumn(),t.break=!0}return fi(!0)}}ih.ignoreList={"table-caption":!0,"table-column-group":!0,"table-column":!0};const oh=[];class sh{layoutEntireTable(t,e){const n=t.formattingContext,i=new nh(n,e);return new al(i,e.layoutContext).iterate(t)}getColumnWidths(t,e,n,i){const o=t.ownerDocument,s=o.createElement("tr"),r=[];for(let t=0;t<e;t++){const t=o.createElement("td");s.appendChild(t),r.push(t)}t.parentNode.insertBefore(s,t.nextSibling);const a=r.map(t=>{const e=i.getElementClientRect(t);return n?e.height:e.width});return t.parentNode.removeChild(s),a}getColGroupElements(t){const e=[];let n=t.firstElementChild;for(;n;)"colgroup"===n.localName&&e.push(n),n=n.nextElementSibling;return e}normalizeAndGetColElements(t){const e=[];return t.forEach(t=>{let n=t.span;t.removeAttribute("span");let i=t.firstElementChild;for(;i;){if("col"===i.localName){let o=i.span;for(i.removeAttribute("span"),n-=o;o-- >1;){const n=i.cloneNode(!0);t.insertBefore(n,i),e.push(n)}e.push(i)}i=i.nextElementSibling}for(;n-- >0;)i=t.ownerDocument.createElement("col"),t.appendChild(i),e.push(i)}),e}addMissingColElements(t,e,n,i){if(t.length<n){const o=i.ownerDocument.createElement("colgroup");e.push(o);for(let e=t.length;e<n;e++){const e=i.ownerDocument.createElement("col");o.appendChild(e),t.push(e)}}}normalizeColGroups(t,e,n){const i=t.vertical,o=t.lastRowViewNode;if(!o)return;t.lastRowViewNode=null;const s=o.ownerDocument.createDocumentFragment(),r=t.getColumnCount();if(!(r>0))return void(t.colGroups=s);const a=t.colWidths=this.getColumnWidths(o,r,i,n.clientLayout),l=this.getColGroupElements(e),h=this.normalizeAndGetColElements(l);this.addMissingColElements(h,l,r,e),h.forEach((t,e)=>{V(t,i?"height":"width",`${a[e]}px`)}),l.forEach(t=>{s.appendChild(t.cloneNode(!0))}),t.colGroups=s}doInitialLayout(t,e){const n=t.formattingContext;n.vertical=t.vertical,n.initializeRepetitiveElements(t.vertical),t.sourceNode;const i=function(t){const e=oh.findIndex(e=>e.root===t),n=oh[e];return n?n.tableLayoutOption:null}(t.sourceNode);!function(t){const e=oh.findIndex(e=>e.root===t);e>=0&&oh.splice(e,1)}(t.sourceNode);const o=pi("TableLayoutProcessor.doInitialLayout"),s=t.copy();return this.layoutEntireTable(t,e).then(r=>{const a=r.viewNode,l=e.clientLayout.getElementClientRect(a);let h=e.vertical?l.left:l.bottom;if(h+=(e.vertical?-1:1)*Xa(t,e.collectElementsOffset()).current,!(e.isOverflown(h)||i&&i.calculateBreakPositionsInside))return e.breakPositions.push(new lh(s)),void o.finish(r);this.normalizeColGroups(n,a,e),n.updateCellSizes(e.clientLayout),o.finish(null)}),o.result()}addCaptions(t,e,n){const i=t.captions;i.forEach((t,o)=>{t&&(e.insertBefore(t.viewNode,n),"top"===t.side&&(i[o]=null))})}addColGroups(t,e,n){t.colGroups&&0===this.getColGroupElements(e).length&&e.insertBefore(t.colGroups.cloneNode(!0),n)}removeColGroups(t,e){if(t.colGroups&&e){const t=this.getColGroupElements(e);t&&t.forEach(t=>{e.removeChild(t)})}}doLayout(t,e){const n=t.formattingContext,i=n.getRootViewNode(t),o=i.firstChild;this.addCaptions(n,i,o),this.addColGroups(n,i,o);const s=new ih(n,e),r=new al(s,e.layoutContext),a=pi("TableFormattingContext.doLayout");return r.iterate(t).thenFinish(a),a.result()}layout(t,e,n){const i=t.formattingContext;return i.getRootViewNode(t)?(n&&Gl(t.parent,e),new rh(i,this).layout(t,e)):e.buildDeepElementView(t)}createEdgeBreakPosition(t,e,n,i){return new ql(t,e,n,i)}startNonInlineElementNode(t){return!1}afterNonInlineElementNode(t,e){return!1}finishBreak(t,e,n,i){const o=e.formattingContext;if("table-row"===e.display){e.sourceNode;const n=o.findRowIndexBySourceNode(e.sourceNode);let i;if(o.cellBreakPositions=[],i=e.after?o.getRowSpanningCellsOverflowingTheRow(n):o.getCellsFallingOnRow(n),i.length){const s=pi("TableLayoutProcessor.finishBreak");let r=0;return s.loopWithFrame(t=>{if(r===i.length)return void t.breakLoop();const e=i[r++],s=o.getCellFragmentOfCell(e),a=s.findAcceptableBreakPosition().nodeContext,l=s.cellNodeContext,h=l.toNodePosition(),c=new da(a.toNodePosition());o.cellBreakPositions.push({cellNodePosition:h,breakChunkPosition:c,cell:e});const u=l.viewNode;s.column.layoutContext.processFragmentedBlockEdge(s.cellNodeContext),n<e.rowIndex+e.rowSpan-1&&(u.rowSpan=n-e.rowIndex+1),s.empty?t.continueLoop():s.pseudoColumn.finishBreak(a,!1,!0).then(()=>{!function(t,e,n){const i=e.getRepetitiveElements();if(!i)return;const o=e.vertical,s=t.column,r=t.pseudoColumn.getColumnElement(),a=t.cellNodeContext.viewNode,l=s.clientLayout.getElementClientRect(a),h=s.getComputedPaddingBorder(a);if(o){const t=l.right-s.footnoteEdge-i.calculateOffset(n)-h.right;V(r,"max-width",`${t}px`)}else{const t=s.footnoteEdge-i.calculateOffset(n)-l.top-h.top;V(r,"max-height",`${t}px`)}V(r,"overflow","hidden")}(s,o,a),t.continueLoop()})}).then(()=>{t.clearOverflownViewNodes(e,!1),t.layoutContext.processFragmentedBlockEdge(e),o.finishFragment(),s.finish(!0)}),s.result()}}return o.finishFragment(),il.finishBreak(t,e,n,i)}clearOverflownViewNodes(t,e,n,i){el.prototype.clearOverflownViewNodes(t,e,n,i)}}class rh extends sl{constructor(t,e){super(),this.tableFormattingContext=t,this.processor=e}resolveLayoutMode(t){const e=this.tableFormattingContext.getRepetitiveElements();return e&&e.doneInitialLayout?(t.sourceNode!==this.tableFormattingContext.tableSourceNode||t.after||e&&e.preventSkippingHeader(),new ch(this.tableFormattingContext,this.processor)):new ah(this.tableFormattingContext,this.processor)}clearNodes(t){super.clearNodes(t);const e=this.tableFormattingContext.getRootViewNode(t);this.processor.removeColGroups(this.tableFormattingContext,e)}restoreState(t,e){super.restoreState(t,e),this.tableFormattingContext.finishFragment()}}class ah extends _l{constructor(t,e){super(t),this.processor=e}doLayout(t,e){return this.processor.doInitialLayout(t,e)}}class lh extends Ya{constructor(t){super(t,null,t.overflow,0)}getMinBreakPenalty(){if(!this.isEdgeUpdated)throw new Error("EdgeBreakPosition.prototype.updateEdge not called");return(this.overflows?3:0)+(this.position.parent?this.position.parent.breakPenalty:0)}breakPositionChosen(t){t.fragmentLayoutConstraints.push(new hh(this.position.sourceNode))}}class hh{constructor(t){this.tableRootNode=t,this.flagmentLayoutConstraintType="EntireTable"}allowLayout(t,e,n){return t.overflow,!1}nextCandidate(t){return!0}postLayout(t,e,n,i){e.sourceNode,oh.push({root:e.sourceNode,tableLayoutOption:{calculateBreakPositionsInside:!0}})}finishBreak(t,e){return fi(!0)}equalsTo(t){return t instanceof hh&&t.tableRootNode===this.tableRootNode}getPriorityOfFinishBreak(){return 0}}class ch extends Bl{constructor(t,e){super(t),this.processor=e}doLayout(t,e){const n=this.formattingContext.getRepetitiveElements();if(n&&!n.isAfterLastContent(t)){const n=new uh(t);e.fragmentLayoutConstraints.some(t=>n.equalsTo(t))||e.fragmentLayoutConstraints.unshift(n)}return this.processor.doLayout(t,e)}}class uh extends Vl{constructor(t){super(t),this.flagmentLayoutConstraintType="TableRow",this.cellFragmentLayoutConstraints=[]}allowLayout(t,e,n){const i=this.getRepetitiveElements();return!i||(!!n.pseudoParent||(!!Ha(this.nodeContext.viewNode)||(!i.isEnableToUpdateState()||!(e&&!t||t&&t.overflow))))}nextCandidate(t){const e=this.nodeContext.formattingContext;return!!this.collectCellFragmentLayoutConstraints(t,e).some(e=>e.constraints.some(e=>e.nextCandidate(t)))||super.nextCandidate(t)}postLayout(t,e,n,i){const o=this.nodeContext.formattingContext;if(this.cellFragmentLayoutConstraints=this.collectCellFragmentLayoutConstraints(e,o),this.cellFragmentLayoutConstraints.forEach(e=>{e.constraints.forEach(o=>{o.postLayout(t,e.breakPosition,n,i)})}),!t){const t=o.getRootViewNode(this.nodeContext);(new sh).removeColGroups(o,t),this.removeDummyRowNodes(n)}super.postLayout(t,e,n,i)}finishBreak(t,e){this.nodeContext.formattingContext;const n=pi("finishBreak"),i=this.cellFragmentLayoutConstraints.reduce((t,e)=>t.concat(e.constraints.map(t=>({constraint:t,breakPosition:e.breakPosition}))),[]);let o=0;return n.loop(()=>{if(o<i.length){const t=i[o++];return t.constraint.finishBreak(t.breakPosition,e).thenReturn(!0)}return fi(!1)}).then(()=>{n.finish(!0)}),n.result().thenAsync(()=>super.finishBreak(t,e))}removeDummyRowNodes(t){if(t&&"table-row"===t.display&&t.viewNode)for(;t.viewNode.previousElementSibling;){const e=t.viewNode.previousElementSibling;e.parentNode&&e.parentNode.removeChild(e)}}collectCellFragmentLayoutConstraints(t,e){return this.getCellFragemnts(t,e).map(t=>({constraints:t.fragment.pseudoColumn.getColumn().fragmentLayoutConstraints,breakPosition:t.breakPosition}))}getCellFragemnts(t,e){let n=Number.MAX_VALUE;t&&"table-row"===t.display&&(t.sourceNode,n=e.findRowIndexBySourceNode(t.sourceNode)+1),n=Math.min(e.cellFragments.length,n);const i=[];for(let t=0;t<n;t++)e.cellFragments[t]&&e.cellFragments[t].forEach(t=>{t&&i.push({fragment:t,breakPosition:t.findAcceptableBreakPosition().nodeContext})});return i}getElementsOffsetsForTableCell(t){const e=this.nodeContext.formattingContext,n=e.findCellFromColumn(t);return n?e.collectElementsOffsetOfUpperCells(n):e.collectElementsOffsetOfHighestColumn()}equalsTo(t){return t instanceof uh&&this.nodeContext.formattingContext===t.nodeContext.formattingContext}}const dh=new sh;function ph(t){return t.reduce((t,e)=>t+e,0)/t.length}d(t.HOOKS.RESOLVE_FORMATTING_CONTEXT,(function(t,e,n,i,o,s){if(!e)return null;if(n===Me.table){const e=t.parent;return new Zl(e?e.formattingContext:null,t.sourceNode)}return null})),d(t.HOOKS.RESOLVE_LAYOUT_PROCESSOR,(function(t){return t instanceof Zl?dh:null}));class fh{constructor(t,e){this.layoutResult=t,this.penalty=e}}function gh(t){return t.vertical?t.width:t.height}function mh(t,e){t.vertical?t.width=e:t.height=e}class Eh{constructor(t,e,n){this.layoutContainer=t,this.columnGenerator=e,this.regionPageFloatLayoutContext=n,this.originalContainerBlockSize=gh(t)}balanceColumns(t){const e=this,n=pi("ColumnBalancer#balanceColumns");e.preBalance(t),e.savePageFloatLayoutContexts(t),e.layoutContainer.clear();const i=[e.createTrialResult(t)];return n.loopWithFrame(t=>{e.hasNextCandidate(i)?(e.updateCondition(i),e.columnGenerator().then(n=>{e.savePageFloatLayoutContexts(n),e.layoutContainer.clear(),n?(i.push(e.createTrialResult(n)),t.continueLoop()):t.breakLoop()})):t.breakLoop()}).then(()=>{const t=i.reduce((t,e)=>e.penalty<t.penalty?e:t,i[0]);e.restoreContents(t.layoutResult),e.postBalance(),n.finish(t.layoutResult)}),n.result()}createTrialResult(t){const e=this.calculatePenalty(t);return new fh(t,e)}preBalance(t){}postBalance(){mh(this.layoutContainer,this.originalContainerBlockSize)}savePageFloatLayoutContexts(t){const e=this.regionPageFloatLayoutContext.detachChildren();t&&(t.columnPageFloatLayoutContexts=e)}restoreContents(t){const e=this.layoutContainer.element;t.columns.forEach(t=>{e.appendChild(t.element)}),t.columnPageFloatLayoutContexts,this.regionPageFloatLayoutContext.attachChildren(t.columnPageFloatLayoutContexts)}}const wh=1;function Nh(t){const e=t[t.length-1];if(0===e.penalty)return!1;const n=t[t.length-2];if(n&&e.penalty>=n.penalty)return!1;const i=e.layoutResult.columns;return Math.max.apply(null,i.map(t=>t.computedBlockSize))>Math.max.apply(null,i.map(t=>t.getMaxBlockSizeOfPageFloats()))+wh}function bh(t,e){const n=t[t.length-1].layoutResult.columns,i=Math.max.apply(null,n.map(t=>isNaN(t.blockDistanceToBlockEndFloats)?t.computedBlockSize:t.computedBlockSize-t.blockDistanceToBlockEndFloats+wh))-wh;i<gh(e)?mh(e,i):mh(e,gh(e)-1)}class Sh extends Eh{constructor(t,e,n,i){super(n,t,e),this.columnCount=i,this.originalPosition=null,this.foundUpperBound=!1}preBalance(t){const e=t.columns.reduce((t,e)=>t+e.computedBlockSize,0);mh(this.layoutContainer,e/this.columnCount),this.originalPosition=t.position}checkPosition(t){return this.originalPosition?this.originalPosition.isSamePosition(t):null===t}calculatePenalty(t){if(!this.checkPosition(t.position))return 1/0;const e=t.columns;return yh(e)?1/0:Math.max.apply(null,e.map(t=>t.computedBlockSize))}hasNextCandidate(t){if(1===t.length)return!0;if(this.foundUpperBound)return Nh(t);{const e=t[t.length-1];return this.checkPosition(e.layoutResult.position)&&!yh(e.layoutResult.columns)?(this.foundUpperBound=!0,!0):gh(this.layoutContainer)<this.originalContainerBlockSize}}updateCondition(t){if(this.foundUpperBound)bh(t,this.layoutContainer);else{const t=Math.min(this.originalContainerBlockSize,gh(this.layoutContainer)+.1*this.originalContainerBlockSize);mh(this.layoutContainer,t)}}}function yh(t){if(t.length<=1)return!1;const e=t[t.length-1].computedBlockSize;return t.slice(0,t.length-1).every(t=>e>t.computedBlockSize)}class Ch extends Eh{constructor(t,e,n){super(n,t,e)}calculatePenalty(t){if(t.columns.every(t=>0===t.computedBlockSize))return 1/0;return function(t){const e=ph(t);return ph(t.map(t=>{const n=t-e;return n*n}))}(t.columns.filter(t=>!t.pageBreakType).map(t=>t.computedBlockSize))}hasNextCandidate(t){return Nh(t)}updateCondition(t){bh(t,this.layoutContainer)}}class Th{constructor(t,e,n){this.endStuckFixed=t,this.endFixed=e,this.endSlipped=n}}class xh{constructor(){this.map=[]}getMaxFixed(){if(0==this.map.length)return 0;return this.map[this.map.length-1].endFixed}getMaxSlipped(){if(0==this.map.length)return 0;return this.map[this.map.length-1].endSlipped}addStuckRange(t){if(0==this.map.length)this.map.push(new Th(t,t,t));else{const e=this.map[this.map.length-1],n=e.endSlipped+t-e.endFixed;e.endFixed==e.endStuckFixed?(e.endFixed=t,e.endStuckFixed=t,e.endSlipped=n):this.map.push(new Th(t,t,n))}}addSlippedRange(t){0==this.map.length?this.map.push(new Th(t,0,0)):this.map[this.map.length-1].endFixed=t}slippedByFixed(t){const e=this,n=Z(this.map.length,n=>t<=e.map[n].endFixed),i=this.map[n];return i.endSlipped-Math.max(0,i.endStuckFixed-t)}fixedBySlipped(t){const e=this,n=Z(this.map.length,n=>t<=e.map[n].endSlipped),i=this.map[n];return i.endStuckFixed-(i.endSlipped-t)}}class Ih{constructor(t,e,n,i,o,s,r,a){if(this.context=t,this.style=e,this.offset=n,this.isRoot=i,this.flowChunk=o,this.atBlockStart=s,this.atFlowStart=r,this.isParentBoxDisplayed=a,this.isBlockValue=null,this.hasBoxValue=null,this.styleValues={},this.beforeBox=null,this.afterBox=null,this.breakBefore=null,this.flowName=o.flowName,this.hasBox()){const i=e._pseudos;if(i&&i.before){const e=new Ih(t,i.before,n,!1,o,this.isBlock(),r,!0);wa(e.styleValue("content"))&&(this.beforeBox=e,this.breakBefore=e.breakBefore)}}this.breakBefore=_a(this.getBreakValue("before"),this.breakBefore),this.atFlowStart&&ka(this.breakBefore)&&(o.breakBefore=_a(o.breakBefore,this.breakBefore))}buildAfterPseudoElementBox(t,e,n){if(this.hasBox()){const i=this.style._pseudos;if(i&&i.after){const o=new Ih(this.context,i.after,t,!1,this.flowChunk,e,n,!0);wa(o.styleValue("content"))&&(this.afterBox=o)}}}styleValue(t,e){if(!(t in this.styleValues)){const n=this.style[t];this.styleValues[t]=n?n.evaluate(this.context,t):e||null}return this.styleValues[t]}displayValue(){return this.styleValue("display",Me.inline)}isBlock(){if(null===this.isBlockValue){const t=this.displayValue(),e=this.styleValue("position"),n=this.styleValue("float");this.isBlockValue=Za(t,e,n,this.isRoot)}return this.isBlockValue}hasBox(){return null===this.hasBoxValue&&(this.hasBoxValue=this.isParentBoxDisplayed&&this.displayValue()!==Me.none),this.hasBoxValue}getBreakValue(t){let e=null;if(this.isBlock()){const n=this.styleValue(`break-${t}`);n&&(e=n.toString())}return e}}class vh{constructor(t){this.context=t,this.stack=[],this.atBlockStart=!0,this.atFlowStart=!0,this.atStartStack=[]}empty(){return 0===this.stack.length}lastBox(){return this.stack[this.stack.length-1]}lastFlowName(){const t=this.lastBox();return t?t.flowChunk.flowName:null}isCurrentBoxDisplayed(){return this.stack.every(t=>t.displayValue()!==Me.none)}push(t,e,n,i){const o=this.lastBox();i&&o&&i.flowName!==o.flowName&&this.atStartStack.push({atBlockStart:this.atBlockStart,atFlowStart:this.atFlowStart});const s=i||o.flowChunk,r=this.atFlowStart||!!i,a=this.isCurrentBoxDisplayed(),l=new Ih(this.context,t,e,n,s,r||this.atBlockStart,r,a);return this.stack.push(l),this.atBlockStart=l.hasBox()?!l.beforeBox&&l.isBlock():this.atBlockStart,this.atFlowStart=l.hasBox()?!l.beforeBox&&r:this.atFlowStart,l}encounteredTextNode(t){const e=this.lastBox();if((this.atBlockStart||this.atFlowStart)&&e.hasBox()){Zr(t,Qr(e.styleValue("white-space",Me.normal).toString()))||(this.atBlockStart=!1,this.atFlowStart=!1)}}pop(t){const e=this.stack.pop();if(e.buildAfterPseudoElementBox(t,this.atBlockStart,this.atFlowStart),this.atFlowStart&&e.afterBox){const t=e.afterBox.getBreakValue("before");e.flowChunk.breakBefore=_a(e.flowChunk.breakBefore,t)}const n=this.lastBox();if(n)if(n.flowName===e.flowName)e.hasBox()&&(this.atBlockStart=this.atFlowStart=!1);else{const t=this.atStartStack.pop();this.atBlockStart=t.atBlockStart,this.atFlowStart=t.atFlowStart}return e}nearestBlockStartOffset(t){if(!t.atBlockStart)return t.offset;let e=this.stack.length-1,n=this.stack[e];for(n===t&&(e--,n=this.stack[e]);e>=0;){if(n.flowName!==t.flowName)return t.offset;if(!n.atBlockStart)return n.offset;if(n.isRoot)return n.offset;t=n,n=this.stack[--e]}throw new Error("No block start offset found!")}}class Ph{constructor(t,e,n,i,o,s,r,a){this.xmldoc=t,this.scope=n,this.context=i,this.primaryFlows=o,this.validatorSet=s,this.counterListener=r,this.rootStyle={},this.styleMap={},this.flows={},this.flowChunks=[],this.flowListener=null,this.flowToReach=null,this.idToReach=null,this.primary=!0,this.primaryStack=[],this.rootBackgroundAssigned=!1,this.rootLayoutAssigned=!1,this.breakBeforeValues={},this.bodyReached=!0,this.root=t.root,this.cascadeHolder=e,this.last=this.root,this.cascade=e.createInstance(i,r,a,t.lang),this.offsetMap=new xh;const l=t.getElementOffset(this.root);this.lastOffset=l,this.boxStack=new vh(i),this.offsetMap.addStuckRange(l);const h=this.getAttrStyle(this.root);switch(this.cascade.pushElement(this.root,h,l),this.postprocessTopStyle(h,!1),this.root.namespaceURI){case k.XHTML:case k.FB2:this.bodyReached=!1}this.primaryStack.push(!0),this.styleMap={},this.styleMap[`e${l}`]=h,this.lastOffset++,this.replayFlowElementsFromOffset(-1)}hasProp(t,e,n){const i=t[n];return i&&i.evaluate(this.context)!==e[n]}transferPropsToRoot(t,e){for(const n in e){const i=t[n];if(i)this.rootStyle[n]=i,delete t[n];else{const t=e[n];t&&(this.rootStyle[n]=new Bo(t,Bi))}}}postprocessTopStyle(t,e){if(["writing-mode","direction"].forEach(n=>{!t[n]||e&&this.rootStyle[n]||(this.rootStyle[n]=t[n])}),!this.rootBackgroundAssigned){const e=this.hasProp(t,this.validatorSet.backgroundProps,"background-color")?t["background-color"].evaluate(this.context):null,n=this.hasProp(t,this.validatorSet.backgroundProps,"background-image")?t["background-image"].evaluate(this.context):null;(e&&e!==Me.inherit||n&&n!==Me.inherit)&&(this.transferPropsToRoot(t,this.validatorSet.backgroundProps),this.rootBackgroundAssigned=!0)}if(!this.rootLayoutAssigned)for(let e=0;e<Rh.length;e++)if(this.hasProp(t,this.validatorSet.layoutProps,Rh[e])){this.transferPropsToRoot(t,this.validatorSet.layoutProps),this.rootLayoutAssigned=!0;break}if(!e){const e=t["font-size"];if(e){const t=e.evaluate(this.context);let n=t.num;switch(t.unit){case"em":case"rem":n*=this.context.initialFontSize;break;case"ex":n*=this.context.initialFontSize*Pt.ex/Pt.em;break;case"%":n*=this.context.initialFontSize/100;break;default:{const e=Pt[t.unit];e&&(n*=e)}}this.context.rootFontSize=n}}}getTopContainerStyle(){let t=0;for(;!this.bodyReached&&(t+=5e3,this.styleUntil(t,0)!=Number.POSITIVE_INFINITY););return this.rootStyle}getAttrStyle(t){if(t.style instanceof CSSStyleDeclaration){const e=t.getAttribute("style");if(e)return ar(this.scope,this.validatorSet,this.xmldoc.url,e)}return{}}getReachedOffset(){return this.lastOffset}replayFlowElementsFromOffset(t){if(t>=this.lastOffset)return;const e=this.context,n=this.xmldoc.getElementOffset(this.root);if(t<n){const t=this.getStyle(this.root,!1),i=$o(t,"flow-into"),o=i?i.evaluate(e,"flow-into").toString():"body",s=this.encounteredFlowElement(o,t,this.root,n);this.boxStack.empty()&&this.boxStack.push(t,n,!0,s)}let i=this.xmldoc.getNodeByOffset(t),o=this.xmldoc.getNodeOffset(i,0,!1);if(!(o>=this.lastOffset))for(;;){if(1!=i.nodeType)o+=i.textContent.length;else{const t=i,n=this.getStyle(t,!1),s=n["flow-into"];if(s){const i=s.evaluate(e,"flow-into").toString();this.encounteredFlowElement(i,n,t,o)}o++}if(o>=this.lastOffset)break;let t=i.firstChild;if(null==t)for(;t=i.nextSibling,!t;)if(i=i.parentNode,i===this.root)return;i=t}}resetFlowChunkStream(t){this.flowListener=t;for(let t=0;t<this.flowChunks.length;t++)this.flowListener.encounteredFlowChunk(this.flowChunks[t],this.flows[this.flowChunks[t].flowName])}styleUntilFlowIsReached(t){this.flowToReach=t;let e=0;for(;null!=this.flowToReach&&(e+=5e3,this.styleUntil(e,0)!=Number.POSITIVE_INFINITY););}styleUntilIdIsReached(t){if(!t)return;this.idToReach=t;let e=0;for(;this.idToReach&&(e+=5e3,this.styleUntil(e,0)!==Number.POSITIVE_INFINITY););this.idToReach=null}encounteredFlowElement(t,e,n,i){let o=0,s=Number.POSITIVE_INFINITY,r=!1,a=!1,l=!1;const c=e["flow-options"];if(c){const t=function(t){if(t){const e=new pn;try{return t.visit(e),e.propSet}catch(t){h.warn(t,"toSet:")}}return{}}(c.evaluate(this.context,"flow-options"));r=!!t.exclusive,a=!!t.static,l=!!t.last}const u=e["flow-linger"];u&&(s=gn(u.evaluate(this.context,"flow-linger"),Number.POSITIVE_INFINITY));const d=e["flow-priority"];d&&(o=gn(d.evaluate(this.context,"flow-priority"),0));const p=this.breakBeforeValues[i]||null;let f=this.flows[t];if(!f){const e=this.boxStack.lastFlowName();f=this.flows[t]=new Jr(t,e)}const g=new ta(t,n,i,o,s,r,a,l,p);return this.flowChunks.push(g),this.flowToReach==t&&(this.flowToReach=null),this.flowListener&&this.flowListener.encounteredFlowChunk(g,f),g}registerForcedBreakOffset(t,e,n){if(ka(t)){const t=this.flows[n].forcedBreakOffsets;(0===t.length||t[t.length-1]<e)&&t.push(e)}const i=this.breakBeforeValues[e];this.breakBeforeValues[e]=_a(i,t)}styleUntil(t,e){let n,i=-1;if(t<=this.lastOffset&&(n=this.offsetMap.slippedByFixed(t),i=n+e,i<this.offsetMap.getMaxSlipped()))return this.offsetMap.fixedBySlipped(i);if(null==this.last)return Number.POSITIVE_INFINITY;const o=this.context;for(;;){let s=this.last.firstChild;if(null==s)for(;;){if(1==this.last.nodeType){this.cascade.popElement(this.last),this.primary=this.primaryStack.pop();const t=this.boxStack.pop(this.lastOffset);let e=null;if(t.afterBox){const n=t.afterBox.getBreakValue("before");this.registerForcedBreakOffset(n,t.afterBox.atBlockStart?this.boxStack.nearestBlockStartOffset(t):t.afterBox.offset,t.flowName),e=t.afterBox.getBreakValue("after")}e=_a(e,t.getBreakValue("after")),this.registerForcedBreakOffset(e,this.lastOffset,t.flowName)}if(s=this.last.nextSibling,s)break;if(this.last=this.last.parentNode,this.last===this.root)return this.last=null,t<this.lastOffset&&(i<0&&(n=this.offsetMap.slippedByFixed(t),i=n+e),i<=this.offsetMap.getMaxSlipped())?this.offsetMap.fixedBySlipped(i):Number.POSITIVE_INFINITY}if(this.last=s,1!=this.last.nodeType)this.lastOffset+=this.last.textContent.length,this.boxStack.encounteredTextNode(this.last),this.primary?this.offsetMap.addStuckRange(this.lastOffset):this.offsetMap.addSlippedRange(this.lastOffset);else{const s=this.last,r=this.getAttrStyle(s);this.primaryStack.push(this.primary),this.cascade.pushElement(s,r,this.lastOffset);const a=s.getAttribute("id")||s.getAttributeNS(k.XML,"id");let l;a&&a===this.idToReach&&(this.idToReach=null),this.bodyReached||"body"!=s.localName||s.parentNode!=this.root||(this.postprocessTopStyle(r,!0),this.bodyReached=!0);const h=r["flow-into"];if(h){const t=h.evaluate(o,"flow-into").toString(),e=this.encounteredFlowElement(t,r,s,this.lastOffset);this.primary=!!this.primaryFlows[t],l=this.boxStack.push(r,this.lastOffset,s===this.root,e)}else l=this.boxStack.push(r,this.lastOffset,s===this.root);const c=this.boxStack.nearestBlockStartOffset(l);if(this.registerForcedBreakOffset(l.breakBefore,c,l.flowName),l.beforeBox){const t=l.beforeBox.getBreakValue("after");this.registerForcedBreakOffset(t,l.beforeBox.atBlockStart?c:l.offset,l.flowName)}if(this.primary&&l.displayValue()===Me.none&&(this.primary=!1),this.styleMap[`e${this.lastOffset}`]=r,this.lastOffset++,this.primary?this.offsetMap.addStuckRange(this.lastOffset):this.offsetMap.addSlippedRange(this.lastOffset),t<this.lastOffset&&(i<0&&(n=this.offsetMap.slippedByFixed(t),i=n+e),i<=this.offsetMap.getMaxSlipped()))return this.offsetMap.fixedBySlipped(i)}}}getStyle(t,e){let n=this.xmldoc.getElementOffset(t);const i=`e${n}`;return e&&(n=this.xmldoc.getNodeOffset(t,0,!0)),this.lastOffset<=n&&this.styleUntil(n,0),this.styleMap[i]}processContent(t,e){}}const Rh=["column-count","column-width","column-fill"];var Ah,Lh="/*\n * Copyright 2013 Google, Inc.\n * Copyright 2015 Trim-marks Inc.\n * Copyright 2019 Vivliostyle Foundation\n *\n * CSS property validation.\n */\nNUM = POS_NUM | ZERO | NEGATIVE;\nNNEG_NUM = POS_NUM | ZERO;\nINT = POS_INT | ZERO | NEGATIVE;\nNNEG_INT = POS_INT | ZERO;\nPERCENTAGE = POS_PERCENTAGE | ZERO | NEGATIVE;\nSTRICT_PERCENTAGE = POS_PERCENTAGE | ZERO_PERCENTAGE | NEGATIVE;\nNNEG_PERCENTAGE = POS_PERCENTAGE | ZERO;\nLENGTH = POS_LENGTH | ZERO | NEGATIVE;\nNNEG_LENGTH = POS_LENGTH | ZERO | NEGATIVE;\nPLENGTH = LENGTH | PERCENTAGE;\nPPLENGTH = POS_LENGTH | ZERO | POS_PERCENTAGE;\nALENGTH = LENGTH | auto;\nAPLENGTH = PLENGTH | auto;\nPAPLENGTH = PPLENGTH | auto;\nANGLE = POS_ANGLE | ZERO | NEGATIVE;\nLENGTH_OR_NUM = LENGTH | NUM;\nANGLE_OR_NUM = ANGLE | NUM;\nSCOLOR = HASHCOLOR | aliceblue: #F0F8FF | antiquewhite: #FAEBD7 | aqua: #00FFFF | aquamarine: #7FFFD4 | azure: #F0FFFF |\n beige: #F5F5DC | bisque: #FFE4C4 | black: #000000 | blanchedalmond: #FFEBCD | blue: #0000FF | blueviolet: #8A2BE2 | brown: #A52A2A |\n burlywood: #DEB887 | cadetblue: #5F9EA0 | chartreuse: #7FFF00 | chocolate: #D2691E | coral: #FF7F50 | cornflowerblue: #6495ED |\n cornsilk: #FFF8DC | crimson: #DC143C | cyan: #00FFFF | darkblue: #00008B | darkcyan: #008B8B | darkgoldenrod: #B8860B |\n darkgray: #A9A9A9 | darkgreen: #006400 | darkgrey: #A9A9A9 | darkkhaki: #BDB76B | darkmagenta: #8B008B | darkolivegreen: #556B2F |\n darkorange: #FF8C00 | darkorchid: #9932CC | darkred: #8B0000 | darksalmon: #E9967A | darkseagreen: #8FBC8F | darkslateblue: #483D8B |\n darkslategray: #2F4F4F | darkslategrey: #2F4F4F | darkturquoise: #00CED1 | darkviolet: #9400D3 | deeppink: #FF1493 |\n deepskyblue: #00BFFF | dimgray: #696969 | dimgrey: #696969 | dodgerblue: #1E90FF | firebrick: #B22222 | floralwhite: #FFFAF0 |\n forestgreen: #228B22 | fuchsia: #FF00FF | gainsboro: #DCDCDC | ghostwhite: #F8F8FF | gold: #FFD700 | goldenrod: #DAA520 |\n gray: #808080 | green: #008000 | greenyellow: #ADFF2F | grey: #808080 | honeydew: #F0FFF0 | hotpink: #FF69B4 | indianred: #CD5C5C |\n indigo: #4B0082 | ivory: #FFFFF0 | khaki: #F0E68C | lavender: #E6E6FA | lavenderblush: #FFF0F5 | lawngreen: #7CFC00 |\n lemonchiffon: #FFFACD | lightblue: #ADD8E6 | lightcoral: #F08080 | lightcyan: #E0FFFF | lightgoldenrodyellow: #FAFAD2 |\n lightgray: #D3D3D3 | lightgreen: #90EE90 | lightgrey: #D3D3D3 | lightpink: #FFB6C1 | lightsalmon: #FFA07A | lightseagreen: #20B2AA |\n lightskyblue: #87CEFA | lightslategray: #778899 | lightslategrey: #778899 | lightsteelblue: #B0C4DE | lightyellow: #FFFFE0 |\n lime: #00FF00 | limegreen: #32CD32 | linen: #FAF0E6 | magenta: #FF00FF | maroon: #800000 | mediumaquamarine: #66CDAA |\n mediumblue: #0000CD | mediumorchid: #BA55D3 | mediumpurple: #9370DB | mediumseagreen: #3CB371 | mediumslateblue: #7B68EE |\n mediumspringgreen: #00FA9A | mediumturquoise: #48D1CC | mediumvioletred: #C71585 | midnightblue: #191970 | mintcream: #F5FFFA |\n mistyrose: #FFE4E1 | moccasin: #FFE4B5 | navajowhite: #FFDEAD | navy: #000080 | oldlace: #FDF5E6 | olive: #808000 |\n olivedrab: #6B8E23 | orange: #FFA500 | orangered: #FF4500 | orchid: #DA70D6 | palegoldenrod: #EEE8AA | palegreen: #98FB98 |\n paleturquoise: #AFEEEE | palevioletred: #DB7093 | papayawhip: #FFEFD5 | peachpuff: #FFDAB9 | peru: #CD853F | pink: #FFC0CB |\n plum: #DDA0DD | powderblue: #B0E0E6 | purple: #800080 | rebeccapurple: #663399 | red: #FF0000 | rosybrown: #BC8F8F | royalblue: #4169E1 |\n saddlebrown: #8B4513 | salmon: #FA8072 | sandybrown: #F4A460 | seagreen: #2E8B57 | seashell: #FFF5EE | sienna: #A0522D |\n silver: #C0C0C0 | skyblue: #87CEEB | slateblue: #6A5ACD | slategray: #708090 | slategrey: #708090 | snow: #FFFAFA |\n springgreen: #00FF7F | steelblue: #4682B4 | tan: #D2B48C | teal: #008080 | thistle: #D8BFD8 | tomato: #FF6347 |\n turquoise: #40E0D0 | violet: #EE82EE | wheat: #F5DEB3 | white: #FFFFFF | whitesmoke: #F5F5F5 | yellow: #FFFF00 |\n yellowgreen: #9ACD32 | transparent | currentcolor;\nRGBCOLOR = rgb(INT{3}) | rgb(STRICT_PERCENTAGE{3});\nRGBACOLOR = rgba(NUM{4}) | rgba(STRICT_PERCENTAGE{3} NUM);\nHSLCOLOR = hsl(NUM PERCENTAGE{2});\nHSLACOLOR = hsl(NUM PERCENTAGE{2} NUM);\nCOLOR = SCOLOR | RGBCOLOR | RGBACOLOR | HSLCOLOR | HSLACOLOR;\nBG_POSITION_TERM = PLENGTH | left | center | right | top | bottom;\nSIDE_OR_CORNER = [left | right] || [top | bottom];\nCOLOR_STOP = SPACE(COLOR [PERCENTAGE | LENGTH]?);\nLINEAR_GRADIENT = linear-gradient([ANGLE | SPACE(to SIDE_OR_CORNER)]? COLOR_STOP+) |\n repeating-linear-gradient([ANGLE | SPACE(to SIDE_OR_CORNER)]? COLOR_STOP+) |;\nGRADIENT_EXTENT = closest-corner | closest-side | farthest-corner | farthest-side;\nGRADIENT_POSITION = at BG_POSITION_TERM{1,4};\nGRADIENT_SHAPE = SPACE(circle LENGTH? GRADIENT_POSITION?) | SPACE(ellipse PLENGTH{2}? GRADIENT_POSITION?)| SPACE([circle | ellipse] GRADIENT_EXTENT? GRADIENT_POSITION?);\nRADIAL_GRADIENT = radial-gradient([GRADIENT_SHAPE | SPACE(GRADIENT_POSITION)]? COLOR_STOP+) |\n repeating-radial-gradient([GRADIENT_SHAPE | SPACE(GRADIENT_POSITION)]? COLOR_STOP+);\nURI_OR_NONE = URI | none;\nIMAGE = URI | LINEAR_GRADIENT | RADIAL_GRADIENT | none;\nazimuth = ANGLE | [[ left-side | far-left | left | center-left | center | center-right | right | far-right | right-side ] || behind ] | leftwards | rightwards;\nbackground-attachment = COMMA( [scroll | fixed | local]+ );\nbackground-color = COLOR;\nbackground-image = COMMA( IMAGE+ );\nbackground-position = COMMA( SPACE(BG_POSITION_TERM{1,4})+ ); /* relaxed */\nbackground-repeat = COMMA( [repeat | repeat-x | repeat-y | no-repeat]+ );\nborder-collapse = collapse | separate;\nBORDER_SIDE_COLOR = COLOR;\nBORDER_SIDE_STYLE = none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset;\nBORDER_SIDE_WIDTH = thin: 1px | medium: 3px | thick: 5px | NNEG_LENGTH;\nborder-spacing = LENGTH LENGTH?;\nborder-top-color = BORDER_SIDE_COLOR;\nborder-right-color = BORDER_SIDE_COLOR;\nborder-bottom-color = BORDER_SIDE_COLOR;\nborder-left-color = BORDER_SIDE_COLOR;\nborder-top-style = BORDER_SIDE_STYLE;\nborder-right-style = BORDER_SIDE_STYLE;\nborder-bottom-style = BORDER_SIDE_STYLE;\nborder-left-style = BORDER_SIDE_STYLE;\nborder-top-width = BORDER_SIDE_WIDTH;\nborder-right-width = BORDER_SIDE_WIDTH;\nborder-bottom-width = BORDER_SIDE_WIDTH;\nborder-left-width = BORDER_SIDE_WIDTH;\nBORDER_RADIUS = PLENGTH{1,2};\nborder-top-left-radius = BORDER_RADIUS;\nborder-top-right-radius = BORDER_RADIUS;\nborder-bottom-right-radius = BORDER_RADIUS;\nborder-bottom-left-radius = BORDER_RADIUS;\nborder-image-source = IMAGE;\nborder-image-slice = [NUM | PERCENTAGE]{1,4} || fill; /* relaxed */\nborder-image-width = [NUM | PLENGTH | auto]{1,4};\nborder-image-outset = [NUM | LENGTH]{1,4};\nborder-image-repeat = [ stretch | repeat | round | space ]{1,2};\nbottom = APLENGTH;\ncaption-side = top | bottom;\nclear = none | left | right | top | bottom | both | all | same;\nclip = rect(ALENGTH{4}) | rect(SPACE(ALENGTH{4})) | auto;\ncolor = COLOR;\nLIST_STYLE_TYPE = disc | circle | square | decimal | decimal-leading-zero | lower-roman |\n upper-roman | lower-greek | lower-latin | upper-latin | armenian | georgian | lower-alpha |\n upper-alpha | russian | upper-russian | lower-russian | cjk-ideographic | trad-chinese-informal |\n hebrew | none;\nTYPE_OR_UNIT_IN_ATTR = string | color | url | integer | number | length | angle | time | frequency;\nATTR = attr(SPACE(IDENT TYPE_OR_UNIT_IN_ATTR?) [ STRING | IDENT | COLOR | INT | NUM | PLENGTH | ANGLE | POS_TIME | FREQUENCY]?);\nCONTENT = normal | none |\n [ STRING | URI | counter(IDENT LIST_STYLE_TYPE?) |\n counters(IDENT STRING LIST_STYLE_TYPE?) | ATTR |\n target-counter([ STRING | URI ] IDENT LIST_STYLE_TYPE?) |\n target-counter(ATTR IDENT LIST_STYLE_TYPE?) |\n target-counters([ STRING | URI ] IDENT STRING LIST_STYLE_TYPE?) |\n target-counters(ATTR IDENT STRING LIST_STYLE_TYPE?) |\n open-quote | close-quote | no-open-quote | no-close-quote ]+;\ncontent = CONTENT;\nCOUNTER = [ IDENT INT? ]+ | none;\ncounter-increment = COUNTER;\ncounter-reset = COUNTER;\ncounter-set = COUNTER;\ncue-after = URI_OR_NONE;\ncue-before = URI_OR_NONE;\ncursor = COMMA(URI* [ auto | crosshair | default | pointer | move | e-resize | ne-resize | nw-resize |\n n-resize | se-resize | sw-resize | s-resize | w-resize | text | wait | help | progress ]);\ndirection = ltr | rtl;\ndisplay = inline | block | list-item | inline-block | table | inline-table | table-row-group |\n table-header-group | table-footer-group | table-row | table-column-group | table-column |\n table-cell | table-caption | none | oeb-page-head | oeb-page-foot | flex | inline-flex |\n ruby | ruby-base | ruby-text | ruby-base-container | ruby-text-container | run-in | compact | marker;\nelevation = ANGLE | below | level | above | higher | lower;\nempty-cells = show | hide;\nFAMILY = SPACE(IDENT+) | STRING;\nFAMILY_LIST = COMMA( FAMILY+ );\nfont-family = FAMILY_LIST;\nfont-size = xx-small | x-small | small | medium | large | x-large | xx-large | larger | smaller | PPLENGTH | POS_NUM;\nfont-style = normal | italic | oblique;\nfont-variant = normal | small-caps;\nfont-weight = normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;\nheight = PAPLENGTH | POS_NUM ;\nleft = APLENGTH;\nletter-spacing = normal | LENGTH_OR_NUM;\nline-height = normal | POS_NUM | PPLENGTH;\nlist-style-image = IMAGE;\nlist-style-position = inside | outside;\nlist-style-type = LIST_STYLE_TYPE;\nmargin-right = APLENGTH;\nmargin-left = APLENGTH;\nmargin-top = APLENGTH;\nmargin-bottom = APLENGTH;\nNPLENGTH = none | PLENGTH;\nmax-height = NPLENGTH;\nmax-width = NPLENGTH;\nmin-height = auto | PLENGTH;\nmin-width = auto | PLENGTH;\norphans = POS_INT;\noutline-offset = LENGTH;\noutline-color = COLOR | invert;\noutline-style = BORDER_SIDE_STYLE;\noutline-width = BORDER_SIDE_WIDTH;\noverflow = visible | hidden | scroll | auto;\npadding-right = PPLENGTH;\npadding-left = PPLENGTH;\npadding-top = PPLENGTH;\npadding-bottom = PPLENGTH;\nPAGE_BREAK = auto | always | avoid | left | right | recto | verso;\npage-break-after = PAGE_BREAK;\npage-break-before = PAGE_BREAK;\npage-break-inside = avoid | auto;\nPAUSE = POS_TIME | ZERO | POS_PERCENTAGE;\npause-after = PAUSE;\npause-before = PAUSE;\npitch-range = NUM;\npitch = FREQUENCY | x-low | low | medium | high | x-high;\nplay-during = [URI [ mix || repeat ]?] | auto | none;\nposition = static | relative | absolute | fixed;\nquotes = [STRING STRING]+ | none;\nrichness = NUM;\nright = APLENGTH;\nspeak-header = once | always;\nspeak-numeral = digits | continuous;\nspeak-punctuation = code | none;\nspeech-rate = NUM | x-slow | slow | medium | fast | x-fast | faster | slower;\nstress = NUM;\ntable-layout = auto | fixed;\ntext-align = left | right | center | justify | start | end;\ntext-decoration = none | [ underline || overline || line-through || blink ];\ntext-indent = PLENGTH;\ntext-transform = capitalize | uppercase | lowercase | none;\ntop = APLENGTH;\nvertical-align = baseline | sub | super | top | text-top | middle | bottom | text-bottom | PLENGTH;\nvisibility = visible | hidden | collapse;\nvoice-family = FAMILY_LIST;\nvolume = NUM | PERCENTAGE | silent | x-soft | soft | medium | loud | x-loud;\nwhite-space = normal | pre | nowrap | pre-wrap | pre-line;\nwidows = POS_INT;\nwidth = PAPLENGTH | POS_NUM ;\nword-spacing = normal | LENGTH_OR_NUM;\nz-index = auto | INT;\n\n[epub,moz,ms,webkit]hyphens = auto | manual | none;\n[webkit]hyphenate-character = auto | STRING;\n\n/* css-logical */\nmargin-block-start = APLENGTH;\nmargin-block-end = APLENGTH;\nmargin-inline-start = APLENGTH;\nmargin-inline-end = APLENGTH;\npadding-block-start = APLENGTH;\npadding-block-end = APLENGTH;\npadding-inline-start = APLENGTH;\npadding-inline-end = APLENGTH;\nborder-block-start-color = BORDER_SIDE_COLOR;\nborder-block-end-color = BORDER_SIDE_COLOR;\nborder-inline-start-color = BORDER_SIDE_COLOR;\nborder-inline-end-color = BORDER_SIDE_COLOR;\nborder-block-start-style = BORDER_SIDE_STYLE;\nborder-block-end-style = BORDER_SIDE_STYLE;\nborder-inline-start-style = BORDER_SIDE_STYLE;\nborder-inline-end-style = BORDER_SIDE_STYLE;\nborder-block-start-width = BORDER_SIDE_WIDTH;\nborder-block-end-width = BORDER_SIDE_WIDTH;\nborder-inline-start-width = BORDER_SIDE_WIDTH;\nborder-inline-end-width = BORDER_SIDE_WIDTH;\nblock-start = APLENGTH;\nblock-end = APLENGTH;\ninline-start = APLENGTH;\ninline-end = APLENGTH;\nblock-size = PAPLENGTH | POS_NUM;\ninline-size = PAPLENGTH | POS_NUM;\nmax-block-size = NPLENGTH;\nmax-inline-size = NPLENGTH;\nmin-block-size = auto | PLENGTH;\nmin-inline-size = auto | PLENGTH;\n\nSHAPE = auto | rectangle( PLENGTH{4} ) | ellipse( PLENGTH{4} ) | circle( PLENGTH{3} ) |\n polygon( SPACE(PLENGTH+)+ );\n[epubx]shape-inside = SHAPE;\n[epubx,webkit]shape-outside = SHAPE;\n[epubx,ms]wrap-flow = auto | both | start | end | maximum | clear | around /* epub al */;\n\nTRANSFORM_FUNCTION = matrix(NUM{6}) | translate(PLENGTH{1,2}) | translateX(PLENGTH) | translateY(PLENGTH) |\n scale(NUM{1,2}) | scaleX(NUM) | scaleY(NUM) | rotate(ANGLE) | skewX(ANGLE) | skewY(ANGLE);\n[epub,ms]transform = none | TRANSFORM_FUNCTION+;\n[epub,ms]transform-origin = [[[ top | bottom | left | right] PLENGTH?] | center | PLENGTH]{1,2}; /* relaxed */\n\nBOX = border-box | padding-box | content-box;\nSHADOW = SPACE(inset || LENGTH{2,4} || COLOR); /* relaxed */\n[webkit]background-size = COMMA( SPACE( [PLENGTH | auto ]{1,2} | cover | contain)+ );\n[webkit]background-origin = COMMA( BOX+ );\n[webkit]background-clip = COMMA( BOX+ );\n[webkit]box-shadow = none | COMMA( SHADOW+ );\ntext-shadow = none | COMMA( SHADOW+ );\n[webkit]box-decoration-break = slice | clone;\nFILTER_FUNCTION = blur(LENGTH) | brightness(NUM | PERCENTAGE) | contrast(NUM | PERCENTAGE) | drop-shadow(SPACE(LENGTH{2,3} COLOR?))\n | grayscale(NUM | PERCENTAGE) | hue-rotate(ANGLE) | invert(NUM | PERCENTAGE) | opacity(NUM | PERCENTAGE)\n | saturate(NUM | PERCENTAGE) | sepia(NUM | PERCENTAGE);\nFILTER_FUNCTION_LIST = FILTER_FUNCTION+;\n[webkit]filter = none | FILTER_FUNCTION_LIST;\n\nopacity = NUM;\n\n[moz,webkit]column-width = LENGTH | auto;\n[moz,webkit]column-count = INT | auto;\n[moz,webkit]column-gap = LENGTH | normal;\n[moz,webkit]column-rule-color = COLOR;\n[moz,webkit]column-rule-style = BORDER_SIDE_STYLE;\n[moz,webkit]column-rule-width = BORDER_SIDE_WIDTH;\nBREAK = auto | avoid | avoid-page | page | left | right | recto | verso | avoid-column | column | avoid-region | region;\nbreak-before = BREAK;\nbreak-after = BREAK;\nbreak-inside = auto | avoid | avoid-page | avoid-column | avoid-region;\n[webkit]column-span = none | auto | all;\n[moz]column-fill = auto | balance | balance-all;\n\nsrc = COMMA([SPACE(URI format(STRING+)?) | local(FAMILY)]+); /* for font-face */\n\n[epubx,webkit]flow-from = IDENT;\n[epubx,webkit]flow-into = IDENT;\n[epubx]flow-linger = INT | none;\n[epubx]flow-priority = INT;\n[epubx]flow-options = none | [ exclusive || last || static ];\n[epubx]page = INT | auto;\n[epubx]min-page-width = LENGTH;\n[epubx]min-page-height = LENGTH;\n[epubx]required = true | false;\n[epubx]enabled = true | false;\n[epubx]conflicting-partitions = COMMA(IDENT+);\n[epubx]required-partitions = COMMA(IDENT+);\n[epubx]snap-height = LENGTH | none;\n[epubx]snap-width = LENGTH | none;\n[epubx]flow-consume = all | some;\n[epubx]utilization = NUM;\n[epubx]text-zoom = font-size | scale;\n\n[adapt]template = URI_OR_NONE;\n[adapt]behavior = IDENT;\n\n/* CSS Fonts */\nfont-size-adjust = none | NNEG_NUM;\n[webkit]font-kerning = auto | normal | none;\nfont-variant-east-asian = normal | [[ jis78 | jis83 | jis90 | jis04 | simplified | traditional ] || [ full-width | proportional-width ] || ruby];\nfont-feature-settings = COMMA( SPACE( STRING [ on | off | INT ]? )+ );\nfont-stretch = normal | wider | narrower | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded;\n\n/* CSS Images */\nimage-resolution = RESOLUTION;\nobject-fit = fill | contain | cover | none | scale-down;\nobject-position = COMMA( SPACE(BG_POSITION_TERM{1,4})+ ); /* relaxed */\n\n/* CSS Paged Media */\nPAGE_SIZE = a5 | a4 | a3 | b5 | b4 | jis-b5 | jis-b4 | letter | legal | ledger;\nbleed = auto | LENGTH;\nmarks = none | [ crop || cross ];\nsize = POS_LENGTH{1,2} | auto | [ PAGE_SIZE || [ portrait | landscape ] ];\n\n/* CSS Page Floats */\nfloat-reference = inline | column | region | page;\nfloat = block-start | block-end | inline-start | inline-end | snap-block | snap-inline | left | right | top | bottom | none | footnote;\nfloat-min-wrap-block = PPLENGTH;\n\n/* CSS Ruby */\nruby-align = start | center | space-between | space-around;\nruby-position = over | under | inter-character;\n\n/* CSS Size Adjust */\n[moz,ms]text-size-adjust = auto | none | POS_PERCENTAGE;\n\n/* CSS Text */\n[ms,webkit]line-break = auto | loose | normal | strict;\noverflow-wrap = normal | break-word;\n[moz]tab-size = NNEG_INT | NNEG_LENGTH;\n[moz,ms]text-align-last = auto | start | end | left | right | center | justify;\n[ms]text-justify = auto | none | inter-word | inter-character | inter-ideograph /* specified in UA stylesheet for IE */;\n[ms]word-break = normal | keep-all | break-all | break-word;\n[ms]word-wrap = normal | break-word;\n\n/* CSS Text Decoration */\n[webkit]text-decoration-color = COLOR;\n[webkit]text-decoration-line = none | [ underline || overline || line-through || blink ];\n[webkit]text-decoration-skip = none | [ objects || spaces || ink || edges || box-decoration ];\n[webkit]text-decoration-style = solid | double | dotted | dashed | wavy;\n[epub,webkit]text-emphasis-color = COLOR;\n[webkit]text-emphasis-position = [ over | under ] [ right | left ];\n[epub,webkit]text-emphasis-style = none | [[ filled | open ] || [ dot | circle | double-circle | triangle | sesame ]] | STRING;\n[ms,webkit]text-underline-position = auto | [ under || [ left | right ]];\n\n/* CSS Transforms */\n[ms,webkit]backface-visibility = visible | hidden;\n\n/* CSS UI */\nbox-sizing = content-box | padding-box | border-box;\n[ms]text-overflow = [clip | ellipsis | STRING]{1,2};\n\n/* CSS Writing Modes */\n[webkit]text-combine = none | horizontal;\n[epub,ms]text-combine-horizontal = none | all | [ digits POS_INT? ]; /* relaxed */\ntext-combine-upright = none | all | [ digits POS_INT? ]; /* relaxed */\n[epub,webkit]text-orientation = mixed | upright | sideways-right | sideways-left | sideways | use-glyph-orientation /* the following values are kept for backward-compatibility */ | vertical-right | rotate-right | rotate-left | rotate-normal | auto;\nunicode-bidi = normal | embed | isolate | bidi-override | isolate-override | plaintext;\n[epub,webkit]writing-mode = horizontal-tb | vertical-rl | lr-tb | rl-tb | tb-rl | lr | rl | tb;\n\n/* CSS Flex box */\nFLEX_BASIS = content | PAPLENGTH;\nflex-direction = row | row-reverse | column | column-reverse;\nflex-wrap = nowrap | wrap | wrap-reverse;\norder = INT;\nflex-grow = NNEG_NUM;\nflex-shrink = NNEG_NUM;\nflex-basis = FLEX_BASIS;\nflex = none | [ [ NNEG_NUM NNEG_NUM? ] || FLEX_BASIS ];\njustify-content = flex-start | flex-end | center | space-between | space-around;\nalign-items = flex-start | flex-end | center | baseline | stretch;\nalign-self = auto | flex-start | flex-end | center | baseline | stretch;\nalign-content = flex-start | flex-end | center | space-between | space-around | stretch;\n\n/* Pointer Events */\n[ms]touch-action = auto | none | [ pan-x || pan-y ] | manipulation;\n\n/* SVG 2 */\nOPACITY_VALUE = NUM | PERCENTAGE;\nDASH_ARRAY = COMMA( SPACE( [ LENGTH | PERCENTAGE | NUM ]+ )+ );\nPAINT = none | child | child(INT) | COLOR | SPACE( URI [none | COLOR]? ) | context-fill | context-stroke;\ncolor-interpolation = auto | sRGB | linearRGB;\ncolor-rendering = auto | optimizeSpeed | optimizeQuality;\nfill = PAINT;\nfill-opacity = OPACITY_VALUE;\nfill-rule = nonzero | evenodd;\nglyph-orientation-vertical = auto | NUM | ANGLE;\nimage-rendering = auto | optimizeSpeed | optimizeQuality | crisp-edges | pixelated;\nmarker-start = none | URI;\nmarker-mid = none | URI;\nmarker-end = none | URI;\npointer-events = bounding-box | visiblePainted | visibleFill | visibleStroke | visible | painted | fill | stroke | all | none;\npaint-order = normal | [ fill || stroke || markers ];\nshape-rendering = auto | optimizeSpeed | crispEdges | geometricPrecision;\nstop-color = COLOR;\nstop-opacity = OPACITY_VALUE;\nstroke = PAINT;\nstroke-dasharray = none | DASH_ARRAY;\nstroke-dashoffset = PERCENTAGE | LENGTH_OR_NUM;\nstroke-linecap = butt | round | square;\nstroke-linejoin = miter | round | bevel;\nstroke-miterlimit = NUM;\nstroke-opacity = OPACITY_VALUE;\nstroke-width = PERCENTAGE | LENGTH_OR_NUM;\ntext-anchor = start | middle | end;\ntext-rendering = auto | optimizeSpeed | optimizeLegibility | geometricPrecision;\nvector-effect = none | SPACE( [ non-scaling-stroke | non-scaling-size | non-rotation | fixed-position ]+ [ viewport | screen ]? );\n\n/* SVG 1.1 */\nalignment-baseline = auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical;\nbaseline-shift = baseline | sub | super | PERCENTAGE | LENGTH_OR_NUM;\ndominant-baseline = auto | use-script | no-change | reset-size | ideographic | alphabetic | hanging | mathematical | central | middle | text-after-edge | text-before-edge;\nmask = none | URI;\n\n/* css-masking-1 */\nSHAPE_RADIUS = PLENGTH | closest-side | farthest-side;\nFILL_RULE = nonzero | evenodd;\nSHAPE_BOX = BOX | margin-box;\nGEOMETRY_BOX = SHAPE_BOX | fill-box | stroke-box | view-box;\nBASIC_SHAPE =\n inset( SPACE( PLENGTH{1,4} [ round PLENGTH{1,4} [ SLASH PLENGTH{1,4} ]? ]? ) )\n | circle( SPACE( [SHAPE_RADIUS]? [at BG_POSITION_TERM{1,4}]? ) )\n | ellipse( SPACE( SHAPE_RADIUS{2}? [at BG_POSITION_TERM{1,4}]? ) )\n | polygon( FILL_RULE? COMMA( SPACE( PLENGTH{2} )+ )+ );\n[webkit]clip-path = none | URI | [ BASIC_SHAPE || GEOMETRY_BOX ];\nclip-rule = nonzero | evenodd;\n\n/* filters */\nflood-color = COLOR;\nflood-opacity = OPACITY_VALUE;\nlighting-color = COLOR;\n\n/* compositing-1 */\nBLEND_MODE = normal | multiply | screen | overlay | darken | lighten | color-dodge | color-burn | hard-light | soft-light | difference | exclusion | hue | saturation | color | luminosity;\nmix-blend-mode = BLEND_MODE;\nisolation = auto | isolate;\nbackground-blend-mode = COMMA( BLEND_MODE+ );\n\n/* CSS GCPM */\nfootnote-policy = auto | line;\n\n[viv]repeat-on-break = auto | none | header | footer;\n\nDEFAULTS\n\nbackground-attachment: scroll;\nbackground-color: transparent;\nbackground-image: none;\nbackground-repeat: repeat;\nbackground-position: 0% 0%;\nbackground-clip: border-box;\nbackground-origin: padding-box;\nbackground-size: auto;\nborder-top-color: currentColor;\nborder-right-color: currentColor;\nborder-bottom-color: currentColor;\nborder-left-color: currentColor;\nborder-top-style: none;\nborder-right-style: none;\nborder-bottom-style: none;\nborder-left-style: none;\nborder-top-width: 3px;\nborder-right-width: 3px;\nborder-bottom-width: 3px;\nborder-left-width: 3px;\nborder-top-left-radius: 0;\nborder-top-right-radius: 0;\nborder-bottom-right-radius: 0;\nborder-bottom-left-radius: 0;\nborder-image-source: none;\nborder-image-slice: 100%;\nborder-image-width: 1;\nborder-image-outset: 0;\nborder-image-repeat: stretch;\ncolumn-count: auto;\ncolumn-gap: normal;\ncolumn-width: auto;\ncolumn-rule-color: currentColor;\ncolumn-rule-style: none;\ncolumn-rule-width: 3px;\ncolumn-fill: balance;\noutline-color: currentColor;\noutline-style: none;\noutline-width: 3px;\nflex-direction: row;\nflex-wrap: nowrap;\nfont-family: serif;\nfont-style: normal;\nfont-size: medium;\nfont-variant: normal;\nfont-weight: normal;\nfont-stretch: normal;\nline-height: normal;\nlist-style-image: none;\nlist-style-position: outside;\nlist-style-type: disc;\nmargin-bottom: auto;\nmargin-left: auto;\nmargin-right: auto;\nmargin-top: auto;\npadding-bottom: auto;\npadding-left: auto;\npadding-right: auto;\npadding-top: auto;\ntext-emphasis-color: currentColor;\ntext-emphasis-style: none;\nmarker-start: none;\nmarker-mid: none;\nmarker-end: none;\n\n/* css-logical */\nborder-block-start-color: currentColor;\nborder-block-end-color: currentColor;\nborder-inline-start-color: currentColor;\nborder-inline-end-color: currentColor;\nborder-block-start-style: none;\nborder-block-end-style: none;\nborder-inline-start-style: none;\nborder-inline-end-style: none;\nborder-block-start-width: 3px;\nborder-block-end-width: 3px;\nborder-inline-start-width: 3px;\nborder-inline-end-width: 3px;\n\nSHORTHANDS\n\nbackground = COMMA background-image [background-position [ / background-size ]] background-repeat\n background-attachment [background-origin background-clip] background-color; /* background-color is a special case, see the code */\nborder-top = border-top-width border-top-style border-top-color;\nborder-right = border-right-width border-right-style border-right-color;\nborder-bottom = border-bottom-width border-bottom-style border-bottom-color;\nborder-left = border-left-width border-left-style border-left-color;\nborder-width = INSETS border-top-width border-right-width border-bottom-width border-left-width;\nborder-style = INSETS border-top-style border-right-style border-bottom-style border-left-style;\nborder-color = INSETS border-top-color border-right-color border-bottom-color border-left-color;\nborder = border-width border-style border-color;\nborder-image = border-image-source border-image-slice [ / border-image-width [ / border-image-outset ] ]\n border-image-repeat;\nborder-radius = INSETS_SLASH border-top-left-radius border-top-right-radius\n border-bottom-right-radius border-bottom-left-radius;\n[moz,webkit]columns = column-width column-count;\n[moz,webkit]column-rule = column-rule-width column-rule-style column-rule-color;\nflex-flow = flex-direction flex-wrap;\noeb-column-number = column-count;\noutline = outline-width outline-style outline-color;\nlist-style = list-style-type list-style-position list-style-image;\nmargin = INSETS margin-top margin-right margin-bottom margin-left;\npadding = INSETS padding-top padding-right padding-bottom padding-left;\npause = INSETS pause-before pause-after;\nfont = FONT font-style font-variant font-weight font-stretch /* font-size line-height font-family are special-cased */;\n[epub,webkit]text-emphasis = text-emphasis-style text-emphasis-color;\nmarker = INSETS marker-start marker-mid marker-end;\n\n/* css-logical */\nmargin-block = INSETS margin-block-start margin-block-end;\nmargin-inline = INSETS margin-inline-start margin-inline-end;\npadding-block = INSETS padding-block-start padding-block-end;\npadding-inline = INSETS padding-inline-start padding-inline-end;\nborder-block-width = INSETS border-block-start-width border-block-end-width;\nborder-block-style = INSETS border-block-start-style border-block-end-style;\nborder-block-color = INSETS border-block-start-color border-block-end-color;\nborder-inline-width = INSETS border-inline-start-width border-inline-end-width;\nborder-inline-style = INSETS border-inline-start-style border-inline-end-style;\nborder-inline-color = INSETS border-inline-start-color border-inline-end-color;\nborder-block = border-block-width border-block-style border-block-color;\nborder-inline = border-inline-width border-inline-style border-inline-color;\nborder-block-start = border-block-start-width border-block-start-style border-block-start-color;\nborder-block-end = border-block-end-width border-block-end-style border-block-end-color;\nborder-inline-start = border-inline-start-width border-inline-start-style border-inline-start-color;\nborder-inline-end = border-inline-end-width border-inline-end-style border-inline-end-color;\ninset-block-start = block-start;\ninset-block-end = block-end;\ninset-inline-start = inline-start;\ninset-inline-end = inline-end;\ninset-block = INSETS block-start block-end;\ninset-inline = INSETS inline-start inline-end;\n\n/* old names */\n[adapt,webkit]margin-before = margin-block-start;\n[adapt,webkit]margin-after = margin-block-end;\n[adapt,webkit]margin-start = margin-inline-start;\n[adapt,webkit]margin-end = margin-inline-end;\n[adapt,webkit]padding-before = padding-block-start;\n[adapt,webkit]padding-after = padding-block-end;\n[adapt,webkit]padding-start = padding-inline-start;\n[adapt,webkit]padding-end = padding-inline-end;\n[adapt,webkit]border-before-color = border-block-start-color;\n[adapt,webkit]border-after-color = border-block-end-color;\n[adapt,webkit]border-start-color = border-inline-start-color;\n[adapt,webkit]border-end-color = border-inline-end-color;\n[adapt,webkit]border-before-style = border-block-start-style;\n[adapt,webkit]border-after-style = border-block-end-style;\n[adapt,webkit]border-start-style = border-inline-start-style;\n[adapt,webkit]border-end-style = border-inline-end-style;\n[adapt,webkit]border-before-width = border-block-start-width;\n[adapt,webkit]border-after-width = border-block-end-width;\n[adapt,webkit]border-start-width = border-inline-start-width;\n[adapt,webkit]border-end-width = border-inline-end-width;\n[adapt,webkit]before = block-start;\n[adapt,webkit]after = block-end;\n[adapt,webkit]start = inline-start;\n[adapt,webkit]end = inline-end;\n";class Oh{constructor(t){this.validator=t,this.success=null,this.failure=null,this.code=0}isSpecial(){return 0!=this.code}markAsStartGroup(){this.code=-1}isStartGroup(){return-1==this.code}markAsEndGroup(){this.code=-2}isEndGroup(){return-2==this.code}markAsStartAlternate(t){this.code=2*t+1}isStartAlternate(){return this.code>0&&this.code%2!=0}markAsEndAlternate(t){this.code=2*t+2}isEndAlternate(){return this.code>0&&this.code%2==0}getAlternate(){return Math.floor((this.code-1)/2)}}class kh{constructor(t,e){this.where=t,this.success=e,this.what=-1}}!function(t){t[t.FOLLOW=1]="FOLLOW",t[t.OPTIONAL=2]="OPTIONAL",t[t.REPEATED=3]="REPEATED",t[t.ALTERNATE=4]="ALTERNATE"}(Ah||(Ah={}));class Fh{constructor(){this.nodes=[],this.connections=[],this.match=[],this.nomatch=[],this.error=[],this.emptyHead=!0}connect(t,e){for(let n=0;n<t.length;n++)this.connections[t[n]].what=e;t.splice(0,t.length)}clone(){const t=new Fh;for(let e=0;e<this.nodes.length;e++){const n=this.nodes[e],i=new Oh(n.validator);i.code=n.code,t.nodes.push(i)}for(let e=0;e<this.connections.length;e++){const n=this.connections[e],i=new kh(n.where,n.success);i.what=n.what,t.connections.push(i)}return t.match.push(...this.match),t.nomatch.push(...this.nomatch),t.error.push(...this.error),t}addSpecialToArr(t,e,n){const i=this.nodes.length,o=new Oh(qh);n>=0?e?o.markAsStartAlternate(n):o.markAsEndAlternate(n):e?o.markAsStartGroup():o.markAsEndGroup(),this.nodes.push(o),this.connect(t,i);const s=new kh(i,!0),r=new kh(i,!1);t.push(this.connections.length),this.connections.push(r),t.push(this.connections.length),this.connections.push(s)}endSpecialGroup(){const t=[this.match,this.nomatch,this.error];for(let e=0;e<t.length;e++)this.addSpecialToArr(t[e],!1,-1)}startSpecialGroup(){if(this.nodes.length)throw new Error("invalid call");this.addSpecialToArr(this.match,!0,-1)}endClause(t){this.addSpecialToArr(this.match,!1,t)}startClause(t){if(this.nodes.length)throw new Error("invalid call");const e=new Oh(qh);e.markAsStartAlternate(t),this.nodes.push(e);const n=new kh(0,!0),i=new kh(0,!1);this.nomatch.push(this.connections.length),this.connections.push(i),this.match.push(this.connections.length),this.connections.push(n)}addPrimitive(t){const e=this.nodes.length;this.nodes.push(new Oh(t));const n=new kh(e,!0),i=new kh(e,!1);this.connect(this.match,e),this.emptyHead?(this.nomatch.push(this.connections.length),this.emptyHead=!1):this.error.push(this.connections.length),this.connections.push(i),this.match.push(this.connections.length),this.connections.push(n)}isSimple(){return 1==this.nodes.length&&!this.nodes[0].isSpecial()}isPrimitive(){return this.isSimple()&&this.nodes[0].validator instanceof Kh}addGroup(t,e){if(0==t.nodes.length)return;const n=this.nodes.length;if(e==Ah.ALTERNATE&&1==n&&t.isPrimitive()&&this.isPrimitive())return void(this.nodes[0].validator=this.nodes[0].validator.combine(t.nodes[0].validator));for(let e=0;e<t.nodes.length;e++)this.nodes.push(t.nodes[e]);e==Ah.ALTERNATE?(this.emptyHead=!0,this.connect(this.nomatch,n)):this.connect(this.match,n);const i=this.connections.length;for(let e=0;e<t.connections.length;e++){const i=t.connections[e];i.where+=n,i.what>=0&&(i.what+=n),this.connections.push(i)}for(let e=0;e<t.match.length;e++)this.match.push(t.match[e]+i);if(e==Ah.REPEATED&&this.connect(this.match,n),e==Ah.OPTIONAL||e==Ah.REPEATED)for(let e=0;e<t.nomatch.length;e++)this.match.push(t.nomatch[e]+i);else if(this.emptyHead){for(let e=0;e<t.nomatch.length;e++)this.nomatch.push(t.nomatch[e]+i);this.emptyHead=t.emptyHead}else for(let e=0;e<t.nomatch.length;e++)this.error.push(t.nomatch[e]+i);for(let e=0;e<t.error.length;e++)this.error.push(t.error[e]+i);t.nodes=null,t.connections=null}finish(t,e){const n=this.nodes.length;this.nodes.push(t),this.nodes.push(e),this.connect(this.match,n),this.connect(this.nomatch,n+1),this.connect(this.error,n+1);for(const t of this.connections)t.success?this.nodes[t.where].success=this.nodes[t.what]:this.nodes[t.where].failure=this.nodes[t.what];for(let t=0;t<n;t++)if(null==this.nodes[t].failure||null==this.nodes[t].success)throw new Error("Invalid validator state");return this.nodes[0]}}const Dh=1,_h=2,Bh=4,Mh=8,Uh=16,Vh=32,Hh=64,zh=128,Gh=256,$h=512,Wh=1024,Xh=2048;class Yh extends ge{constructor(){super()}validateForShorthand(t,e){const n=t[e].visit(this);return n?[n]:null}}class Kh extends Yh{constructor(t,e,n){super(),this.allowed=t,this.idents=e,this.units=n}visitEmpty(t){return this.allowed&Dh?t:null}visitSlash(t){return this.allowed&Xh?t:null}visitStr(t){return this.allowed&_h?t:null}visitIdent(t){const e=this.idents[t.name.toLowerCase()];return e||(this.allowed&Bh?t:null)}visitNumeric(t){return 0!=t.num||this.allowed&$h?t.num<0&&!(this.allowed&Gh)?null:this.units[t.unit]?t:null:"%"==t.unit&&this.allowed&Wh?t:null}visitNum(t){return 0==t.num?this.allowed&$h?t:null:t.num<=0&&!(this.allowed&Gh)?null:this.allowed&Uh?t:null}visitInt(t){if(0==t.num)return this.allowed&$h?t:null;if(t.num<=0&&!(this.allowed&Gh))return null;if(this.allowed&(Vh|Uh))return t;const e=this.idents[`${t.num}`];return e||null}visitColor(t){return this.allowed&Hh?t:null}visitURL(t){return this.allowed&zh?t:null}visitSpaceList(t){return null}visitCommaList(t){return null}visitFunc(t){return null}visitExpr(t){return 2046&this.allowed?t:null}combine(t){const e={},n={};for(const t in this.idents)e[t]=this.idents[t];for(const n in t.idents)e[n]=t.idents[n];for(const t in this.units)n[t]=this.units[t];for(const e in t.units)n[e]=t.units[e];return new Kh(this.allowed|t.allowed,e,n)}}const jh={},qh=new Kh(0,jh,jh);class Qh extends Yh{constructor(t){super(),this.successTerminal=new Oh(null),this.failureTerminal=new Oh(null),this.first=t.finish(this.successTerminal,this.failureTerminal)}validateList(t,e,n){let i=e?[]:t,o=this.first,s=n,r=null,a=null;for(;o!==this.successTerminal&&o!==this.failureTerminal;){if(s>=t.length){o=o.failure;continue}const l=t[s];let h=l;if(o.isSpecial()){let t=!0;o.isStartGroup()?(r?r.push(a):r=[a],a=[]):o.isEndGroup()?a=r.length>0?r.pop():null:o.isEndAlternate()?a[o.getAlternate()]="taken":t=null==a[o.getAlternate()],o=t?o.success:o.failure}else{if(0==s&&!e&&o.validator instanceof Zh&&this instanceof Zh){if(h=new Oe(t).visit(o.validator),h){s=t.length,o=o.success;continue}}else if(0==s&&!e&&o.validator instanceof Jh&&this instanceof Zh){if(h=new ke(t).visit(o.validator),h){s=t.length,o=o.success;continue}}else h=l.visit(o.validator);if(!h){o=o.failure;continue}if(h!==l&&t===i){i=[];for(let e=0;e<s;e++)i[e]=t[e]}t!==i&&(i[s-n]=h),s++,o=o.success}}return o===this.successTerminal&&(e?i.length>0:s==t.length)?i:null}validateSingle(t){let e=null,n=this.first;for(;n!==this.successTerminal&&n!==this.failureTerminal;)t?n.isSpecial()?n=n.success:(e=t.visit(n.validator),e?(t=null,n=n.success):n=n.failure):n=n.failure;return n===this.successTerminal?e:null}visitEmpty(t){return this.validateSingle(t)}visitSlash(t){return this.validateSingle(t)}visitStr(t){return this.validateSingle(t)}visitIdent(t){return this.validateSingle(t)}visitNumeric(t){return this.validateSingle(t)}visitNum(t){return this.validateSingle(t)}visitInt(t){return this.validateSingle(t)}visitColor(t){return this.validateSingle(t)}visitURL(t){return this.validateSingle(t)}visitSpaceList(t){return null}visitCommaList(t){return null}visitFunc(t){return this.validateSingle(t)}visitExpr(t){return null}}class Zh extends Qh{constructor(t){super(t)}visitSpaceList(t){const e=this.validateList(t.values,!1,0);return e===t.values?t:e?new Oe(e):null}visitCommaList(t){let e=this.first,n=!1;for(;e;){if(e.validator instanceof Jh){n=!0;break}e=e.failure}if(n){const e=this.validateList(t.values,!1,0);return e===t.values?t:e?new ke(e):null}return null}validateForShorthand(t,e){return this.validateList(t,!0,e)}}class Jh extends Qh{constructor(t){super(t)}visitSpaceList(t){return this.validateSingle(t)}visitCommaList(t){const e=this.validateList(t.values,!1,0);return e===t.values?t:e?new ke(e):null}validateForShorthand(t,e){let n,i=this.first;for(;i!==this.failureTerminal;){if(n=i.validator.validateForShorthand(t,e),n)return n;i=i.failure}return null}}class tc extends Qh{constructor(t,e){super(e),this.name=t}validateSingle(t){return null}visitFunc(t){if(t.name.toLowerCase()!=this.name)return null;const e=this.validateList(t.values,!1,0);return e===t.values?t:e?new Fe(t.name,e):null}}class ec{tryParse(t,e,n){return e}success(t,e){}}class nc extends ec{constructor(t,e){super(),this.name=e,this.validator=t.validators[this.name]}tryParse(t,e,n){if(n.values[this.name])return e;const i=this.validator.validateForShorthand(t,e);if(i){const t=i.length,o=t>1?new Oe(i):i[0];return this.success(o,n),e+t}return e}success(t,e){e.values[this.name]=t}}class ic extends nc{constructor(t,e){super(t,e[0]),this.names=e}success(t,e){for(let n=0;n<this.names.length;n++)e.values[this.names[n]]=t}}class oc extends ec{constructor(t,e){super(),this.nodes=t,this.slash=e}tryParse(t,e,n){const i=e;if(this.slash){if(t[e]!=Se)return i;if(++e==t.length)return i}let o=this.nodes[0].tryParse(t,e,n);if(o==e)return i;e=o;for(let i=1;i<this.nodes.length&&e<t.length&&(o=this.nodes[i].tryParse(t,e,n),o!=e);i++)e=o;return e}}class sc extends ge{constructor(){super(...arguments),this.syntax=null,this.propList=null,this.error=!1,this.values={},this.validatorSet=null}setOwner(t){this.validatorSet=t}syntaxNodeForProperty(t){return new nc(this.validatorSet,t)}clone(){const t=new this.constructor;return t.syntax=this.syntax,t.propList=this.propList,t.validatorSet=this.validatorSet,t}init(t,e){this.syntax=t,this.propList=e}finish(t,e){if(!this.error){for(const n of this.propList)e.simpleProperty(n,this.values[n]||this.validatorSet.defaultValues[n],t);return!0}return!1}propagateInherit(t,e){for(const n of this.propList)e.simpleProperty(n,Me.inherit,t)}validateList(t){return this.error=!0,0}validateSingle(t){return this.validateList([t]),null}visitEmpty(t){return this.validateSingle(t)}visitStr(t){return this.validateSingle(t)}visitIdent(t){return this.validateSingle(t)}visitNumeric(t){return this.validateSingle(t)}visitNum(t){return this.validateSingle(t)}visitInt(t){return this.validateSingle(t)}visitColor(t){return this.validateSingle(t)}visitURL(t){return this.validateSingle(t)}visitSpaceList(t){return this.validateList(t.values),null}visitCommaList(t){return this.error=!0,null}visitFunc(t){return this.validateSingle(t)}visitExpr(t){return this.error=!0,null}}class rc extends sc{constructor(){super()}validateList(t){let e=0,n=0;for(;e<t.length;){const i=this.syntax[n].tryParse(t,e,this);if(i>e)e=i,n=0;else if(++n==this.syntax.length){this.error=!0;break}}return e}}class ac extends sc{constructor(){super()}validateList(t){if(t.length>this.syntax.length||0==t.length)return this.error=!0,0;for(let e=0;e<this.syntax.length;e++){let n=e;for(;n>=t.length;)n=1==n?0:n-2;if(this.syntax[e].tryParse(t,n,this)!=n+1)return this.error=!0,0}return t.length}createSyntaxNode(){return new ic(this.validatorSet,this.propList)}}const lc={SIMPLE:rc,INSETS:ac,INSETS_SLASH:class extends sc{constructor(){super()}validateList(t){let e=t.length;for(let n=0;n<t.length;n++)if(t[n]===Se){e=n;break}if(e>this.syntax.length||0==t.length)return this.error=!0,0;for(let n=0;n<this.syntax.length;n++){let i,o=n;for(;o>=e;)o=1==o?0:o-2;if(e+1<t.length)for(i=e+n+1;i>=t.length;)i-=i==e+2?1:2;else i=o;const s=[t[o],t[i]];if(2!=this.syntax[n].tryParse(s,0,this))return this.error=!0,0}return t.length}},COMMA:class extends rc{constructor(){super()}mergeIn(t,e){for(const n of this.propList){const i=e[n]||this.validatorSet.defaultValues[n];let o=t[n];o||(o=[],t[n]=o),o.push(i)}}visitCommaList(t){const e={};for(let n=0;n<t.values.length;n++)if(this.values={},t.values[n]instanceof ke?this.error=!0:(t.values[n].visit(this),this.mergeIn(e,this.values),this.values["background-color"]&&n!=t.values.length-1&&(this.error=!0)),this.error)return null;this.values={};for(const t in e)this.values[t]="background-color"==t?e[t].pop():new ke(e[t]);return null}},FONT:class extends rc{constructor(){super()}init(t,e){super.init(t,e),this.propList.push("font-family","line-height","font-size")}validateList(t){let e=super.validateList(t);if(e+2>t.length)return this.error=!0,e;this.error=!1;const n=this.validatorSet.validators;if(!t[e].visit(n["font-size"]))return this.error=!0,e;if(this.values["font-size"]=t[e++],t[e]===Se){if(e++,e+2>t.length)return this.error=!0,e;if(!t[e].visit(n["line-height"]))return this.error=!0,e;this.values["line-height"]=t[e++]}const i=e==t.length-1?t[e]:new Oe(t.slice(e,t.length));return i.visit(n["font-family"])?(this.values["font-family"]=i,t.length):(this.error=!0,e)}visitCommaList(t){if(t.values[0].visit(this),this.error)return null;const e=[this.values["font-family"]];for(let n=1;n<t.values.length;n++)e.push(t.values[n]);const n=new ke(e);return n.visit(this.validatorSet.validators["font-family"])?this.values["font-family"]=n:this.error=!0,null}visitIdent(t){const e=this.validatorSet.systemFonts[t.name];if(e)for(const t in e)this.values[t]=e[t];else this.error=!0;return null}}};class hc{constructor(){this.validators={},this.prefixes={},this.defaultValues={},this.namedValidators={},this.systemFonts={},this.shorthands={},this.layoutProps={},this.backgroundProps={}}addReplacement(t,e){let n;if(e.type==An.NUMERIC)n=new Ie(e.num,e.text);else if(e.type==An.HASH)n=Gi(e.text);else{if(e.type!=An.IDENT)throw new Error("unexpected replacement");n=xe(e.text)}if(t.isPrimitive()){const e=t.nodes[0].validator.idents;for(const t in e)e[t]=n;return t}throw new Error("unexpected replacement")}newGroup(t,e){const n=new Fh;if("||"==t){for(let t=0;t<e.length;t++){const i=new Fh;i.startClause(t),i.addGroup(e[t],Ah.FOLLOW),i.endClause(t),n.addGroup(i,0==t?Ah.FOLLOW:Ah.ALTERNATE)}const t=new Fh;return t.startSpecialGroup(),t.addGroup(n,Ah.REPEATED),t.endSpecialGroup(),t}{let i;switch(t){case" ":i=Ah.FOLLOW;break;case"|":case"||":i=Ah.ALTERNATE;break;default:throw new Error("unexpected op")}for(let t=0;t<e.length;t++)n.addGroup(e[t],0==t?Ah.FOLLOW:i);return n}}addCounts(t,e,n){const i=new Fh;for(let n=0;n<e;n++)i.addGroup(t.clone(),Ah.FOLLOW);if(n==Number.POSITIVE_INFINITY)i.addGroup(t,Ah.REPEATED);else for(let o=e;o<n;o++)i.addGroup(t.clone(),Ah.OPTIONAL);return i}primitive(t){const e=new Fh;return e.addPrimitive(t),e}newFunc(t,e){let n;switch(t){case"COMMA":n=new Jh(e);break;case"SPACE":n=new Zh(e);break;default:n=new tc(t.toLowerCase(),e)}return this.primitive(n)}initBuiltInValidators(){this.namedValidators.HASHCOLOR=this.primitive(new Kh(Hh,jh,jh)),this.namedValidators.POS_INT=this.primitive(new Kh(Vh,jh,jh)),this.namedValidators.POS_NUM=this.primitive(new Kh(Uh,jh,jh)),this.namedValidators.POS_PERCENTAGE=this.primitive(new Kh(Mh,jh,{"%":Ne})),this.namedValidators.NEGATIVE=this.primitive(new Kh(Gh,jh,jh)),this.namedValidators.ZERO=this.primitive(new Kh($h,jh,jh)),this.namedValidators.ZERO_PERCENTAGE=this.primitive(new Kh(Wh,jh,jh)),this.namedValidators.POS_LENGTH=this.primitive(new Kh(Mh,jh,{em:Ne,ex:Ne,ch:Ne,rem:Ne,vw:Ne,vh:Ne,vi:Ne,vb:Ne,vmin:Ne,vmax:Ne,pvw:Ne,pvh:Ne,pvi:Ne,pvb:Ne,pvmin:Ne,pvmax:Ne,cm:Ne,mm:Ne,in:Ne,px:Ne,pt:Ne,pc:Ne,q:Ne})),this.namedValidators.POS_ANGLE=this.primitive(new Kh(Mh,jh,{deg:Ne,grad:Ne,rad:Ne,turn:Ne})),this.namedValidators.POS_TIME=this.primitive(new Kh(Mh,jh,{s:Ne,ms:Ne})),this.namedValidators.FREQUENCY=this.primitive(new Kh(Mh,jh,{Hz:Ne,kHz:Ne})),this.namedValidators.RESOLUTION=this.primitive(new Kh(Mh,jh,{dpi:Ne,dpcm:Ne,dppx:Ne})),this.namedValidators.URI=this.primitive(new Kh(zh,jh,jh)),this.namedValidators.IDENT=this.primitive(new Kh(Bh,jh,jh)),this.namedValidators.STRING=this.primitive(new Kh(_h,jh,jh)),this.namedValidators.SLASH=this.primitive(new Kh(Xh,jh,jh));const t={"font-family":xe("sans-serif")};this.systemFonts.caption=t,this.systemFonts.icon=t,this.systemFonts.menu=t,this.systemFonts["message-box"]=t,this.systemFonts["small-caption"]=t,this.systemFonts["status-bar"]=t}isBuiltIn(t){return!!t.match(/^[A-Z_0-9]+$/)}readNameAndPrefixes(t,e){let n=t.token();if(n.type==An.EOF)return null;const i={"":!0};if(n.type==An.O_BRK){do{if(t.consume(),n=t.token(),n.type!=An.IDENT)throw new Error("Prefix name expected");i[n.text]=!0,t.consume(),n=t.token()}while(n.type==An.COMMA);if(n.type!=An.C_BRK)throw new Error("']' expected");t.consume(),n=t.token()}if(n.type!=An.IDENT)throw new Error("Property name expected");if(2==e?"SHORTHANDS"==n.text:"DEFAULTS"==n.text)return t.consume(),null;const o=n.text;if(t.consume(),2!=e){if(t.token().type!=An.EQ)throw new Error("'=' expected");this.isBuiltIn(o)||(this.prefixes[o]=i)}else if(t.token().type!=An.COLON)throw new Error("':' expected");return o}parseValidators(t){for(;;){const e=this.readNameAndPrefixes(t,1);if(!e)return;let n=[];const i=[];let o,s="",r=!0;const a=this,l=()=>{if(0==n.length)throw new Error("No values");return 1==n.length?n[0]:a.newGroup(s,n)},h=t=>{if(r)throw new Error(`'${t}': unexpected`);if(s&&s!=t)throw new Error(`mixed operators: '${t}' and '${s}'`);s=t,r=!0};let c=null;for(;!c;){t.consume();let e=t.token();switch(e.type){case An.IDENT:if(r||h(" "),this.isBuiltIn(e.text)){const t=this.namedValidators[e.text];if(!t)throw new Error(`'${e.text}' unexpected`);n.push(t.clone())}else{const t={};t[e.text.toLowerCase()]=xe(e.text),n.push(this.primitive(new Kh(0,t,jh)))}r=!1;break;case An.INT:{const t={};t[`${e.num}`]=new Pe(e.num),n.push(this.primitive(new Kh(0,t,jh))),r=!1;break}case An.BAR:h("|");break;case An.BAR_BAR:h("||");break;case An.O_BRK:r||h(" "),i.push({vals:n,op:s,b:"["}),s="",n=[],r=!0;break;case An.FUNC:r||h(" "),i.push({vals:n,op:s,b:"(",fn:e.text}),s="",n=[],r=!0;break;case An.C_BRK:{o=l();const t=i.pop();if("["!=t.b)throw new Error("']' unexpected");n=t.vals,n.push(o),s=t.op,r=!1;break}case An.C_PAR:{o=l();const t=i.pop();if("("!=t.b)throw new Error("')' unexpected");n=t.vals,n.push(this.newFunc(t.fn,o)),s=t.op,r=!1;break}case An.COLON:if(r)throw new Error("':' unexpected");t.consume(),n.push(this.addReplacement(n.pop(),t.token()));break;case An.QMARK:if(r)throw new Error("'?' unexpected");n.push(this.addCounts(n.pop(),0,1));break;case An.STAR:if(r)throw new Error("'*' unexpected");n.push(this.addCounts(n.pop(),0,Number.POSITIVE_INFINITY));break;case An.PLUS:if(r)throw new Error("'+' unexpected");n.push(this.addCounts(n.pop(),1,Number.POSITIVE_INFINITY));break;case An.O_BRC:{if(t.consume(),e=t.token(),e.type!=An.INT)throw new Error("<int> expected");const i=e.num;let o=i;if(t.consume(),e=t.token(),e.type==An.COMMA){if(t.consume(),e=t.token(),e.type!=An.INT)throw new Error("<int> expected");o=e.num,t.consume(),e=t.token()}if(e.type!=An.C_BRC)throw new Error("'}' expected");n.push(this.addCounts(n.pop(),i,o));break}case An.SEMICOL:if(c=l(),i.length>0)throw new Error(`unclosed '${i.pop().b}'`);break;default:throw new Error("unexpected token")}}t.consume(),this.isBuiltIn(e)?this.namedValidators[e]=c:c.isSimple()?this.validators[e]=c.nodes[0].validator:this.validators[e]=new Zh(c)}}parseDefaults(t){for(;;){const e=this.readNameAndPrefixes(t,2);if(!e)return;const n=[];for(;;){t.consume();const e=t.token();if(e.type==An.SEMICOL){t.consume();break}switch(e.type){case An.IDENT:n.push(xe(e.text));break;case An.NUM:n.push(new ve(e.num));break;case An.INT:n.push(new Pe(e.num));break;case An.NUMERIC:n.push(new Ie(e.num,e.text));break;default:throw new Error("unexpected token")}}this.defaultValues[e]=n.length>1?new Oe(n):n[0]}}parseShorthands(t){for(;;){const e=this.readNameAndPrefixes(t,3);if(!e)return;let n,i=t.nthToken(1);i.type==An.IDENT&&lc[i.text]?(n=new lc[i.text],t.consume()):n=new rc,n.setOwner(this);let o=!1,s=[],r=!1;const a=[],l=[];for(;!o;)switch(t.consume(),i=t.token(),i.type){case An.IDENT:if(this.validators[i.text])s.push(n.syntaxNodeForProperty(i.text)),l.push(i.text);else{if(!(this.shorthands[i.text]instanceof ac))throw new Error(`'${i.text}' is neither a simple property nor an inset shorthand`);{const t=this.shorthands[i.text];s.push(t.createSyntaxNode()),l.push(...t.propList)}}break;case An.SLASH:if(s.length>0||r)throw new Error("unexpected slash");r=!0;break;case An.O_BRK:a.push({slash:r,syntax:s}),s=[],r=!1;break;case An.C_BRK:{const t=new oc(s,r),e=a.pop();s=e.syntax,r=e.slash,s.push(t);break}case An.SEMICOL:o=!0,t.consume();break;default:throw new Error("unexpected token")}n.init(s,l),this.shorthands[e]=n}}parse(t){const e=new hi(t,null);this.parseValidators(e),this.parseDefaults(e),this.parseShorthands(e),this.backgroundProps=this.makePropSet(["background"]),this.layoutProps=this.makePropSet(["margin","border","padding","columns","column-gap","column-rule","column-fill"])}makePropSet(t){const e={};for(const n of t){const t=this.shorthands[n],i=t?t.propList:[n];for(const t of i){const n=this.defaultValues[t];n?e[t]=n:h.warn("Unknown property in makePropSet:",t)}}return e}validatePropertyAndHandleShorthand(t,e,n,i){let o="";const s=t,r=(t=t.toLowerCase()).match(/^-([a-z]+)-([-a-z0-9]+)$/);r&&(o=r[1],t=r[2]);const a=this.prefixes[t];if(!a||!a[o])return void i.unknownProperty(s,e);const l=this.validators[t];if(l){const o=e===Me.inherit||e.isExpr()?e:e.visit(l);o?i.simpleProperty(t,o,n):i.invalidPropertyValue(s,e)}else{const o=this.shorthands[t].clone();e===Me.inherit?o.propagateInherit(n,i):(e.visit(o),o.finish(n,i)||i.invalidPropertyValue(s,e))}}}function cc(){const t=new hc;return t.initBuiltInValidators(),t.parse(Lh),t}const uc={"font-style":Me.normal,"font-variant":Me.normal,"font-weight":Me.normal},dc=`OTTO${(new Date).valueOf()}`;let pc=1;function fc(t,e){const n={};for(const i in t)n[i]=$o(t,i).evaluate(e,i);return function(t){for(const e in uc)t[e]||(t[e]=uc[e])}(n),n}class gc{constructor(t){this.properties=t,this.blobURLs=[],this.blobs=[],this.fontTraitKey=function(t){const e=new G;for(const n in uc)e.append(" "),e.append(t[n].toString());return e.toString()}(this.properties),this.src=this.properties.src?this.properties.src.toString():null;const e=this.properties["font-family"];this.family=e?e.stringValue():null}traitsEqual(t){return this.fontTraitKey==t.fontTraitKey}makeAtRule(t,e){const n=new G;n.append("@font-face {\n font-family: "),n.append(this.family),n.append(";\n ");for(const t in uc)n.append(t),n.append(": "),this.properties[t].appendTo(n,!0),n.append(";\n ");if(e){n.append('src: url("');const t=(i=e,(window.URL||window.webkitURL).createObjectURL(i));n.append(t),this.blobURLs.push(t),this.blobs.push(e),n.append('")')}else n.append("src: "),n.append(t);var i;return n.append(";\n}\n"),n.toString()}}class mc{constructor(t){this.deobfuscator=t,this.familyMap={}}registerFamily(t,e){const n=t.family,i=this.familyMap[n],o=e.family;if(i){if(i!=o)throw new Error(`E_FONT_FAMILY_INCONSISTENT ${t.family}`)}else this.familyMap[n]=o}filterFontFamily(t){if(t instanceof ke){const e=t.values,n=[];for(const t of e){const e=this.familyMap[t.stringValue()];e&&n.push(xe(e)),n.push(t)}return new ke(n)}{const e=this.familyMap[t.stringValue()];return e?new ke([xe(e),t]):t}}}class Ec{constructor(t,e,n){this.head=t,this.body=e,this.srcURLMap={},this.familyCounter=0,this.familyPrefix=n||"Fnt_"}getViewFontFamily(t,e){const n=t.family;let i=e.familyMap[n];return i||(i=this.familyPrefix+ ++this.familyCounter,e.familyMap[n]=i,i)}initFont(t,e,n){const i=pi("initFont"),o=this,s=t.src,r={};for(const e in uc)r[e]=t.properties[e];const a=o.getViewFontFamily(t,n);r["font-family"]=xe(a);const l=new gc(r),c=o.body.ownerDocument.createElement("span");c.textContent="M";const u=(new Date).valueOf()+1e3,d=o.head.ownerDocument.createElement("style"),p=dc+pc++;d.textContent=l.makeAtRule("",Oi([p])),o.head.appendChild(d),o.body.appendChild(c),c.style.visibility="hidden",c.style.fontFamily=a;for(const t in uc)V(c,t,r[t].toString());const f=c.getBoundingClientRect(),g=f.right-f.left,m=f.bottom-f.top;d.textContent=l.makeAtRule(s,e),h.info("Starting to load font:",s);let E=!1;return i.loop(()=>{const t=c.getBoundingClientRect(),e=t.right-t.left,n=t.bottom-t.top;return g!=e||m!=n?(E=!0,fi(!1)):(new Date).valueOf()>u?fi(!1):i.sleep(10)}).then(()=>{E?h.info("Loaded font:",s):h.warn("Failed to load font:",s),o.body.removeChild(c),i.finish(l)}),i.result()}loadFont(t,e){const n=t.src;let i=this.srcURLMap[n];const o=this;return i?i.piggyback(i=>{const o=i;o.traitsEqual(t)?(e.registerFamily(t,o),h.warn("Found already-loaded font:",n)):h.warn("E_FONT_FACE_INCOMPATIBLE",t.src)}):(i=new Ii(()=>{const i=pi("loadFont"),s=e.deobfuscator?e.deobfuscator(n):null;return s?Li(n,Ri.BLOB).then(n=>{n.responseBlob?s(n.responseBlob).then(n=>{o.initFont(t,n,e).thenFinish(i)}):i.finish(null)}):o.initFont(t,null,e).thenFinish(i),i.result()},`loadFont ${n}`),this.srcURLMap[n]=i,i.start()),i}findOrLoadFonts(t,e){const n=[];for(const i of t)i.src&&i.family?n.push(this.loadFont(i,e)):h.warn("E_FONT_FACE_INVALID");return vi(n)}}let wc=1;class Nc{constructor(t,e,n,i,o){this.name=e,this.pseudoName=n,this.classes=i,this.parent=o,this.specified={},this.children=[],this.pageMaster=null,this.index=0,this._scope=t,this.key=`p${wc++}`,o&&(this.index=o.children.length,o.children.push(this))}get scope(){return this._scope}createInstance(t){throw new Error("E_UNEXPECTED_CALL")}clone(t){throw new Error("E_UNEXPECTED_CALL")}copySpecified(t){const e=this.specified,n=t.specified;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=e[t])}cloneChildren(t){for(let e=0;e<this.children.length;e++)this.children[e].clone({parent:t})}}class bc extends Nc{constructor(t){super(t,null,null,[],null),this.specified.width=new Bo(Ve,0),this.specified.height=new Bo(He,0)}}class Sc extends It{constructor(t,e){super(t,(function(t,e){const i=t.match(/^([^.]+)\.([^.]+)$/);if(i){const t=n.pageMaster.keyMap[i[1]];if(t){const n=this.lookupInstance(t);if(n)return e?n.resolveFunc(i[2]):n.resolveName(i[2])}}return null})),this.pageMaster=e;const n=this}}class yc extends Nc{constructor(t,e,n,i,o,s,r){super(t,e,n,i,o),this.condition=s,this.specificity=r,this.keyMap={},t instanceof Sc||(this._scope=new Sc(t,this)),this.pageMaster=this,this.specified.width=new Bo(Ve,0),this.specified.height=new Bo(He,0),this.specified["wrap-flow"]=new Bo(Me.auto,0),this.specified.position=new Bo(Me.relative,0),this.specified.overflow=new Bo(Me.visible,0)}createInstance(t){return new Mc(t,this)}clone(t){const e=new yc(this.scope,this.name,t.pseudoName||this.pseudoName,this.classes,this.parent,this.condition,this.specificity);return this.copySpecified(e),this.cloneChildren(e),e}resetScope(){this.scope.pageMaster=this}}class Cc extends Nc{constructor(t,e,n,i,o){super(t,e,n,i,o),this.pageMaster=o.pageMaster,e&&(this.pageMaster.keyMap[e]=this.key),this.specified["wrap-flow"]=new Bo(Me.auto,0)}createInstance(t){return new Uc(t,this)}clone(t){const e=new Cc(t.parent.scope,this.name,this.pseudoName,this.classes,t.parent);return this.copySpecified(e),this.cloneChildren(e),e}}class Tc extends Nc{constructor(t,e,n,i,o){super(t,e,n,i,o),this.pageMaster=o.pageMaster,e&&(this.pageMaster.keyMap[e]=this.key)}createInstance(t){return new Vc(t,this)}clone(t){const e=new Tc(t.parent.scope,this.name,this.pseudoName,this.classes,t.parent);return this.copySpecified(e),this.cloneChildren(e),e}}function xc(t,e,n){return e&&e!==Me.auto?e.toExpr(t,n):null}function Ic(t,e,n){return e&&e!==Me.auto?e.toExpr(t,n):t.zero}function vc(t,e,n){return e?e===Me.auto?null:e.toExpr(t,n):t.zero}function Pc(t,e,n,i){return e&&n!==Me.none?e.toExpr(t,i):t.zero}function Rc(t,e,n){return e?e===Me._true?t._true:e===Me._false?t._false:e.toExpr(t,t.zero):n}class Ac{constructor(t,e){this.parentInstance=t,this.pageBox=e,this.cascaded={},this.style={},this.autoWidth=null,this.autoHeight=null,this.children=[],this.isAutoWidth=!1,this.isAutoHeight=!1,this.isTopDependentOnAutoHeight=!1,this.isRightDependentOnAutoWidth=!1,this.calculatedWidth=0,this.calculatedHeight=0,this.pageMasterInstance=null,this.namedValues={},this.namedFuncs={},this.vertical=!1,this.rtl=!1,this.suppressEmptyBoxGeneration=!1,t&&t.children.push(this)}reset(){this.calculatedWidth=0,this.calculatedHeight=0}addNamedValues(t,e){const n=this.resolveName(t),i=this.resolveName(e);if(!n||!i)throw new Error("E_INTERNAL");return ue(this.pageBox.scope,n,i)}resolveName(t){let e=this.namedValues[t];if(e)return e;const n=this.style[t];switch(n&&(e=n.toExpr(this.pageBox.scope,this.pageBox.scope.zero)),t){case"margin-left-edge":e=this.resolveName("left");break;case"margin-top-edge":e=this.resolveName("top");break;case"margin-right-edge":e=this.addNamedValues("border-right-edge","margin-right");break;case"margin-bottom-edge":e=this.addNamedValues("border-bottom-edge","margin-bottom");break;case"border-left-edge":e=this.addNamedValues("margin-left-edge","margin-left");break;case"border-top-edge":e=this.addNamedValues("margin-top-edge","margin-top");break;case"border-right-edge":e=this.addNamedValues("padding-right-edge","border-right-width");break;case"border-bottom-edge":e=this.addNamedValues("padding-bottom-edge","border-bottom-width");break;case"padding-left-edge":e=this.addNamedValues("border-left-edge","border-left-width");break;case"padding-top-edge":e=this.addNamedValues("border-top-edge","border-top-width");break;case"padding-right-edge":e=this.addNamedValues("right-edge","padding-right");break;case"padding-bottom-edge":e=this.addNamedValues("bottom-edge","padding-bottom");break;case"left-edge":e=this.addNamedValues("padding-left-edge","padding-left");break;case"top-edge":e=this.addNamedValues("padding-top-edge","padding-top");break;case"right-edge":e=this.addNamedValues("left-edge","width");break;case"bottom-edge":e=this.addNamedValues("top-edge","height")}if(!e){let n;if("extent"==t)n=this.vertical?"width":"height";else if("measure"==t)n=this.vertical?"height":"width";else{const e=this.vertical?ko:Fo;n=t;for(const t in e)n=n.replace(t,e[t])}n!=t&&(e=this.resolveName(n))}return e&&(this.namedValues[t]=e),e}resolveFunc(t){let e=this.namedFuncs[t];if(e)return e;switch(t){case"columns":{const t=this.pageBox.scope,n=new he(t,0),i=this.resolveName("column-count"),o=this.resolveName("column-width"),s=this.resolveName("column-gap");e=de(t,pe(t,new se(t,"min",[n,i]),ue(t,o,s)),s);break}}return e&&(this.namedFuncs[t]=e),e}initEnabled(){const t=this.pageBox.scope,e=this.style;let n=Rc(t,e.enabled,t._true);const i=xc(t,e.page,t.zero);if(i){const e=new ne(t,"page-number");n=ce(t,n,new Kt(t,i,e))}const o=xc(t,e["min-page-width"],t.zero);o&&(n=ce(t,n,new Yt(t,new ne(t,"page-width"),o)));const s=xc(t,e["min-page-height"],t.zero);s&&(n=ce(t,n,new Yt(t,new ne(t,"page-height"),s))),n=this.boxSpecificEnabled(n),e.enabled=new De(n)}boxSpecificEnabled(t){return t}initHorizontal(){const t=this.pageBox.scope,e=this.style,n=this.parentInstance?this.parentInstance.style.width.toExpr(t,null):null;let i=xc(t,e.left,n),o=xc(t,e["margin-left"],n);const s=Pc(t,e["border-left-width"],e["border-left-style"],n),r=Ic(t,e["padding-left"],n);let a=xc(t,e.width,n),l=xc(t,e["max-width"],n);const h=Ic(t,e["padding-right"],n),c=Pc(t,e["border-right-width"],e["border-right-style"],n);let u=xc(t,e["margin-right"],n),d=xc(t,e.right,n);const p=ue(t,s,r),f=ue(t,s,h);if(i&&d&&a){let e=de(t,n,ue(t,a,ue(t,ue(t,i,p),f)));o?u?d=de(t,e,u):u=de(t,e,ue(t,d,o)):(e=de(t,e,d),u?o=de(t,e,u):(o=pe(t,e,new ae(t,.5)),u=o))}else{o||(o=t.zero),u||(u=t.zero),i||d||a||(i=t.zero),i||a?i||d?a||d||(a=this.autoWidth,this.isAutoWidth=!0):i=t.zero:(a=this.autoWidth,this.isAutoWidth=!0);const s=de(t,n,ue(t,ue(t,o,p),ue(t,u,f)));this.isAutoWidth&&(l||(l=de(t,s,i||d)),this.vertical||!xc(t,e["column-width"],null)&&!xc(t,e["column-count"],null)||(a=l,this.isAutoWidth=!1)),i?a?d||(d=de(t,s,ue(t,i,a))):a=de(t,s,ue(t,i,d)):i=de(t,s,ue(t,d,a))}const g=Ic(t,e["snap-width"]||(this.parentInstance?this.parentInstance.style["snap-width"]:null),n);e.left=new De(i),e["margin-left"]=new De(o),e["border-left-width"]=new De(s),e["padding-left"]=new De(r),e.width=new De(a),e["max-width"]=new De(l||a),e["padding-right"]=new De(h),e["border-right-width"]=new De(c),e["margin-right"]=new De(u),e.right=new De(d),e["snap-width"]=new De(g)}initVertical(){const t=this.pageBox.scope,e=this.style,n=this.parentInstance?this.parentInstance.style.width.toExpr(t,null):null,i=this.parentInstance?this.parentInstance.style.height.toExpr(t,null):null;let o=xc(t,e.top,i),s=xc(t,e["margin-top"],n);const r=Pc(t,e["border-top-width"],e["border-top-style"],n),a=Ic(t,e["padding-top"],n);let l=xc(t,e.height,i),h=xc(t,e["max-height"],i);const c=Ic(t,e["padding-bottom"],n),u=Pc(t,e["border-bottom-width"],e["border-bottom-style"],n);let d=xc(t,e["margin-bottom"],n),p=xc(t,e.bottom,i);const f=ue(t,r,a),g=ue(t,u,c);if(o&&p&&l){let e=de(t,i,ue(t,l,ue(t,ue(t,o,f),g)));s?d?p=de(t,e,s):d=de(t,e,ue(t,p,s)):(e=de(t,e,p),d?s=de(t,e,d):(s=pe(t,e,new ae(t,.5)),d=s))}else{s||(s=t.zero),d||(d=t.zero),o||p||l||(o=t.zero),o||l?o||p?l||p||(l=this.autoHeight,this.isAutoHeight=!0):o=t.zero:(l=this.autoHeight,this.isAutoHeight=!0);const n=de(t,i,ue(t,ue(t,s,f),ue(t,d,g)));this.isAutoHeight&&(h||(h=de(t,n,o||p)),this.vertical&&(xc(t,e["column-width"],null)||xc(t,e["column-count"],null))&&(l=h,this.isAutoHeight=!1)),o?l?p||(p=de(t,n,ue(t,o,l))):l=de(t,n,ue(t,p,o)):o=de(t,n,ue(t,p,l))}const m=Ic(t,e["snap-height"]||(this.parentInstance?this.parentInstance.style["snap-height"]:null),n);e.top=new De(o),e["margin-top"]=new De(s),e["border-top-width"]=new De(r),e["padding-top"]=new De(a),e.height=new De(l),e["max-height"]=new De(h||l),e["padding-bottom"]=new De(c),e["border-bottom-width"]=new De(u),e["margin-bottom"]=new De(d),e.bottom=new De(p),e["snap-height"]=new De(m)}initColumns(){const t=this.pageBox.scope,e=this.style,n=xc(t,e[this.vertical?"height":"width"],null);let i=xc(t,e["column-width"],n),o=xc(t,e["column-count"],null),s=function(t,e,n){return e&&e!==Me.normal?e.toExpr(t,n):null}(t,e["column-gap"],null);s||(s=new ee(t,1,"em")),i&&!o&&(o=new se(t,"floor",[fe(t,ue(t,n,s),ue(t,i,s))]),o=new se(t,"max",[t.one,o])),o||(o=t.one),i=de(t,fe(t,ue(t,n,s),o),s),e["column-width"]=new De(i),e["column-count"]=new De(o),e["column-gap"]=new De(s)}depends(t,e,n){return this.style[t].toExpr(this.pageBox.scope,null).depend(e,n)}init(t){t.registerInstance(this.pageBox.key,this);const e=this.pageBox.scope,n=this.style,i=this,o=this.parentInstance?this.parentInstance.getActiveRegions(t):null,s=cr(this.cascaded,t,o,!1);this.vertical=lr(s,t,!!this.parentInstance&&this.parentInstance.vertical),this.rtl=hr(s,t,!!this.parentInstance&&this.parentInstance.rtl),pr(s,n,this.vertical,this.rtl,(t,e)=>e.value),this.autoWidth=new oe(e,()=>i.calculatedWidth,"autoWidth"),this.autoHeight=new oe(e,()=>i.calculatedHeight,"autoHeight"),this.initHorizontal(),this.initVertical(),this.initColumns(),this.initEnabled()}getProp(t,e){let n=this.style[e];return n&&(n=No(t,n,e)),n}getPropAsNumber(t,e){let n=this.style[e];return n&&(n=No(t,n,e)),_e(n,t)}getSpecial(t,e){const n=jo(this.cascaded,e);if(n){const e=[];for(let i=0;i<n.length;i++){const o=n[i].evaluate(t,"");o&&o!==Ne&&e.push(o)}if(e.length)return e}return null}getActiveRegions(t){const e=this.getSpecial(t,"region-id");if(e){const t=[];for(let n=0;n<e.length;n++)t[n]=e[n].toString();return t}return null}propagateProperty(t,e,n,i){this.propagatePropertyToElement(t,e.element,n,i)}propagatePropertyToElement(t,e,n,i){let o=this.getProp(t,n);o&&(o.isNumeric()&&Rt(o.unit)&&(o=Be(o,t)),"font-family"===n&&(o=i.filterFontFamily(o)),V(e,n,o.toString()))}propagateDelayedProperty(t,e,n,i){const o=this.getProp(t,n);o&&i.push(new Wr(e.element,n,o))}assignLeftPosition(t,e){const n=this.getPropAsNumber(t,"left"),i=this.getPropAsNumber(t,"margin-left"),o=this.getPropAsNumber(t,"padding-left"),s=this.getPropAsNumber(t,"border-left-width"),r=this.getPropAsNumber(t,"width");e.setHorizontalPosition(n,r),V(e.element,"margin-left",`${i}px`),V(e.element,"padding-left",`${o}px`),V(e.element,"border-left-width",`${s}px`),e.marginLeft=i,e.borderLeft=s,e.paddingLeft=o}assignRightPosition(t,e){const n=this.getPropAsNumber(t,"right"),i=this.getPropAsNumber(t,"snap-height"),o=this.getPropAsNumber(t,"margin-right");let s=this.getPropAsNumber(t,"padding-right");const r=this.getPropAsNumber(t,"border-right-width");if(V(e.element,"margin-right",`${o}px`),V(e.element,"padding-right",`${s}px`),V(e.element,"border-right-width",`${r}px`),e.marginRight=o,e.borderRight=r,this.vertical&&i>0){const t=n+e.getInsetRight(),o=t-Math.floor(t/i)*i;o>0&&(e.snapOffsetX=i-o,s+=e.snapOffsetX)}e.paddingRight=s,e.snapWidth=i}assignTopPosition(t,e){const n=this.getPropAsNumber(t,"snap-height"),i=this.getPropAsNumber(t,"top"),o=this.getPropAsNumber(t,"margin-top");let s=this.getPropAsNumber(t,"padding-top");const r=this.getPropAsNumber(t,"border-top-width");if(e.top=i,e.marginTop=o,e.borderTop=r,e.snapHeight=n,!this.vertical&&n>0){const t=i+e.getInsetTop(),o=t-Math.floor(t/n)*n;o>0&&(e.snapOffsetY=n-o,s+=e.snapOffsetY)}e.paddingTop=s,V(e.element,"top",`${i}px`),V(e.element,"margin-top",`${o}px`),V(e.element,"padding-top",`${s}px`),V(e.element,"border-top-width",`${r}px`)}assignBottomPosition(t,e){const n=this.getPropAsNumber(t,"margin-bottom"),i=this.getPropAsNumber(t,"padding-bottom"),o=this.getPropAsNumber(t,"border-bottom-width"),s=this.getPropAsNumber(t,"height")-e.snapOffsetY;V(e.element,"height",`${s}px`),V(e.element,"margin-bottom",`${n}px`),V(e.element,"padding-bottom",`${i}px`),V(e.element,"border-bottom-width",`${o}px`),e.height=s-e.snapOffsetY,e.marginBottom=n,e.borderBottom=o,e.paddingBottom=i}assignBeforePosition(t,e){this.vertical?this.assignRightPosition(t,e):this.assignTopPosition(t,e)}assignAfterPosition(t,e){this.vertical?this.assignLeftPosition(t,e):this.assignBottomPosition(t,e)}assignStartEndPosition(t,e){this.vertical?(this.assignTopPosition(t,e),this.assignBottomPosition(t,e)):(this.assignRightPosition(t,e),this.assignLeftPosition(t,e))}sizeWithMaxHeight(t,e){V(e.element,"border-top-width","0px");let n=this.getPropAsNumber(t,"max-height");this.isTopDependentOnAutoHeight?e.setVerticalPosition(0,n):(this.assignTopPosition(t,e),n-=e.snapOffsetY,e.height=n,V(e.element,"height",`${n}px`))}sizeWithMaxWidth(t,e){V(e.element,"border-left-width","0px");let n=this.getPropAsNumber(t,"max-width");if(this.isRightDependentOnAutoWidth)e.setHorizontalPosition(0,n);else{this.assignRightPosition(t,e),n-=e.snapOffsetX,e.width=n;const i=this.getPropAsNumber(t,"right");V(e.element,"right",`${i}px`),V(e.element,"width",`${n}px`)}}prepareContainer(t,e,n,i,o){this.parentInstance&&this.vertical==this.parentInstance.vertical||V(e.element,"writing-mode",this.vertical?"vertical-rl":"horizontal-tb"),(this.vertical?this.isAutoWidth:this.isAutoHeight)?this.vertical?this.sizeWithMaxWidth(t,e):this.sizeWithMaxHeight(t,e):(this.assignBeforePosition(t,e),this.assignAfterPosition(t,e)),(this.vertical?this.isAutoHeight:this.isAutoWidth)?this.vertical?this.sizeWithMaxHeight(t,e):this.sizeWithMaxWidth(t,e):this.assignStartEndPosition(t,e);for(let n=0;n<Lc.length;n++)this.propagateProperty(t,e,Lc[n],i)}transferContentProps(t,e,n,i){for(let n=0;n<kc.length;n++)this.propagateProperty(t,e,kc[n],i)}transferSinglUriContentProps(t,e,n){for(let i=0;i<Fc.length;i++)this.propagatePropertyToElement(t,e,Fc[i],n)}finishContainer(t,e,n,i,o,s,r){this.vertical?this.calculatedWidth=e.computedBlockSize+e.snapOffsetX:this.calculatedHeight=e.computedBlockSize+e.snapOffsetY;const a=(this.vertical||!i)&&this.isAutoHeight,l=(!this.vertical||!i)&&this.isAutoWidth;let h=null;if((l||a)&&(l&&V(e.element,"width","auto"),a&&V(e.element,"height","auto"),h=s.getElementClientRect(i?i.element:e.element),l&&(this.calculatedWidth=Math.ceil(h.right-h.left-e.paddingLeft-e.borderLeft-e.paddingRight-e.borderRight),this.vertical&&(this.calculatedWidth+=e.snapOffsetX)),a&&(this.calculatedHeight=h.bottom-h.top-e.paddingTop-e.borderTop-e.paddingBottom-e.borderBottom,this.vertical||(this.calculatedHeight+=e.snapOffsetY))),(this.vertical?this.isAutoHeight:this.isAutoWidth)&&this.assignStartEndPosition(t,e),(this.vertical?this.isAutoWidth:this.isAutoHeight)&&((this.vertical?this.isRightDependentOnAutoWidth:this.isTopDependentOnAutoHeight)&&this.assignBeforePosition(t,e),this.assignAfterPosition(t,e)),o>1){const n=this.getPropAsNumber(t,"column-rule-width"),i=this.getProp(t,"column-rule-style"),s=this.getProp(t,"column-rule-color");if(n>0&&i&&i!=Me.none&&s!=Me.transparent){const r=this.getPropAsNumber(t,"column-gap"),a=this.vertical?e.height:e.width,l=this.vertical?"border-top":"border-left";for(let t=1;t<o;t++){const h=(a+r)*t/o-r/2+e.paddingLeft-n/2,c=e.height+e.paddingTop+e.paddingBottom,u=e.element.ownerDocument.createElement("div");V(u,"position","absolute"),V(u,this.vertical?"left":"top","0px"),V(u,this.vertical?"top":"left",`${h}px`),V(u,this.vertical?"height":"width","0px"),V(u,this.vertical?"width":"height",`${c}px`),V(u,l,`${n}px ${i.toString()}${s?` ${s.toString()}`:""}`),e.element.insertBefore(u,e.element.firstChild)}}}for(let n=0;n<Oc.length;n++)this.propagateProperty(t,e,Oc[n],r);for(let i=0;i<Dc.length;i++)this.propagateDelayedProperty(t,e,Dc[i],n.delayedItems)}applyCascadeAndInit(t,e){const n=this.cascaded,i=this.pageBox.specified;for(const t in i)zo(t)&&Wo(n,t,$o(i,t));if(this.pageBox.pseudoName==_c)for(const t in e)(t.match(/^background-/)||"writing-mode"==t)&&(n[t]=e[t]);if("layout-host"==this.pageBox.pseudoName)for(const t in e)t.match(/^background-/)||"writing-mode"==t||(n[t]=e[t]);t.pushRule(this.pageBox.classes,null,n),n.content&&(n.content=n.content.filterValue(new Us(t,null,t.counterResolver))),this.init(t.context);for(const n of this.pageBox.children){n.createInstance(this).applyCascadeAndInit(t,e)}t.popRule()}resolveAutoSizing(t){this.isAutoWidth&&(this.isRightDependentOnAutoWidth=this.depends("right",this.autoWidth,t)||this.depends("margin-right",this.autoWidth,t)||this.depends("border-right-width",this.autoWidth,t)||this.depends("padding-right",this.autoWidth,t)),this.isAutoHeight&&(this.isTopDependentOnAutoHeight=this.depends("top",this.autoHeight,t)||this.depends("margin-top",this.autoHeight,t)||this.depends("border-top-width",this.autoHeight,t)||this.depends("padding-top",this.autoHeight,t));for(const e of this.children)e.resolveAutoSizing(t)}}const Lc=["border-left-style","border-right-style","border-top-style","border-bottom-style","border-left-color","border-right-color","border-top-color","border-bottom-color","outline-style","outline-color","outline-width","overflow","visibility"],Oc=["border-top-left-radius","border-top-right-radius","border-bottom-right-radius","border-bottom-left-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","opacity","z-index","background-blend-mode","isolation","mix-blend-mode","filter"],kc=["color","font-family","font-size","font-style","font-weight","font-variant","line-height","letter-spacing","text-align","text-decoration","text-indent","text-transform","white-space","word-spacing","font-feature-settings","font-kerning","font-size-adjust","font-variant-east-asian","font-stretch","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-shadow","text-underline-position"],Fc=["width","height","image-resolution","object-fit","object-position"],Dc=["transform","transform-origin"],_c="background-host";class Bc extends Ac{constructor(t){super(null,t)}applyCascadeAndInit(t,e){super.applyCascadeAndInit(t,e),this.children.sort((t,e)=>e.pageBox.specificity-t.pageBox.specificity||t.pageBox.index-e.pageBox.index)}}class Mc extends Ac{constructor(t,e){super(t,e),this.pageMasterInstance=this}boxSpecificEnabled(t){const e=this.pageBox.pageMaster;return e.condition&&(t=ce(e.scope,t,e.condition)),t}adjustPageLayout(t,e,n){}}class Uc extends Ac{constructor(t,e){super(t,e),this.pageMasterInstance=t.pageMasterInstance}}class Vc extends Ac{constructor(t,e){super(t,e),this.pageMasterInstance=t.pageMasterInstance}processPartitionList(t,e,n){let i=null;if(e instanceof Te&&(i=[e]),e instanceof ke&&(i=e.values),i){const e=this.pageBox.scope;for(let o=0;o<i.length;o++)if(i[o]instanceof Te){const s=Tt(i[o].name,"enabled");let r=new ne(e,s);n&&(r=new Mt(e,r)),t=ce(e,t,r)}}return t}boxSpecificEnabled(t){const e=this.pageBox.scope,n=this.style,i=Rc(e,n.required,e._false)!==e._false;if(i||this.isAutoHeight){const i=function(t,e,n){return e?e.toExpr(t,t.zero):new ae(t,n)}(e,n["flow-from"],"body");t=ce(e,t,new se(e,"has-content",[i]))}if(t=this.processPartitionList(t,n["required-partitions"],!1),t=this.processPartitionList(t,n["conflicting-partitions"],!0),i){const n=this.pageMasterInstance.style.enabled;let i=n?n.toExpr(e,null):e._true;i=ce(e,i,t),this.pageMasterInstance.style.enabled=new De(i)}return t}prepareContainer(t,e,n,i,o){V(e.element,"overflow","hidden"),super.prepareContainer(t,e,n,i,o)}}class Hc extends Yi{constructor(t,e,n,i){super(t,e,!1),this.target=n,this.validatorSet=i}property(t,e,n){this.validatorSet.validatePropertyAndHandleShorthand(t,e,n,this)}unknownProperty(t,e){this.report(`E_INVALID_PROPERTY ${t}: ${e.toString()}`)}invalidPropertyValue(t,e){this.report(`E_INVALID_PROPERTY_VALUE ${t}: ${e.toString()}`)}simpleProperty(t,e,n){this.target.specified[t]=new Bo(e,n?Mi:Ui)}}class zc extends Hc{constructor(t,e,n,i){super(t,e,n,i)}}class Gc extends Hc{constructor(t,e,n,i){super(t,e,n,i),n.specified.width=new Bo(Ue,0),n.specified.height=new Bo(Ue,0)}startPartitionRule(t,e,n){const i=new Tc(this.scope,t,e,n,this.target),o=new zc(this.scope,this.owner,i,this.validatorSet);this.owner.pushHandler(o)}startPartitionGroupRule(t,e,n){const i=new Cc(this.scope,t,e,n,this.target),o=new Gc(this.scope,this.owner,i,this.validatorSet);this.owner.pushHandler(o)}}class $c extends Hc{constructor(t,e,n,i){super(t,e,n,i)}startPartitionRule(t,e,n){const i=new Tc(this.scope,t,e,n,this.target),o=new zc(this.scope,this.owner,i,this.validatorSet);this.owner.pushHandler(o)}startPartitionGroupRule(t,e,n){const i=new Cc(this.scope,t,e,n,this.target),o=new Gc(this.scope,this.owner,i,this.validatorSet);this.owner.pushHandler(o)}}function Wc(e){let n=e["writing-mode"];n=n&&n.value;let i=e.direction;return i=i&&i.value,n===Me.vertical_lr||n!==Me.vertical_rl&&i!==Me.rtl?t.PageProgression.LTR:t.PageProgression.RTL}const Xc={a5:{width:new Ie(148,"mm"),height:new Ie(210,"mm")},a4:{width:new Ie(210,"mm"),height:new Ie(297,"mm")},a3:{width:new Ie(297,"mm"),height:new Ie(420,"mm")},b5:{width:new Ie(176,"mm"),height:new Ie(250,"mm")},b4:{width:new Ie(250,"mm"),height:new Ie(353,"mm")},"jis-b5":{width:new Ie(182,"mm"),height:new Ie(257,"mm")},"jis-b4":{width:new Ie(257,"mm"),height:new Ie(364,"mm")},letter:{width:new Ie(8.5,"in"),height:new Ie(11,"in")},legal:{width:new Ie(8.5,"in"),height:new Ie(14,"in")},ledger:{width:new Ie(11,"in"),height:new Ie(17,"in")}},Yc=new Ie(.24,"pt"),Kc=new Ie(3,"mm"),jc=new Ie(10,"mm"),qc=new Ie(13,"mm");function Qc(t){const e={width:Ve,height:He,bleed:ze,bleedOffset:ze},n=t.size;if(n&&n.value!==Me.auto){const t=n.value;let i,o;if(t.isSpaceList()?(i=t.values[0],o=t.values[1]):(i=t,o=null),i.isNumeric())e.width=i,e.height=o||i;else{const t=i.name&&Xc[i.name.toLowerCase()];t&&(o&&o===Me.landscape?(e.width=t.height,e.height=t.width):(e.width=t.width,e.height=t.height))}}else;const i=t.marks;i&&i.value!==Me.none&&(e.bleedOffset=qc);const o=t.bleed;if(o&&o.value!==Me.auto)o.value&&o.value.isNumeric()&&(e.bleed=o.value);else if(i){let t=!1;t=i.value.isSpaceList()?i.value.values.some(t=>t===Me.crop):i.value===Me.crop,t&&(e.bleed=new Ie(6,"pt"))}return e}function Zc(t,e){const n={},i=t.bleed.num*e.queryUnitSize(t.bleed.unit,!1),o=t.bleedOffset.num*e.queryUnitSize(t.bleedOffset.unit,!1),s=i+o,r=t.width;r===Ve?e.pref.defaultPaperSize?n.pageWidth=e.pref.defaultPaperSize.width*e.queryUnitSize("px",!1):n.pageWidth=(e.pref.spreadView?Math.floor(e.viewportWidth/2)-e.pref.pageBorder:e.viewportWidth)-2*s:n.pageWidth=r.num*e.queryUnitSize(r.unit,!1);const a=t.height;return a===He?e.pref.defaultPaperSize?n.pageHeight=e.pref.defaultPaperSize.height*e.queryUnitSize("px",!1):n.pageHeight=e.viewportHeight-2*s:n.pageHeight=a.num*e.queryUnitSize(a.unit,!1),n.bleed=i,n.bleedOffset=o,n.cropOffset=s,n}function Jc(t,e,n){const i=t.createElementNS(k.SVG,"svg");return i.setAttribute("width",e),i.setAttribute("height",n),i.style.position="absolute",i}function tu(t,e,n){n=n||"polyline";const i=t.createElementNS(k.SVG,n);return i.setAttribute("stroke","black"),i.setAttribute("stroke-width",e),i.setAttribute("fill","none"),i}var eu,nu;function iu(t,e,n,i){let o=!1,s=!1;const r=t.marks;if(r){const t=r.value;t.isSpaceList()?t.values.forEach(t=>{t===Me.crop?o=!0:t===Me.cross&&(s=!0)}):t===Me.crop?o=!0:t===Me.cross&&(s=!0)}if(!o&&!s)return;const a=n.container,l=a.ownerDocument,h=e.bleed,c=_e(Yc,i),u=_e(Kc,i),d=_e(jc,i);if(h){const e=t["background-color"];e&&e.value&&(n.bleedBox.style.backgroundColor=e.value.stringValue())}o&&Object.keys(eu).forEach(t=>{const e=eu[t],n=function(t,e,n,i,o,s){let r=i;r<=o+2*Pt.mm&&(r=o+i/2);const a=Math.max(i,r),l=o+a+n/2,h=Jc(t,l,l);let c=[[0,o+i],[i,o+i],[i,o+i-r]],u=c.map(t=>[t[1],t[0]]);e!==eu.TOP_RIGHT&&e!==eu.BOTTOM_RIGHT||(c=c.map(t=>[o+a-t[0],t[1]]),u=u.map(t=>[o+a-t[0],t[1]])),e!==eu.BOTTOM_LEFT&&e!==eu.BOTTOM_RIGHT||(c=c.map(t=>[t[0],o+a-t[1]]),u=u.map(t=>[t[0],o+a-t[1]]));const d=tu(t,n);d.setAttribute("points",c.map(t=>t.join(",")).join(" ")),h.appendChild(d);const p=tu(t,n);return p.setAttribute("points",u.map(t=>t.join(",")).join(" ")),h.appendChild(p),e.split(" ").forEach(t=>{h.style[t]=`${s}px`}),h}(l,e,c,d,h,u);a.appendChild(n)}),s&&Object.keys(nu).forEach(t=>{const e=nu[t],n=function(t,e,n,i,o){const s=2*i;let r,a;e===nu.TOP||e===nu.BOTTOM?(r=s,a=i):(r=i,a=s);const l=Jc(t,r,a),h=tu(t,n);h.setAttribute("points",`0,${a/2} ${r},${a/2}`),l.appendChild(h);const c=tu(t,n);c.setAttribute("points",`${r/2},0 ${r/2},${a}`),l.appendChild(c);const u=tu(t,n,"circle");let d;switch(u.setAttribute("cx",r/2),u.setAttribute("cy",a/2),u.setAttribute("r",i/4),l.appendChild(u),e){case nu.TOP:d=nu.BOTTOM;break;case nu.BOTTOM:d=nu.TOP;break;case nu.LEFT:d=nu.RIGHT;break;case nu.RIGHT:d=nu.LEFT}return Object.keys(nu).forEach(t=>{const n=nu[t];n===e?l.style[n]=`${o}px`:n!==d&&(l.style[n]="0",l.style[`margin-${n}`]="auto")}),l}(l,e,c,d,u);a.appendChild(n)})}!function(t){t.TOP_LEFT="top left",t.TOP_RIGHT="top right",t.BOTTOM_LEFT="bottom left",t.BOTTOM_RIGHT="bottom right"}(eu||(eu={})),function(t){t.TOP="top",t.BOTTOM="bottom",t.LEFT="left",t.RIGHT="right"}(nu||(nu={}));const ou=(()=>{const 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};return["left","right","top","bottom","before","after","start","end","block-start","block-end","inline-start","inline-end"].forEach(e=>{t[`margin-${e}`]=!0,t[`padding-${e}`]=!0,t[`border-${e}-width`]=!0,t[`border-${e}-style`]=!0,t[`border-${e}-color`]=!0}),t})();var su;!function(t){t.START="start",t.CENTER="center",t.END="end"}(su||(su={}));const ru={"top-left-corner":{order:1,isInTopRow:!0,isInBottomRow:!1,isInLeftColumn:!0,isInRightColumn:!0,positionAlongVariableDimension:null},"top-left":{order:2,isInTopRow:!0,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:su.START},"top-center":{order:3,isInTopRow:!0,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:su.CENTER},"top-right":{order:4,isInTopRow:!0,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:su.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:su.START},"right-middle":{order:7,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!0,positionAlongVariableDimension:su.CENTER},"right-bottom":{order:8,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!1,isInRightColumn:!0,positionAlongVariableDimension:su.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:su.END},"bottom-center":{order:11,isInTopRow:!1,isInBottomRow:!0,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:su.CENTER},"bottom-left":{order:12,isInTopRow:!1,isInBottomRow:!0,isInLeftColumn:!1,isInRightColumn:!1,positionAlongVariableDimension:su.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:su.END},"left-middle":{order:15,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!0,isInRightColumn:!1,positionAlongVariableDimension:su.CENTER},"left-top":{order:16,isInTopRow:!1,isInBottomRow:!1,isInLeftColumn:!0,isInRightColumn:!1,positionAlongVariableDimension:su.START}},au=(()=>{const t=ru;return Object.keys(t).sort((e,n)=>t[e].order-t[n].order)})(),lu="vivliostyle-page-rule-master",hu="_marginBoxes";class cu extends yc{constructor(t,e,n){super(t,null,lu,[],e,null,0),this.pageMarginBoxes={};const i=Qc(n),o=new uu(this.scope,this,n,i);this.bodyPartitionKey=o.key,this.createPageMarginBoxes(n),this.applySpecified(n,i)}createPageMarginBoxes(t){const e=t[hu];if(e){const n=this;au.forEach(i=>{e[i]&&(n.pageMarginBoxes[i]=new du(n.scope,n,i,t))})}}applySpecified(t,e){this.specified.position=new Bo(Me.relative,0),this.specified.width=new Bo(e.width,0),this.specified.height=new Bo(e.height,0);for(const e in t)ou[e]||"background-clip"===e||(this.specified[e]=t[e])}createInstance(t){return new pu(t,this)}}class uu extends Tc{constructor(t,e,n,i){super(t,null,null,[],e),this.pageSize=i,this.specified["z-index"]=new Bo(new Pe(0),0),this.applySpecified(n)}applySpecified(t){this.specified["flow-from"]=new Bo(xe("body"),0),this.specified.position=new Bo(Me.absolute,0),this.specified.overflow=new Bo(Me.visible,0);for(const e in ou)ou.hasOwnProperty(e)&&(this.specified[e]=t[e])}createInstance(t){return new Eu(t,this)}}class du extends Tc{constructor(t,e,n,i){super(t,null,null,[],e),this.marginBoxName=n,this.applySpecified(i)}applySpecified(t){const e=t[hu][this.marginBoxName];for(const n in t){const i=t[n],o=e[n];(xo[n]||o&&o.value===Me.inherit)&&(this.specified[n]=i)}for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const n=e[t];n&&n.value!==Me.inherit&&(this.specified[t]=n)}}createInstance(t){return new wu(t,this)}}class pu extends Mc{constructor(t,e){super(t,e),this.pageAreaDimension=null,this.pageMarginBoxInstances={}}applyCascadeAndInit(t,e){const n=this.cascaded;for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))switch(t){case"writing-mode":case"direction":n[t]=e[t]}super.applyCascadeAndInit(t,e)}initHorizontal(){const t=this.style;t.left=ze,t["margin-left"]=ze,t["border-left-width"]=ze,t["padding-left"]=ze,t["padding-right"]=ze,t["border-right-width"]=ze,t["margin-right"]=ze,t.right=ze}initVertical(){const t=this.style;t.top=ze,t["margin-top"]=ze,t["border-top-width"]=ze,t["padding-top"]=ze,t["padding-bottom"]=ze,t["border-bottom-width"]=ze,t["margin-bottom"]=ze,t.bottom=ze}setPageAreaDimension(t){this.pageAreaDimension=t;const e=this.style;e.width=new De(t.borderBoxWidth),e.height=new De(t.borderBoxHeight),e["padding-left"]=new De(t.marginLeft),e["padding-right"]=new De(t.marginRight),e["padding-top"]=new De(t.marginTop),e["padding-bottom"]=new De(t.marginBottom)}adjustPageLayout(t,e,n){const i=e.marginBoxes,o={start:this.pageAreaDimension.marginLeft,end:this.pageAreaDimension.marginRight,extent:this.pageAreaDimension.borderBoxWidth},s={start:this.pageAreaDimension.marginTop,end:this.pageAreaDimension.marginBottom,extent:this.pageAreaDimension.borderBoxHeight};this.sizeMarginBoxesAlongVariableDimension(i.top,!0,o,t,n),this.sizeMarginBoxesAlongVariableDimension(i.bottom,!0,o,t,n),this.sizeMarginBoxesAlongVariableDimension(i.left,!1,s,t,n),this.sizeMarginBoxesAlongVariableDimension(i.right,!1,s,t,n)}sizeMarginBoxesAlongVariableDimension(t,e,n,i,o){const s=su.START,r=su.CENTER,a=su.END,l=this.pageBox.scope,h={},c={},u={};for(const n in t){const i=ru[n];if(i){const s=t[n],r=this.pageMarginBoxInstances[n],a=new fu(s,r.style,e,l,o);h[i.positionAlongVariableDimension]=s,c[i.positionAlongVariableDimension]=r,u[i.positionAlongVariableDimension]=a}}const d={start:n.start.evaluate(i),end:n.end.evaluate(i),extent:n.extent.evaluate(i)};let p=this.getSizesOfMarginBoxesAlongVariableDimension(u,d.extent),f=!1;const g={};Object.keys(h).forEach(t=>{const s=t,r=xc(l,c[s].style[e?"max-width":"max-height"],n.extent);if(r){const t=r.evaluate(i);if(p[s]>t){const n=u[s]=new mu(h[s],c[s].style,e,l,o,t);g[s]=n.getOuterSize(),f=!0}}}),f&&(p=this.getSizesOfMarginBoxesAlongVariableDimension(u,d.extent),f=!1,[s,r,a].forEach(t=>{p[t]=g[t]||p[t]}));const m={};Object.keys(h).forEach(t=>{const s=t,r=xc(l,c[s].style[e?"min-width":"min-height"],n.extent);if(r){const t=r.evaluate(i);if(p[s]<t){const n=u[s]=new mu(h[s],c[s].style,e,l,o,t);m[s]=n.getOuterSize(),f=!0}}}),f&&(p=this.getSizesOfMarginBoxesAlongVariableDimension(u,d.extent),[s,r,a].forEach(t=>{p[t]=m[t]||p[t]}));const E=d.start+d.extent,w=d.start+(d.start+d.extent);[s,r,a].forEach(t=>{const n=p[t];if(n){const i=h[t];let o=0;switch(t){case s:o=e?i.left:i.top;break;case r:o=(w-n)/2;break;case a:o=E-n}e?i.setHorizontalPosition(o,n-i.getInsetLeft()-i.getInsetRight()):i.setVerticalPosition(o,n-i.getInsetTop()-i.getInsetBottom())}})}getSizesOfMarginBoxesAlongVariableDimension(t,e){const n=t[su.START],i=t[su.CENTER],o=t[su.END],s={};if(i){const t=[n,o].filter(t=>t),r=t.length?new gu(t):null,a=this.distributeAutoMarginBoxSizes(i,r,e);a.xSize&&(s[su.CENTER]=a.xSize);const l=(e-(a.xSize||i.getOuterSize()))/2;n&&n.hasAutoSize()&&(s[su.START]=l),o&&o.hasAutoSize()&&(s[su.END]=l)}else{const t=this.distributeAutoMarginBoxSizes(n,o,e);t.xSize&&(s[su.START]=t.xSize),t.ySize&&(s[su.END]=t.ySize)}return s}distributeAutoMarginBoxSizes(t,e,n){const i={xSize:null,ySize:null};if(t&&e)if(t.hasAutoSize()&&e.hasAutoSize()){const o=t.getOuterMaxContentSize(),s=e.getOuterMaxContentSize();if(o>0&&s>0){const r=o+s;if(r<n)i.xSize=n*o/r;else{const s=t.getOuterMinContentSize(),a=s+e.getOuterMinContentSize();a<n?i.xSize=s+(n-a)*(o-s)/(r-a):a>0&&(i.xSize=n*s/a)}i.xSize>0&&(i.ySize=n-i.xSize)}else o>0?i.xSize=n:s>0&&(i.ySize=n)}else t.hasAutoSize()?i.xSize=Math.max(n-e.getOuterSize(),0):e.hasAutoSize()&&(i.ySize=Math.max(n-t.getOuterSize(),0));else t?t.hasAutoSize()&&(i.xSize=n):e&&e.hasAutoSize()&&(i.ySize=n);return i}prepareContainer(t,e,n,i,o){super.prepareContainer(t,e,n,i,o),e.element.setAttribute("data-vivliostyle-page-box",!0)}}class fu{constructor(t,e,n,i,o){this.container=t,this.isHorizontal=n,this.clientLayout=o,this.size=null,this.hasAutoSize_=!xc(i,e[n?"width":"height"],new ee(i,0,"px"))}hasAutoSize(){return this.hasAutoSize_}getSize(){if(!this.size){const t=this.isHorizontal?[Nr.MAX_CONTENT_WIDTH,Nr.MIN_CONTENT_WIDTH]:[Nr.MAX_CONTENT_HEIGHT,Nr.MIN_CONTENT_HEIGHT];this.size=br(this.clientLayout,this.container.element,t)}return this.size}getOuterMaxContentSize(){const t=this.getSize();return this.isHorizontal?this.container.getInsetLeft()+t[Nr.MAX_CONTENT_WIDTH]+this.container.getInsetRight():this.container.getInsetTop()+t[Nr.MAX_CONTENT_HEIGHT]+this.container.getInsetBottom()}getOuterMinContentSize(){const t=this.getSize();return this.isHorizontal?this.container.getInsetLeft()+t[Nr.MIN_CONTENT_WIDTH]+this.container.getInsetRight():this.container.getInsetTop()+t[Nr.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()}}class gu{constructor(t){this.params=t}hasAutoSize(){return this.params.some(t=>t.hasAutoSize())}getOuterMaxContentSize(){const t=this.params.map(t=>t.getOuterMaxContentSize());return Math.max.apply(null,t)*t.length}getOuterMinContentSize(){const t=this.params.map(t=>t.getOuterMinContentSize());return Math.max.apply(null,t)*t.length}getOuterSize(){const t=this.params.map(t=>t.getOuterSize());return Math.max.apply(null,t)*t.length}}class mu extends fu{constructor(t,e,n,i,o,s){super(t,e,n,i,o),this.fixedSize=s}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()}}class Eu extends Vc{constructor(t,e){super(t,e),this.borderBoxWidth=null,this.borderBoxHeight=null,this.marginTop=null,this.marginRight=null,this.marginBottom=null,this.marginLeft=null}applyCascadeAndInit(t,e){const n=this.cascaded;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(t.match(/^column.*$/)||t.match(/^background-/))&&(n[t]=e[t]);super.applyCascadeAndInit(t,e),this.parentInstance.setPageAreaDimension({borderBoxWidth:this.borderBoxWidth,borderBoxHeight:this.borderBoxHeight,marginTop:this.marginTop,marginRight:this.marginRight,marginBottom:this.marginBottom,marginLeft:this.marginLeft})}initHorizontal(){const t=this.resolvePageBoxDimensions({start:"left",end:"right",extent:"width"});this.borderBoxWidth=t.borderBoxExtent,this.marginLeft=t.marginStart,this.marginRight=t.marginEnd}initVertical(){const t=this.resolvePageBoxDimensions({start:"top",end:"bottom",extent:"height"});this.borderBoxHeight=t.borderBoxExtent,this.marginTop=t.marginStart,this.marginBottom=t.marginEnd}resolvePageBoxDimensions(t){const e=this.style,n=this.pageBox.pageSize,i=this.pageBox.scope,o=t.start,s=t.end,r=t.extent,a=n[r].toExpr(i,null);let l=xc(i,e[r],a),h=xc(i,e[`margin-${o}`],a),c=xc(i,e[`margin-${s}`],a);const u=Ic(i,e[`padding-${o}`],a),d=Ic(i,e[`padding-${s}`],a),p=Pc(i,e[`border-${o}-width`],e[`border-${o}-style`],a),f=Pc(i,e[`border-${s}-width`],e[`border-${s}-style`],a);let g=de(i,a,ue(i,ue(i,p,u),ue(i,f,d)));return l?(g=de(i,g,l),h||c?h?c=de(i,g,h):h=de(i,g,c):(h=pe(i,g,new ae(i,.5)),c=h)):(h||(h=i.zero),c||(c=i.zero),l=de(i,g,ue(i,h,c))),e[o]=new De(h),e[s]=new De(c),e[`margin-${o}`]=ze,e[`margin-${s}`]=ze,e[`padding-${o}`]=new De(u),e[`padding-${s}`]=new De(d),e[`border-${o}-width`]=new De(p),e[`border-${s}-width`]=new De(f),e[r]=new De(l),e[`max-${r}`]=new De(l),{borderBoxExtent:de(i,a,ue(i,h,c)),marginStart:h,marginEnd:c}}prepareContainer(t,e,n,i,o){super.prepareContainer(t,e,n,i,o),n.pageAreaElement=e.element,t.pageAreaWidth=parseFloat(n.pageAreaElement.style.width),t.pageAreaHeight=parseFloat(n.pageAreaElement.style.height)}}class wu extends Vc{constructor(t,e){super(t,e),this.suppressEmptyBoxGeneration=!0;const n=e.marginBoxName;this.boxInfo=ru[n],t.pageMarginBoxInstances[n]=this}prepareContainer(t,e,n,i,o){this.applyVerticalAlign(t,e.element),super.prepareContainer(t,e,n,i,o)}applyVerticalAlign(t,e){V(e,"display","flex");const n=this.getProp(t,"vertical-align");let i=null;n===xe("middle")?i="center":n===xe("top")?i="flex-start":n===xe("bottom")&&(i="flex-end"),i&&(V(e,"flex-flow",this.vertical?"row":"column"),V(e,"justify-content",i))}positionAlongVariableDimension(t,e){const n=this.style,i=this.pageBox.scope,o=t.start,s=t.end,r=t.extent,a="left"===o,l=a?e.borderBoxWidth:e.borderBoxHeight,h=xc(i,n[r],l),c=a?e.marginLeft:e.marginTop;if(this.boxInfo.positionAlongVariableDimension===su.START)n[o]=new De(c);else if(h){const t=Ic(i,n[`margin-${o}`],l),e=Ic(i,n[`margin-${s}`],l),r=Ic(i,n[`padding-${o}`],l),a=Ic(i,n[`padding-${s}`],l),u=Pc(i,n[`border-${o}-width`],n[`border-${o}-style`],l),d=Pc(i,n[`border-${s}-width`],n[`border-${s}-style`],l),p=ue(i,h,ue(i,ue(i,r,a),ue(i,ue(i,u,d),ue(i,t,e))));switch(this.boxInfo.positionAlongVariableDimension){case su.CENTER:n[o]=new De(ue(i,c,fe(i,de(i,l,p),new ae(i,2))));break;case su.END:n[o]=new De(de(i,ue(i,c,l),p))}}}positionAndSizeAlongFixedDimension(t,e){const n=this.style,i=this.pageBox.scope,o=t.inside,s=t.outside,r=t.extent,a=e[`margin${s.charAt(0).toUpperCase()}${s.substring(1)}`],l=vc(i,n[`margin-${o}`],a),h=vc(i,n[`margin-${s}`],a),c=Ic(i,n[`padding-${o}`],a),u=Ic(i,n[`padding-${s}`],a),d=Pc(i,n[`border-${o}-width`],n[`border-${o}-style`],a),p=Pc(i,n[`border-${s}-width`],n[`border-${s}-style`],a),f=xc(i,n[r],a);let g=null;function m(t){if(g)return g;g={extent:f?f.evaluate(t):null,marginInside:l?l.evaluate(t):null,marginOutside:h?h.evaluate(t):null};const e=a.evaluate(t);let n=0;if([d,c,u,p].forEach(e=>{e&&(n+=e.evaluate(t))}),null===g.marginInside||null===g.marginOutside){n+g.extent+g.marginInside+g.marginOutside>e&&(null===g.marginInside&&(g.marginInside=0),null===g.marginOutside&&(g.marginOutside=0))}return null!==g.extent&&null!==g.marginInside&&null!==g.marginOutside&&(g.marginOutside=null),null===g.extent&&null!==g.marginInside&&null!==g.marginOutside?g.extent=e-n-g.marginInside-g.marginOutside:null!==g.extent&&null===g.marginInside&&null!==g.marginOutside?g.marginInside=e-n-g.extent-g.marginOutside:null!==g.extent&&null!==g.marginInside&&null===g.marginOutside?g.marginOutside=e-n-g.extent-g.marginInside:null===g.extent?(g.marginInside=g.marginOutside=0,g.extent=e-n):g.marginInside=g.marginOutside=(e-n-g.extent)/2,g}n[r]=new De(new oe(i,(function(){const t=m(this).extent;return null===t?0:t}),r)),n[`margin-${o}`]=new De(new oe(i,(function(){const t=m(this).marginInside;return null===t?0:t}),`margin-${o}`)),n[`margin-${s}`]=new De(new oe(i,(function(){const t=m(this).marginOutside;return null===t?0:t}),`margin-${s}`)),"left"===o?n.left=new De(ue(i,e.marginLeft,e.borderBoxWidth)):"top"===o&&(n.top=new De(ue(i,e.marginTop,e.borderBoxHeight)))}initHorizontal(){const t=this.parentInstance.pageAreaDimension;this.boxInfo.isInLeftColumn?this.positionAndSizeAlongFixedDimension({inside:"right",outside:"left",extent:"width"},t):this.boxInfo.isInRightColumn?this.positionAndSizeAlongFixedDimension({inside:"left",outside:"right",extent:"width"},t):this.positionAlongVariableDimension({start:"left",end:"right",extent:"width"},t)}initVertical(){const t=this.parentInstance.pageAreaDimension;this.boxInfo.isInTopRow?this.positionAndSizeAlongFixedDimension({inside:"bottom",outside:"top",extent:"height"},t):this.boxInfo.isInBottomRow?this.positionAndSizeAlongFixedDimension({inside:"top",outside:"bottom",extent:"height"},t):this.positionAlongVariableDimension({start:"top",end:"bottom",extent:"height"},t)}finishContainer(t,e,n,i,o,s,r){super.finishContainer(t,e,n,i,o,s,r);const a=n.marginBoxes,l=this.pageBox.marginBoxName,h=this.boxInfo;h.isInLeftColumn||h.isInRightColumn?h.isInTopRow||h.isInBottomRow||(h.isInLeftColumn?a.left[l]=e:h.isInRightColumn&&(a.right[l]=e)):h.isInTopRow?a.top[l]=e:h.isInBottomRow&&(a.bottom[l]=e)}}class Nu{constructor(t,e,n,i,o){this.cascadeInstance=t,this.pageScope=e,this.rootPageBoxInstance=n,this.context=i,this.docElementStyle=o,this.pageMasterCache={},this.definePageProgression()}definePageProgression(){const e=this.pageScope,n=new ne(e,"page-number"),i=new Kt(e,new te(e,n,new ae(e,2)),e.zero);e.defineName("recto-page",new Mt(e,i)),e.defineName("verso-page",i),(this.context.pageProgression||Wc(this.docElementStyle))===t.PageProgression.LTR?(e.defineName("left-page",i),e.defineName("right-page",new Mt(e,i))):(e.defineName("left-page",new Mt(e,i)),e.defineName("right-page",i))}getCascadedPageStyle(){const t={};return this.cascadeInstance.pushRule([],"",t),this.cascadeInstance.popRule(),t}getPageRulePageMaster(t,e){const n=t.pageBox;if(0===Object.keys(e).length)return n.resetScope(),t;const i=this.makeCacheKey(e,n);let o=this.pageMasterCache[i];return o||(o=n.pseudoName===_c?this.generatePageRuleMaster(e):this.generateCascadedPageMaster(e,n),this.pageMasterCache[i]=o),o.pageBox.resetScope(),o}makeCacheKey(t,e){const n=this.makeCascadeValueObjectKey(t);return`${e.key}^${n}`}makeCascadeValueObjectKey(t){const e=[];for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const i=t[n];let o;o=i instanceof Bo?`${i.value}`:this.makeCascadeValueObjectKey(i),e.push(n+o+(i.priority||""))}return e.sort().join("^")}generatePageRuleMaster(t){const e=new cu(this.pageScope,this.rootPageBoxInstance.pageBox,t).createInstance(this.rootPageBoxInstance);return e.applyCascadeAndInit(this.cascadeInstance,this.docElementStyle),e.resolveAutoSizing(this.context),e}generateCascadedPageMaster(t,e){const n=e.clone({pseudoName:lu}),i=n.specified,o=t.size;if(o){const e=Qc(t),n=o.priority;i.width=Uo(this.context,i.width,new Bo(e.width,n)),i.height=Uo(this.context,i.height,new Bo(e.height,n))}["counter-reset","counter-increment"].forEach(e=>{i[e]&&(t[e]=i[e])});const s=n.createInstance(this.rootPageBoxInstance);return s.applyCascadeAndInit(this.cascadeInstance,this.docElementStyle),s.resolveAutoSizing(this.context),s}}class bu extends ss{constructor(t){super(),this.pageType=t}apply(t){t.currentPageType===this.pageType&&this.chained.apply(t)}getPriority(){return 3}makePrimary(t){return this.chained&&t.insertInTable(t.pagetypes,this.pageType,this.chained),!0}}class Su extends ss{constructor(t){super(),this.scope=t}apply(t){1===new ne(this.scope,"page-number").evaluate(t.context)&&this.chained.apply(t)}getPriority(){return 2}}class yu extends ss{constructor(t){super(),this.scope=t}apply(t){new ne(this.scope,"left-page").evaluate(t.context)&&this.chained.apply(t)}getPriority(){return 1}}class Cu extends ss{constructor(t){super(),this.scope=t}apply(t){new ne(this.scope,"right-page").evaluate(t.context)&&this.chained.apply(t)}getPriority(){return 1}}class Tu extends ss{constructor(t){super(),this.scope=t}apply(t){new ne(this.scope,"recto-page").evaluate(t.context)&&this.chained.apply(t)}getPriority(){return 1}}class xu extends ss{constructor(t){super(),this.scope=t}apply(t){new ne(this.scope,"verso-page").evaluate(t.context)&&this.chained.apply(t)}getPriority(){return 1}}class Iu extends os{constructor(t,e){super(t,e,null,null,null)}apply(t){!function(t,e,n,i,o){Qo(t,e,n,i,null,null,null);const s=n[hu];if(s){const n=Yo(e,hu);for(const e in s)if(s.hasOwnProperty(e)){let o=n[e];o||(o={},n[e]=o),Qo(t,o,s[e],i,null,null,null)}}}(t.context,t.currentStyle,this.style,this.specificity)}}class vu extends Zs{constructor(t,e,n,i,o){super(t,e,null,n,null,i,!1),this.pageProps=o,this.currentPageSelectors=[],this.currentNamedPageSelector="",this.currentPseudoPageClassSelectors=[]}startPageRule(){this.startSelectorRule()}tagSelector(t,e){this.currentNamedPageSelector=e,e&&(this.chain.push(new bu(e)),this.specificity+=65536)}pseudoclassSelector(t,e){switch(e&&this.reportAndSkip(`E_INVALID_PAGE_SELECTOR :${t}(${e.join("")})`),this.currentPseudoPageClassSelectors.push(`:${t}`),t.toLowerCase()){case"first":this.chain.push(new Su(this.scope)),this.specificity+=256;break;case"left":this.chain.push(new yu(this.scope)),this.specificity+=1;break;case"right":this.chain.push(new Cu(this.scope)),this.specificity+=1;break;case"recto":this.chain.push(new Tu(this.scope)),this.specificity+=1;break;case"verso":this.chain.push(new xu(this.scope)),this.specificity+=1;break;default:this.reportAndSkip(`E_INVALID_PAGE_SELECTOR :${t}`)}}finishSelector(){let t;t=this.currentNamedPageSelector||this.currentPseudoPageClassSelectors.length?[this.currentNamedPageSelector].concat(this.currentPseudoPageClassSelectors.sort()):null,this.currentPageSelectors.push({selectors:t,specificity:this.specificity}),this.currentNamedPageSelector="",this.currentPseudoPageClassSelectors=[]}nextSelector(){this.finishSelector(),super.nextSelector()}startRuleBody(){this.finishSelector(),super.startRuleBody()}simpleProperty(t,e,n){if(("bleed"===t||"marks"===t)&&!this.currentPageSelectors.some(t=>null===t.selectors))return;super.simpleProperty(t,e,n);const i=$o(this.elementStyle,t),o=this.pageProps;if("bleed"===t||"marks"===t)o[""]||(o[""]={}),Object.keys(o).forEach(e=>{Wo(o[e],t,i)});else if("size"===t){const e=o[""];this.currentPageSelectors.forEach(n=>{let s=new Bo(i.value,i.priority+n.specificity);const r=n.selectors?n.selectors.join(""):"";let a=o[r];if(a){const e=$o(a,t);s=e?Uo(null,s,e):s,Wo(a,t,s)}else a=o[r]={},Wo(a,t,s),e&&["bleed","marks"].forEach(t=>{e[t]&&Wo(a,t,e[t])},this)})}}insertNonPrimary(t){this.cascade.insertInTable(this.cascade.pagetypes,"*",t)}makeApplyRuleAction(t){return new Iu(this.elementStyle,t)}startPageMarginBoxRule(t){const e=Yo(this.elementStyle,hu);let n=e[t];n||(n={},e[t]=n);const i=new Pu(this.scope,this.owner,this.validatorSet,n);this.owner.pushHandler(i)}}class Pu extends Yi{constructor(t,e,n,i){super(t,e,!1),this.validatorSet=n,this.boxStyle=i}property(t,e,n){this.validatorSet.validatePropertyAndHandleShorthand(t,e,n,this)}invalidPropertyValue(t,e){this.report(`E_INVALID_PROPERTY_VALUE ${t}: ${e.toString()}`)}unknownProperty(t,e){this.report(`E_INVALID_PROPERTY ${t}: ${e.toString()}`)}simpleProperty(t,e,n){const i=n?this.getImportantSpecificity():this.getBaseSpecificity(),o=new Bo(e,i);Wo(this.boxStyle,t,o)}}const Ru=(t,e,n)=>t.replace(/[uU][rR][lL]\(\s*"((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^"\r\n])+)"/gm,(t,i)=>`url("${n.transformURL(i,e)}"`).replace(/[uU][rR][lL]\(\s*'((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^'\r\n])+)'/gm,(t,i)=>`url('${n.transformURL(i,e)}'`).replace(/[uU][rR][lL]\(\s*((\\([^0-9a-fA-F]+|[0-9a-fA-F]+\s*)|[^"'\r\n\)\s])+)/gm,(t,i)=>`url(${n.transformURL(i,e)}`),Au={},Lu={"text-indent":"0px","margin-top":"0px","padding-top":"0px","border-top-width":"0px","border-top-style":"none","border-top-color":"transparent","border-top-left-radius":"0px","border-top-right-radius":"0px"},Ou={"text-indent":"0px","margin-right":"0px","padding-right":"0px","border-right-width":"0px","border-right-style":"none","border-right-color":"transparent","border-top-right-radius":"0px","border-bottom-right-radius":"0px"},ku={"margin-top":"0px"},Fu={"margin-right":"0px"};class Du extends nt{constructor(t,e,n,i,o,s,r,a,l,h,c,u,d){super(),this.flowName=t,this.context=e,this.viewport=n,this.styler=i,this.regionIds=o,this.xmldoc=s,this.docFaces=r,this.footnoteStyle=a,this.stylerProducer=l,this.page=h,this.customRenderer=c,this.fallbackMap=u,this.documentURLTransformer=d,this.nodeContext=null,this.viewRoot=null,this.isFootnote=!1,this.sourceNode=null,this.offsetInNode=0,this.viewNode=null,this.document=n.document,this.exprContentListener=i.counterListener.getExprContentListener()}clone(){return new Du(this.flowName,this.context,this.viewport,this.styler,this.regionIds,this.xmldoc,this.docFaces,this.footnoteStyle,this.stylerProducer,this.page,this.customRenderer,this.fallbackMap,this.documentURLTransformer)}createPseudoelementShadow(t,e,n,i,o,s,r,a){const l=this.getPseudoMap(n,this.regionIds,this.isFootnote,this.nodeContext,s);if(!l)return a;const h=[],c=cl.createElementNS(k.SHADOW,"root");let u=c;for(const t of ul){let n;if(t){if(!l[t])continue;if(!("footnote-marker"!=t||e&&this.isFootnote))continue;if(t.match(/^first-/)){const t=i.display;if(!t||t===Me.inline)continue}if("before"===t||"after"===t){const e=l[t].content;if(!e||e===Me.normal||e===Me.none)continue}h.push(t),n=cl.createElementNS(k.XHTML,"span"),fl(n,t)}else n=cl.createElementNS(k.SHADOW,"content");u.appendChild(n),t.match(/^first-/)&&(u=n)}if(!h.length)return a;const d=new gl(t,n,o,s,this.exprContentListener);return new la(t,c,null,r,a,aa.ROOTLESS,d)}getPseudoMap(t,e,n,i,o){const s=Xo(t,"_pseudos");if(!s)return null;const r={};for(const t in s){const i=r[t]={};dr(i,s[t],o),rr(i,o,s[t]),ur(s[t],e,n,(t,e)=>{dr(i,e,o),sr(e,t=>{dr(i,t,o)})})}return r}createRefShadow(t,e,n,i,o){const s=this,r=pi("createRefShadow");return s.xmldoc.store.load(t).then(a=>{const l=a;if(l){const r=l.getElement(t);if(r){const t=s.stylerProducer.getStylerForDoc(l);o=new la(n,r,l,i,o,e,t)}}r.finish(o)}),r.result()}createShadows(t,e,n,i,o,s,r){const a=this,l=pi("createShadows"),h=i.template;let c;if(h instanceof Ae){const e=h.url;c=a.createRefShadow(e,aa.ROOTLESS,t,r,null)}else c=fi(null);return c.then(h=>{let c=null;if(t.namespaceURI==k.SHADOW&&"include"==t.localName){let e=t.getAttribute("href"),n=null;e?n=r?r.xmldoc:a.xmldoc:r&&(e=r.owner.namespaceURI==k.XHTML?r.owner.getAttribute("href"):r.owner.getAttributeNS(k.XLINK,"href"),n=r.parentShadow?r.parentShadow.xmldoc:a.xmldoc),e&&(e=L(e,n.url),c=a.createRefShadow(e,aa.ROOTED,t,r,h))}null==c&&(c=fi(h));let u=null;c.then(e=>{if(i.display===Me.table_cell){const n=L("user-agent.xml#table-cell",R);u=a.createRefShadow(n,aa.ROOTLESS,t,r,e)}else u=fi(e)}),u.then(h=>{h=a.createPseudoelementShadow(t,e,n,i,o,s,r,h),l.finish(h)})}),l.result()}setViewRoot(t,e){this.viewRoot=t,this.isFootnote=e}computeStyle(t,e,n,i){const o=this.context,s=cr(n,o,this.regionIds,this.isFootnote,this.nodeContext);t=lr(s,o,t),e=hr(s,o,e);const r=this;pr(s,i,t,e,(t,e)=>{let n=e.evaluate(o,t);return"font-family"==t&&(n=r.docFaces.filterFontFamily(n)),n});const a=i.position,l=i.float,h=Qa(i.display||Me.inline,a,l,this.sourceNode===this.xmldoc.root);return["display","position","float"].forEach(t=>{h[t]&&(i[t]=h[t])}),t}inheritFromSourceParent(t){let e=this.nodeContext.sourceNode;const n=[];let i=null,o=this.nodeContext.shadowContext,s=-1;for(;e&&1==e.nodeType;){const t=o&&o.root==e;if(!t||o.type==aa.ROOTLESS){const t=(o?o.styler:this.styler).getStyle(e,!1);n.push(t),i=i||z(e)}t?(e=o.owner,o=o.parentShadow):(e=e.parentNode,s++)}const r=0===s,a=this.context.queryUnitSize("em",r),l={"font-size":new Bo(new Ie(a,"px"),0)},h=new Jo(l,this.context);for(let t=n.length-1;t>=0;--t){const e=n[t],i=[];for(const t in e)Go(t)&&i.push(t);i.sort($e);for(const t of i){h.setPropName(t);const n=$o(e,t);n.value!==Me.inherit&&(l[t]=n.filterValue(h))}}for(const e in t)Go(e)||(l[e]=t[e]);return{lang:i,elementStyle:l}}resolveURL(t){return t=L(t,this.xmldoc.url),this.fallbackMap[t]||t}inheritLangAttribute(){this.nodeContext.lang=z(this.nodeContext.sourceNode)||this.nodeContext.parent&&this.nodeContext.parent.lang||this.nodeContext.lang}transferPolyfilledInheritedProps(t){const e=vo().filter(e=>t[e]);if(e.length){let n=this.nodeContext.inheritedProps;if(this.nodeContext.parent){n=this.nodeContext.inheritedProps={};for(const t in this.nodeContext.parent.inheritedProps)n[t]=this.nodeContext.parent.inheritedProps[t]}e.forEach(e=>{const i=t[e];if(i){if(i instanceof Pe)n[e]=i.num;else if(i instanceof Te)n[e]=i.name;else if(i instanceof Ie){const t=i;switch(t.unit){case"dpi":case"dpcm":case"dppx":n[e]=t.num*Pt[t.unit]}}else n[e]=i;delete t[e]}})}}resolveFormattingContext(e,n,i,o,s,r){const a=f(t.HOOKS.RESOLVE_FORMATTING_CONTEXT);for(let t=0;t<a.length;t++){const l=a[t](e,n,i,o,s,r);if(l)return void(e.formattingContext=l)}}createElementView(t,e){const n=this;let i=!0;const o=pi("createElementView");let s=n.sourceNode;const r=n.nodeContext.shadowContext?n.nodeContext.shadowContext.styler:n.styler;let a=r.getStyle(s,!1);if(!n.nodeContext.shadowContext){const t=this.xmldoc.getElementOffset(s);Co.registerFragmentIndex(t,n.nodeContext.fragmentIndex,0)}const l={};if(!n.nodeContext.parent){const t=n.inheritFromSourceParent(a);a=t.elementStyle,n.nodeContext.lang=t.lang}const h=a["float-reference"]&&function(t){switch(t){case"inline":return Na.INLINE;case"column":return Na.COLUMN;case"region":return Na.REGION;case"page":return Na.PAGE;default:throw new Error(`Unknown float-reference: ${t}`)}}(a["float-reference"].value.toString());if(n.nodeContext.parent&&h&&ba(h)){const t=n.inheritFromSourceParent(a);a=t.elementStyle,n.nodeContext.lang=t.lang}n.nodeContext.vertical=n.computeStyle(n.nodeContext.vertical,"rtl"===n.nodeContext.direction,a,l),r.processContent(s,l),this.transferPolyfilledInheritedProps(l),this.inheritLangAttribute(),l.direction&&(n.nodeContext.direction=l.direction.toString());const c=l["flow-into"];if(c&&c.toString()!=n.flowName)return o.finish(!1),o.result();let u=l.display;if(u===Me.none)return o.finish(!1),o.result();const d=null==n.nodeContext.parent;return n.nodeContext.flexContainer=u===Me.flex,n.createShadows(s,d,a,l,r,n.context,n.nodeContext.shadowContext).then(c=>{n.nodeContext.nodeShadow=c;const p=l.position;let f=l.float,g=l.clear;const m=n.nodeContext.vertical?Me.vertical_rl:Me.horizontal_tb,E=n.nodeContext.parent?n.nodeContext.parent.vertical?Me.vertical_rl:Me.horizontal_tb:m,w=function(t){return"true"===t.getAttribute(Ka)}(s);n.nodeContext.establishesBFC=function(t,e,n,i,o,s,r){return o=o||s||Me.horizontal_tb,!!r||!!n&&n!==Me.none||qa(e)||t===Me.inline_block||t===Me.table_cell||t===Me.table_caption||t==Me.flex||(t===Me.block||t===Me.list_item)&&!!i&&i!==Me.visible||!!s&&o!==s}(u,p,f,l.overflow,m,E,w),n.nodeContext.containingBlockForAbsolute=function(t){return t===Me.relative||t===Me.absolute||t===Me.fixed}(p),!n.nodeContext.isInsideBFC()||f===Me.footnote||h&&ba(h)||(f=null,g=null);let N=f===Me.left||f===Me.right||f===Me.top||f===Me.bottom||f===Me.inline_start||f===Me.inline_end||f===Me.block_start||f===Me.block_end||f===Me.snap_block||f===Me.footnote;f&&(delete l.float,f===Me.footnote&&(n.isFootnote?(N=!1,l.display=Me.block):l.display=Me.inline)),g&&(g===Me.inherit&&n.nodeContext.parent&&n.nodeContext.parent.clearSide&&(g=xe(n.nodeContext.parent.clearSide)),g!==Me.left&&g!==Me.right&&g!==Me.top&&g!==Me.bottom&&g!==Me.both&&g!==Me.all&&g!==Me.same||(delete l.clear,l.display&&l.display!=Me.inline&&(n.nodeContext.clearSide=g.toString())));const b=u===Me.list_item&&l["ua-list-item-count"];if((N||l["break-inside"]&&l["break-inside"]!==Me.auto)&&n.nodeContext.breakPenalty++,u&&u!==Me.inline&&Ja(u)&&n.nodeContext.breakPenalty++,n.nodeContext.inline=!N&&!u||Ja(u)||function(t){switch(t.toString()){case"ruby-base":case"ruby-text":case"ruby-base-container":case"ruby-text-container":return!0;default:return!1}}(u),n.nodeContext.display=u?u.toString():"inline",n.nodeContext.floatSide=N?f.toString():null,n.nodeContext.floatReference=h||Na.INLINE,n.nodeContext.floatMinWrapBlock=l["float-min-wrap-block"]||null,n.nodeContext.columnSpan=l["column-span"],!n.nodeContext.inline){const t=l["break-after"];t&&(n.nodeContext.breakAfter=t.toString());const e=l["break-before"];e&&(n.nodeContext.breakBefore=e.toString())}n.nodeContext.verticalAlign=l["vertical-align"]&&l["vertical-align"].toString()||"baseline",n.nodeContext.captionSide=l["caption-side"]&&l["caption-side"].toString()||"top";const S=l["border-collapse"];if(!S||S===xe("separate")){const t=l["border-spacing"];let e,i;t&&(t.isSpaceList()?(e=t.values[0],i=t.values[1]):e=i=t,e.isNumeric()&&(n.nodeContext.inlineBorderSpacing=_e(e,n.context)),i.isNumeric()&&(n.nodeContext.blockBorderSpacing=_e(i,n.context)))}n.nodeContext.footnotePolicy=l["footnote-policy"];const y=l["x-first-pseudo"];if(y){const t=n.nodeContext.parent?n.nodeContext.parent.firstPseudo:null;n.nodeContext.firstPseudo=new ca(t,y.num)}n.nodeContext.inline||n.processAfterIfcontinues(s,a,r,n.context);const C=l["white-space"];if(C){const t=Qr(C.toString());null!==t&&(n.nodeContext.whitespace=t)}const T=l["hyphenate-character"];T&&T!==Me.auto&&(n.nodeContext.hyphenateCharacter=T.str);const x=l["word-break"],I=l["overflow-wrap"]||["word-wrap"];n.nodeContext.breakWord=x===Me.break_all||I===Me.break_word,n.resolveFormattingContext(n.nodeContext,t,u,p,f,d),n.nodeContext.parent&&n.nodeContext.parent.formattingContext&&(t=n.nodeContext.parent.formattingContext.isFirstTime(n.nodeContext,t)),n.nodeContext.inline||(n.nodeContext.repeatOnBreak=n.processRepeatOnBreak(l),n.findAndProcessRepeatingElements(s,r));let v=!1,P=null;const R=[];let A,L=s.namespaceURI,O=s.localName;if(L==k.XHTML)"html"==O||"body"==O||"script"==O||"link"==O||"meta"==O?O="div":"vide_"==O?O="video":"audi_"==O?O="audio":"object"==O&&(v=!!n.customRenderer),s.getAttribute(dl)&&a.content&&a.content.value&&a.content.value.url&&(O="img");else if(L==k.epub)O="span",L=k.XHTML;else if(L==k.FB2){if(L=k.XHTML,"image"==O){O="div";const t=s.getAttributeNS(k.XLINK,"href");if(t&&"#"==t.charAt(0)){const e=n.xmldoc.getElement(t);if(e){P=n.createElement(L,"img");const t=`data:${e.getAttribute("content-type")||"image/jpeg"};base64,${e.textContent.replace(/[ \t\n\t]/g,"")}`;R.push(Pi(P,t))}}}else O=_u[O];O||(O=n.nodeContext.inline?"span":"div")}else if(L==k.NCX)if(L=k.XHTML,"ncx"==O||"navPoint"==O)O="div";else if("navLabel"==O){O="span";const t=s.parentNode;if(t){let e=null;for(let n=t.firstChild;n;n=n.nextSibling){if(1!=n.nodeType)continue;const t=n;if(t.namespaceURI==k.NCX&&"content"==t.localName){e=t.getAttribute("src");break}}e&&(O="a",s=s.ownerDocument.createElementNS(L,"a"),s.setAttribute("href",e))}}else O="span";else L==k.SHADOW?(L=k.XHTML,O=n.nodeContext.inline?"span":"div"):v=!!n.customRenderer;if(b)t?O="li":(O="div",u=Me.block,l.display=u);else if("body"==O||"li"==O)O="div";else if("q"==O)O="span";else if("a"==O){const t=l["hyperlink-processing"];t&&"normal"!=t.toString()&&(O="span")}if(l.behavior){"none"!=l.behavior.toString()&&n.customRenderer&&(v=!0)}if(s.dataset&&"true"===s.getAttribute("data-math-typeset")&&(v=!0),v){const t=n.nodeContext.parent?n.nodeContext.parent.viewNode:null;A=n.customRenderer(s,t,l)}else A=fi(null);A.then(r=>{r?v&&(i="true"==r.getAttribute("data-adapt-process-children")):r=n.createElement(L,O),"a"==O&&r.addEventListener("click",n.page.hrefHandler,!1),P&&(n.applyPseudoelementStyle(n.nodeContext,"inner",P),r.appendChild(P)),"iframe"==r.localName&&r.namespaceURI==k.XHTML&&function(t){t.addEventListener("load",()=>{t.contentWindow.navigator.epubReadingSystem={name:"adapt",version:"0.1",layoutStyle:"paginated",hasFeature:function(t,e){switch(t){case"mouse-events":return!0}return!1}}},!1)}(r);const a=n.nodeContext.inheritedProps["image-resolution"],h=[],c=l.width,u=l.height,d=s.getAttribute("width"),p=s.getAttribute("height"),f=c===Me.auto||!c&&!d,g=u===Me.auto||!u&&!p;if(s.namespaceURI!=k.FB2||"td"==O){const e=s.attributes,i=e.length;let o=null;for(let s=0;s<i;s++){const i=e[s],a=i.namespaceURI;let l=i.localName,c=i.nodeValue;if(a){if("http://www.w3.org/2000/xmlns/"==a)continue;a==k.XLINK&&"href"==l&&(c=n.resolveURL(c))}else{if(l.match(/^on/))continue;if("style"==l)continue;if(("id"==l||"name"==l)&&t){c=n.documentURLTransformer.transformFragment(c,n.xmldoc.url),r.setAttribute(l,c),n.page.registerElementWithId(r,c);continue}if("src"==l||"href"==l||"poster"==l?(c=n.resolveURL(c),"href"===l&&(c=n.documentURLTransformer.transformURL(c,n.xmldoc.url))):"srcset"==l&&(c=c.split(",").map(t=>n.resolveURL(t.trim())).join(",")),"poster"===l&&"video"===O&&L===k.XHTML&&f&&g){const t=new Image,e=Pi(t,c);R.push(e),h.push({image:t,element:r,fetcher:e})}}if(L==k.SVG&&/^[A-Z\-]+$/.test(l)&&(l=l.toLowerCase()),n.isSVGUrlAttribute(l)&&(c=Ru(c,n.xmldoc.url,n.documentURLTransformer)),a){const t=Au[a];t&&(l=`${t}:${l}`)}"src"!=l||a||"img"!=O&&"input"!=O||L!=k.XHTML?"href"==l&&"image"==O&&L==k.SVG&&a==k.XLINK?n.page.fetchers.push(Pi(r,c)):a?r.setAttributeNS(a,l,c):r.setAttribute(l,c):o=c}if(o){const t="input"===O?new Image:r,e=Pi(t,o);t!==r&&(r.src=o),f||g?(f&&g&&a&&1!==a&&h.push({image:t,element:r,fetcher:e}),R.push(e)):n.page.fetchers.push(e)}}delete l.content;const m=l["list-style-image"];if(m&&m instanceof Ae){const t=m.url;R.push(Pi(new Image,t))}if(n.preprocessElementStyle(l),n.applyComputedStyles(r,l),!n.nodeContext.inline){let i=null;if(t?e&&(i=n.nodeContext.vertical?Fu:ku):i="clone"!==n.nodeContext.inheritedProps["box-decoration-break"]?n.nodeContext.vertical?Ou:Lu:n.nodeContext.vertical?Fu:ku,i)for(const t in i)V(r,t,i[t])}b&&r.setAttribute("value",l["ua-list-item-count"].stringValue()),n.viewNode=r,R.length?vi(R).then(()=>{a>0&&n.modifyElemDimensionWithImageResolution(h,a,l,n.nodeContext.vertical),o.finish(i)}):o.timeSlice().then(()=>{o.finish(i)})})}),o.result()}processAfterIfcontinues(t,e,n,i){const o=this.getPseudoMap(e,this.regionIds,this.isFootnote,this.nodeContext,i);if(o&&o["after-if-continues"]&&o["after-if-continues"].content){const o=new gl(t,e,n,i,this.exprContentListener);this.nodeContext.afterIfContinues=new El(t,o)}}isSVGUrlAttribute(t){return Du.SVG_URL_ATTRIBUTES.includes(t.toLowerCase())}modifyElemDimensionWithImageResolution(t,e,n,i){const o=this;t.forEach(t=>{if("load"===t.fetcher.get().get()){const s=t.image;let r=s.width/e,a=s.height/e;const l=t.element;if(r>0&&a>0)if(n["box-sizing"]===Me.border_box&&(n["border-left-style"]!==Me.none&&(r+=_e(n["border-left-width"],o.context)),n["border-right-style"]!==Me.none&&(r+=_e(n["border-right-width"],o.context)),n["border-top-style"]!==Me.none&&(a+=_e(n["border-top-width"],o.context)),n["border-bottom-style"]!==Me.none&&(a+=_e(n["border-bottom-width"],o.context))),e>1){const t=n["max-width"]||Me.none,e=n["max-height"]||Me.none;if(t===Me.none&&e===Me.none)V(l,"max-width",`${r}px`);else if(t!==Me.none&&e===Me.none)V(l,"width",`${r}px`);else if(t===Me.none&&e!==Me.none)V(l,"height",`${a}px`);else{t.isNumeric(),e.isNumeric();const n=t,s=e;"%"!==n.unit?V(l,"max-width",`${Math.min(r,_e(n,o.context))}px`):"%"!==s.unit?V(l,"max-height",`${Math.min(a,_e(s,o.context))}px`):i?V(l,"height",`${a}px`):V(l,"width",`${r}px`)}}else if(e<1){const t=n["min-width"]||ze,e=n["min-height"]||ze;t.isNumeric(),t.isNumeric();const s=t,h=e;0===s.num&&0===h.num?V(l,"min-width",`${r}px`):0!==s.num&&0===h.num?V(l,"width",`${r}px`):0===s.num&&0!==h.num?V(l,"height",`${a}px`):"%"!==s.unit?V(l,"min-width",`${Math.max(r,_e(s,o.context))}px`):"%"!==h.unit?V(l,"min-height",`${Math.max(a,_e(h,o.context))}px`):i?V(l,"height",`${a}px`):V(l,"width",`${r}px`)}}})}preprocessElementStyle(e){const n=this;f(t.HOOKS.PREPROCESS_ELEMENT_STYLE).forEach(t=>{t(n.nodeContext,e)})}findAndProcessRepeatingElements(t,e){for(let n=t.firstChild;n;n=n.nextSibling){if(1!==n.nodeType)continue;const t={},i=e.getStyle(n,!1);if(this.computeStyle(this.nodeContext.vertical,"rtl"===this.nodeContext.direction,i,t),!this.processRepeatOnBreak(t))continue;if(this.nodeContext.formattingContext instanceof Fl&&!this.nodeContext.belongsTo(this.nodeContext.formattingContext))return;const o=this.nodeContext.parent,s=o&&o.formattingContext;return this.nodeContext.formattingContext=new Fl(s,this.nodeContext.sourceNode),void this.nodeContext.formattingContext.initializeRepetitiveElements(this.nodeContext.vertical)}}processRepeatOnBreak(t){let e=t["repeat-on-break"];return e!==Me.none&&(e===Me.auto&&(e=t.display===Me.table_header_group?Me.header:t.display===Me.table_footer_group?Me.footer:Me.none),e&&e!==Me.none)?e.toString():null}createTextNodeView(){const t=this,e=pi("createTextNodeView");return this.preprocessTextContent().then(()=>{const n=t.offsetInNode||0,i=Hr(t.nodeContext.preprocessedTextContent).substr(n);t.viewNode=document.createTextNode(i),e.finish(!0)}),e.result()}preprocessTextContent(){if(null!=this.nodeContext.preprocessedTextContent)return fi(!0);const e=this;let n,i=n=e.sourceNode.textContent;const o=pi("preprocessTextContent"),s=f(t.HOOKS.PREPROCESS_TEXT_CONTENT);let r=0;return o.loop(()=>r>=s.length?fi(!1):s[r++](e.nodeContext,i).thenAsync(t=>(i=t,fi(!0)))).then(()=>{e.nodeContext.preprocessedTextContent=function(t,e){return Vr(t,e,0)}(n,i),o.finish(!0)}),o.result()}createNodeView(t,e){const n=this,i=pi("createNodeView");let o,s=!0;return 1==n.sourceNode.nodeType?o=n.createElementView(t,e):8==n.sourceNode.nodeType?(n.viewNode=null,o=fi(!0)):o=n.createTextNodeView(),o.then(t=>{if(s=t,n.nodeContext.viewNode=n.viewNode,n.viewNode){const t=n.nodeContext.parent?n.nodeContext.parent.viewNode:n.viewRoot;t&&t.appendChild(n.viewNode)}i.finish(s)}),i.result()}setCurrent(t,e,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(e,!!n):fi(!0)}processShadowContent(t){if(null==t.shadowContext||"content"!=t.sourceNode.localName||t.sourceNode.namespaceURI!=k.SHADOW)return t;const e=t.boxOffset,n=t.shadowContext,i=t.parent;let o,s,r;n.subShadow?(r=n.subShadow,o=n.root,s=n.type,s==aa.ROOTLESS&&(o=o.firstChild)):(r=n.parentShadow,o=n.owner.firstChild,s=aa.ROOTLESS);const a=t.sourceNode.nextSibling;if(a?(t.sourceNode=a,t.resetView()):t.shadowSibling?t=t.shadowSibling:o?t=null:(t=t.parent.modify()).after=!0,o){const n=new ua(o,i,e);return n.shadowContext=r,n.shadowType=s,n.shadowSibling=t,n}return t.boxOffset=e,t}nextPositionInTree(t){let e=t.boxOffset+1;if(t.after){if(!t.parent)return null;if(t.shadowType!=aa.ROOTED){const n=t.sourceNode.nextSibling;if(n)return(t=t.modify()).boxOffset=e,t.sourceNode=n,t.resetView(),this.processShadowContent(t)}return t.shadowSibling?((t=t.shadowSibling.modify()).boxOffset=e,t):((t=t.parent.modify()).boxOffset=e,t.after=!0,t)}{if(t.nodeShadow){let n=t.nodeShadow.root;if(t.nodeShadow.type==aa.ROOTLESS&&(n=n.firstChild),n){const i=new ua(n,t,e);return i.shadowContext=t.nodeShadow,i.shadowType=t.nodeShadow.type,this.processShadowContent(i)}}const n=t.sourceNode.firstChild;if(n)return this.processShadowContent(new ua(n,t,e));if(1!=t.sourceNode.nodeType){e+=Hr(t.preprocessedTextContent).length-1-t.offsetInNode}return(t=t.modify()).boxOffset=e,t.after=!0,t}}isTransclusion(t,e,n){const i=$o(e,"hyperlink-processing");if(!i)return!1;const o=i.evaluate(this.context,"hyperlink-processing");return!!o&&o.toString()==n}nextInTree(t,e){let n=this.nextPositionInTree(t);if(!n||n.after)return fi(n);const i=pi("nextInTree");return this.setCurrent(n,!0,e).then(t=>{n.viewNode&&t||(n=n.modify(),n.after=!0,n.viewNode||(n.inline=!0)),this.dispatchEvent({type:"nextInTree",nodeContext:n}),i.finish(n)}),i.result()}addImageFetchers(t){if(t instanceof ke){const e=t.values;for(let t=0;t<e.length;t++)this.addImageFetchers(e[t])}else if(t instanceof Ae){const e=t.url;this.page.fetchers.push(Pi(new Image,e))}}applyComputedStyles(t,e){const n=e["background-image"];n&&this.addImageFetchers(n);const i=e.position===Me.relative;for(const n in e){if(Bu[n])continue;let o=e[n];o=o.visit(new bn(this.xmldoc.url,this.documentURLTransformer)),o.isNumeric()&&Rt(o.unit)&&(o=Be(o,this.context)),Gr[n]||i&&$r[n]?this.page.delayedItems.push(new Wr(t,n,o)):V(t,n,o.toString())}}applyPseudoelementStyle(t,e,n){if(t.after)return;const i=this.sourceNode;let o=(t.shadowContext?t.shadowContext.styler:this.styler).getStyle(i,!1);const s=Xo(o,"_pseudos");if(!s)return;if(o=s[e],!o)return;const r={};t.vertical=this.computeStyle(t.vertical,"rtl"===t.direction,o,r);const a=r.content;wa(a)&&(a.visit(new Ea(n,this.context,a,this.exprContentListener)),delete r.content),this.applyComputedStyles(n,r)}peelOff(t,e){const n=pi("peelOff"),i=t.firstPseudo;let o=t.offsetInNode;const s=t.after;if(e>0){const n=t.viewNode.textContent;t.viewNode.textContent=n.substr(0,e),o+=e}else if(!s&&t.viewNode&&0==o){const e=t.viewNode.parentNode;e&&e.removeChild(t.viewNode)}const r=t.boxOffset+e,a=[];for(;t.firstPseudo===i;)a.push(t),t=t.parent;let l=a.pop(),h=l.shadowSibling;const c=this;return n.loop(()=>{for(;a.length>0;){l=a.pop(),t=new ua(l.sourceNode,t,r),0==a.length&&(t.offsetInNode=o,t.after=s),t.shadowType=l.shadowType,t.shadowContext=l.shadowContext,t.nodeShadow=l.nodeShadow,t.shadowSibling=l.shadowSibling?l.shadowSibling:h,h=null;const e=c.setCurrent(t,!1);if(e.isPending())return e}return fi(!1)}).then(()=>{n.finish(t)}),n.result()}createElement(t,e){return t==k.XHTML?this.document.createElement(e):this.document.createElementNS(t,e)}applyFootnoteStyle(t,e,n){const i={},o=Xo(this.footnoteStyle,"_pseudos");if(t=this.computeStyle(t,e,this.footnoteStyle,i),o&&o.before){const i={},s=this.createElement(k.XHTML,"span");fl(s,"before"),n.appendChild(s),this.computeStyle(t,e,o.before,i),delete i.content,this.applyComputedStyles(s,i)}return delete i.content,this.applyComputedStyles(n,i),t}processFragmentedBlockEdge(t){t&&t.walkUpBlocks(t=>{const e=t.inheritedProps["box-decoration-break"];if(!e||"slice"===e){const e=t.viewNode;t.vertical?(V(e,"padding-left","0"),V(e,"border-left","none"),V(e,"border-top-left-radius","0"),V(e,"border-bottom-left-radius","0")):(V(e,"padding-bottom","0"),V(e,"border-bottom","none"),V(e,"border-bottom-left-radius","0"),V(e,"border-bottom-right-radius","0"))}})}convertLengthToPx(t,e,n){const i=t.num,o=t.unit;if(function(t){switch(t.toLowerCase()){case"em":case"ex":case"rem":return!0;default:return!1}}(o)){let i=e;for(;i&&1!==i.nodeType;)i=i.parentNode;const o=parseFloat(n.getElementComputedStyle(i)["font-size"]);return this.context,ts(t,o,this.context).num}{const e=this.context.queryUnitSize(o,!1);return e?i*e:t}}isSameNodePositionStep(t,e){if(t.shadowContext){if(!e.shadowContext)return!1;const n=1===t.node.nodeType?t.node:t.node.parentElement,i=1===e.node.nodeType?e.node:e.node.parentElement;return t.shadowContext.owner===e.shadowContext.owner&&pl(n)===pl(i)}return t.node===e.node}isSameNodePosition(t,e){return t.offsetInNode===e.offsetInNode&&t.after==e.after&&t.steps.length===e.steps.length&&t.steps.every((t,n)=>{const i=e.steps[n];return this.isSameNodePositionStep(t,i)})}isPseudoelement(t){return!!pl(t)}}Du.SVG_URL_ATTRIBUTES=["color-profile","clip-path","cursor","filter","marker","marker-start","marker-end","marker-mid","fill","stroke","mask"];const _u={a:"a",sub:"sub",sup:"sup",table:"table",tr:"tr",td:"td",th:"th",code:"code",body:"div",p:"p",v:"p",date:"p",emphasis:"em",strong:"strong",style:"span",strikethrough:"del"},Bu={"box-decoration-break":!0,"float-min-wrap-block":!0,"float-reference":!0,"flow-into":!0,"flow-linger":!0,"flow-options":!0,"flow-priority":!0,"footnote-policy":!0,page:!0};class Mu{constructor(t){this.layoutBox=t.layoutBox,this.window=t.window}subtractOffsets(t,e){const n=e.left,i=e.top;return{left:t.left-n,top:t.top-i,right:t.right-n,bottom:t.bottom-i,width:t.width,height:t.height}}getRangeClientRects(t){const e=t.getClientRects(),n=this.layoutBox.getBoundingClientRect();return Array.from(e).map(t=>this.subtractOffsets(t,n))}getElementClientRect(t){const e=t.getBoundingClientRect(),n=this.layoutBox.getBoundingClientRect();return this.subtractOffsets(e,n)}getElementComputedStyle(t){return this.window.getComputedStyle(t,null)}}class Uu{constructor(t,e,n,i,o){this.window=t,this.fontSize=e,this.document=t.document,this.root=n||this.document.body;let s=this.root.firstElementChild;s||(s=this.document.createElement("div"),s.setAttribute("data-vivliostyle-outer-zoom-box","true"),this.root.appendChild(s));let r=s.firstElementChild;r||(r=this.document.createElement("div"),r.setAttribute("data-vivliostyle-spread-container","true"),s.appendChild(r));let a=s.nextElementSibling;a||(a=this.document.createElement("div"),a.setAttribute("data-vivliostyle-layout-box","true"),this.root.appendChild(a)),this.outerZoomBox=s,this.contentContainer=r,this.layoutBox=a;const l=new Mu(this).getElementComputedStyle(this.root);this.width=i||parseFloat(l.width)||t.innerWidth,this.height=o||parseFloat(l.height)||t.innerHeight}resetZoom(){V(this.outerZoomBox,"width",""),V(this.outerZoomBox,"height",""),V(this.contentContainer,"width",""),V(this.contentContainer,"height",""),V(this.contentContainer,"transform","")}zoom(t,e,n){V(this.outerZoomBox,"width",`${t*n}px`),V(this.outerZoomBox,"height",`${e*n}px`),V(this.contentContainer,"width",`${t}px`),V(this.contentContainer,"height",`${e}px`),V(this.contentContainer,"transform",`scale(${n})`)}clear(){const t=this.root;for(;t.lastChild;)t.removeChild(t.lastChild)}}const Vu="data-adapt-eloff";class Hu{constructor(t,e,n){this.store=t,this.url=e,this.document=n,this.lang=null,this.totalOffset=-1,this.lastOffset=1,this.root=n.documentElement;let i=null,o=null;if(this.root.namespaceURI==k.XHTML){for(let t=this.root.firstChild;t;t=t.nextSibling){if(1!=t.nodeType)continue;const e=t;if(e.namespaceURI==k.XHTML)switch(e.localName){case"head":o=e;break;case"body":i=e}}this.lang=this.root.getAttribute("lang")}else if(this.root.namespaceURI==k.FB2){o=this.root;for(let t=this.root.firstChild;t;t=t.nextSibling){if(1!=t.nodeType)continue;const e=t;e.namespaceURI==k.FB2&&"body"==e.localName&&(i=e)}const t=this.doc().child("FictionBook").child("description").child("title-info").child("lang").textContent();t.length>0&&(this.lang=t[0])}else if(this.root.namespaceURI==k.SSE)for(let t=this.root.firstElementChild;t;t=t.nextElementSibling){const e=t.localName;"meta"===e?o=t:"body"===e&&(i=t)}this.body=i,this.head=o,this.last=this.root,this.last.setAttribute(Vu,"0")}doc(){return new Yu([this.document])}getElementOffset(t){const e=t.getAttribute(Vu);if(e)return parseInt(e,10);let n=this.lastOffset,i=this.last;for(;i!=t;){let t=i.firstChild;if(!t)for(;t=i.nextSibling,!t;)if(i=i.parentNode,null==i)throw new Error("Internal error");if(i=t,1==t.nodeType){t.setAttribute(Vu,n.toString()),++n}else n+=t.textContent.length}return this.lastOffset=n,this.last=t,n-1}getNodeOffset(t,e,n){let i=0,o=t,s=null;if(1==o.nodeType){if(!n)return this.getElementOffset(o)}else{if(i=e,s=o.previousSibling,!s)return o=o.parentNode,i+=1,this.getElementOffset(o)+i;o=s}for(;;){for(;o.lastChild;)o=o.lastChild;if(1==o.nodeType)break;if(i+=o.textContent.length,s=o.previousSibling,!s){o=o.parentNode;break}o=s}return i+=1,this.getElementOffset(o)+i}getTotalOffset(){return this.totalOffset<0&&(this.totalOffset=this.getNodeOffset(this.root,0,!0)),this.totalOffset}getNodeByOffset(t){let e;const n=this;let i=this.root;for(;;){if(e=this.getElementOffset(i),e>=t)return i;const o=i.children;if(!o)break;const s=Z(o.length,e=>{const i=o[e];return n.getElementOffset(i)>t});if(0==s)break;i=o[s-1]}let o=e+1,s=i,r=s.firstChild||s.nextSibling,a=null;for(;;){if(r){if(1==r.nodeType)break;if(s=r,a=s,o+=r.textContent.length,o>t)break}else if(s=s.parentNode,!s)break;r=s.nextSibling}return a||i}buildIdMap(t){const e=t.getAttribute("id");e&&!this.idMap[e]&&(this.idMap[e]=t);const n=t.getAttributeNS(k.XML,"id");n&&!this.idMap[n]&&(this.idMap[n]=t);for(let e=t.firstElementChild;e;e=e.nextElementSibling)this.buildIdMap(e)}getElement(t){const e=t.match(/([^#]*)#(.+)$/);if(!e||e[1]&&e[1]!=this.url)return null;const n=e[2];let i=this.document.getElementById(n);return!i&&this.document.getElementsByName&&(i=this.document.getElementsByName(n)[0]),i||(this.idMap||(this.idMap={},this.buildIdMap(this.document.documentElement)),i=this.idMap[n]),i}}var zu;function Gu(t,e,n){const i=n||new DOMParser;let o;try{o=i.parseFromString(t,e)}catch(t){}if(!o)return null;{const t=o.documentElement,e="parsererror";if(t.localName===e)return null;for(let n=t.firstElementChild;n;n=n.nextElementSibling)if(n.localName===e)return null}return o}function $u(t,e){let n=t.responseXML;if(!n){const e=new DOMParser,i=t.responseText;if(i){const o=function(t){const e=t.contentType;if(e){const t=Object.keys(zu);for(let n=0;n<t.length;n++)if(zu[t[n]]===e)return e;if(e.match(/\+xml$/))return zu.APPLICATION_XML}const n=t.url.match(/\.([^./]+)$/);if(n){switch(n[1]){case"html":case"htm":return zu.TEXT_HTML;case"xhtml":case"xht":return zu.APPLICATION_XHTML_XML;case"svg":case"svgz":return zu.IMAGE_SVG_XML;case"opf":case"xml":return zu.APPLICATION_XML}}return null}(t);if(n=Gu(i,o||zu.APPLICATION_XML,e),n&&!o){const t=n.documentElement;"html"!==t.localName.toLowerCase()||t.namespaceURI?"svg"===t.localName.toLowerCase()&&n.contentType!==zu.IMAGE_SVG_XML&&(n=Gu(i,zu.IMAGE_SVG_XML,e)):n=Gu(i,zu.TEXT_HTML,e)}n||(n=Gu(i,zu.TEXT_HTML,e))}}return fi(n?new Hu(e,t.url,n):null)}!function(t){t.TEXT_HTML="text/html",t.TEXT_XML="text/xml",t.APPLICATION_XML="application/xml",t.APPLICATION_XHTML_XML="application/xhtml_xml",t.IMAGE_SVG_XML="image/svg+xml"}(zu||(zu={}));class Wu{constructor(t){this.fn=t}check(t){return this.fn(t)}withAttribute(t,e){const n=this;return new Wu(i=>n.check(i)&&1==i.nodeType&&i.getAttribute(t)==e)}withChild(t,e){const n=this;return new Wu(i=>{if(!n.check(i))return!1;let o=new Yu([i]);return o=o.child(t),e&&(o=o.predicate(e)),o.size()>0})}}const Xu=new Wu(t=>!0);class Yu{constructor(t){this.nodes=t}asArray(){return this.nodes}size(){return this.nodes.length}predicate(t){const e=[];for(const n of this.nodes)t.check(n)&&e.push(n);return new Yu(e)}forEachNode(t){const e=[],n=t=>{e.push(t)};for(let e=0;e<this.nodes.length;e++)t(this.nodes[e],n);return new Yu(e)}forEach(t){const e=[];for(let n=0;n<this.nodes.length;n++)e.push(t(this.nodes[n]));return e}forEachNonNull(t){const e=[];for(let n=0;n<this.nodes.length;n++){const i=t(this.nodes[n]);null!=i&&e.push(i)}return e}child(t){return this.forEachNode((e,n)=>{for(let i=e.firstChild;i;i=i.nextSibling)1==i.nodeType&&i.localName==t&&n(i)})}childElements(){return this.forEachNode((t,e)=>{for(let n=t.firstChild;n;n=n.nextSibling)1==n.nodeType&&e(n)})}attribute(t){return this.forEachNonNull(e=>1==e.nodeType?e.getAttribute(t):null)}textContent(){return this.forEach(t=>t.textContent)}}var Ku='@namespace html "http://www.w3.org/1999/xhtml";\n@namespace fb2 "http://www.gribuser.ru/xml/fictionbook/2.0";\n\nhtml|body,\nfb2|body {\n hyphens: -epubx-expr(pref-hyphenate? "auto": "manual");\n}\n\n@-adapt-footnote-area {\n display: block;\n margin-block-start: 0.5em;\n margin-block-end: 0.5em;\n}\n\n@-adapt-footnote-area ::before {\n display: block;\n border-block-start-width: 1px;\n border-block-start-style: solid;\n border-block-start-color: black;\n margin-block-end: 0.4em;\n margin-inline-start: 0;\n margin-inline-end: 60%;\n}\n\n/* default page master */\n@-epubx-page-master :background-host {\n @-epubx-partition :layout-host {\n -epubx-flow-from: body;\n top: -epubx-expr(header.margin-bottom-edge);\n bottom: -epubx-expr(page-height - footer.margin-top-edge);\n left: 0px;\n right: 0px;\n column-width: 25em;\n }\n @-epubx-partition footer :oeb-page-foot {\n writing-mode: horizontal-tb;\n -epubx-flow-from: oeb-page-foot;\n bottom: 0px;\n left: 0px;\n right: 0px;\n }\n @-epubx-partition header :oeb-page-head {\n writing-mode: horizontal-tb;\n -epubx-flow-from: oeb-page-head;\n top: 0px;\n left: 0px;\n right: 0px;\n }\n}\n\n@page {\n @top-left-corner {\n text-align: right;\n vertical-align: middle;\n }\n @top-left {\n text-align: left;\n vertical-align: middle;\n }\n @top-center {\n text-align: center;\n vertical-align: middle;\n }\n @top-right {\n text-align: right;\n vertical-align: middle;\n }\n @top-right-corner {\n text-align: left;\n vertical-align: middle;\n }\n @left-top {\n text-align: center;\n vertical-align: top;\n }\n @left-middle {\n text-align: center;\n vertical-align: middle;\n }\n @left-bottom {\n text-align: center;\n vertical-align: bottom;\n }\n @right-top {\n text-align: center;\n vertical-align: top;\n }\n @right-middle {\n text-align: center;\n vertical-align: middle;\n }\n @right-bottom {\n text-align: center;\n vertical-align: bottom;\n }\n @bottom-left-corner {\n text-align: right;\n vertical-align: middle;\n }\n @bottom-left {\n text-align: left;\n vertical-align: middle;\n }\n @bottom-center {\n text-align: center;\n vertical-align: middle;\n }\n @bottom-right {\n text-align: right;\n vertical-align: middle;\n }\n @bottom-right-corner {\n text-align: left;\n vertical-align: middle;\n }\n}\n\n@media print {\n @page {\n margin: 10%;\n }\n}\n';const ju=new Ii(()=>{const t=pi("uaStylesheetBase"),e=cc(),n=L("user-agent-base.css",R),i=new Zs(null,null,null,null,null,e,!0);return i.startStylesheet(zi.USER_AGENT),function(t){Qs=t}(i.cascade),fo('@namespace html "http://www.w3.org/1999/xhtml";\n\nhtml|html,\nhtml|address,\nhtml|blockquote,\nhtml|body,\nhtml|dd,\nhtml|div,\nhtml|dl,\nhtml|dt,\nhtml|fieldset,\nhtml|form,\nhtml|frame,\nhtml|frameset,\nhtml|h1,\nhtml|h2,\nhtml|h3,\nhtml|h4,\nhtml|h5,\nhtml|h6,\nhtml|noframes,\nhtml|ol,\nhtml|p,\nhtml|ul,\nhtml|center,\nhtml|dir,\nhtml|hr,\nhtml|menu,\nhtml|pre,\nhtml|article,\nhtml|section,\nhtml|nav,\nhtml|aside,\nhtml|hgroup,\nhtml|footer,\nhtml|header,\nhtml|figure,\nhtml|figcaption,\nhtml|main {\n display: block;\n unicode-bidi: normal;\n}\nhtml|li {\n display: list-item;\n}\nhtml|head {\n display: none !important;\n}\nhtml|table {\n display: table;\n}\nhtml|tr {\n display: table-row;\n}\nhtml|thead {\n display: table-header-group;\n break-after: avoid;\n}\nhtml|tbody {\n display: table-row-group;\n}\nhtml|tfoot {\n display: table-footer-group;\n break-before: avoid;\n}\nhtml|col {\n display: table-column;\n}\nhtml|colgroup {\n display: table-column-group;\n}\nhtml|td,\nhtml|th {\n display: table-cell;\n}\nhtml|caption {\n display: table-caption;\n text-align: center;\n}\nhtml|th {\n font-weight: bolder;\n text-align: center;\n}\nhtml|script {\n display: none;\n}\nhtml|body {\n margin: 8px;\n}\nhtml|h1 {\n font-size: 2em;\n margin-block-start: 0.67em;\n margin-block-end: 0.67em;\n margin-inline-start: 0em;\n margin-inline-end: 0em;\n}\nhtml|h2 {\n font-size: 1.5em;\n margin-block-start: 0.75em;\n margin-block-end: 0.75em;\n margin-inline-start: 0em;\n margin-inline-end: 0em;\n}\nhtml|h3 {\n font-size: 1.17em;\n margin-block-start: 0.83em;\n margin-block-end: 0.83em;\n margin-inline-start: 0em;\n margin-inline-end: 0em;\n}\nhtml|h4,\nhtml|p,\nhtml|blockquote,\nhtml|ul,\nhtml|fieldset,\nhtml|form,\nhtml|ol,\nhtml|dl,\nhtml|dir,\nhtml|menu,\nhtml|h5,\nhtml|h6 {\n margin-block-start: 1em;\n margin-block-end: 1em;\n margin-inline-start: 0em;\n margin-inline-end: 0em;\n}\nhtml|h5 {\n font-size: 0.83em;\n}\nhtml|h6 {\n font-size: 0.75em;\n}\nhtml|h1,\nhtml|h2,\nhtml|h3,\nhtml|h4,\nhtml|h5,\nhtml|h6,\nhtml|b,\nhtml|strong {\n font-weight: bolder;\n}\nhtml|h1,\nhtml|h2,\nhtml|h3,\nhtml|h4,\nhtml|h5,\nhtml|h6 {\n break-after: avoid;\n}\nhtml|blockquote {\n margin-block-start: 0px;\n margin-block-end: 0px;\n margin-inline-start: 40px;\n margin-inline-end: 40px;\n}\nhtml|i,\nhtml|cite,\nhtml|em,\nhtml|var,\nhtml|address {\n font-style: italic;\n}\nhtml|pre,\nhtml|tt,\nhtml|code,\nhtml|kbd,\nhtml|samp {\n font-family: monospace;\n}\nhtml|pre {\n white-space: pre;\n}\nhtml|button,\nhtml|textarea,\nhtml|input,\nhtml|select {\n display: inline-block;\n}\nhtml|big {\n font-size: 1.17em;\n}\nhtml|small,\nhtml|sub,\nhtml|sup {\n font-size: 0.83em;\n}\nhtml|sub {\n vertical-align: sub;\n}\nhtml|sup {\n vertical-align: super;\n}\nhtml|table {\n border-spacing: 2px;\n}\nhtml|thead,\nhtml|tbody,\nhtml|tfoot {\n vertical-align: middle;\n}\n/* for XHTML tables without tbody */\nhtml|table > html|tr {\n vertical-align: middle;\n}\nhtml|td,\nhtml|th {\n vertical-align: inherit;\n}\nhtml|s,\nhtml|strike,\nhtml|del {\n text-decoration: line-through;\n}\nhtml|hr {\n border: 1px inset;\n}\nhtml|ol,\nhtml|ul,\nhtml|dir,\nhtml|menu,\nhtml|dd {\n margin: 0px;\n margin-inline-start: 40px;\n}\nhtml|ol {\n list-style-type: decimal;\n}\nhtml|ol html|ul,\nhtml|ul html|ol,\nhtml|ul html|ul,\nhtml|ol html|ol {\n margin-top: 0;\n margin-bottom: 0;\n}\nhtml|u,\nhtml|ins {\n text-decoration: underline;\n}\nhtml|center {\n text-align: center;\n}\nhtml|q:before {\n content: open-quote;\n}\nhtml|q:after {\n content: close-quote;\n}\n\nhtml|audio,\nhtml|video {\n break-inside: avoid;\n}\n\nhtml|ruby {\n display: ruby;\n}\nhtml|rp {\n display: none;\n}\nhtml|rbc {\n display: ruby-base-container;\n}\nhtml|rtc {\n display: ruby-text-container;\n}\nhtml|rb {\n display: ruby-base;\n white-space: nowrap;\n}\nhtml|rt {\n display: ruby-text;\n}\nhtml|ruby,\nhtml|rb,\nhtml|rt,\nhtml|rbc,\nhtml|rtc {\n unicode-bidi: isolate;\n}\n\nhtml|rtc,\nhtml|rt {\n font-variant-east-asian: ruby;\n text-emphasis: none;\n white-space: nowrap;\n line-height: 1;\n}\n\nhtml|rtc:lang(zh),\nhtml|rt:lang(zh) {\n ruby-align: center;\n}\n\nhtml|rtc,\nhtml|rt {\n font-size: 50%;\n}\n\nhtml|rtc:lang(zh-TW),\nhtml|rt:lang(zh-TW) {\n font-size: 30%;\n}\n\nhtml|rtc > html|rt,\nhtml|rtc > html|rt:lang(zh-TW) {\n font-size: 100%;\n}\n\n/* Bidi settings */\nhtml|bdo[dir="ltr"] {\n direction: ltr;\n unicode-bidi: bidi-override;\n}\nhtml|bdo[dir="rtl"] {\n direction: rtl;\n unicode-bidi: bidi-override;\n}\nhtml|*[dir="ltr"] {\n direction: ltr;\n unicode-bidi: embed;\n}\nhtml|*[dir="rtl"] {\n direction: rtl;\n unicode-bidi: embed;\n}\n\n/*------------------ epub-specific ---------------------*/\n\n@namespace epub "http://www.idpf.org/2007/ops";\n\nhtml|a[epub|type="noteref"] {\n font-size: 0.75em;\n vertical-align: super;\n line-height: 0.01;\n}\n\nhtml|a[epub|type="noteref"]:href-epub-type(footnote) {\n -adapt-template: url(user-agent.xml#footnote);\n text-decoration: none;\n}\n\nhtml|aside[epub|type="footnote"] {\n display: none;\n}\n\nhtml|aside[epub|type="footnote"]:footnote-content {\n display: block;\n margin: 0.25em;\n font-size: 1.2em;\n line-height: 1.2;\n}\n\nepub|trigger {\n display: none;\n}\n\nepub|switch {\n display: inline;\n}\n\nepub|default {\n display: inline;\n}\n\nepub|case {\n display: none;\n}\n\nepub|case[required-namespace::supported] {\n display: inline;\n}\n\nepub|case[required-namespace::supported] ~ epub|case {\n display: none;\n}\n\nepub|case[required-namespace::supported] ~ epub|default {\n display: none;\n}\n\n/*--------------- ncx and toc ----------------------*/\n\n@namespace ncx "http://www.daisy.org/z3986/2005/ncx/";\n\nncx|ncx {\n display: block;\n padding-top: 10px;\n padding-bottom: 10px;\n}\n\nncx|content {\n display: none;\n}\n\nbody > * {\n -adapt-behavior: body-child;\n}\n\n[role="doc-toc"],\n[role="directory"],\nnav,\n.toc,\n#toc,\n#table-of-contents,\n#contents {\n -adapt-behavior: toc-root;\n}\n\n[role="doc-toc"] a,\n[role="directory"] a,\nnav a,\n.toc a,\n#toc a,\nncx|navLabel {\n -adapt-behavior: toc-node-anchor;\n}\n\n[role="doc-toc"] li,\n[role="directory"] li,\nnav li,\n.toc li,\n#toc li,\nncx|navPoint {\n -adapt-behavior: toc-node;\n}\n\n[role="doc-toc"] li > *:first-child,\n[role="directory"] li > *:first-child,\nnav li > *:first-child,\n.toc li > *:first-child,\n#toc li > *:first-child {\n -adapt-behavior: toc-node-first-child;\n}\n\n[role="doc-toc"] ol,\n[role="directory"] ol,\nnav ol,\n.toc ol,\n#toc ol,\n[role="doc-toc"] ul,\n[role="directory"] ul,\nnav ul,\n.toc ul,\n#toc ul,\nol[role="doc-toc"],\nol[role="directory"],\nol.toc,\nol#toc,\nul[role="doc-toc"],\nul[role="directory"],\nul.toc,\nul#toc {\n -adapt-behavior: toc-container;\n}\n\n/*---------------- fb2 ---------------------*/\n\n@namespace fb2 "http://www.gribuser.ru/xml/fictionbook/2.0";\n\nfb2|FictionBook {\n display: block;\n}\n\nfb2|body {\n font-family: serif;\n margin: 8px;\n column-width: 25em;\n}\n\nfb2|a {\n line-height: 0.1;\n vertical-align: super;\n font-size: 0.7em;\n}\n\nfb2|sub {\n line-height: 0.1;\n font-size: 0.7em;\n}\n\nfb2|sup {\n line-height: 0.1;\n font-size: 0.7em;\n}\n\nfb2|table {\n display: table;\n font-size: 0.8em;\n font-family: sans-serif;\n margin: 0.5em;\n border-collapse: collapse;\n border: 1px solid black;\n}\n\nfb2|td {\n border: 1px solid black;\n padding: 0.3em;\n}\n\nfb2|th {\n font-weight: bold;\n text-align: center;\n border: 1px solid black;\n background-color: #cee;\n padding: 0.3em;\n}\n\nfb2|code {\n font-family: monospace;\n}\n\nfb2|p {\n display: block;\n margin: 0px;\n text-indent: 1.5em;\n text-align: justify;\n}\n\nfb2|title fb2|p {\n margin: 0px 0px 0.5em 0px;\n text-indent: 0px;\n text-align: inherit;\n}\n\nfb2|title {\n font-size: 2.2em;\n font-weight: bold;\n break-inside: avoid;\n break-after: avoid;\n text-align: center;\n margin: 1em 0px 0.5em 0px;\n display: block;\n}\n\nfb2|section {\n display: block;\n}\n\nfb2|section fb2|title {\n font-size: 1.8em;\n text-align: center;\n margin: 1em 0px 0.5em 0px;\n}\n\nfb2|section fb2|section fb2|title {\n font-size: 1.5em;\n text-align: left;\n margin: 1em 0px 0.5em 1.5625em;\n}\n\nfb2|section fb2|section fb2|section fb2|title {\n font-size: 1.3em;\n text-align: left;\n margin: 1em 0px 0.5em 1.923em;\n}\n\nfb2|section fb2|section fb2|section fb2|section fb2|title {\n font-size: 1.2em;\n text-align: left;\n margin: 1em 0px 0.5em 2.083em;\n}\n\nfb2|section fb2|section fb2|section fb2|section fb2|section fb2|title {\n font-size: 1.1em;\n text-align: left;\n margin: 1em 0px 0.5em 2.272em;\n}\n\nfb2|section\n fb2|section\n fb2|section\n fb2|section\n fb2|section\n fb2|section\n fb2|title {\n text-align: left;\n margin: 1em 0px 0.5em 2.5em;\n}\n\nfb2|epigraph {\n text-align: left;\n font-style: italic;\n margin: 1em 1em 2em 30%;\n display: block;\n}\n\nfb2|image {\n text-align: center;\n padding: 3px;\n}\n\nfb2|image::inner {\n max-width: 95%;\n}\n\nfb2|image::after {\n display: block;\n content: attr(title);\n}\n\nfb2|v {\n text-indent: -1em;\n padding-left: 1em;\n margin: 0px;\n display: block;\n}\nfb2|poem {\n margin: 0.5em 0px 0.5em 2em;\n display: block;\n}\nfb2|date {\n margin: 0.5em 0px 0.5em 50%;\n font-style: italic;\n display: block;\n}\nfb2|stanza {\n margin: 0.5em 0px;\n break-inside: avoid;\n display: block;\n}\nfb2|empty-line {\n height: 1em;\n margin: 0px;\n display: block;\n}\nfb2|cite {\n margin: 0.5em 0px 0.5em 1em;\n font-size: 0.95em;\n display: block;\n}\nfb2|subtitle {\n text-indent: 0px;\n text-align: center;\n font-style: italic;\n font-weight: bold;\n margin: 0.5em 2em;\n break-inside: avoid;\n break-after: avoid;\n display: block;\n}\nfb2|annotation {\n margin: 1em 0px 1em 2em;\n text-indent: 0px;\n font-style: italic;\n display: block;\n}\nfb2|text-author {\n text-indent: 0px;\n margin: 0.2em 0px 0px 3em;\n display: block;\n}\nfb2|emphasis {\n font-style: italic;\n}\nfb2|strong {\n font-weight: bold;\n}\nfb2|strikethrough {\n text-decoration: line-through;\n}\nfb2|*.italic {\n font-style: italic;\n}\nfb2|*.bold {\n font-weight: bold;\n}\n\nfb2|binary,\nfb2|description,\nfb2|stylesheet {\n display: none;\n}\n\nfb2|a[type="note"] {\n font-size: 0.75em;\n vertical-align: super;\n line-height: 0.01;\n text-decoration: none;\n -adapt-template: url(user-agent.xml#footnote);\n}\n\nfb2|body[name="notes"] {\n display: none;\n}\n\nfb2|body[name="notes"] fb2|title {\n display: inline;\n vertical-align: super;\n line-height: 0.01;\n text-align: left;\n font-size: 0.75em;\n font-weight: bold;\n margin: 0px;\n}\n\nfb2|body[name="notes"] fb2|p {\n text-indent: 0px;\n display: inline; /* for now */\n}\n\nfb2|body[name="notes"] fb2|p + fb2|p {\n display: block;\n}\n\nfb2|body[name="notes"] fb2|section {\n text-indent: 0px;\n line-height: 1.2;\n font-size: 1.2em;\n}\n',i,n,null,null).thenFinish(t),t.result()},"uaStylesheetBaseFetcher");class qu{constructor(t,e,n,i,o,s,r,a,l,h){this.store=t,this.rootScope=e,this.pageScope=n,this.cascade=i,this.rootBox=o,this.fontFaces=s,this.footnoteProps=r,this.flowProps=a,this.viewportProps=l,this.pageProps=h,this.fontDeobfuscator=t.fontDeobfuscator,this.validatorSet=t.validatorSet,this.pageScope.defineBuiltIn("has-content",(function(t){t=t;const e=this.currentLayoutPosition,n=e.firstFlowChunkOfFlow(t);return this.matchPageSide(e.startSideOfFlow(t))&&e.hasContent(t,this.lookupOffset)&&!!n&&!this.flowChunkIsAfterParentFlowForcedBreak(n)})),this.pageScope.defineName("page-number",new oe(this.pageScope,(function(){return this.pageNumberOffset+this.currentLayoutPosition.page}),"page-number"))}sizeViewport(t,e,n,i){if(this.viewportProps.length){const o=new At(this.rootScope,t,e,n),s=function(t,e){const n={};for(let i=0;i<e.length;i++)Qo(t,n,e[i],0,null,null,null);return n}(o,this.viewportProps),r=s.width,a=s.height,l=s["text-zoom"];let h=1;if(r&&a||l){const s=Pt.em;if((l?l.evaluate(o,"text-zoom"):null)===Me.scale&&(h=s/n,n=s,t*=h,e*=h),r&&a){const t=_e(r.evaluate(o,"width"),o),e=_e(a.evaluate(o,"height"),o);if(t>0&&e>0){return{width:i&&i.spreadView?2*(t+i.pageBorder):t,height:e,fontSize:n}}}}}return{width:t,height:e,fontSize:n}}}class Qu extends At{constructor(t,e,n,i,o,s,r,a,l,h,c,u){super(t.rootScope,i.width,i.height,i.fontSize),this.style=t,this.xmldoc=e,this.viewport=i,this.clientLayout=o,this.fontMapper=s,this.customRenderer=r,this.fallbackMap=a,this.pageNumberOffset=l,this.documentURLTransformer=h,this.counterStore=c,this.primaryFlows={body:!0},this.rootPageBoxInstance=null,this.styler=null,this.stylerMap=null,this.currentLayoutPosition=null,this.layoutPositionAtPageStart=null,this.lookupOffset=0,this.pageBoxInstances={},this.pageManager=null,this.pageBreaks={},this.pageProgression=null,this.pageSheetSize={},this.pageSheetHeight=0,this.pageSheetWidth=0,this.lang=e.lang||n,this.faces=new mc(this.style.fontDeobfuscator),this.rootPageFloatLayoutContext=new xa(null,null,null,null,null,null,null),this.pageProgression=u||null;for(const e in t.flowProps){const n=$o(t.flowProps[e],"flow-consume");if(n){n.evaluate(this,"flow-consume")==Me.all?this.primaryFlows[e]=!0:delete this.primaryFlows[e]}}}init(){const t=this,e=pi("StyleInstance.init"),n=t.counterStore.createCounterListener(t.xmldoc.url),i=t.counterStore.createCounterResolver(t.xmldoc.url,t.style.rootScope,t.style.pageScope);t.styler=new Ph(t.xmldoc,t.style.cascade,t.style.rootScope,t,this.primaryFlows,t.style.validatorSet,n,i),i.setStyler(t.styler),t.styler.resetFlowChunkStream(t),t.stylerMap={},t.stylerMap[t.xmldoc.url]=t.styler;const o=t.styler.getTopContainerStyle();t.pageProgression||(t.pageProgression=Wc(o));const s=this.style.rootBox;this.rootPageBoxInstance=new Bc(s);const r=this.style.cascade.createInstance(t,n,i,this.lang);this.rootPageBoxInstance.applyCascadeAndInit(r,o),this.rootPageBoxInstance.resolveAutoSizing(t),this.pageManager=new Nu(r,this.style.pageScope,this.rootPageBoxInstance,t,o);const a=[];for(const e of t.style.fontFaces){if(e.condition&&!e.condition.evaluate(t))continue;const n=fc(e.properties,t),i=new gc(n);a.push(i)}t.fontMapper.findOrLoadFonts(a,t.faces).thenFinish(e);const l=t.style.pageProps;return Object.keys(l).forEach(t=>{const e=Zc(Qc(l[t]),this);this.pageSheetSize[t]={width:e.pageWidth+2*e.cropOffset,height:e.pageHeight+2*e.cropOffset}}),e.result()}getStylerForDoc(t){let e=this.stylerMap[t.url];if(!e){const n=this.style.store.getStyleForDoc(t),i=new At(n.rootScope,this.pageWidth(),this.pageHeight(),this.initialFontSize),o=this.counterStore.createCounterListener(t.url),s=this.counterStore.createCounterResolver(t.url,n.rootScope,n.pageScope);e=new Ph(t,n.cascade,n.rootScope,i,this.primaryFlows,n.validatorSet,o,s),this.stylerMap[t.url]=e}return e}registerInstance(t,e){this.pageBoxInstances[t]=e}lookupInstance(t){return this.pageBoxInstances[t]}encounteredFlowChunk(t,e){const n=this.currentLayoutPosition;if(n){n.flows[t.flowName]?e=n.flows[t.flowName]:n.flows[t.flowName]=e;let i=n.flowPositions[t.flowName];i||(i=new fa,n.flowPositions[t.flowName]=i);const o={steps:[{node:t.element,shadowType:aa.NONE,shadowContext:null,nodeShadow:null,shadowSibling:null,formattingContext:null,fragmentIndex:0}],offsetInNode:0,after:!1,preprocessedTextContent:null},s=new da(o),r=new pa(s,t);i.positions.push(r)}}getConsumedOffset(t){let e=Number.POSITIVE_INFINITY;for(let n=0;n<t.positions.length;n++){const i=t.positions[n].chunkPosition.primary;let o=i.steps[0].node,s=i.offsetInNode,r=i.after,a=0;for(;o.ownerDocument!=this.xmldoc.document;)a++,o=i.steps[a].node,r=!1,s=0;const l=this.xmldoc.getNodeOffset(o,s,r);l<e&&(e=l)}return e}getPosition(t,e){if(!t)return 0;let n=Number.POSITIVE_INFINITY;for(const i in this.primaryFlows){let o=t.flowPositions[i];if(e||o&&0!=o.positions.length||!this.currentLayoutPosition||(this.styler.styleUntilFlowIsReached(i),o=this.currentLayoutPosition.flowPositions[i],t!=this.currentLayoutPosition&&o&&(o=o.clone(),t.flowPositions[i]=o)),o){const t=this.getConsumedOffset(o);t<n&&(n=t)}}return n}dumpLocation(t){h.debug("Location - page",this.currentLayoutPosition.page),h.debug(" current:",t),h.debug(" lookup:",this.lookupOffset);for(const t in this.currentLayoutPosition.flowPositions){const e=this.currentLayoutPosition.flowPositions[t];for(const n of e.positions)h.debug(" Chunk",`${t}:`,n.flowChunk.startOffset)}}matchPageSide(t){switch(t){case"left":case"right":case"recto":case"verso":return new ne(this.style.pageScope,`${t}-page`).evaluate(this);default:return!0}}updateStartSide(t){for(const e in t.flowPositions){const n=t.flowPositions[e];if(n&&n.positions.length>0){const t=n.positions[0].flowChunk;if(this.getConsumedOffset(n)===t.startOffset){const t=n.positions[0].flowChunk.breakBefore,e=Ma(n.startSide);n.startSide=Ba(_a(e,t))}}}}selectPageMaster(t){const e=this,n=this.currentLayoutPosition,i=this.getPosition(n);if(i==Number.POSITIVE_INFINITY)return null;const o=this.rootPageBoxInstance.children;let s;for(let r=0;r<o.length;r++){if(s=o[r],s.pageBox.pseudoName===lu)continue;let a=1;const l=s.getProp(e,"utilization");l&&l.isNum()&&(a=l.num);const h=e.queryUnitSize("em",!1),c=e.pageWidth()*e.pageHeight(),u=Math.ceil(a*c/(h*h));this.lookupOffset=this.styler.styleUntil(i,u),this.updateStartSide(n),this.layoutPositionAtPageStart=n.clone(),this.initLingering(),e.clearScope(this.style.pageScope);const d=s.getProp(e,"enabled");if(!d||d===Me._true)return this.pageManager.getPageRulePageMaster(s,t)}throw new Error("No enabled page masters")}flowChunkIsAfterParentFlowForcedBreak(t){const e=this.layoutPositionAtPageStart.flows,n=e[t.flowName].parentFlowName;if(n){const i=t.startOffset,o=e[n].forcedBreakOffsets;if(!o.length||i<o[0])return!1;const s=Z(o.length,t=>o[t]>i)-1,r=o[s],a=this.layoutPositionAtPageStart.flowPositions[n],l=this.getConsumedOffset(a);return!(r<l)&&(l<r||!this.matchPageSide(a.startSide))}return!1}setFormattingContextToColumn(t,e){const n=this.currentLayoutPosition.flows[e];n.formattingContext||(n.formattingContext=new nl(null)),t.flowRootFormattingContext=n.formattingContext}layoutDeferredPageFloats(t){const e=t.pageFloatLayoutContext,n=e.getDeferredPageFloatContinuations(),i=pi("layoutDeferredPageFloats");let o=!1,s=0;return i.loopWithFrame(i=>{if(s===n.length)return void i.breakLoop();const r=n[s++],a=r.float,l=(new va).findByFloat(a),h=l.findPageFloatFragment(a,e);if(!h||!h.hasFloat(a))return e.isForbidden(a)||e.hasPrecedingFloatsDeferredToNext(a)?(e.deferPageFloat(r),void i.breakLoop()):void t.layoutPageFloatInner(r,l,null,h).then(t=>{if(!t)return void i.breakLoop();const n=e.parent.isInvalidated();n?i.breakLoop():(e.isInvalidated()&&!n&&(o=!0,e.validate()),i.continueLoop())});i.continueLoop()}).then(()=>{o&&e.invalidate(),i.finish(!0)}),i.result()}getLastAfterPositionIfDeferredFloatsExists(t,e){if(t.pageFloatLayoutContext.getPageFloatContinuationsDeferredToNext().length>0){if(t.lastAfterPosition){let n;return e?(n=e.clone(),n.primary=t.lastAfterPosition):n=new da(t.lastAfterPosition),n}return null}return null}layoutColumn(t,e){const n=this.currentLayoutPosition.flowPositions[e];if(!n||!this.matchPageSide(n.startSide))return fi(!0);n.startSide="any",this.setFormattingContextToColumn(t,e),t.init(),this.primaryFlows[e]&&t.bands.length>0&&(t.forceNonfitting=!1);const i=this,o=pi("layoutColumn");return this.layoutDeferredPageFloats(t).then(()=>{if(t.pageFloatLayoutContext.isInvalidated())return void o.finish(!0);const s=[],r=[];let a=!0;o.loopWithFrame(o=>{if(t.pageFloatLayoutContext.hasContinuingFloatFragmentsInFlow(e))o.breakLoop();else{for(;n.positions.length-r.length>0;){let e=0;for(;r.includes(e);)e++;let l=n.positions[e];if(l.flowChunk.startOffset>i.lookupOffset||i.flowChunkIsAfterParentFlowForcedBreak(l.flowChunk))break;for(let t=e+1;t<n.positions.length;t++){if(r.includes(t))continue;const o=n.positions[t];if(o.flowChunk.startOffset>i.lookupOffset||i.flowChunkIsAfterParentFlowForcedBreak(o.flowChunk))break;o.flowChunk.isBetter(l.flowChunk)&&(l=o,e=t)}const h=l.flowChunk;let c=!0;if(t.layout(l.chunkPosition,a,n.breakAfter).then(u=>{if(t.pageFloatLayoutContext.isInvalidated())o.breakLoop();else{if(a=!1,l.flowChunk.repeated&&(null===u||h.exclusive)&&s.push(e),h.exclusive)return r.push(e),void o.breakLoop();{const a=!!u||!!t.pageBreakType,h=i.getLastAfterPositionIfDeferredFloatsExists(t,u);if(t.pageBreakType&&h?(l.chunkPosition=h,n.breakAfter=t.pageBreakType,t.pageBreakType=null):(r.push(e),(u||h)&&(l.chunkPosition=u||h,s.push(e)),t.pageBreakType&&(n.startSide=Ba(t.pageBreakType))),a)return void o.breakLoop()}t.forceNonfitting=!1,c?c=!1:o.continueLoop()}}),c)return void(c=!1)}o.breakLoop()}}).then(()=>{if(!t.pageFloatLayoutContext.isInvalidated()){n.positions=n.positions.filter((t,e)=>s.includes(e)||!r.includes(e)),"column"===n.breakAfter&&(n.breakAfter=null),t.saveDistanceToBlockEndFloats();const e=t.pageFloatLayoutContext.getMaxReachedAfterEdge();t.updateMaxReachedAfterEdge(e)}o.finish(!0)})}),o.result()}createLayoutConstraint(t){const e=this.currentLayoutPosition.page-1,n=this.counterStore.createLayoutConstraint(e);return new Cl([n].concat(t.getLayoutConstraints()))}createAndLayoutColumn(t,e,n,i,o,s,r,a,l,h,c,u,d,p){const f=this,g=t.vertical?t.isAutoWidth&&t.isRightDependentOnAutoWidth:t.isAutoHeight&&t.isTopDependentOnAutoHeight,m=o.element,E=new xa(a,Na.COLUMN,null,r,null,null,null),w=f.currentLayoutPosition.clone(),N=pi("createAndLayoutColumn");let b;return N.loopWithFrame(t=>{const N=f.createLayoutConstraint(E);if(l>1){const t=f.viewport.document.createElement("div");if(V(t,"position","absolute"),m.appendChild(t),b=new Il(t,d,f.clientLayout,N,E),b.forceNonfitting=p,b.vertical=o.vertical,b.snapHeight=o.snapHeight,b.snapWidth=o.snapWidth,o.vertical){const t=s*(c+h)+o.paddingTop;b.setHorizontalPosition(o.paddingLeft,o.width),b.setVerticalPosition(t,c)}else{const t=s*(c+h)+o.paddingLeft;b.setVerticalPosition(o.paddingTop,o.height),b.setHorizontalPosition(t,c)}b.originX=e,b.originY=n}else b=new Il(m,d,f.clientLayout,N,E),b.copyFrom(o);b.exclusions=g?[]:i.concat(),b.innerShape=u,E.setContainer(b),b.width>=0?f.layoutColumn(b,r).then(()=>{E.isInvalidated()||E.finish(),b.pageFloatLayoutContext.isInvalidated()&&!a.isInvalidated()?(b.pageFloatLayoutContext.validate(),f.currentLayoutPosition=w.clone(),b.element!==m&&m.removeChild(b.element),t.continueLoop()):t.breakLoop()}):(E.finish(),t.breakLoop())}).then(()=>{N.finish(b)}),N.result()}setPagePageFloatLayoutContextContainer(t,e,n){(e instanceof Eu||e instanceof Mc&&!(e instanceof pu))&&t.setContainer(n)}getRegionPageFloatLayoutContext(t,e,n,i){const o=e.getProp(this,"writing-mode")||null,s=e.getProp(this,"direction")||null;return new xa(t,Na.REGION,n,i,null,o,s)}layoutFlowColumnsWithBalancing(t,e,n,i,o,s,r,a,l){const h=this,c=h.currentLayoutPosition.clone(),u=h.getRegionPageFloatLayoutContext(s,e,r,a);let d=!0;function p(){return h.currentLayoutPosition=c.clone(),h.layoutFlowColumns(t,e,n,i,o,s,u,r,a,l,d).thenAsync(t=>fi(t?{columns:t,position:h.currentLayoutPosition}:null))}return p().thenAsync(t=>{if(!t)return fi(null);if(l<=1)return fi(t.columns);const n=e.getProp(h,"column-fill")||Me.balance,i=h.currentLayoutPosition.flowPositions[a],o=function(t,e,n,i,o,s,r){if(e===Me.auto)return null;{const a=0===r.positions.length,l=s[s.length-1],h=!(!l||!l.pageBreakType);return a||h?new Sh(n,i,o,t):e===Me.balance_all?new Ch(n,i,o):null}}(l,n,p,u,r,t.columns,i);return o?(d=!1,s.lock(),u.lock(),o.balanceColumns(t).thenAsync(t=>(s.unlock(),s.validate(),u.unlock(),h.currentLayoutPosition=t.position,fi(t.columns)))):fi(t.columns)})}layoutFlowColumns(t,e,n,i,o,s,r,a,l,h,c){const u=this,d=pi("layoutFlowColumns"),p=u.currentLayoutPosition.clone(),f=e.getPropAsNumber(u,"column-gap"),g=h>1?e.getPropAsNumber(u,"column-width"):a.width,m=e.getActiveRegions(u),E=En(e.getProp(u,"shape-inside"),0,0,a.width,a.height,u),w=new Du(l,u,u.viewport,u.styler,m,u.xmldoc,u.faces,u.style.footnoteProps,u,t,u.customRenderer,u.fallbackMap,this.documentURLTransformer);let N=0,b=null,S=[];return d.loopWithFrame(t=>{u.createAndLayoutColumn(e,n,i,o,a,N++,l,r,h,f,g,E,w,c).then(e=>{if(s.isInvalidated())return S=null,void t.breakLoop();if(!(!!e.pageBreakType&&"column"!==e.pageBreakType)&&N!==h||r.isInvalidated()||r.finish(),r.isInvalidated())return N=0,u.currentLayoutPosition=p.clone(),r.validate(),void(r.isLocked()?(S=null,t.breakLoop()):t.continueLoop());b=e,S[N-1]=b,b.pageBreakType&&"column"!=b.pageBreakType&&(N=h,"region"!=b.pageBreakType&&(u.pageBreaks[l]=!0)),N<h?t.continueLoop():t.breakLoop()})}).then(()=>{d.finish(S)}),d.result()}layoutContainer(t,e,n,i,o,s,r){const a=this;e.reset();const l=e.getProp(a,"enabled");if(l&&l!==Me._true)return fi(!0);const h=pi("layoutContainer"),c=e.getProp(a,"wrap-flow")===Me.auto,u=e.getProp(a,"flow-from"),d=a.viewport.document.createElement("div"),p=e.getProp(a,"position");V(d,"position",p?p.name:"absolute"),n.insertBefore(d,n.firstChild);let f,g=new ma(d);g.vertical=e.vertical,g.exclusions=s,e.prepareContainer(a,g,t,a.faces,a.clientLayout),g.originX=i,g.originY=o,i+=g.left+g.marginLeft+g.borderLeft,o+=g.top+g.marginTop+g.borderTop,this.setPagePageFloatLayoutContextContainer(r,e,g);let m=!1;if(u&&u.isIdent())if(a.pageBreaks[u.toString()])r.isInvalidated()||e.finishContainer(a,g,t,null,1,a.clientLayout,a.faces),f=fi(!0);else{const n=pi("layoutContainer.inner"),l=u.toString(),h=e.getPropAsNumber(a,"column-count");a.layoutFlowColumnsWithBalancing(t,e,i,o,s,r,g,l,h).then(i=>{if(!r.isInvalidated()){const n=i[0];n.element===d&&(g=n),g.computedBlockSize=Math.max.apply(null,i.map(t=>t.computedBlockSize)),e.finishContainer(a,g,t,n,h,a.clientLayout,a.faces);const o=a.currentLayoutPosition.flowPositions[l];o&&"region"===o.breakAfter&&(o.breakAfter=null)}n.finish(!0)}),f=n.result()}else{const i=e.getProp(a,"content");if(i&&wa(i)){let n="span";i.url&&(n="img");const o=a.viewport.document.createElement(n);i.visit(new Ea(o,a,i,a.counterStore.getExprContentListener())),d.appendChild(o),"img"==n&&e.transferSinglUriContentProps(a,o,a.faces),e.transferContentProps(a,g,t,a.faces)}else e.suppressEmptyBoxGeneration&&(n.removeChild(d),m=!0);m||e.finishContainer(a,g,t,null,1,a.clientLayout,a.faces),f=fi(!0)}return f.then(()=>{if(r.isInvalidated())return void h.finish(!0);if(!e.isAutoHeight||Math.floor(g.computedBlockSize)>0){if(!m&&!c){const t=e.getProp(a,"shape-outside"),n=g.getOuterShape(t,a);s.push(n)}}else if(0==e.children.length)return n.removeChild(d),void h.finish(!0);let l=e.children.length-1;h.loop(()=>{for(;l>=0;){const n=e.children[l--],h=a.layoutContainer(t,n,d,i,o,s,r);if(h.isPending())return h.thenAsync(()=>fi(!r.isInvalidated()));if(r.isInvalidated())break}return fi(!1)}).then(()=>{h.finish(!0)})}),h.result()}processLinger(){const t=this.currentLayoutPosition.page;for(const e in this.currentLayoutPosition.flowPositions){const n=this.currentLayoutPosition.flowPositions[e];for(let e=n.positions.length-1;e>=0;e--){const i=n.positions[e];i.flowChunk.startPage>=0&&i.flowChunk.startPage+i.flowChunk.linger-1<=t&&n.positions.splice(e,1)}}}initLingering(){const t=this.currentLayoutPosition.page;for(const e in this.currentLayoutPosition.flowPositions){const n=this.currentLayoutPosition.flowPositions[e];for(let e=n.positions.length-1;e>=0;e--){const i=n.positions[e];i.flowChunk.startPage<0&&i.flowChunk.startOffset<this.lookupOffset&&(i.flowChunk.startPage=t)}}}noMorePrimaryFlows(t){for(const e in this.primaryFlows){const n=t.flowPositions[e];if(n&&n.positions.length>0)return!1}return!0}layoutNextPage(e,n){const i=this,o=e.container===e.bleedBox;i.pageBreaks={},n?(i.currentLayoutPosition=n.clone(),i.styler.replayFlowElementsFromOffset(n.highestSeenOffset)):(i.currentLayoutPosition=new ga,i.styler.replayFlowElementsFromOffset(-1)),this.lang&&e.bleedBox.setAttribute("lang",this.lang),(n=i.currentLayoutPosition).page++,i.clearScope(i.style.pageScope),i.layoutPositionAtPageStart=n.clone();const s=o?{}:i.pageManager.getCascadedPageStyle(),r=i.selectPageMaster(s);if(!r)return fi(null);let a=0;if(!o){e.setAutoPageWidth(r.pageBox.specified.width.value===Ve),e.setAutoPageHeight(r.pageBox.specified.height.value===He),i.counterStore.setCurrentPage(e),i.counterStore.updatePageCounters(s,i);const t=Zc(Qc(s),this);i.setPageSizeAndBleed(t,e),iu(s,t,e,this),a=t.bleedOffset+t.bleed}const l=!o&&r.getProp(i,"writing-mode")||Me.horizontal_tb;this.pageVertical=l!=Me.horizontal_tb;const h=r.getProp(i,"direction")||Me.ltr,c=new xa(i.rootPageFloatLayoutContext,Na.PAGE,null,null,null,l,h),u=pi("layoutNextPage");return u.loopWithFrame(t=>{i.layoutContainer(e,r,e.bleedBox,a,a,[],c).then(()=>{c.isInvalidated()||c.finish(),c.isInvalidated()?(i.currentLayoutPosition=i.layoutPositionAtPageStart.clone(),c.validate(),t.continueLoop()):t.breakLoop()})}).then(()=>{if(r.adjustPageLayout(i,e,i.clientLayout),!o){const o=new ne(r.pageBox.scope,"left-page");e.side=o.evaluate(i)?t.PageSide.LEFT:t.PageSide.RIGHT,i.processLinger(),n=i.currentLayoutPosition,Object.keys(n.flowPositions).forEach(t=>{const e=n.flowPositions[t],o=e.breakAfter;!o||"page"!==o&&i.matchPageSide(o)||(e.breakAfter=null)})}i.currentLayoutPosition=i.layoutPositionAtPageStart=null,n.highestSeenOffset=i.styler.getReachedOffset();const s=i.style.store.getTriggersForDoc(i.xmldoc);e.finish(s,i.clientLayout),i.noMorePrimaryFlows(n)&&(n=null),u.finish(n)}),u.result()}setPageSizeAndBleed(t,e){this.actualPageWidth=t.pageWidth,this.actualPageHeight=t.pageHeight,this.pageSheetWidth=t.pageWidth+2*t.cropOffset,this.pageSheetHeight=t.pageHeight+2*t.cropOffset,e.container.style.width=`${this.pageSheetWidth}px`,e.container.style.height=`${this.pageSheetHeight}px`,e.bleedBox.style.left=`${t.bleedOffset}px`,e.bleedBox.style.right=`${t.bleedOffset}px`,e.bleedBox.style.top=`${t.bleedOffset}px`,e.bleedBox.style.bottom=`${t.bleedOffset}px`,e.bleedBox.style.padding=`${t.bleed}px`,e.bleedBox.style.paddingTop=`${t.bleed+.01}px`}}class Zu extends Zs{constructor(t,e,n,i){super(t.rootScope,t,e,n,i,t.validatorSet,!n),this.masterHandler=t,this.insideRegion=!1}startPageTemplateRule(){}startPageMasterRule(t,e,n){const i=new yc(this.masterHandler.pageScope,t,e,n,this.masterHandler.rootBox,this.condition,this.owner.getBaseSpecificity());this.masterHandler.pushHandler(new $c(i.scope,this.masterHandler,i,this.validatorSet))}startWhenRule(t){let e=t.expr;null!=this.condition&&(e=ce(this.scope,this.condition,e)),this.masterHandler.pushHandler(new Zu(this.masterHandler,e,this,this.regionId))}startDefineRule(){this.masterHandler.pushHandler(new nr(this.scope,this.owner))}startFontFaceRule(){const t={};this.masterHandler.fontFaces.push({properties:t,condition:this.condition}),this.masterHandler.pushHandler(new ir(this.scope,this.owner,null,t,this.masterHandler.validatorSet))}startFlowRule(t){let e=this.masterHandler.flowProps[t];e||(e={},this.masterHandler.flowProps[t]=e),this.masterHandler.pushHandler(new ir(this.scope,this.owner,null,e,this.masterHandler.validatorSet))}startViewportRule(){const t={};this.masterHandler.viewportProps.push(t),this.masterHandler.pushHandler(new ir(this.scope,this.owner,this.condition,t,this.masterHandler.validatorSet))}startFootnoteRule(t){let e=this.masterHandler.footnoteProps;if(t){const n=Yo(e,"_pseudos");e=n[t],e||(e={},n[t]=e)}this.masterHandler.pushHandler(new ir(this.scope,this.owner,null,e,this.masterHandler.validatorSet))}startRegionRule(){this.insideRegion=!0,this.startSelectorRule()}startPageRule(){const t=new vu(this.masterHandler.pageScope,this.masterHandler,this,this.validatorSet,this.masterHandler.pageProps);this.masterHandler.pushHandler(t),t.startPageRule()}startRuleBody(){if(Zs.prototype.startRuleBody.call(this),this.insideRegion){this.insideRegion=!1;const t=`R${this.masterHandler.regionCount++}`;this.special("region-id",xe(t)),this.endRule();const e=new Zu(this.masterHandler,this.condition,this,t);this.masterHandler.pushHandler(e),e.startRuleBody()}}}function Ju(t){let e=t.getAttribute("content");if(!e)return"";const n={};let i;for(;null!=(i=e.match(/^,?\s*([-A-Za-z_.][-A-Za-z_0-9.]*)\s*=\s*([-+A-Za-z_0-9.]*)\s*/));)e=e.substr(i[0].length),n[i[1]]=i[2];const o=n.width-0,s=n.height-0;return o&&s?`@-epubx-viewport{width:${o}px;height:${s}px;}`:""}class td extends Wi{constructor(t){super(),this.validatorSet=t,this.regionCount=0,this.fontFaces=[],this.footnoteProps={},this.flowProps={},this.viewportProps=[],this.pageProps={},this.rootScope=new It(null),this.pageScope=new It(this.rootScope),this.rootBox=new bc(this.rootScope),this.cascadeParserHandler=new Zu(this,null,null,null),this.slave=this.cascadeParserHandler}error(t,e){h.warn("CSS parser:",t)}}function ed(t,e){return e.parseOPSResource(t)}class nd extends ki{constructor(t){super(ed,Ri.DOCUMENT),this.fontDeobfuscator=t,this.styleByKey={},this.styleFetcherByKey={},this.styleByDocURL={},this.triggersByDocURL={},this.validatorSet=null,this.styleSheets=[],this.triggerSingleDocumentPreprocessing=!1}init(t,e){this.setStyleSheets(t,e);const n=L("user-agent.xml",R),i=pi("OPSDocStore.init");return this.validatorSet=cc(),ju.get().then(()=>{this.load(n).then(()=>{this.triggerSingleDocumentPreprocessing=!0,i.finish(!0)})}),i.result()}getStyleForDoc(t){return this.styleByDocURL[t.url]}getTriggersForDoc(t){return this.triggersByDocURL[t.url]}setStyleSheets(t,e){this.clearStyleSheets(),t&&t.forEach(this.addAuthorStyleSheet,this),e&&e.forEach(this.addUserStyleSheet,this)}clearStyleSheets(){this.styleSheets.splice(0)}addAuthorStyleSheet(t){let e=t.url;e&&(e=L(O(e),v)),this.styleSheets.push({url:e,text:t.text,flavor:zi.AUTHOR,classes:null,media:null})}addUserStyleSheet(t){let e=t.url;e&&(e=L(O(e),v)),this.styleSheets.push({url:e,text:t.text,flavor:zi.USER,classes:null,media:null})}parseOPSResource(e){const n=pi("OPSDocStore.load"),i=this,o=e.url,s=o.endsWith("?viv-toc-box");return $u(e,i).then(e=>{if(!e)return void n.finish(null);if(i.triggerSingleDocumentPreprocessing){const n=f(t.HOOKS.PREPROCESS_SINGLE_DOCUMENT);for(let t=0;t<n.length;t++)try{n[t](e.document)}catch(t){h.warn("Error during single document preprocessing:",t)}}const r=[],a=e.document.getElementsByTagNameNS(k.epub,"trigger");for(let t=0;t<a.length;t++){const e=a[t],n=e.getAttributeNS(k.EV,"observer"),i=e.getAttributeNS(k.EV,"event"),o=e.getAttribute("action"),s=e.getAttribute("ref");n&&i&&o&&s&&r.push({observer:n,event:i,action:o,ref:s})}i.triggersByDocURL[o]=r;const l=[],c=L("user-agent-page.css",R);l.push({url:c,text:Ku,flavor:zi.USER_AGENT,classes:null,media:null});const u=e.head;if(!s&&u)for(let t=u.firstChild;t;t=t.nextSibling){if(1!=t.nodeType)continue;const e=t,n=e.namespaceURI,i=e.localName;if(n==k.XHTML)if("style"==i){const t=e.getAttribute("class"),n=e.getAttribute("media"),i=e.getAttribute("title");l.push({url:o,text:e.textContent,flavor:zi.AUTHOR,classes:i?t:null,media:n})}else if("link"==i){const t=e.getAttribute("rel"),n=e.getAttribute("class"),i=e.getAttribute("media");if("stylesheet"==t||"alternate stylesheet"==t&&n){let t=e.getAttribute("href");t=L(t,o);const s=e.getAttribute("title");l.push({url:t,text:null,classes:s?n:null,media:i,flavor:zi.AUTHOR})}}else"meta"==i&&"viewport"==e.getAttribute("name")&&l.push({url:o,text:Ju(e),flavor:zi.AUTHOR,classes:null,media:null});else if(n==k.FB2)"stylesheet"==i&&"text/css"==e.getAttribute("type")&&l.push({url:o,text:e.textContent,flavor:zi.AUTHOR,classes:null,media:null});else if(n==k.SSE&&"property"===i){const t=e.getElementsByTagName("name")[0];if(t&&"stylesheet"===t.textContent){const t=e.getElementsByTagName("value")[0];if(t){const e=L(t.textContent,o);l.push({url:e,text:null,classes:null,media:null,flavor:zi.AUTHOR})}}}}if(!s)for(let t=0;t<i.styleSheets.length;t++)l.push(i.styleSheets[t]);let d="";for(let t=0;t<l.length;t++)d+=l[t].url,d+="^",l[t].text&&(d+=l[t].text),d+="^";let p=i.styleByKey[d];if(p)return i.styleByDocURL[o]=p,void n.finish(e);let g=i.styleFetcherByKey[d];g||(g=new Ii(()=>{const t=pi("fetchStylesheet");let e=0;const n=new td(i.validatorSet);return t.loop(()=>{if(e<l.length){const t=l[e++];return n.startStylesheet(t.flavor),null!==t.text?fo(t.text,n,t.url,t.classes,t.media).thenReturn(!0):go(t.url,n,t.classes,t.media)}return fi(!1)}).then(()=>{const e=n.cascadeParserHandler.finish();p=new qu(i,n.rootScope,n.pageScope,e,n.rootBox,n.fontFaces,n.footnoteProps,n.flowProps,n.viewportProps,n.pageProps),i.styleByKey[d]=p,delete i.styleFetcherByKey[d],t.finish(p)}),t.result()},`FetchStylesheet ${o}`),i.styleFetcherByKey[d]=g,g.start()),g.get().then(t=>{i.styleByDocURL[o]=t,n.finish(e)})}),n.result()}}function id(t){return String.fromCharCode(t>>>24&255,t>>>16&255,t>>>8&255,255&t)}function od(t){return(255&t.charCodeAt(0))<<24|(255&t.charCodeAt(1))<<16|(255&t.charCodeAt(2))<<8|255&t.charCodeAt(3)}function sd(t){const e=new G;e.append(t);let n=55-t.length&63;for(e.append("€");n>0;)n--,e.append("\0");e.append("\0\0\0\0"),e.append(id(8*t.length)),t=e.toString();const i=[1732584193,4023233417,2562383102,271733878,3285377520],o=[];let s;for(let e=0;e<t.length;e+=64){for(s=0;s<16;s++)o[s]=od(t.substr(e+4*s,4));for(;s<80;s++){const t=o[s-3]^o[s-8]^o[s-14]^o[s-16];o[s]=t<<1|t>>>31}let n,r=i[0],a=i[1],l=i[2],h=i[3],c=i[4];for(s=0;s<80;s++)n=s<20?1518500249+(a&l|~a&h):s<40?1859775393+(a^l^h):s<60?2400959708+(a&l|a&h|l&h):3395469782+(a^l^h),n+=(r<<5|r>>>27)+c+o[s],c=h,h=l,l=a<<30|a>>>2,a=r,r=n;i[0]=i[0]+r|0,i[1]=i[1]+a|0,i[2]=i[2]+l|0,i[3]=i[3]+h|0,i[4]=i[4]+c|0}return i}function rd(t){const e=function(t){const e=sd(t),n=new G;for(let t=0;t<e.length;t++)n.append(id(e[t]));return n.toString()}(t),n=new G;for(let t=0;t<e.length;t++)n.append((256|e.charCodeAt(t)).toString(16).substr(1));return n.toString()}const ad="▸",ld="▾",hd="▹";class cd{constructor(t,e,n,i,o,s,r,a,l,h){this.store=t,this.url=e,this.lang=n,this.clientLayout=i,this.fontMapper=o,this.rendererFactory=r,this.fallbackMap=a,this.documentURLTransformer=l,this.counterStore=h,this.page=null,this.instance=null,this.pref=wt(s),this.pref.spreadView=!1}setAutoHeight(t,e){if(0!=e--)for(let n=t.firstChild;n;n=n.nextSibling)if(1==n.nodeType){const t=n;"auto"!=H(t,"height","auto")&&(V(t,"height","auto"),this.setAutoHeight(t,e)),"absolute"==H(t,"position","static")&&(V(t,"position","relative"),this.setAutoHeight(t,e))}}makeCustomRenderer(t){const e=this.rendererFactory.makeCustomRenderer(t);return(t,n,i)=>{const o=i.behavior;if(o)switch(o.toString()){case"body-child":t.parentElement.getAttribute("data-vivliostyle-primary-entry")&&(t.querySelector("[role=doc-toc], [role=directory], nav li a, .toc, #toc")||(i.display=Me.none));break;case"toc-node-anchor":i.color=Me.inherit,i["text-decoration"]=Me.none;break;case"toc-node":i.display=Me.block,i.margin=ze,i.padding=ze,i["padding-inline-start"]=new Ie(1.25,"em");break;case"toc-node-first-child":i.display=Me.inline_block,i.margin=new Ie(.2,"em"),i["vertical-align"]=Me.top,i.color=Me.inherit,i["text-decoration"]=Me.none}if(!o||"toc-node"!=o.toString()&&"toc-container"!=o.toString())return e(t,n,i);const s=t.firstChild;s&&1!==s.nodeType&&""===s.textContent.trim()&&t.replaceChild(t.ownerDocument.createComment(s.textContent),s);const r=n.getAttribute("data-adapt-class");if("toc-node"==r){const t=n.firstChild;t.textContent!=ad&&(t.textContent=ad,V(t,"cursor","pointer"),t.addEventListener("click",ud,!1),t.setAttribute("role","button"),t.setAttribute("aria-expanded","false"),n.setAttribute("aria-expanded","false"),"0px"!==n.style.height&&(t.tabIndex=0))}const a=n.ownerDocument.createElement("div");if(a.setAttribute("data-adapt-process-children","true"),"toc-node"==o.toString()){const e=n.ownerDocument.createElement("div");if(e.textContent=hd,V(e,"margin","0.2em 0 0 -1em"),V(e,"margin-inline-start","-1em"),V(e,"margin-inline-end","0"),V(e,"display","inline-block"),V(e,"width","1em"),V(e,"text-align","center"),V(e,"vertical-align","top"),V(e,"cursor","default"),V(e,"font-family","Menlo,sans-serif"),a.appendChild(e),V(a,"overflow","hidden"),a.setAttribute("data-adapt-class","toc-node"),a.setAttribute("role","treeitem"),"toc-node"==r||"toc-container"==r){V(a,"height","0px");const e=t.firstElementChild;e&&"a"===e.localName&&(e.tabIndex=-1)}else n.setAttribute("role","tree")}else"toc-node"==r&&(a.setAttribute("data-adapt-class","toc-container"),a.setAttribute("role","group"),a.setAttribute("aria-hidden","true"));return fi(a)}}showTOC(t,e,n,i,o){if(this.page)return fi(this.page);const s=this,r=pi("showTOC"),a=new Kr(t,t);this.page=a;const l=this.url+"?viv-toc-box";return this.store.load(l).then(i=>{const l=this.store.resources[this.url];l&&l.body&&l.body.getAttribute("data-vivliostyle-primary-entry")&&i.body.setAttribute("data-vivliostyle-primary-entry",!0);const h=s.store.getStyleForDoc(i),c=h.sizeViewport(n,1e5,o);e=new Uu(e.window,c.fontSize,e.root,c.width,c.height);const u=s.makeCustomRenderer(i),d=new Qu(h,i,s.lang,e,s.clientLayout,s.fontMapper,u,s.fallbackMap,0,s.documentURLTransformer,s.counterStore);s.instance=d,d.pref=s.pref,d.init().then(()=>{d.layoutNextPage(a,null).then(()=>{Array.from(a.container.querySelectorAll("[data-vivliostyle-toc-box]>*>*>*>*>*[style*='display: none']")).forEach(t=>{t.setAttribute("aria-hidden","true"),t.setAttribute("hidden","hidden")}),s.setAutoHeight(t,2),r.finish(a)})})}),r.result()}hideTOC(){this.page&&(this.page.container.style.visibility="hidden",this.page.container.setAttribute("aria-hidden","true"))}isTOCVisible(){return!!this.page&&"visible"===this.page.container.style.visibility}}function ud(t){const e=t.target,n=e.textContent==ad;e.textContent=n?ld:ad;const i=e.parentNode;e.setAttribute("aria-expanded",n?"true":"false"),i.setAttribute("aria-expanded",n?"true":"false");let o=i.firstChild;for(;o;){if(1===o.nodeType){const t=o,e=t.getAttribute("data-adapt-class");if("toc-container"===e){if(t.setAttribute("aria-hidden",n?"false":"true"),t.firstChild){o=t.firstChild;continue}}else if("toc-node"===e&&(t.style.height=n?"auto":"0px",t.children.length>=2&&(t.children[1].tabIndex=n?0:-1),t.children.length>=3&&(t.children[0].tabIndex=n?0:-1,!n))){const e=t.children[0];if(e.textContent==ld){e.textContent=ad,e.setAttribute("aria-expanded","false"),t.setAttribute("aria-expanded","false"),o=t.children[2];continue}}}for(;!o.nextSibling&&o.parentNode!==i;)o=o.parentNode;o=o.nextSibling}t.stopPropagation()}class dd extends nd{constructor(){super(null),this.opfByURL={},this.primaryOPFByEPubURL={},this.deobfuscators={},this.documents={},this.fontDeobfuscator=this.makeDeobfuscatorFactory(),this.plainXMLStore=new ki($u,Ri.DOCUMENT),this.jsonStore=new ki(Fi,Ri.TEXT)}makeDeobfuscatorFactory(){const t=this;return e=>t.deobfuscators[e]}loadAsPlainXML(t,e,n){return this.plainXMLStore.load(t,e,n)}startLoadingAsPlainXML(t){this.plainXMLStore.fetch(t)}loadAsJSON(t,e,n){return this.jsonStore.load(t,e,n)}startLoadingAsJSON(t){this.jsonStore.fetch(t)}loadPubDoc(t,e){const n=pi("loadPubDoc");return Li(t,null,"HEAD").then(i=>{if(i.status>=400)this.loadEPUBDoc(t,e).then(e=>{e?n.finish(e):(h.error(`Failed to fetch a source document from ${t} (${i.status}${i.statusText?" "+i.statusText:""})`),n.finish(null))});else if(i.status||i.responseXML||i.responseText||i.responseBlob||i.contentType||/\/[^/.]+(?:[#?]|$)/.test(t)&&(t=t.replace(/([#?]|$)/,"/$1")),"application/oebps-package+xml"==i.contentType||/\.opf(?:[#?]|$)/.test(t)){const[,i,o]=t.match(/^((?:.*\/)?)([^/]*)$/);this.loadOPF(i,o,e).thenFinish(n)}else"application/ld+json"==i.contentType||"application/webpub+json"==i.contentType||"application/audiobook+json"==i.contentType||"application/json"==i.contentType||/\.json(?:ld)?(?:[#?]|$)/.test(t)?this.loadAsJSON(t,!0).then(e=>{if(!e)return h.error(`Received an empty response for ${t}. This may be caused by the server not allowing cross-origin resource sharing (CORS).`),void n.finish(null);const i=new Cd(this,t);i.initWithWebPubManifest(e).then(()=>{n.finish(i)})}):this.loadWebPub(t).then(i=>{i?n.finish(i):this.loadEPUBDoc(t,e).then(e=>{e?n.finish(e):(h.error(`Failed to load ${t}.`),n.finish(null))})})}),n.result()}loadEPUBDoc(t,e){const n=pi("loadEPUBDoc");t.endsWith("/")||(t+="/"),e&&this.startLoadingAsJSON(t+"?r=list"),this.startLoadingAsPlainXML(t+"META-INF/encryption.xml");const i=t+"META-INF/container.xml";return this.loadAsPlainXML(i).then(i=>{if(i){const o=i.doc().child("container").child("rootfiles").child("rootfile").attribute("full-path");for(const i of o)if(i)return void this.loadOPF(t,i,e).thenFinish(n);n.finish(null)}}),n.result()}loadOPF(t,e,n){const i=this,o=t+e;let s=i.opfByURL[o];if(s)return fi(s);const r=pi("loadOPF");return i.loadAsPlainXML(o,!0,`Failed to fetch EPUB OPF ${o}`).then(e=>{e?i.loadAsPlainXML(`${t}META-INF/encryption.xml`).then(a=>{(n?i.loadAsJSON(`${t}?r=list`):fi(null)).then(n=>{s=new Cd(i,t),s.initWithXMLDoc(e,a,n,`${t}?r=manifest`).then(()=>{i.opfByURL[o]=s,i.primaryOPFByEPubURL[t]=s,r.finish(s)})})}):h.error(`Received an empty response for EPUB OPF ${o}. This may be caused by the server not allowing cross-origin resource sharing (CORS).`)}),r.result()}loadWebPub(t){const e=pi("loadWebPub");return this.load(t).then(n=>{if(n)if(n.document.querySelector("a[href='META-INF/'],a[href$='/META-INF/']"))e.finish(null);else{const i=n.document,o=new Cd(this,t);i.body&&i.body.setAttribute("data-vivliostyle-primary-entry",!0);const s=i.querySelector("link[rel='publication'],link[rel='manifest'][type='application/webpub+json']");if(s){const n=s.getAttribute("href");if(/^#/.test(n)){const t=x(i.getElementById(n.substr(1)).textContent);o.initWithWebPubManifest(t,i).then(()=>{e.finish(o)})}else this.loadAsJSON(L(s.getAttribute("href"),t)).then(t=>{o.initWithWebPubManifest(t,i).then(()=>{e.finish(o)})})}else o.initWithWebPubManifest({},i).then(()=>{o.xhtmlToc&&o.xhtmlToc.src===n.url&&(i.querySelector("[role=doc-toc], [role=directory], nav, .toc, #toc")||(o.xhtmlToc=null)),e.finish(o)})}else h.error(`Received an empty response for ${t}. This may be caused by the server not allowing cross-origin resource sharing (CORS).`)}),e.result()}addDocument(t,e){const n=pi("EPUBDocStore.load"),i=I(t);return(this.documents[i]=this.parseOPSResource({status:200,statusText:"",url:i,contentType:e.contentType,responseText:null,responseXML:e,responseBlob:null})).thenFinish(n),n.result()}load(t){const e=I(t);let n=this.documents[e];if(n)return n.isPending()?n:fi(n.get());{const t=pi("EPUBDocStore.load");return n=super.load(e,!0,`Failed to fetch a source document from ${e}`),n.then(n=>{n?t.finish(n):e.startsWith("data:")?h.error(`Failed to load ${e}. Invalid data.`):e.startsWith("http:")&&v.startsWith("https:")?h.error(`Failed to load ${e}. Mixed Content ("http:" content on "https:" context) is not allowed.`):h.error(`Received an empty response for ${e}. This may be caused by the server not allowing cross-origin resource sharing (CORS).`)}),t.result()}}}class pd{constructor(){this.id=null,this.src="",this.mediaType=null,this.title=null,this.itemRefElement=null,this.spineIndex=-1,this.compressedSize=0,this.compressed=null,this.epage=0,this.epageCount=0,this.startPage=null,this.skipPagesBefore=null,this.itemProperties=T}initWithElement(t,e){this.id=t.getAttribute("id"),this.src=L(t.getAttribute("href"),e),this.mediaType=t.getAttribute("media-type");const n=t.getAttribute("properties");n&&(this.itemProperties=function(t){const e={};for(let n=0;n<t.length;n++)e[t[n]]=!0;return e}(n.split(/\s+/)))}initWithParam(t){this.spineIndex=t.index,this.id=`item${t.index+1}`,this.src=t.url,this.startPage=t.startPage,this.skipPagesBefore=t.skipPagesBefore}}function fd(t){return t.id}function gd(t){const e=function(t){const e=sd(t),n=[];for(const t of e)n.push(t>>>24&255,t>>>16&255,t>>>8&255,255&t);return n}(t);return t=>{const n=pi("deobfuscator");let i,o;return t.slice?(i=t.slice(0,1040),o=t.slice(1040,t.size)):(i=t.webkitSlice(0,1040),o=t.webkitSlice(1040,t.size-1040)),function(t){const e=pi("readBlob"),n=new FileReader,i=e.suspend(n);return n.addEventListener("load",()=>{i.schedule(n.result)},!1),n.readAsArrayBuffer(t),e.result()}(i).then(t=>{const i=new DataView(t);for(let t=0;t<i.byteLength;t++){let n=i.getUint8(t);n^=e[t%20],i.setUint8(t,n)}n.finish(Oi([i,o]))}),n.result()}}const md={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#"},Ed="http://idpf.org/epub/vocab/package/#",wd={language:`${md.dcterms}language`,title:`${md.dcterms}title`,creator:`${md.dcterms}creator`,layout:`${md.rendition}layout`,titleType:`${Ed}title-type`,displaySeq:`${Ed}display-seq`,alternateScript:`${Ed}alternate-script`};function Nd(t,e){const n={};return(i,o)=>{let s,r;const a=i.r||n,l=o.r||n;if(t==wd.title&&(s="main"==a[wd.titleType],r="main"==l[wd.titleType],s!=r))return s?-1:1;let h=parseInt(a[wd.displaySeq],10);isNaN(h)&&(h=Number.MAX_VALUE);let c=parseInt(l[wd.displaySeq],10);return isNaN(c)&&(c=Number.MAX_VALUE),h!=c?h-c:t!=wd.language&&e&&(s=(a[wd.language]||a[wd.alternateScript])==e,r=(l[wd.language]||l[wd.alternateScript])==e,s!=r)?s?-1:1:i.o-o.o}}function bd(){const t=window.MathJax;return t?t.Hub:null}const Sd={"application/xhtml+xml":!0,"image/jpeg":!0,"image/png":!0,"image/svg+xml":!0,"image/gif":!0,"audio/mp3":!0},yd="viv-id-";class Cd{constructor(t,e){this.store=t,this.pubURL=e,this.opfXML=null,this.encXML=null,this.items=null,this.spine=null,this.itemMap=null,this.itemMapByPath=null,this.uid=null,this.bindings={},this.lang=null,this.epageCount=0,this.prePaginated=!1,this.epageIsRenderedPage=!0,this.epageCountCallback=null,this.metadata={},this.ncxToc=null,this.xhtmlToc=null,this.cover=null,this.fallbackMap={},this.pageProgression=null,this.documentURLTransformer=this.createDocumentURLTransformer(),bd()&&(Po[k.MATHML]=!0)}createDocumentURLTransformer(){const t=this;return new class{transformFragment(t,e){return yd+j(e+(t?`#${t}`:""),":")}transformURL(e,n){const i=e.match(/^([^#]*)#?(.*)$/);if(i){const e=i[1]||n,o=i[2];if(e&&t.items.some(t=>t.src===e))return`#${this.transformFragment(o,e)}`}return e}restoreURL(t){"#"===t.charAt(0)&&(t=t.substring(1)),0===t.indexOf(yd)&&(t=t.substring(yd.length));const e=Q(t,":").match(/^([^#]*)#?(.*)$/);return e?[e[1],e[2]]:[]}}}getMetadata(){return this.metadata}getPathFromURL(t){if(t.startsWith("data:"))return t===this.pubURL?"":t;if(this.pubURL){let e=L("",this.pubURL);return t===e||t+"/"===e?"":("/"!=e.charAt(e.length-1)&&(e+="/"),t.substr(0,e.length)==e?decodeURI(t.substr(e.length)):null)}return t}initWithXMLDoc(t,e,i,o){const s=this;this.opfXML=t,this.encXML=e;const r=t.doc().child("package"),a=r.attribute("unique-identifier")[0];if(a){const e=t.getElement(`${t.url}#${a}`);e&&(this.uid=e.textContent.replace(/[ \n\r\t]/g,""))}const l={};this.items=r.child("manifest").child("item").asArray().map(e=>{const n=new pd,i=e;n.initWithElement(i,t.url);const o=i.getAttribute("fallback");return o&&!Sd[n.mediaType]&&(l[n.src]=o),!s.xhtmlToc&&n.itemProperties.nav&&(s.xhtmlToc=n),!s.cover&&n.itemProperties["cover-image"]&&(s.cover=n),n}),this.itemMap=tt(this.items,fd),this.itemMapByPath=tt(this.items,t=>s.getPathFromURL(t.src));for(const t in l){let e=t;for(;;){const n=this.itemMap[l[e]];if(!n)break;if(Sd[n.mediaType]){this.fallbackMap[t]=n.src;break}e=n.src}}this.spine=r.child("spine").child("itemref").asArray().map((t,e)=>{const n=t,i=n.getAttribute("idref"),o=s.itemMap[i];return o&&(o.itemRefElement=n,o.spineIndex=e),o});const h=r.child("spine").attribute("toc")[0];h&&(this.ncxToc=this.itemMap[h]);const c=r.child("spine").attribute("page-progression-direction")[0];c&&(this.pageProgression=n(c));const u=e?e.doc().child("encryption").child("EncryptedData").predicate(Xu.withChild("EncryptionMethod",Xu.withAttribute("Algorithm","http://www.idpf.org/2008/embedding"))).child("CipherData").child("CipherReference").attribute("URI"):[],d=r.child("bindings").child("mediaType").asArray();for(let t=0;t<d.length;t++){const e=d[t].getAttribute("handler"),n=d[t].getAttribute("media-type");n&&e&&this.itemMap[e]&&(this.bindings[n]=this.itemMap[e].src)}if(this.metadata=function(t,e){let n;if(e){n={};for(const t in md)n[t]=md[t];let t;for(;null!=(t=e.match(/^\s*([A-Z_a-z\u007F-\uFFFF][-.A-Z_a-z0-9\u007F-\uFFFF]*):\s*(\S+)/));)e=e.substr(t[0].length),n[t[1]]=t[2]}else n=md;const i=t=>{if(t){const e=t.match(/^\s*(([^:]*):)?(\S+)\s*$/);if(e){const t=e[2]?n[e[2]]:Ed;if(t)return t+e[3]}}return null};let o=1;const s=t.childElements().forEachNonNull(t=>{if("meta"==t.localName){const e=i(t.getAttribute("property"));if(e)return{name:e,value:t.textContent,id:t.getAttribute("id"),order:o++,refines:t.getAttribute("refines"),lang:null,scheme:i(t.getAttribute("scheme"))}}else if(t.namespaceURI==k.DC)return{name:md.dcterms+t.localName,order:o++,lang:t.getAttribute("xml:lang"),value:t.textContent,id:t.getAttribute("id"),refines:null,scheme:null};return null}),r=et(s,t=>t.refines),a=t=>(function(t,e){const n={};for(const i in t)n[i]=e(t[i],i);return n})(t,(t,e)=>t.map(t=>{const e={v:t.value,o:t.order};if(t.schema&&(e.s=t.scheme),t.id||t.lang){let n=r[t.id];if(n||t.lang){if(t.lang){const e={name:wd.language,value:t.lang,lang:null,id:null,refines:t.id,scheme:null,order:t.order};n?n.push(e):n=[e]}const i=et(n,t=>t.name);e.r=a(i)}}return e})),l=a(et(s,t=>t.refines?null:t.name));let h=null;l[wd.language]&&(h=l[wd.language][0].v);const c=t=>{for(const e in t){const n=t[e];n.sort(Nd(e,h));for(let t=0;t<n.length;t++){const e=n[t].r;e&&c(e)}}};return c(l),l}(r.child("metadata"),r.attribute("prefix")[0]),this.metadata[wd.language]&&(this.lang=this.metadata[wd.language][0].v),this.metadata[wd.layout]&&(this.prePaginated="pre-paginated"===this.metadata[wd.layout][0].v),!i){if(u.length>0&&this.uid){const t=gd(this.uid);for(let e=0;e<u.length;e++)this.store.deobfuscators[this.pubURL+u[e]]=t}return this.prePaginated&&this.assignAutoPages(),fi(!0)}const p=new G,f={};if(u.length>0&&this.uid){const t=`1040:${rd(this.uid)}`;for(let e=0;e<u.length;e++)f[u[e]]=t}for(let t=0;t<i.length;t++){const e=i[t],n=e.n;if(n){const t=decodeURI(n),i=this.itemMapByPath[t];let o=null;i&&(i.compressed=0!=e.m,i.compressedSize=e.c,i.mediaType&&(o=i.mediaType.replace(/\s+/g,"")));const s=f[t];(o||s)&&(p.append(n),p.append(" "),p.append(o||"application/octet-stream"),s&&(p.append(" "),p.append(s)),p.append("\n"))}}return s.assignAutoPages(),Li(o,Ri.DEFAULT,"POST",p.toString(),"text/plain")}assignAutoPages(){let t=0;for(const e of this.spine){const n=this.prePaginated?1:Math.ceil(e.compressedSize/1024);e.epage=t,e.epageCount=n,t+=n}this.epageCount=t,this.epageCountCallback&&this.epageCountCallback(this.epageCount)}setEPageCountMode(t){this.epageIsRenderedPage=t||this.prePaginated}countEPages(t){if(this.epageCountCallback=t,this.epageIsRenderedPage)return this.prePaginated&&0==this.epageCount&&this.assignAutoPages(),fi(!0);let e=0,n=0;const i=pi("countEPages");return i.loopWithFrame(t=>{if(n===this.spine.length)return void t.breakLoop();const i=this.spine[n++];i.epage=e,this.store.load(i.src).then(n=>{let o=1800;const s=n.lang||this.lang;s&&s.match(/^(ja|ko|zh)/)&&(o/=3),i.epageCount=Math.ceil(n.getTotalOffset()/o),e+=i.epageCount,this.epageCount=e,this.epageCountCallback&&this.epageCountCallback(this.epageCount),t.continueLoop()})}).thenFinish(i),i.result()}initWithChapters(t,e){this.itemMap={},this.itemMapByPath={},this.items=[],this.spine=this.items;const n=this.opfXML=new Hu(null,"",(new DOMParser).parseFromString("<spine></spine>","text/xml"));return t.forEach(t=>{const e=new pd;e.initWithParam(t);const i=n.document.createElement("itemref");i.setAttribute("idref",e.id),n.root.appendChild(i),e.itemRefElement=i,this.itemMap[e.id]=e;let o=this.getPathFromURL(t.url);null==o&&(o=t.url),this.itemMapByPath[o]=e,this.items.push(e)}),e?this.store.addDocument(t[0].url,e):fi(null)}initWithWebPubManifest(t,e){t.readingProgression&&(this.pageProgression=t.readingProgression),void 0===this.metadata&&(this.metadata={});const n=e&&e.title||t.name||t.metadata&&t.metadata.title;n&&(this.metadata[wd.title]=[{v:n}]);const i=this.getPathFromURL(this.pubURL);if(!t.readingOrder&&e&&null!==i){t.readingOrder=[encodeURI(i)];const n="[role=doc-toc] a[href],[role=directory] a[href],nav li a[href],.toc a[href],#toc a[href]";Array.from(e.querySelectorAll(n)).forEach(e=>{const n=I(L(e.getAttribute("href"),this.pubURL)),i=this.getPathFromURL(n),o=null!==i?encodeURI(i):n;-1==t.readingOrder.indexOf(o)&&t.readingOrder.push(o)})}const o=[];let s=0,r=-1;[t.readingOrder,t.resources].forEach(e=>{e instanceof Array&&e.forEach(e=>{const n=t.readingOrder.includes(e),i="string"==typeof e?e:e.url||e.href,a="string"==typeof e?"":e.encodingFormat||e.href&&e.type||"";if(n||"text/html"===a||"application/xhtml+xml"===a||/(^|\/)([^/]+\.(x?html|htm|xht)|[^/.]*)([#?]|$)/.test(i)){const t={url:L(O(i),this.pubURL),index:s++,startPage:null,skipPagesBefore:null};"contents"===e.rel&&-1===r&&(r=t.index),o.push(t)}})});const a=pi("initWithWebPubManifest");return this.initWithChapters(o).then(()=>{-1!==r&&(this.xhtmlToc=this.items[r]),this.xhtmlToc||(this.xhtmlToc=this.itemMapByPath[i]),a.finish(!0)}),a.result()}getCFI(t,e){const n=this.spine[t],i=pi("getCFI");return this.store.load(n.src).then(t=>{const o=t.getNodeByOffset(e);let s=null;if(o){const i=t.getNodeOffset(o,0,!1),r=e-i,a=new Et;a.prependPathFromNode(o,r,!1,null),n.itemRefElement&&a.prependPathFromNode(n.itemRefElement,0,!1,null),s=a.toString()}i.finish(s)}),i.result()}resolveFragment(t){const e=this;return gi("resolveFragment",n=>{if(!t)return void n.finish(null);let i,o=new Et;if(o.fromString(t),e.opfXML){const t=o.navigate(e.opfXML.document);if(1!=t.node.nodeType||t.after||!t.ref)return void n.finish(null);const s=t.node,r=s.getAttribute("idref");if("itemref"!=s.localName||!r||!e.itemMap[r])return void n.finish(null);i=e.itemMap[r],o=t.ref}else i=e.spine[0];e.store.load(i.src).then(t=>{const e=o.navigate(t.document),s=t.getNodeOffset(e.node,e.offset,e.after);n.finish({spineIndex:i.spineIndex,offsetInItem:s,pageIndex:-1})})},(e,n)=>{h.warn(n,"Cannot resolve fragment:",t),e.finish(null)})}resolveEPage(t){const e=this;return gi("resolveEPage",n=>{if(t<=0)return void n.finish({spineIndex:0,offsetInItem:0,pageIndex:-1});if(e.epageIsRenderedPage){let i=e.spine.findIndex(e=>0==e.epage&&0==e.epageCount||e.epage<=t&&e.epage+e.epageCount>t);-1==i&&(i=e.spine.length-1);let o=e.spine[i];o&&0!=o.epageCount||(o=e.spine[--i]);const s=Math.floor(t-o.epage);return void n.finish({spineIndex:i,offsetInItem:-1,pageIndex:s})}let i=Z(e.spine.length,n=>{const i=e.spine[n];return i.epage+i.epageCount>t});i==e.spine.length&&i--;const o=e.spine[i];e.store.load(o.src).then(e=>{(t-=o.epage)>o.epageCount&&(t=o.epageCount);let s=0;if(t>0){const n=e.getTotalOffset();s=Math.round(n*t/o.epageCount),s==n&&s--}n.finish({spineIndex:i,offsetInItem:s,pageIndex:-1})})},(e,n)=>{h.warn(n,"Cannot resolve epage:",t),e.finish(null)})}getEPageFromPosition(t){const e=this.spine[t.spineIndex];if(this.epageIsRenderedPage){return fi(e.epage+t.pageIndex)}if(t.offsetInItem<=0)return fi(e.epage);const n=pi("getEPage");return this.store.load(e.src).then(i=>{const o=i.getTotalOffset(),s=Math.min(o,t.offsetInItem);n.finish(e.epage+s*e.epageCount/o)}),n.result()}}const Td=(t,e)=>({page:t,position:{spineIndex:t.spineIndex,pageIndex:e,offsetInItem:t.offset}});class xd{constructor(t,e,n,i,o){this.opf=t,this.viewport=e,this.fontMapper=n,this.pageSheetSizeReporter=o,this.spineItems=[],this.spineItemLoadingContinuations=[],this.tocAutohide=!1,this.pref=wt(i),this.clientLayout=new Mu(e),this.counterStore=new xn(t.documentURLTransformer)}getPage(t){const e=this.spineItems[t.spineIndex];return e?e.pages[t.pageIndex]:null}getCurrentPageProgression(t){if(this.opf.pageProgression)return this.opf.pageProgression;{const e=this.spineItems[t?t.spineIndex:0];return e?e.instance.pageProgression:null}}finishPageContainer(t,e,n){e.container.style.display="none",e.container.style.visibility="visible",e.container.style.position="",e.container.style.top="",e.container.style.left="",e.container.setAttribute("data-vivliostyle-page-side",e.side);const i=t.pages[n];if(e.isFirstPage=0==t.item.spineIndex&&0==n,t.pages[n]=e,this.opf.epageIsRenderedPage){if(0==n&&t.item.spineIndex>0){const e=this.opf.spine[t.item.spineIndex-1];t.item.epage=e.epage+e.epageCount}t.item.epageCount=t.pages.length,this.opf.epageCount=this.opf.spine.reduce((t,e)=>t+e.epageCount,0),this.opf.epageCountCallback&&this.opf.epageCountCallback(this.opf.epageCount)}if(i)t.instance.viewport.contentContainer.replaceChild(e.container,i.container),i.dispatchEvent({type:"replaced",target:null,currentTarget:null,preventDefault:null,newPage:e});else{let i=null;if(n>0)i=t.pages[n-1].container.nextElementSibling;else for(let e=t.item.spineIndex+1;e<this.spineItems.length;e++){const t=this.spineItems[e];if(t&&t.pages[0]){i=t.pages[0].container;break}}t.instance.viewport.contentContainer.insertBefore(e.container,i)}this.pageSheetSizeReporter({width:t.instance.pageSheetWidth,height:t.instance.pageSheetHeight},t.instance.pageSheetSize,t.item.spineIndex,t.instance.pageNumberOffset+n)}renderSinglePage(t,e){const n=pi("renderSinglePage");let i=this.makePage(t,e);const o=this;return t.instance.layoutNextPage(i,e).then(s=>{const r=(e=s)?e.page-1:t.layoutPositions.length-1;o.finishPageContainer(t,i,r),o.counterStore.finishPage(i.spineIndex,r);let a=null;if(e){const n=t.layoutPositions[e.page];t.layoutPositions[e.page]=e,n&&t.pages[e.page]&&(e.isSamePosition(n)||(a=o.renderSinglePage(t,e)))}a||(a=fi(!0)),a.then(()=>{const s=o.counterStore.getUnresolvedRefsToPage(i);let a=0;n.loopWithFrame(t=>{if(a++,a>s.length)return void t.breakLoop();const e=s[a-1];e.refs=e.refs.filter(t=>!t.isResolved()),0!==e.refs.length?o.getPageViewItem(e.spineIndex).then(n=>{if(!n)return void t.continueLoop();o.counterStore.pushPageCounters(e.pageCounters),o.counterStore.pushReferencesToSolve(e.refs);const s=n.layoutPositions[e.pageIndex];o.renderSinglePage(n,s).then(e=>{o.counterStore.popPageCounters(),o.counterStore.popReferencesToSolve();const n=e.pageAndPosition.position;n.spineIndex===i.spineIndex&&n.pageIndex===r&&(i=e.pageAndPosition.page),t.continueLoop()})}):t.continueLoop()}).then(()=>{i.container.parentElement||(i=t.pages[r]),i.isLastPage=!e&&t.item.spineIndex===o.opf.spine.length-1,i.isLastPage&&(o.viewport,o.counterStore.finishLastPage(o.viewport)),n.finish({pageAndPosition:Td(i,r),nextLayoutPosition:e})})})}),n.result()}normalizeSeekPosition(t,e){let n=t.pageIndex,i=-1;if(n<0){i=t.offsetInItem;const o=Z(e.layoutPositions.length,t=>{return e.instance.getPosition(e.layoutPositions[t],!0)>i});n=o===e.layoutPositions.length?e.complete?e.layoutPositions.length-1:Number.POSITIVE_INFINITY:o-1}else n===Number.POSITIVE_INFINITY&&-1!==t.offsetInItem&&(i=t.offsetInItem);return{spineIndex:t.spineIndex,pageIndex:n,offsetInItem:i}}findPage(t,e){const n=this,i=pi("findPage");return n.getPageViewItem(t.spineIndex).then(o=>{if(!o)return void i.finish(null);let s,r=null;i.loopWithFrame(a=>{const l=n.normalizeSeekPosition(t,o);s=l.pageIndex,r=o.pages[s],r?a.breakLoop():o.complete?(s=o.layoutPositions.length-1,r=o.pages[s],a.breakLoop()):e?n.renderPage(l).then(t=>{t&&(r=t.page,s=t.position.pageIndex),a.breakLoop()}):i.sleep(100).then(()=>{a.continueLoop()})}).then(()=>{i.finish(Td(r,s))})}),i.result()}renderPage(t){const e=this,n=pi("renderPage");return e.getPageViewItem(t.spineIndex).then(i=>{if(!i)return void n.finish(null);const o=e.normalizeSeekPosition(t,i);let s=o.pageIndex;const r=o.offsetInItem;let a=i.pages[s];a?n.finish(Td(a,s)):n.loopWithFrame(t=>{if(s<i.layoutPositions.length)return void t.breakLoop();if(i.complete)return s=i.layoutPositions.length-1,void t.breakLoop();let n=i.layoutPositions[i.layoutPositions.length-1];e.renderSinglePage(i,n).then(e=>{const o=e.pageAndPosition.page;if(n=e.nextLayoutPosition,n){if(r>=0){if(i.instance.getPosition(n)>r)return a=o,s=i.layoutPositions.length-2,void t.breakLoop()}t.continueLoop()}else a=o,s=e.pageAndPosition.position.pageIndex,i.complete=!0,t.breakLoop()})}).then(()=>{a=a||i.pages[s];const t=i.layoutPositions[s];a?n.finish(Td(a,s)):e.renderSinglePage(i,t).then(t=>{t.nextLayoutPosition||(i.complete=!0),n.finish(t.pageAndPosition)})})}),n.result()}renderAllPages(){return this.renderPagesUpto({spineIndex:this.opf.spine.length-1,pageIndex:Number.POSITIVE_INFINITY,offsetInItem:-1},!1)}renderPagesUpto(t,e){const n=this,i=pi("renderPagesUpto");t||(t={spineIndex:0,pageIndex:0,offsetInItem:0});const o=t.spineIndex,s=t.pageIndex;let r,a=0;return e&&(a=o),i.loopWithFrame(e=>{const i={spineIndex:a,pageIndex:a===o?s:Number.POSITIVE_INFINITY,offsetInItem:a===o?t.offsetInItem:-1};n.renderPage(i).then(t=>{r=t,++a>o?e.breakLoop():e.continueLoop()})}).then(()=>{i.finish(r)}),i.result()}firstPage(t,e){return this.findPage({spineIndex:0,pageIndex:0,offsetInItem:-1},e)}lastPage(t,e){return this.findPage({spineIndex:this.opf.spine.length-1,pageIndex:Number.POSITIVE_INFINITY,offsetInItem:-1},e)}nextPage(t,e){const n=this;let i=t.spineIndex,o=t.pageIndex;const s=pi("nextPage");return n.getPageViewItem(i).then(t=>{if(t){if(t.complete&&o==t.layoutPositions.length-1){if(i>=n.opf.spine.length-1)return void s.finish(null);i++,o=0;const e=this.spineItems[i],r=e&&e.pages[0],a=t.pages[t.pages.length-1];r&&a&&r.side==a.side&&(e.pages.forEach(t=>{t.container&&t.container.remove()}),this.spineItems[i]=null,this.spineItemLoadingContinuations[i]=null)}else o++;n.findPage({spineIndex:i,pageIndex:o,offsetInItem:-1},e).thenFinish(s)}else s.finish(null)}),s.result()}previousPage(t,e){let n=t.spineIndex,i=t.pageIndex;if(0==i){if(0==n)return fi(null);n--,i=Number.POSITIVE_INFINITY}else i--;return this.findPage({spineIndex:n,pageIndex:i,offsetInItem:-1},e)}isRectoPage(e,n){const i=e.side===t.PageSide.LEFT,o=this.getCurrentPageProgression(n)===t.PageProgression.LTR;return!i&&o||i&&!o}getSpread(e,n){const i=pi("getCurrentSpread"),o=this.getPage(e);if(!o)return fi({left:null,right:null});const s=o.side===t.PageSide.LEFT;let r;return r=this.isRectoPage(o,e)?this.previousPage(e,n):this.nextPage(e,n),r.then(t=>{const n=this.getPage(e);let o=t&&t.page;o&&o.side===n.side&&(o=null),s?i.finish({left:n,right:o}):i.finish({left:o,right:n})}),i.result()}nextSpread(t,e){const n=this.getPage(t);if(!n)return fi(null);const i=this.isRectoPage(n,t),o=this.nextPage(t,e);if(i)return o;{const t=this;return o.thenAsync(i=>{if(i){if(i.page.side===n.side)return o;const s=t.nextPage(i.position,e);return s.thenAsync(t=>t?s:o)}return fi(null)})}}previousSpread(t,e){const n=this.getPage(t);if(!n)return fi(null);const i=this.isRectoPage(n,t),o=this.previousPage(t,e),s=n.container.previousElementSibling;if(i){const t=this;return o.thenAsync(i=>i?i.page.side===n.side?o:i.page.container!==s?o:t.previousPage(i.position,e):fi(null))}return o}navigateToEPage(t,e,n){const i=pi("navigateToEPage"),o=this;return this.opf.resolveEPage(t).then(t=>{t?o.findPage(t,n).thenFinish(i):i.finish(null)}),i.result()}navigateToFragment(t,e,n){const i=pi("navigateToCFI"),o=this;return o.opf.resolveFragment(t).then(t=>{t?o.findPage(t,n).thenFinish(i):i.finish(null)}),i.result()}navigateTo(t,e,n){h.debug("Navigate to",t);let i=this.opf.getPathFromURL(I(t));if(!i){if(this.opf.opfXML&&t.match(/^#epubcfi\(/))i=this.opf.getPathFromURL(this.opf.opfXML.url);else if("#"===t.charAt(0)){const e=this.opf.documentURLTransformer.restoreURL(t);this.opf.opfXML?(i=this.opf.getPathFromURL(e[0]),null==i&&(i=e[0])):i=e[0],t=e[0]+(e[1]?`#${e[1]}`:"")}if(null==i)return fi(null)}const o=this.opf.itemMapByPath[i];if(!o){if(this.opf.opfXML&&i==this.opf.getPathFromURL(this.opf.opfXML.url)){const i=t.indexOf("#");if(i>=0)return this.navigateToFragment(t.substr(i+1),e,n)}return fi(null)}const s=pi("navigateTo"),r=this;return r.getPageViewItem(o.spineIndex).then(i=>{if(!i)return void s.finish(null);const a=i.xmldoc.getElement(t);a?r.findPage({spineIndex:o.spineIndex,pageIndex:-1,offsetInItem:i.xmldoc.getElementOffset(a)},n).thenFinish(s):e.spineIndex!==o.spineIndex?r.findPage({spineIndex:o.spineIndex,pageIndex:0,offsetInItem:-1},n).thenFinish(s):s.finish(null)}),s.result()}makePage(e,n){const i=e.instance.viewport,o=i.document.createElement("div");o.setAttribute("data-vivliostyle-page-container","true"),o.setAttribute("role","region"),o.style.position="absolute",o.style.top="0",o.style.left="0",t.isDebug||(o.style.visibility="hidden",o.setAttribute("aria-hidden","true")),i.layoutBox.appendChild(o);const s=i.document.createElement("div");s.setAttribute("data-vivliostyle-bleed-box","true"),o.appendChild(s);const r=new Kr(o,s);if(r.spineIndex=e.item.spineIndex,r.position=n,r.offset=e.instance.getPosition(n),0===r.offset){const t=this.opf.documentURLTransformer.transformFragment("",e.item.src);s.setAttribute("id",t),r.registerElementWithId(s,t)}if(i!==this.viewport){const t=St(this.viewport.width,this.viewport.height,i.width,i.height),e=mo(null,new hi(t,null),"");r.delayedItems.push(new Wr(o,"transform",e))}return r}makeObjectView(t,e,n,i){let o=e.getAttribute("data"),s=null;if(o){o=L(o,t.url);let n=e.getAttribute("media-type");if(!n){const t=this.opf.getPathFromURL(o);if(t){const e=this.opf.itemMapByPath[t];e&&(n=e.mediaType)}}if(n){const t=this.opf.bindings[n];if(t){s=this.viewport.document.createElement("iframe"),s.style.border="none";const i=Y(o),r=Y(n),a=new G;a.append(t),a.append("?src="),a.append(i),a.append("&type="),a.append(r);for(let t=e.firstChild;t;t=t.nextSibling)if(1==t.nodeType){const e=t;if("param"==e.localName&&e.namespaceURI==k.XHTML){const t=e.getAttribute("name"),n=e.getAttribute("value");t&&n&&(a.append("&"),a.append(encodeURIComponent(t)),a.append("="),a.append(encodeURIComponent(n)))}}s.setAttribute("src",a.toString());const l=e.getAttribute("width");l&&s.setAttribute("width",l);const h=e.getAttribute("height");h&&s.setAttribute("height",h)}}}return s||(s=this.viewport.document.createElement("span"),s.setAttribute("data-adapt-process-children","true")),fi(s)}makeMathJaxView(t,e,n,i){const o=bd();if(o){const i=n.ownerDocument,s=i.createElement("span");n.appendChild(s);const r=i.importNode(e,!0);this.resolveURLsInMathML(r,t),s.appendChild(r);const a=o.queue;a.Push(["Typeset",o,s]);const l=pi("makeMathJaxView"),h=l.suspend();return a.Push(()=>{h.schedule(s)}),l.result()}return fi(null)}resolveURLsInMathML(t,e){if(null!=t){if(1===t.nodeType&&"mglyph"===t.tagName){const n=Array.from(t.attributes);for(const i of n){if("src"!==i.name)continue;const n=L(i.nodeValue,e.url);i.namespaceURI?t.setAttributeNS(i.namespaceURI,i.name,n):t.setAttribute(i.name,n)}}t.firstChild&&this.resolveURLsInMathML(t.firstChild,e),t.nextSibling&&this.resolveURLsInMathML(t.nextSibling,e)}}makeSSEView(t,e,n,i){const o=n?n.ownerDocument:this.viewport.document,s=e.localName;let r;switch(s){case"t":case"tab":case"ec":case"nt":case"fraction":case"comment":case"mark":r="span";break;case"ruby":case"rp":case"rt":r=s;break;default:r="div"}const a=o.createElement(r);return a.setAttribute("data-adapt-process-children","true"),fi(a)}makeCustomRenderer(t){const e=this;return(n,i,o)=>"object"==n.localName&&n.namespaceURI==k.XHTML?e.makeObjectView(t,n,i,o):n.namespaceURI==k.MATHML?e.makeMathJaxView(t,n,i,o):n.namespaceURI==k.SSE?e.makeSSEView(t,n,i,o):n.dataset&&"true"==n.dataset.mathTypeset?e.makeMathJaxView(t,n,i,o):fi(null)}getPageViewItem(t){const e=this;if(-1===t||t>=e.opf.spine.length)return fi(null);let n=e.spineItems[t];if(n)return fi(n);const i=pi("getPageViewItem");let o=this.spineItemLoadingContinuations[t];if(o){const t=i.suspend();return o.push(t),i.result()}o=this.spineItemLoadingContinuations[t]=[];const s=e.opf.spine[t],r=e.opf.store;return r.load(s.src).then(a=>{s.title=a.document.title;const l=r.getStyleForDoc(a),h=e.makeCustomRenderer(a);let c=e.viewport;const u=l.sizeViewport(c.width,c.height,c.fontSize,e.pref);u.width==c.width&&u.height==c.height&&u.fontSize==c.fontSize||(c=new Uu(c.window,u.fontSize,c.root,u.width,u.height));const d=e.spineItems[t-1];let p;null!==s.startPage?p=s.startPage-1:(!(t>0)||d&&d.complete?p=d?d.instance.pageNumberOffset+d.pages.length:0:(p=s.epage||t,e.opf.prePaginated||p%2!=0||p++),null!==s.skipPagesBefore&&(p+=s.skipPagesBefore)),e.counterStore.forceSetPageCounter(p);const f=new Qu(l,a,e.opf.lang,c,e.clientLayout,e.fontMapper,h,e.opf.fallbackMap,p,e.opf.documentURLTransformer,e.counterStore,e.opf.pageProgression);f.pref=e.pref;const g=e.opf.metadata&&e.opf.metadata[wd.title];f.pubTitle=g&&g[0]&&g[0].v||"",f.docTitle=s.title||"",f.init().then(()=>{n={item:s,xmldoc:a,instance:f,layoutPositions:[null],pages:[],complete:!1},e.spineItems[t]=n,i.finish(n),o.forEach(t=>{t.schedule(n)})})}),i.result()}removeRenderedPages(){const t=this.spineItems;for(const e of t)e&&e.pages.splice(0);this.viewport.clear()}hasAutoSizedPages(){const t=this.spineItems;for(const e of t)if(e){const t=e.pages;for(const e of t)if(e.isAutoPageWidth&&e.isAutoPageHeight)return!0}return!1}hasPages(){return this.spineItems.some(t=>t&&t.pages.length>0)}showTOC(t){const e=this.opf,n=e.xhtmlToc||e.ncxToc;if(this.tocAutohide=t,!n)return fi(null);if(this.tocView&&this.tocView.page)return this.tocView.page.container.style.visibility="visible",this.tocView.page.container.setAttribute("aria-hidden","false"),fi(this.tocView.page);const i=pi("showTOC");this.tocView||(this.tocView=new cd(e.store,n.src,e.lang,this.clientLayout,this.fontMapper,this.pref,this,e.fallbackMap,e.documentURLTransformer,this.counterStore));const o=this.viewport,s=Math.min(350,Math.round(.67*o.width)-16),r=o.height-6,a=o.document.createElement("div");return o.root.appendChild(a),a.style.visibility="hidden",a.style.width=`${s+10}px`,a.style.maxHeight=`${r}px`,a.setAttribute("data-vivliostyle-toc-box","true"),a.setAttribute("role","navigation"),this.tocView.showTOC(a,o,s,r,this.viewport.fontSize).then(t=>{a.style.visibility="visible",a.setAttribute("aria-hidden","false"),i.finish(t)}),i.result()}hideTOC(){this.tocView&&this.tocView.hideTOC()}isTOCVisible(){return!!this.tocView&&this.tocView.isTOCVisible()}}const Id="data-vivliostyle-viewer-status",vd="data-vivliostyle-spread-view";var Pd,Rd;!function(t){t.SINGLE_PAGE="singlePage",t.SPREAD="spread",t.AUTO_SPREAD="autoSpread"}(Pd||(Pd={}));class Ad{constructor(e,n,i,o){this.window=e,this.viewportElement=n,this.instanceId=i,this.callbackFn=o,this.pageSheetSizeAlreadySet=!1,this.renderTask=null;const s=this;n.setAttribute("data-vivliostyle-viewer-viewport",!0),t.isDebug&&n.setAttribute("data-vivliostyle-debug",!0),n.setAttribute(Id,"loading");const r=e.document;this.fontMapper=new Ec(r.head,n),this.init(),this.kick=()=>{},this.sendCommand=()=>{},this.resizeListener=()=>{s.needResize=!0,s.kick()},this.pageReplacedListener=this.pageReplacedListener.bind(this),this.hyperlinkListener=t=>{},this.pageRuleStyleElement=r.getElementById("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=t.ReadyState.LOADING,this.packageURL=[],this.opf=null,this.haveZipMetadata=!1,this.touchActive=!1,this.touchX=0,this.touchY=0,this.needResize=!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=Pd.SINGLE_PAGE,this.waitForLoading=!1,this.renderAllPages=!0,this.pref={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},this.pageSizes=[]}addLogListeners(){const t=r;h.addListener(t.DEBUG,t=>{this.callback({t:"debug",content:t})}),h.addListener(t.INFO,t=>{this.callback({t:"info",content:t})}),h.addListener(t.WARN,t=>{this.callback({t:"warn",content:t})}),h.addListener(t.ERROR,t=>{this.callback({t:"error",content:t})})}callback(t){t.i=this.instanceId,this.callbackFn(t)}setReadyState(t){this.readyState!==t&&(this.readyState=t,this.viewportElement.setAttribute(Id,t),this.callback({t:"readystatechange"}))}loadPublication(e){y.registerStartTiming("beforeRender"),this.setReadyState(t.ReadyState.LOADING);const n=e.url,i=e.fragment,o=!!e.zipmeta,s=e.authorStyleSheet,r=e.userStyleSheet;this.viewport=null;const a=pi("loadPublication"),l=this;return l.configure(e).then(()=>{const t=new dd;t.init(s,r).then(()=>{const e=L(O(n),l.window.location.href);l.packageURL=[e],t.loadPubDoc(e,o).then(t=>{t?(l.opf=t,l.render(i).then(()=>{a.finish(!0)})):a.finish(!1)})})}),a.result()}loadXML(e){y.registerStartTiming("beforeRender"),this.setReadyState(t.ReadyState.LOADING);const n=e.url,i=e.document,o=e.fragment,s=e.authorStyleSheet,r=e.userStyleSheet;this.viewport=null;const a=pi("loadXML"),l=this;return l.configure(e).then(()=>{const t=new dd;t.init(s,r).then(()=>{const e=n.map((t,e)=>({url:L(O(t.url),l.window.location.href),index:e,startPage:t.startPage,skipPagesBefore:t.skipPagesBefore}));l.packageURL=e.map(t=>t.url),l.opf=new Cd(t,""),l.opf.initWithChapters(e,i).then(()=>{l.render(o).then(()=>{a.finish(!0)})})})}),a.result()}render(t){this.cancelRenderingTask();const e=this;let n;return n=t?this.opf.resolveFragment(t).thenAsync(t=>(e.pagePosition=t,fi(!0))):fi(!0),n.thenAsync(()=>(y.registerEndTiming("beforeRender"),e.resize()))}resolveLength(t){const e=parseFloat(t);let n;if("string"==typeof t&&(n=t.match(/[a-z]+$/))){const t=n[0];if("em"===t||"rem"===t)return e*this.fontSize;if("ex"===t)return e*Pt.ex*this.fontSize/Pt.em;const i=Pt[t];if(i)return e*i}return e}configure(t){if("boolean"==typeof t.autoresize&&(t.autoresize?(this.viewportSize=null,this.window.addEventListener("resize",this.resizeListener,!1),this.needResize=!0):this.window.removeEventListener("resize",this.resizeListener,!1)),"number"==typeof t.fontSize){const e=t.fontSize;e>=5&&e<=72&&this.fontSize!=e&&(this.fontSize=e,this.needResize=!0)}if("object"==typeof t.viewport&&t.viewport){const e=t.viewport,n={marginLeft:this.resolveLength(e["margin-left"])||0,marginRight:this.resolveLength(e["margin-right"])||0,marginTop:this.resolveLength(e["margin-top"])||0,marginBottom:this.resolveLength(e["margin-bottom"])||0,width:this.resolveLength(e.width)||0,height:this.resolveLength(e.height)||0};(n.width>=200||n.height>=200)&&(this.window.removeEventListener("resize",this.resizeListener,!1),this.viewportSize=n,this.needResize=!0)}return"boolean"==typeof t.hyphenate&&(this.pref.hyphenate=t.hyphenate,this.needResize=!0),"boolean"==typeof t.horizontal&&(this.pref.horizontal=t.horizontal,this.needResize=!0),"boolean"==typeof t.nightMode&&(this.pref.nightMode=t.nightMode,this.needResize=!0),"number"==typeof t.lineHeight&&(this.pref.lineHeight=t.lineHeight,this.needResize=!0),"number"==typeof t.columnWidth&&(this.pref.columnWidth=t.columnWidth,this.needResize=!0),"string"==typeof t.fontFamily&&(this.pref.fontFamily=t.fontFamily,this.needResize=!0),"boolean"==typeof t.load&&(this.waitForLoading=t.load),"boolean"==typeof t.renderAllPages&&(this.renderAllPages=t.renderAllPages),"string"==typeof t.userAgentRootURL&&(P(t.userAgentRootURL.replace(/resources\/?$/,"")),A(t.userAgentRootURL)),"string"==typeof t.rootURL&&(P(t.rootURL),A(`${v}resources/`)),"string"==typeof t.pageViewMode&&t.pageViewMode!==this.pageViewMode&&(this.pageViewMode=t.pageViewMode,this.needResize=!0),"number"==typeof t.pageBorder&&t.pageBorder!==this.pref.pageBorder&&(this.viewport=null,this.pref.pageBorder=t.pageBorder,this.needResize=!0),"number"==typeof t.zoom&&t.zoom!==this.zoom&&(this.zoom=t.zoom,this.needRefresh=!0),"boolean"==typeof t.fitToScreen&&t.fitToScreen!==this.fitToScreen&&(this.fitToScreen=t.fitToScreen,this.needRefresh=!0),"object"==typeof t.defaultPaperSize&&"number"==typeof t.defaultPaperSize.width&&"number"==typeof t.defaultPaperSize.height&&(this.viewport=null,this.pref.defaultPaperSize=t.defaultPaperSize,this.needResize=!0),this.configurePlugins(t),fi(!0)}configurePlugins(e){f(t.HOOKS.CONFIGURATION).forEach(t=>{const n=t(e);this.needResize=n.needResize||this.needResize,this.needRefresh=n.needRefresh||this.needRefresh})}pageReplacedListener(t){const e=this.currentPage,n=this.currentSpread,i=t.target;n?n.left!==i&&n.right!==i||this.showCurrent(t.newPage):e===t.target&&this.showCurrent(t.newPage)}forCurrentPages(t){const e=[];this.currentPage&&e.push(this.currentPage),this.currentSpread&&(e.push(this.currentSpread.left),e.push(this.currentSpread.right)),e.forEach(e=>{e&&t(e)})}removePageListeners(){this.forCurrentPages(t=>{t.removeEventListener("hyperlink",this.hyperlinkListener,!1),t.removeEventListener("replaced",this.pageReplacedListener,!1)})}hidePages(){this.removePageListeners(),this.forCurrentPages(t=>{V(t.container,"display","none"),t.container.setAttribute("aria-hidden","true")}),this.currentPage=null,this.currentSpread=null}showSinglePage(t){t.addEventListener("hyperlink",this.hyperlinkListener,!1),t.addEventListener("replaced",this.pageReplacedListener,!1),V(t.container,"visibility","visible"),V(t.container,"display","block"),t.container.setAttribute("aria-hidden","false")}showPage(t){this.hidePages(),this.currentPage=t,t.container.style.marginLeft="",t.container.style.marginRight="",this.showSinglePage(t)}showSpread(t){if(this.hidePages(),this.currentSpread=t,t.left&&t.right){let e=parseFloat(t.left.container.style.width),n=parseFloat(t.right.container.style.width);e&&n&&e!==n&&(e<n?t.left.container.style.marginLeft=`${n-e}px`:t.right.container.style.marginRight=`${e-n}px`)}t.left&&(this.showSinglePage(t.left),t.right?t.left.container.removeAttribute("data-vivliostyle-unpaired-page"):t.left.container.setAttribute("data-vivliostyle-unpaired-page",!0)),t.right&&(this.showSinglePage(t.right),t.left?t.right.container.removeAttribute("data-vivliostyle-unpaired-page"):t.right.container.setAttribute("data-vivliostyle-unpaired-page",!0))}reportPosition(){const t=pi("reportPosition"),e=this;return e.pagePosition,e.opf.getCFI(this.pagePosition.spineIndex,this.pagePosition.offsetInItem).then(n=>{const i=e.currentPage;(e.waitForLoading&&i.fetchers.length>0?vi(i.fetchers):fi(!0)).then(()=>{e.sendLocationNotification(i,n).thenFinish(t)})}),t.result()}createViewport(){const t=this.viewportElement;if(this.viewportSize){const e=this.viewportSize;return t.style.marginLeft=`${e.marginLeft}px`,t.style.marginRight=`${e.marginRight}px`,t.style.marginTop=`${e.marginTop}px`,t.style.marginBottom=`${e.marginBottom}px`,new Uu(this.window,this.fontSize,t,e.width,e.height)}return new Uu(this.window,this.fontSize,t)}resolveSpreadView(t){switch(this.pageViewMode){case Pd.SINGLE_PAGE:return!1;case Pd.SPREAD:return!0;case Pd.AUTO_SPREAD:default:return t.width/t.height>=1.45&&t.width>800}}updateSpreadView(t){this.pref.spreadView=t,this.viewportElement.setAttribute(vd,t.toString())}sizeIsGood(){const t=this.createViewport(),e=this.resolveSpreadView(t),n=this.pref.spreadView!==e;return this.updateSpreadView(e),!(this.viewportSize||!this.viewport||this.viewport.fontSize!=this.fontSize)&&(!n&&t.width==this.viewport.width&&t.height==this.viewport.height||(!(n||t.width!=this.viewport.width||t.height==this.viewport.height||!/Android|iPhone|iPad|iPod/.test(navigator.userAgent))||!(!this.opfView||!this.opfView.hasPages()||this.opfView.hasAutoSizedPages())&&(this.viewport.width=t.width,this.viewport.height=t.height,this.needRefresh=!0,!0)))}setPageSize(t,e,n,i){this.pageSizes[i]=t,this.setPageSizePageRules(e,n,i)}setPageSizePageRules(t,e,n){if(!this.pageSheetSizeAlreadySet&&this.pageRuleStyleElement){let e="";Object.keys(t).forEach(n=>{e+=`@page ${n}{margin:0;size:`;const i=t[n];e+=`${i.width}px ${i.height}px;}`}),this.pageRuleStyleElement.textContent=e,this.pageSheetSizeAlreadySet=!0}}removePageSizePageRules(){this.pageRuleStyleElement&&(this.pageRuleStyleElement.textContent="",this.pageSheetSizeAlreadySet=!1)}reset(){let t=!1,e=!1;this.opfView&&(t=this.opfView.isTOCVisible(),e=this.opfView.tocAutohide,this.opfView.hideTOC(),this.opfView.removeRenderedPages()),this.removePageSizePageRules(),this.viewport=this.createViewport(),this.viewport.resetZoom(),this.opfView=new xd(this.opf,this.viewport,this.fontMapper,this.pref,this.setPageSize.bind(this)),t&&this.sendCommand({a:"toc",v:"show",autohide:e})}showCurrent(t,e){this.needRefresh=!1,this.removePageListeners();const n=this;return this.pref.spreadView?this.opfView.getSpread(this.pagePosition,e).thenAsync(e=>(n.showSpread(e),n.setSpreadZoom(e),n.currentPage=t,fi(null))):(this.showPage(t),this.setPageZoom(t),this.currentPage=t,fi(null))}setPageZoom(t){const e=this.getAdjustedZoomFactor(t.dimensions);this.viewport.zoom(t.dimensions.width,t.dimensions.height,e)}setSpreadZoom(t){const e=this.getSpreadDimensions(t);this.viewport.zoom(e.width,e.height,this.getAdjustedZoomFactor(e))}getAdjustedZoomFactor(t){return this.fitToScreen?this.calculateZoomFactorToFitInsideViewPort(t):this.zoom}getSpreadDimensions(t){let e=0,n=0;return t.left&&(e+=t.left.dimensions.width,n=t.left.dimensions.height),t.right&&(e+=t.right.dimensions.width,n=Math.max(n,t.right.dimensions.height)),t.left&&t.right&&(e+=2*this.pref.pageBorder,e+=Math.abs(t.left.dimensions.width-t.right.dimensions.width)),{width:e,height:n}}queryZoomFactor(t){if(!this.currentPage)throw new Error("no page exists.");switch(t){case Rd.FIT_INSIDE_VIEWPORT:{let t;return this.pref.spreadView?(this.currentSpread,t=this.getSpreadDimensions(this.currentSpread)):t=this.currentPage.dimensions,this.calculateZoomFactorToFitInsideViewPort(t)}default:throw new Error(`unknown zoom type: ${t}`)}}calculateZoomFactorToFitInsideViewPort(t){const e=this.viewport.width/t.width,n=this.viewport.height/t.height;return Math.min(e,n)}cancelRenderingTask(){this.renderTask&&this.renderTask.interrupt(new Ld),this.renderTask=null}resize(){if(this.needResize=!1,this.needRefresh=!1,this.sizeIsGood())return fi(!0);const e=this;this.setReadyState(t.ReadyState.LOADING),this.cancelRenderingTask();const n=di().getScheduler().run(()=>gi("resize",i=>{e.opf?(e.renderTask=n,y.registerStartTiming("render (resize)"),e.reset(),e.pagePosition&&(0==e.pagePosition.pageIndex&&0==e.pagePosition.offsetInItem||(e.pagePosition.pageIndex=-1)),e.opf.setEPageCountMode(e.renderAllPages),e.opfView.renderPagesUpto(e.pagePosition,!e.renderAllPages).then(o=>{o?(e.pagePosition=o.position,e.showCurrent(o.page,!0).then(()=>{e.setReadyState(t.ReadyState.INTERACTIVE),e.opf.countEPages(t=>{const n={t:"nav",epageCount:t,first:e.currentPage.isFirstPage,last:e.currentPage.isLastPage,metadata:e.opf.metadata,docTitle:e.opf.spine[e.pagePosition.spineIndex].title};(e.currentPage.isFirstPage||0==e.pagePosition.pageIndex&&e.opf.spine[e.pagePosition.spineIndex].epage)&&(n.epage=e.opf.spine[e.pagePosition.spineIndex].epage),e.callback(n)}).then(()=>{e.reportPosition().then(o=>{(e.renderAllPages?e.opfView.renderAllPages():fi(null)).then(()=>{e.renderTask===n&&(e.renderTask=null),y.registerEndTiming("render (resize)"),e.renderAllPages&&e.setReadyState(t.ReadyState.COMPLETE),e.callback({t:"loaded"}),i.finish(o)})})})})):i.finish(!1)})):i.finish(!1)},(t,e)=>{if(!(e instanceof Ld))throw e;y.registerEndTiming("render (resize)"),h.debug(e.message)}));return fi(!0)}sendLocationNotification(t,e){const n=pi("sendLocationNotification"),i={t:"nav",first:t.isFirstPage,last:t.isLastPage,metadata:this.opf.metadata,docTitle:this.opf.spine[t.spineIndex].title},o=this;return this.opf.getEPageFromPosition(o.pagePosition).then(t=>{i.epage=t,i.epageCount=o.opf.epageCount,e&&(i.cfi=e),o.callback(i),n.finish(!0)}),n.result()}getCurrentPageProgression(){return this.opfView?this.opfView.getCurrentPageProgression(this.pagePosition):null}moveTo(e){let n;const i=this;if(this.readyState!==t.ReadyState.COMPLETE&&"next"!==e.where&&this.setReadyState(t.ReadyState.LOADING),"string"==typeof e.where){let t;switch(e.where){case"next":t=this.pref.spreadView?this.opfView.nextSpread:this.opfView.nextPage;break;case"previous":t=this.pref.spreadView?this.opfView.previousSpread:this.opfView.previousPage;break;case"last":t=this.opfView.lastPage;break;case"first":t=this.opfView.firstPage;break;default:return fi(!0)}t&&(n=()=>t.call(i.opfView,i.pagePosition,!i.renderAllPages))}else if("number"==typeof e.epage){const t=e.epage;n=()=>i.opfView.navigateToEPage(t,i.pagePosition,!i.renderAllPages)}else{if("string"!=typeof e.url)return fi(!0);{const t=e.url;n=()=>i.opfView.navigateTo(t,i.pagePosition,!i.renderAllPages)}}const o=pi("moveTo");return n.call(i.opfView).then(e=>{let n;if(e){i.pagePosition=e.position;const t=pi("moveTo.showCurrent");n=t.result(),i.showCurrent(e.page,!i.renderAllPages).then(()=>{i.reportPosition().thenFinish(t)})}else n=fi(!0);n.then(e=>{i.readyState===t.ReadyState.LOADING&&i.setReadyState(t.ReadyState.INTERACTIVE),o.finish(e)})}),o.result()}showTOC(t){const e=!!t.autohide,n=t.v,i=this.opfView.isTOCVisible(),o=e!=this.opfView.tocAutohide&&"hide"!=n;if(i){if("show"==n&&!o)return fi(!0)}else if("hide"==n)return fi(!0);if(i&&"show"!=n)return this.opfView.hideTOC(),fi(!0);{const t=this,n=pi("showTOC");return this.opfView.showTOC(e).then(i=>{if(i){if(o&&(i.listeners={}),e){const e=()=>{t.opfView.hideTOC()};i.addEventListener("hyperlink",e,!1)}i.addEventListener("hyperlink",t.hyperlinkListener,!1)}n.finish(!0)}),n.result()}}runCommand(t){const e=this,n=t.a||"";return gi("runCommand",i=>{const o=e.actions[n];o?o.call(e,t).then(()=>{e.callback({t:"done",a:n}),i.finish(!0)}):(h.error("No such action:",n),i.finish(!0))},(t,e)=>{h.error(e,"Error during action:",n),t.finish(!0)})}initEmbed(t){let e=Od(t),n=null;const i=this;mi(()=>{const t=pi("commandLoop"),o=di().getScheduler();return i.hyperlinkListener=t=>{const e=t,n="#"===e.href.charAt(0)||i.packageURL.some(t=>e.href.substr(0,t.length)==t);if(n){t.preventDefault();const s={t:"hyperlink",href:e.href,internal:n};o.run(()=>(i.callback(s),fi(!0)))}},t.loopWithFrame(t=>{if(i.needResize)i.resize().then(()=>{t.continueLoop()});else if(i.needRefresh)i.currentPage&&i.showCurrent(i.currentPage).then(()=>{t.continueLoop()});else if(e){const n=e;e=null,i.runCommand(n).then(()=>{t.continueLoop()})}else{const e=pi("waitForCommand");n=e.suspend(self),e.result().then(()=>{t.continueLoop()})}}).thenFinish(t),t.result()}),i.kick=()=>{const t=n;t&&(n=null,t.schedule(!0))},i.sendCommand=t=>!e&&(e=Od(t),i.kick(),!0),this.window.adapt_command=i.sendCommand}}!function(t){t.FIT_INSIDE_VIEWPORT="fit inside viewport"}(Rd||(Rd={}));class Ld extends Error{constructor(){super(),this.name="RenderingCanceledError",this.message="Page rendering has been canceled",Object.setPrototypeOf(this,Ld.prototype),this.stack=(new Error).stack}}function Od(t){return"string"==typeof t?x(t):t}const kd=t.PageProgression;function Fd(t){const e={};return Object.keys(t).forEach(n=>{const i=t[n];switch(n){case"autoResize":e.autoresize=i;break;case"pageBorderWidth":e.pageBorder=i;break;default:e[n]=i}}),e}class Dd{constructor(t,n){this.settings=t,this.initialized=!1,e(t.debug),this.adaptViewer_=new Ad(t.window||window,t.viewportElement,"main",this.dispatcher.bind(this)),this.options={autoResize:!0,fontSize:16,pageBorderWidth:1,renderAllPages:!0,pageViewMode:Pd.AUTO_SPREAD,zoom:1,fitToScreen:!1,defaultPaperSize:void 0},n&&this.setOptions(n),this.eventTarget=new nt,Object.defineProperty(this,"readyState",{get(){return this.adaptViewer_.readyState}})}setOptions(t){const e=Object.assign({a:"configure"},Fd(t));this.adaptViewer_.sendCommand(e),Object.assign(this.options,t)}dispatcher(t){const e={type:t.t},n=t;Object.keys(n).forEach(t=>{"t"!==t&&(e[t]=n[t])}),this.eventTarget.dispatchEvent(e)}addListener(t,e){this.eventTarget.addEventListener(t,e,!1)}removeListener(t,e){this.eventTarget.removeEventListener(t,e,!1)}loadDocument(t,e,n){t||this.eventTarget.dispatchEvent({type:"error",content:"No URL specified"}),this.loadDocumentOrPublication(t,null,e,n)}loadPublication(t,e,n){t||this.eventTarget.dispatchEvent({type:"error",content:"No URL specified"}),this.loadDocumentOrPublication(null,t,e,n)}loadDocumentOrPublication(t,e,n,i){const o=n||{};function s(t){return t?t.map(t=>({url:t.url||null,text:t.text||null})):void 0}const r=s(o.authorStyleSheet),a=s(o.userStyleSheet);i&&Object.assign(this.options,i);const l=Object.assign({a:t?"loadXML":"loadPublication",userAgentRootURL:this.settings.userAgentRootURL,url:_d(t)||e,document:o.documentObject,fragment:o.fragment,authorStyleSheet:r,userStyleSheet:a},Fd(this.options));this.initialized?this.adaptViewer_.sendCommand(l):(this.initialized=!0,this.adaptViewer_.initEmbed(l))}getCurrentPageProgression(){return this.adaptViewer_.getCurrentPageProgression()}resolveNavigation(e){switch(e){case t.Navigation.LEFT:return this.getCurrentPageProgression()===kd.LTR?t.Navigation.PREVIOUS:t.Navigation.NEXT;case t.Navigation.RIGHT:return this.getCurrentPageProgression()===kd.LTR?t.Navigation.NEXT:t.Navigation.PREVIOUS;default:return e}}navigateToPage(e,n){e===t.Navigation.EPAGE?this.adaptViewer_.sendCommand({a:"moveTo",epage:n}):this.adaptViewer_.sendCommand({a:"moveTo",where:this.resolveNavigation(e)})}navigateToInternalUrl(t){this.adaptViewer_.sendCommand({a:"moveTo",url:t})}isTOCVisible(){return this.adaptViewer_.opfView&&this.adaptViewer_.opfView.opf&&(this.adaptViewer_.opfView.opf.xhtmlToc||this.adaptViewer_.opfView.opf.ncxToc)?!!this.adaptViewer_.opfView.isTOCVisible():null}showTOC(t,e){const n=null==t?"toggle":t?"show":"hide";this.adaptViewer_.sendCommand({a:"toc",v:n,autohide:e})}queryZoomFactor(t){return this.adaptViewer_.queryZoomFactor(t)}getPageSizes(){return this.adaptViewer_.pageSizes}}function _d(t){function e(t){return"number"==typeof t?t:null}function n(t){return"string"==typeof t?{url:t,startPage:null,skipPagesBefore:null}:{url:t.url,startPage:e(t.startPage),skipPagesBefore:e(t.skipPagesBefore)}}return Array.isArray(t)?t.map(n):t?[n(t)]:null}var Bd;(Bd=t.Navigation||(t.Navigation={})).PREVIOUS="previous",Bd.NEXT="next",Bd.LEFT="left",Bd.RIGHT="right",Bd.FIRST="first",Bd.LAST="last",Bd.EPAGE="epage";const Md=Rd,Ud=Pd,Vd={CoreViewer:Dd,PageViewMode:Ud,ZoomType:Md};y.forceRegisterEndTiming("load_vivliostyle");var Hd="/*\n * Copyright 2015 Trim-marks Inc.\n * Copyright 2019 Vivliostyle Foundation\n *\n * Vivliostyle.js is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Vivliostyle.js is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with Vivliostyle.js. If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n[data-vivliostyle-layout-box] {\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n overflow: hidden;\n z-index: -1;\n}\n\n[data-vivliostyle-debug] [data-vivliostyle-layout-box] {\n right: auto;\n bottom: auto;\n overflow: visible;\n z-index: auto;\n}\n\n[data-vivliostyle-page-container] {\n position: relative;\n overflow: hidden;\n}\n\n[data-vivliostyle-bleed-box] {\n position: absolute;\n overflow: hidden;\n max-width: 100%;\n max-height: 100%;\n box-sizing: border-box;\n}\n\n[data-vivliostyle-page-box] ~ [data-vivliostyle-page-box] {\n display: none;\n}\n\n[data-vivliostyle-toc-box] {\n position: absolute;\n left: 3px;\n top: 3px;\n overflow: scroll;\n overflow-x: hidden;\n background: rgba(248,248,248,0.9);\n border-radius: 2px;\n box-shadow: 1px 1px 2px rgba(0,0,0,0.4);\n}\n\n@media print {\n [data-vivliostyle-toc-box] {\n display: none;\n }\n\n [data-vivliostyle-outer-zoom-box], [data-vivliostyle-spread-container] {\n width: 100% !important;\n height: 100% !important;\n }\n\n [data-vivliostyle-spread-container], [data-vivliostyle-page-container] {\n -moz-transform: none !important;\n -ms-transform: none !important;\n -webkit-transform: none !important;\n transform: none !important;\n }\n\n [data-vivliostyle-page-container] {\n display: block !important;\n max-width: 100%;\n height: 100% !important;\n max-height: 100%;\n }\n\n /* Workaround for Chrome printing problem */\n /* [data-vivliostyle-page-box] {\n padding-bottom: 0 !important;\n overflow: visible !important;\n } */\n [data-vivliostyle-bleed-box] > div > div::before {\n display: block;\n content: \"\";\n padding-top: 0.015625px;\n margin-bottom: -0.015625px;\n }\n\n /* Gecko-only hack, see https://bugzilla.mozilla.org/show_bug.cgi?id=267029#c17 */\n @-moz-document regexp('.*') {\n [data-vivliostyle-page-container]:nth-last-child(n+2) {\n top: -1px;\n margin-top: 1px;\n margin-bottom: -1px;\n }\n }\n}\n",zd="/*\n * Copyright 2017 Trim-marks Inc.\n *\n * Vivliostyle.js is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Vivliostyle.js is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with Vivliostyle.js. If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n@media screen {\n\n [data-vivliostyle-viewer-viewport] {\n background: #AAAAAA;\n }\n\n [data-vivliostyle-page-container] {\n background: white;\n }\n\n [data-vivliostyle-viewer-viewport] {\n display: -webkit-flex;\n display: flex;\n overflow: auto;\n position: relative;\n }\n\n [data-vivliostyle-outer-zoom-box] {\n margin: auto;\n overflow: hidden;\n -webkit-flex: none;\n flex: none;\n }\n\n [data-vivliostyle-viewer-viewport] [data-vivliostyle-spread-container] {\n display: -webkit-flex;\n display: flex;\n -webkit-flex: none;\n flex: none;\n -webkit-justify-content: center;\n justify-content: center;\n -moz-transform-origin: left top;\n -ms-transform-origin: left top;\n -webkit-transform-origin: left top;\n transform-origin: left top;\n }\n\n [data-vivliostyle-viewer-viewport][data-vivliostyle-page-progression=ltr] [data-vivliostyle-spread-container] {\n -webkit-flex-direction: row;\n flex-direction: row;\n }\n\n [data-vivliostyle-viewer-viewport][data-vivliostyle-page-progression=rtl] [data-vivliostyle-spread-container] {\n -webkit-flex-direction: row-reverse;\n flex-direction: row-reverse;\n }\n\n [data-vivliostyle-viewer-viewport] [data-vivliostyle-page-container] {\n margin: 0 auto;\n -webkit-flex: none;\n flex: none;\n transform-origin: center top;\n }\n\n [data-vivliostyle-viewer-viewport][data-vivliostyle-spread-view=true] [data-vivliostyle-page-container][data-vivliostyle-page-side=left] {\n margin-right: 1px;\n transform-origin: right top;\n }\n\n [data-vivliostyle-viewer-viewport][data-vivliostyle-spread-view=true] [data-vivliostyle-page-container][data-vivliostyle-page-side=right] {\n margin-left: 1px;\n transform-origin: left top;\n }\n\n [data-vivliostyle-viewer-viewport][data-vivliostyle-spread-view=true] [data-vivliostyle-page-container][data-vivliostyle-unpaired-page=true] {\n margin-left: auto;\n margin-right: auto;\n transform-origin: center top;\n }\n\n}\n";class Gd{constructor(t,{title:e="",printCallback:n=(t=>t.print()),hideIframe:i=!0,removeIframe:o=!0}){this.htmlDoc=t,this.title=e,this.printCallback=n,this.hideIframe=i,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=`\n <!DOCTYPE html>\n <html data-vivliostyle-paginated="true">\n <head>\n <meta charset='utf-8'/>\n <meta name='viewport' content='width=device-width, initial-scale=1.0'/>\n <title>${this.title}</title>\n <style>${Hd}</style>\n <style>${zd}</style>\n <style>\n html[data-vivliostyle-paginated] {\n width: 100%;\n height: 100%;\n }\n html[data-vivliostyle-paginated] body,\n html[data-vivliostyle-paginated] [data-vivliostyle-viewer-viewport] {\n width: 100% !important;\n height: 100% !important;\n }\n html[data-vivliostyle-paginated],\n html[data-vivliostyle-paginated] body {\n margin: 0;\n padding: 0;\n }\n </style>\n <style id='vivliostyle-page-rules'></style>\n </head>\n <body onload='parent.printInstance.runInIframe(window)'>\n <div id="vivliostyle-viewer-viewport"></div>\n </body>\n </html>`,document.body.appendChild(this.iframe)}runInIframe(t){return this.iframeWin=t,this.preparePrint().then(()=>this.browserPrint()).then(()=>this.cleanUp())}preparePrint(){this.iframeWin.document.title=this.title;const t=new Blob([this.htmlDoc],{type:"text/html"}),e=URL.createObjectURL(t),n=new Dd({viewportElement:this.iframeWin.document.body.firstElementChild,window:this.iframeWin,debug:!0},{defaultPaperSize:{width:794,height:1122}});return new Promise(t=>{n.addListener("readystatechange",()=>{"complete"===n.readyState&&t()}),n.loadDocument({url:e})})}browserPrint(){this.printCallback(this.iframeWin)}cleanUp(){delete this.window.printInstance,this.removeIframe&&this.iframe.parentElement.removeChild(this.iframe)}}t.CoreViewer=Dd,t.PageViewMode=Ud,t.Profiler=m,t.ZoomType=Md,t.constants=s,t.getHooksForName=f,t.pageProgressionOf=n,t.plugin=g,t.printHTML=function(t,e){new Gd(t,e).init()},t.profile=C,t.profiler=y,t.registerHook=d,t.removeHook=p,t.setDebug=e,t.viewer=Vd,Object.defineProperty(t,"__esModule",{value:!0})}));
10//# sourceMappingURL=vivliostyle.js.map