diff --git a/html2pdf4doc/html2pdf4doc_js/html2pdf4doc.min.js b/html2pdf4doc/html2pdf4doc_js/html2pdf4doc.min.js index 0a236a6..da6c431 100644 --- a/html2pdf4doc/html2pdf4doc_js/html2pdf4doc.min.js +++ b/html2pdf4doc/html2pdf4doc_js/html2pdf4doc.min.js @@ -1,11 +1,11 @@ /*! Version: 0.3.0 */ -var HTML2PDF4DOC;(()=>{"use strict";var e={d:(t,o)=>{for(var i in o)e.o(o,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:o[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{init:()=>Wi});var o={};e.r(o),e.d(o,{log:()=>F,logGroup:()=>N,logGroupEnd:()=>B,strictAssert:()=>k});var i={};e.r(i),e.d(i,{isAfterContentFlowStart:()=>ee,isComplexTextBlock:()=>oe,isContentFlowEnd:()=>te,isContentFlowStart:()=>Q,isFlexRow:()=>_e,isForcedPageBreak:()=>le,isGrid:()=>ce,isGridAutoFlowRow:()=>ue,isIMG:()=>z,isInline:()=>ae,isInlineBlock:()=>he,isLiNode:()=>q,isNeutral:()=>K,isNoBreak:()=>ne,isNoHanging:()=>re,isOBJECT:()=>U,isPRE:()=>pe,isPageStartElement:()=>J,isSTYLE:()=>j,isSVG:()=>V,isSelectorMatching:()=>G,isSignificantTextNode:()=>W,isSlice:()=>se,isSliced:()=>fe,isSlough:()=>me,isSyntheticTextWrapper:()=>ie,isTableLikeNode:()=>de,isTableNode:()=>ge,isWrappedTextGroup:()=>Z,isWrappedTextLine:()=>X,isWrappedTextNode:()=>Y});var n={};e.r(n),e.d(n,{explainHeuristicSelectorMismatch:()=>Te,filterHeuristicSelectorMatches:()=>Oe,hasNoSignificantSiblingNodes:()=>Me,hasSignificantLeadingText:()=>Pe,hasSignificantTrailingText:()=>Ce,isHeuristicSelector:()=>Se,resolveConfigSelectorConstraints:()=>we,validateHeuristicSelectorMatch:()=>Ee});var r={};e.r(r),e.d(r,{insertStyle:()=>ye});var s={};e.r(s),e.d(s,{isFirstChildOfFirstChild:()=>De,isLastChildOfLastChild:()=>Re,isLineChanged:()=>xe,isLineKept:()=>Ne,resolveFlowElement:()=>Fe,setInitStyle:()=>Be});var l={};e.r(l),e.d(l,{getBottom:()=>Ge,getBottomWithMargin:()=>We,getContentHeightByProbe:()=>Je,getEmptyNodeHeightByProbe:()=>Ue,getHeightWithMargin:()=>je,getLineHeight:()=>qe,getMaxWidth:()=>Ve,getNormalizedBottomWithMargin:()=>Ie,getNormalizedTop:()=>Ae,getTableEmptyRowHeight:()=>Ye,getTableEntries:()=>Ze,getTableRowHeight:()=>Ke,getTableRowShellHeightByTD:()=>Xe,getTop:()=>Le,getTopForPageStartCandidate:()=>He,getTopWithMargin:()=>ze,resolveRowBoundsGeneric:()=>Qe});var a={};e.r(a),e.d(a,{create:()=>et,createComplexTextBlock:()=>at,createForcedPageBreak:()=>dt,createNeutral:()=>tt,createNeutralBlock:()=>ot,createPrintPageBreak:()=>lt,createSignpost:()=>gt,createSliceWrapper:()=>ut,createTable:()=>pt,createTestNodeFrom:()=>ht,createTextGroup:()=>rt,createTextLine:()=>nt,createTextNodeWrapper:()=>it,createWithFlagNoBreak:()=>st,createWord:()=>ct});var h={};e.r(h),e.d(h,{prepareSplittedNode:()=>bt,splitByWordsGreedyWithSpacesFilter:()=>mt,splitTextByLinesGreedy:()=>_t,splitTextByWordsGreedy:()=>ft});var c={};e.r(c),e.d(c,{markBottomCut:()=>xt,markCleanBottomCut:()=>Dt,markCleanTopCut:()=>vt,markPageEndElement:()=>Ot,markPageNumber:()=>yt,markPageStartElement:()=>Et,markProcessed:()=>St,markSliceCuts:()=>Nt,markSliceCutsInRows:()=>Bt,markTopCut:()=>Rt,setFlagNoBreak:()=>Mt,setFlagNoHanging:()=>Pt,setFlagSlice:()=>Ct,unmarkPageStartElement:()=>Tt});var d={};e.r(d),e.d(d,{wrapNodeChildrenWithNeutralBlock:()=>Ft});var g={};e.r(g),e.d(g,{copyNodeWidth:()=>Lt,estimateInlineImgGapBelow:()=>Wt,fitElementWithinBoundaries:()=>Ht,fitElementWithinHeight:()=>At,lockNodesWidths:()=>Gt,lockTableWidths:()=>$t,scaleCellsToHeight:()=>It});var p={};e.r(p),e.d(p,{findAllForcedPageBreakInside:()=>Xt,findBetterForcedPageStarter:()=>zt,findBetterPageStart:()=>Vt,findFirstChildParent:()=>Kt,findFirstChildParentFromPage:()=>Ut,findLastChildParent:()=>Yt,findPreviousNonHangingsFromPage:()=>qt});var u={};e.r(u),e.d(u,{getFirstChildrenChain:()=>no,getLastChildrenChain:()=>ro,getPreparedChildren:()=>oo,getSplitChildren:()=>io});var _={};e.r(_),e.d(_,{isReplacedElement:()=>_o,resolveReplacedElement:()=>fo});var f={};e.r(f),e.d(f,{cloneAndCleanOutsideRange:()=>Eo,getSplitPoints:()=>bo,getSplitPointsPerCells:()=>wo,isFirstSliceEmpty:()=>Co,normalizeContentCuts:()=>Mo,sliceNodeBySplitPoints:()=>So,sliceNodeContentBySplitPoints:()=>Po});var m={};e.r(m),e.d(m,{shouldSkipFlowElement:()=>Do});var b={};e.r(b),e.d(b,{buildRowSlices:()=>xo,evaluateRowSplitPlacement:()=>Bo,paginationBuildBalancedRowSlices:()=>No,replaceCurrentRowsAfterRowSplit:()=>Fo,sliceCellsBySplitPoints:()=>Ro});var w={};e.r(w),e.d(w,{paginationApplyFullPageScaling:()=>Io,paginationScaleCellsToHeight:()=>Ho,paginationShouldScaleFullPage:()=>Ao});var S={};e.r(S),e.d(S,{applyRowSlicesToEntriesAfterRowSplit:()=>Lo,computeRowFlags:()=>$o});var M={};e.r(M),e.d(M,{paginationRefreshRowsAfterSplit:()=>Wo,validateSplitterAdapter:()=>Go});var P={};e.r(P),e.d(P,{paginationComputeCellShellHeights:()=>jo});var C={};e.r(C),e.d(C,{handleRowOverflow:()=>Uo,handleRowSplitFailure:()=>qo,scaleRowCellsToHeight:()=>Vo});var E={};e.r(E),e.d(E,{absorbShortTrailingSliceIfFits:()=>Yo,calculateFinalPartReclaimedHeight:()=>Ko});var T={};e.r(T),e.d(T,{paginationBuildRowEvaluationContext:()=>Zo,paginationCanAbsorbLastRow:()=>Jo});var O={};e.r(O),e.d(O,{paginationCalculateRowSplitBudget:()=>ii,paginationHandleRowSlicesPlacement:()=>ai,paginationProcessRowSplitResult:()=>si,paginationResolveAlreadySlicedRow:()=>oi,paginationResolveOverflowingRow:()=>ei,paginationResolveRowWithRowspan:()=>ti,paginationResolveSplittableRow:()=>li,paginationSplitRow:()=>ni});const y="html2pdf4doc",v="html2pdf";function D(e){if("string"!=typeof e)return e;if(!e.includes(y))return e;const t=e.replaceAll(y,v);return t===e?e:`${e},${t}`}const R={init:"[html2pdf4doc]",root:"html2pdf4doc-root",paperFlow:"html2pdf4doc-paper-flow",contentFlow:"html2pdf4doc-content-flow",overlayFlow:"html2pdf4doc-overlay-flow",pageDivider:"html2pdf4doc-page",pageStartMarker:"[html2pdf4doc-page-start]",pageEndMarker:"[html2pdf4doc-page-end]",pageMarker:"[html2pdf4doc-page]",contentFlowStart:"html2pdf4doc-content-flow-start",contentFlowEnd:"html2pdf4doc-content-flow-end",style:"[html2pdf4doc-style]",frontpageTemplate:"[html2pdf4doc-frontpage]",headerTemplate:"[html2pdf4doc-header]",footerTemplate:"[html2pdf4doc-footer]",frontpageElement:"html2pdf4doc-frontpage",frontpageContent:"html2pdf4doc-frontpage-content",headerContent:"html2pdf4doc-header",footerContent:"html2pdf4doc-footer",pageNumberRoot:"[html2pdf4doc-page-number]",pageNumberCurrent:"[html2pdf4doc-page-number-current]",pageNumberTotal:"[html2pdf4doc-page-number-total]",pageChrome:"html2pdf4doc-page-chrome",pageBodySpacer:"html2pdf4doc-page-body-spacer",pageHeader:"html2pdf4doc-page-header",pageFooter:"html2pdf4doc-page-footer",printPageBreak:"html2pdf4doc-print-page-break",runningSafety:"html2pdf4doc-print-running",virtualPaper:"html2pdf4doc-virtual-paper",virtualPaperTopMargin:"html2pdf4doc-virtual-paper-margin-top",virtualPaperBottomMargin:"html2pdf4doc-virtual-paper-margin-bottom",virtualPaperGap:"html2pdf4doc-virtual-paper-gap",printIgnore:"[html2pdf4doc-print-ignore]",printHide:"[html2pdf4doc-print-hide]",neutral:"html2pdf4doc-neutral",word:"html2pdf4doc-word",textNode:"html2pdf4doc-text-node",textLine:"html2pdf4doc-text-line",textGroup:"html2pdf4doc-text-group",complexTextBlock:"html2pdf4doc-complex-text-block",printForcedPageBreak:"html2pdf4doc-print-forced-page-break",split:"[html2pdf4doc-split]",processed:"[html2pdf4doc-processed]",flagNoBreak:"[html2pdf4doc-flag-no-break]",flagNoHanging:"[html2pdf4doc-flag-no-hanging]",flagSlice:"[html2pdf4doc-flag-slice]",topCutPart:".html2pdf4doc-top-cut",bottomCutPart:".html2pdf4doc-bottom-cut",cleanTopCut:".html2pdf4doc-clean-top-cut",cleanBottomCut:".html2pdf4doc-clean-bottom-cut",tocPageNumber:"html2pdf4doc-toc-page-number"},x="background:#eee;color:#888;padding: 0 1px 0 0;";function N(e,t="",o=!1){"boolean"==typeof t&&(o=t,t=""),!0===o?this._debug._&&console.groupCollapsed(`%c${e}`,t):this._debug._&&console.group(`%c${e}`,t)}function B(e){this._debug._&&console.log(`%c ▲ ${e} `,x),this._debug._&&console.groupEnd()}function F(e,...t){this._debug._&&console.log(`[${e}]`,...t)}function k(e,...t){this._assert&&console.assert(e,"⛔",...t)}class H{constructor({DOM:e,config:t}){this.document=e,this.body=e.body,this._debug=t.debugMode?{...t.debugConfig.DOM}:{},this._assert=!!t.consoleAssert,Object.assign(this,o)}createElement(e){return this.document.createElement(e)}createDocumentFragment(){return this.document.createDocumentFragment()}cloneNode(e){return e?.cloneNode(!0)}cloneNodeWrapper(e){return e?.cloneNode(!1)}insertBefore(e,...t){const o=t.filter(e=>null!=e);e.before(...o)}insertAfter(e,...t){const o=t.filter(e=>null!=e);e.after(...o)}insertAtEnd(e,...t){const o=t.filter(e=>null!=e);e.append(...o)}insertAtStart(e,...t){const o=t.filter(e=>null!=e);e.prepend(...o)}insertInsteadOf(e,...t){this.insertBefore(e,...t),e.remove()}wrap(e,t){return e.before(t),t.append(e),t}moveContent(e,t){for(;e.firstChild;)t.append(e.firstChild);this.strictAssert(""===this.getInnerHTML(e))}moveRowContent(e,t){if(!e||!t)return void(this._debug._&&console.warn("moveRowContent(): sourceTR or targetTR is missing"));const o=this.getElementTagName(e),i=this.getElementTagName(t);this.strictAssert("TR"===o,`moveRowContent(): source is not TR, got ${o}`),this.strictAssert("TR"===i,`moveRowContent(): target is not TR, got ${i}`);const n=[...this.getChildren(e)],r=[...this.getChildren(t)];n.length!==r.length&&this._debug._&&console.warn(`moveRowContent(): cells count mismatch: ${n.length} (source) vs ${r.length} (target)`);const s=Math.min(n.length,r.length);for(let e=0;e0,"getAll(selectors), selectors:",e),1===e.length?[...this.getAllElements(e[0],t)]:[...e].flatMap(e=>[...this.getAllElements(e,t)])}getElement(e,t=this.document){return this.strictAssert(e),t.querySelector(e)}getAllElements(e,t=this.document){return this.strictAssert(e),t.querySelectorAll(e)}getElementById(e,t=this.document){return t.getElementById(e)}getNodeType(e){return e.nodeType}getRightNeighbor(e){return e.nextElementSibling}getLeftNeighbor(e){return e.previousElementSibling}getParentNode(e){return e.parentElement}getNodeValue(e){return e.nodeValue}getNodeWholeText(e){return e.wholeText}getLastElementChild(e){return e.lastElementChild}getFirstElementChild(e){return e.firstElementChild}getChildNodes(e){return e.childNodes}getChildren(e){return e.children}getElementOffsetParent(e){return e.offsetParent}getComputedStyle(e){return window.getComputedStyle(e)}getElementBCR(e){return e.getBoundingClientRect()}getElementOffsetLeft(e){return e?.offsetLeft}getElementOffsetHeight(e){return e?.offsetHeight}getElementOffsetWidth(e){return e?.offsetWidth}getElementOffsetTop(e){return e?.offsetTop}getElementOffsetBottom(e){return e?.offsetTop+e?.offsetHeight||void 0}getElementTagName(e){return e.tagName}getDataId(e){return e.dataset.id}getAttribute(e,t){if(!e||!t)return void(this._debug._&&console.warn("getAttribute() must have 2 params"));const o=t.charAt(0);if("."!==o&&"#"!==o||this.log("getAttribute",`you're really sure ${t} is attribute selector?`),"["===o){this.strictAssert("]"===t.at(-1),`the ${t} selector is not OK.`);const o=t.substring(1,t.length-1);return e.getAttribute(o)}e.getAttribute(t)}setAttribute(e,t,o){if(!e||!t)return void(this._debug._&&console.warn("setAttribute() must have 2 params"));const i=t.charAt(0);if("."===i){const o=t.substring(1);return void e.classList.add(o)}if("#"===i){const o=t.substring(1);return void(e.id=o)}if("["===i){this.strictAssert("]"===t.at(-1),`the ${t} selector is not OK.`);const i=t.substring(1,t.length-1);return void e.setAttribute(i,o||"")}this.log("setAttribute",`you're really sure ${t} is a selector?`)}setStyles(e,t){Object.entries(t).forEach(([t,o])=>{Array.isArray(o)?this.setStyle(e,t,o[0],o[1]||""):this.setStyle(e,t,o)})}setStyle(e,t,o,i=""){const n=this._toKebab(t);null==o||""===o?e.style.removeProperty(n):e.style.setProperty(n,String(o),i)}_toKebab=e=>{if(e.includes("-"))return e;const t=e.match(/^(webkit|moz|ms|o)(?=[A-Z])/);return t&&(e="-"+t[1]+"-"+e.slice(t[1].length)),e.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())};addClasses(e,...t){e.classList.add(...t)}removeAttribute(e,t){if(!e||!t)return void(this._debug._&&console.warn("removeAttribute() must have 2 params"));const o=t.charAt(0);if(this.strictAssert(o.match(/[a-zA-Z#\[\.]/),`removeAttribute() expects a valid selector, but received ${t}`),"."===o){const o=t.substring(1);return void e.classList.remove(o)}if("#"===o){const o=t.substring(1);return void e.removeAttribute(o)}if("["===o){this.strictAssert("]"===t.at(-1),`the ${t} selector is not OK.`);const o=t.substring(1,t.length-1);return void e.removeAttribute(o)}e.removeAttribute(attr)}removeAllAttributes(e){for(;e.attributes.length>0;)e.removeAttribute(e.attributes[0].name)}removeClasses(e,...t){e.classList.remove(...t)}removeAllClasses(e){e.classList=""}removeAllStyles(e){e.style=""}getInnerHTML(e){if("string"==typeof e){const t=this.document.querySelector(e);return t?t.innerHTML:void 0}return e.innerHTML}setInnerHTML(e,t){if("string"==typeof e){const o=this.document.querySelector(e);o&&(o.innerHTML=t)}e.innerHTML=t}isDocumentBody(e){return"BODY"===e.tagName}isTextNode(e){return e.nodeType===Node.TEXT_NODE}isElementNode(e){return e.nodeType===Node.ELEMENT_NODE}hasClass(e,t){return e.classList.contains(t)}hasID(e,t){return e.id===t}hasAttribute(e,t){return e.hasAttribute(t)}}class A{constructor(e){this.config=e,this._printWidth=parseFloat(this.config.paperWidth),this._printLeft=parseFloat(this.config.printLeftMargin),this._printRight=parseFloat(this.config.printRightMargin),this._printContentWidth=this._printWidth-this._printLeft-this._printRight+"px",this._flowPreviewPaddingBottom="100px",this._chromeBorderSafeSpace="2px",this._ensureBFC="display: flow-root",this.charWidth="10px"}create(){return this._pageRule()+this._layoutStyles().screen+this._layoutStyles().print+this._chromeStyles().screen+this._chromeStyles().print+this._serviceElementsStyle().screen+this._serviceElementsStyle().print+this._cutEdgeStyle()+(this.config.debugMode?this._testScreenOnlyStyle():"")}_pageRule(){return`@page {\n size: A4;\n size: ${`${this.config.paperWidth} ${this.config.paperHeight}`};\n margin-left: ${this.config.printLeftMargin};\n margin-right: ${this.config.printRightMargin};\n margin-top: ${this.config.printTopMargin};\n margin-bottom: 0;\n}`}_layoutStyles(){return{screen:`\n${R.root} {\n --paper-color: ${this.config.paperColor};\n display: flow-root;\n position: relative;\n z-index: 1;\n width: ${this._printContentWidth};\n margin: 0 auto;\n font-size: ${this.config.printFontSize};\n padding-bottom: ${this._flowPreviewPaddingBottom};\n}\n\n${R.contentFlow} {\n display: block;\n}\n\n${R.paperFlow} {\n display: block;\n position: absolute;\n width: 100%;\n z-index: -1;\n padding-bottom: ${this._flowPreviewPaddingBottom};\n pointer-events: none;\n}\n\n${R.overlayFlow} {\n display: block;\n position: absolute;\n width: 100%;\n z-index: 2147483647;\n padding-bottom: ${this._flowPreviewPaddingBottom};\n pointer-events: none;\n}\n\n${R.virtualPaper} {\n display: grid;\n grid-template-columns: 1fr;\n grid-template-rows: minmax(min-content, max-content) minmax(min-content, max-content) 1fr minmax(min-content, max-content) minmax(min-content, max-content);\n place-items: stretch stretch;\n place-content: stretch stretch;\n width: ${this._printContentWidth};\n height: ${this.config.paperHeight};\n font-size: ${this.config.printFontSize};\n}\n\n${R.virtualPaper}::before {\n position: absolute;\n content: '';\n width: ${this.config.paperWidth};\n height: ${this.config.paperHeight};\n left: -${this.config.printLeftMargin};\n background: var(--paper-color, white);\n box-shadow: rgba(0, 0, 0, 0.1) 2px 2px 12px 0px;\n z-index: -1;\n}\n\n${R.pageChrome} {\n display: block;\n pointer-events: none;\n}\n\n${R.pageBodySpacer} {\n display: block;\n pointer-events: none;\n}\n\n${R.pageFooter},\n${R.pageHeader} {\n display: block;\n position: relative;\n pointer-events: auto;\n}\n\n${R.pageFooter}::before,\n${R.pageHeader}::before {\n content: '';\n position: absolute;\n inset: 0;\n z-index: -1;\n background: var(--paper-color, white);\n}\n\n${R.pageFooter}::before {\n top: ${this._chromeBorderSafeSpace};\n}\n\n${R.pageHeader}::before {\n bottom: ${this._chromeBorderSafeSpace};\n}\n\n${R.virtualPaperTopMargin} {\n display: block;\n height: ${this.config.printTopMargin};\n}\n\n${R.virtualPaperBottomMargin} {\n display: block;\n height: ${this.config.printBottomMargin};\n}\n\n${R.virtualPaperGap} {\n display: block;\n padding-top: ${this.config.virtualPagesGap};\n}\n\n${R.contentFlowStart},\n${R.contentFlowEnd},\n${R.pageDivider},\n${R.runningSafety} {\n ${this._ensureBFC};\n}\n `,print:`\n@media print {\n\n ${R.root},\n ${R.overlayFlow},\n ${R.paperFlow} {\n padding: 0;\n }\n\n ${R.paperFlow},\n ${R.printHide} {\n display: none !important;\n }\n\n ${R.printIgnore} {\n display: contents !important;\n }\n\n ${R.virtualPaperTopMargin},\n ${R.virtualPaperBottomMargin},\n ${R.virtualPaperGap} {\n display: none !important;\n }\n\n ${R.pageChrome},\n ${R.frontpageElement},\n ${R.pageBodySpacer} {\n break-inside: avoid;\n }\n}\n `}}_chromeStyles(){return{screen:`\n${R.headerContent},\n${R.footerContent} {\n display: block;\n font-size: small;\n}\n\n${R.headerContent} p,\n${R.footerContent} p {\n margin: 0;\n}\n\n${R.headerContent} {\n padding-bottom: ${this.config.headerMargin};\n padding-top: 10px; /* for page numbers */\n}\n\n${R.footerContent} {\n padding-top: ${this.config.footerMargin};\n min-height: 32px; /* for page numbers */\n}\n\n${R.tocPageNumber} {\n min-width: 3ch;\n display: flex;\n justify-content: flex-end;\n align-items: baseline;\n}\n\n${R.pageNumberRoot} {\n display: flex;\n column-gap: 2px;\n position: absolute;\n right: 0;\n text-align: right;\n line-height: 1;\n}\n\n${R.headerContent} ${R.pageNumberRoot} {\n top: 0;\n}\n\n${R.footerContent} ${R.pageNumberRoot} {\n bottom: 0;\n}\n `,print:""}}_cutEdgeStyle(){return`\n${R.topCutPart} {\n margin-top: 0 !important;\n}\n${R.bottomCutPart} {\n margin-bottom: 0 !important;\n}\n${R.cleanTopCut} {\n margin-top: 0 !important;\n padding-top: 0 !important;\n border-top: none !important;\n}\n${R.cleanBottomCut} {\n margin-bottom: 0 !important;\n padding-bottom: 0 !important;\n border-bottom: none !important;\n}\n `}_serviceElementsStyle(){const e="display: inline";return{screen:`\n.null {\n display: inline;\n padding: 0;\n margin: 0;\n font: 0;\n color: transparent;\n line-height: 0;\n border: none;\n outline: none;\n background: none;\n background-color: transparent;\n}\n\n${R.word},\n${R.textNode},\n${R.textLine},\n${R.textGroup},\n${R.neutral},\n${R.neutral} span {\n display: inline;\n padding: 0;\n margin: 0;\n font: inherit;\n color: inherit;\n line-height: inherit;\n background: none;\n background-color: transparent;\n}\n\n${R.textGroup} {\n display: block;\n}\n\n${R.textLine} {\n display: inline-block;\n}\n\n${R.textGroup} ${R.textLine} {\n ${e};\n}\n\n${R.complexTextBlock} {\n display: block;\n}\n\n${R.complexTextBlock} ${R.complexTextBlock} {\n ${e};\n}\n\n${R.printPageBreak} {\n ${this._ensureBFC};\n}\n\n${R.printForcedPageBreak} {\n display: block;\n visibility: hidden;\n height: 0;\n overflow: hidden;\n}\n `,print:`\n@media print {\n\n ${R.printPageBreak} {\n break-after: page;\n }\n\n ${R.textLine} {\n ${e};\n }\n}\n `}}_testScreenOnlyStyle(){return`\n/* DEBUG PREVIEW */\n@media screen {\n\n ${R.contentFlow} {\n background:repeating-linear-gradient(\n -45deg,\n rgba(222, 222, 222, .1),\n rgba(222, 222, 222, .1) 10px,\n rgba(222, 222, 222, .2) 10px,\n rgba(222, 222, 222, .2) 20px\n );\n }\n\n ${R.overlayFlow} {\n background:repeating-linear-gradient(\n 45deg,\n rgba(222, 222, 222, 0),\n rgba(222, 222, 222, 0) 18px,\n rgba(0, 166, 255, 0.05) 18px,\n rgba(0, 166, 255, 0.05) 20px\n );\n }\n\n ${R.virtualPaperGap} {\n background: #ff000020;\n }\n\n ${R.pageFooter},\n ${R.pageHeader} {\n background: #fff1ff99;\n }\n ${R.pageBodySpacer} {\n background: #ffee0020;\n }\n ${R.runningSafety} {\n background: #f200ff;\n outline: 0.1px dashed #f200ff88;\n }\n ${R.frontpageElement} {\n background: #00fcff20;\n }\n\n ${R.neutral} {\n background: #00ffee10;\n }\n\n ${R.textNode} {\n background: #00ff0010;\n }\n\n ${R.textGroup},\n ${R.textLine} {\n background: #0000ff08;\n }\n}\n `}}class I{constructor({config:e,DOM:t,node:i,selector:n}){this.success=!1,Object.assign(this,o),this.root,this.paperFlow,this.contentFlow,this.overlayFlow,this.frontpageTemplate,this.headerTemplate,this.footerTemplate,this._initialRoot,this._contentRoot,this._config=e,this._debug=e.debugMode?{...e.debugConfig.layout}:{},this._assert=!!e.consoleAssert,this._DOM=t,this._selector=n,this._node=i,this._customInitialRootSelector=e.initialRoot,this._defaultInitialRootSelector=n.init}create(){if(this._getTemplates(),this._insertStyle(),this._DOM.getElement(`style${this._selector.style}`)){if(this._createLayout(),this._DOM.getParentNode(this.root)!==this._initialRoot||this._DOM.getElementOffsetParent(this.paperFlow)!==this.root||this._DOM.getElementOffsetParent(this.contentFlow)!==this.root||this._DOM.getElementOffsetParent(this.overlayFlow)!==this.root)return this.strictAssert(this._DOM.getParentNode(this.root)===this._initialRoot,"Failed to insert the layout root into the DOM."),this.strictAssert(this._DOM.getElementOffsetParent(this.paperFlow)===this.root,"Failed to insert the paperFlow element into the DOM."),void this.strictAssert(this._DOM.getElementOffsetParent(this.contentFlow)===this.root,"Failed to insert the contentFlow element into the DOM.");this.success=!0}else console.error("Failed to add print styles into the DOM.")}_getTemplates(){this.strictAssert(this._selector.frontpageTemplate,"frontpageTemplate selector is missing"),this.strictAssert(this._selector.headerTemplate,"headerTemplate selector is missing"),this.strictAssert(this._selector.footerTemplate,"footerTemplate selector is missing"),this.frontpageTemplate=this._DOM.getInnerHTML(D(this._selector.frontpageTemplate)),this.headerTemplate=this._DOM.getInnerHTML(D(this._selector.headerTemplate)),this.footerTemplate=this._DOM.getInnerHTML(D(this._selector.footerTemplate))}_insertStyle(){this._node.insertStyle(new A(this._config).create())}_createLayout(){this._getInitialRoot(),this._initialRoot?(this.log("create Layout","initial root:",this._initialRoot),this._createRoot(),this._createPaperFlow(),this._createContentFlow(),this._createOverlayFlow(),this._DOM.moveContent(this._initialRoot,this.contentFlow),this._DOM.insertAtEnd(this._initialRoot,this.root),this._DOM.insertAtEnd(this.root,this.paperFlow,this.overlayFlow,this.contentFlow),this._insertContentFlowStartAndEnd(this.contentFlow),this._ignoreUnprintableEnvironment(this.root)):console.error("Failed to initialize the root element.")}_insertContentFlowStartAndEnd(e){const t=this._node.create(this._selector.contentFlowStart),o=this._node.create(this._selector.contentFlowEnd);return this._DOM.insertAtStart(e,t),this._DOM.insertAtEnd(e,o),{contentFlowStart:t,contentFlowEnd:o}}_getInitialRoot(){let e=this._customInitialRootSelector?this._DOM.getElement(this._customInitialRootSelector):this._DOM.getElement(this._defaultInitialRootSelector);if(!e){if(!this._DOM.body)return void console.error("We expected to find the BODY tag.");e=this._DOM.body,console.warn(`The printable area is currently unspecified and encompasses the entire contents of the BODY tag. To restrict the printed content to a specific area, include ${this._defaultInitialRootSelector} in the root element of the desired printing area.`)}return this._initialRoot=e,e}_createRoot(){const e=this._node.create(this._selector.root);return this._DOM.setStyles(e,{visibility:"hidden"}),this.root=e,e}_createPaperFlow(){const e=this._node.create(this._selector.paperFlow);return this.paperFlow=e,e}_createOverlayFlow(){const e=this._node.create(this._selector.overlayFlow);return this.overlayFlow=e,e}_createContentFlow(){const e=this._node.create(this._selector.contentFlow);return this.contentFlow=e,e}_ignoreUnprintableEnvironment(e){if(e===this._DOM.body)return void this.strictAssert(!1,"misshapen root");let t=this._DOM.getParentNode(e);this._DOM.setAttribute(t,this._selector.printIgnore),this._DOM.getChildNodes(t).forEach(t=>{if(t!==e&&this._DOM.isElementNode(t))this._DOM.setAttribute(t,this._selector.printHide);else{if(!this._node.isSignificantTextNode(t))return;{const e=this._node.createTextNodeWrapper();this._DOM.wrap(t,e),this._DOM.setAttribute(e,this._selector.printHide)}}}),this._DOM.isDocumentBody(t)||this._ignoreUnprintableEnvironment(t)}}function L(e){return function(t){return t._config.debugMode&&t._debug[e]}}const $=L("selectors");function G(e,t){if(!e||!t)return void($(this)&&console.warn("isSelectorMatching() must have 2 params","\n element: ",e,"\n selector: ",t));const o=[t];if("string"==typeof t&&t.includes("html2pdf4doc")){const e=t.replaceAll("html2pdf4doc","html2pdf");e!==t&&o.push(e)}return o.some(t=>{const o=t.charAt(0);if("."===o){const o=t.substring(1);return this._DOM.hasClass(e,o)}if("#"===o){const o=t.substring(1);return this._DOM.hasID(e,o)}if("["===o){this.strictAssert("]"===t.at(-1),`the ${t} selector is not OK.`);const o=t.substring(1,t.length-1);return this._DOM.hasAttribute(e,o)}return this._DOM.getElementTagName(e)===t.toUpperCase()})}function W(e){return!!this._DOM.isTextNode(e)&&this._DOM.getNodeValue(e).trim().length>0}function j(e){return"STYLE"===this._DOM.getElementTagName(e)}function z(e){return"IMG"===this._DOM.getElementTagName(e)}function V(e){return"svg"===this._DOM.getElementTagName(e)}function U(e){return"OBJECT"===this._DOM.getElementTagName(e)}function q(e){return"LI"===this._DOM.getElementTagName(e)}function K(e){return this.isSelectorMatching(e,this._selector.neutral)}function Y(e){return this.isSelectorMatching(e,this._selector.textNode)}function X(e){return this.isSelectorMatching(e,this._selector.textLine)}function Z(e){return this.isSelectorMatching(e,this._selector.textGroup)}function J(e){return this.isSelectorMatching(e,this._selector.pageStartMarker)}function Q(e){return this.isSelectorMatching(e,this._selector.contentFlowStart)}function ee(e){const t=this._DOM.getLeftNeighbor(e);return this.isSelectorMatching(t,this._selector.contentFlowStart)}function te(e){return this.isSelectorMatching(e,this._selector.contentFlowEnd)}function oe(e){return this.isSelectorMatching(e,this._selector.complexTextBlock)}function ie(e){return this.isComplexTextBlock(e)||this.isWrappedTextNode(e)||this.isWrappedTextLine(e)||this.isWrappedTextGroup(e)}function ne(e,t){return this.isSelectorMatching(e,this._selector.flagNoBreak)||this.isWrappedTextLine(e)||this.isWrappedTextGroup(e)||this.isInlineBlock(e,t)||this.notSolved(e)}function re(e){return this.isSelectorMatching(e,this._selector.flagNoHanging)}function se(e){return this.isSelectorMatching(e,this._selector.flagSlice)}function le(e){return this.isSelectorMatching(e,this._selector.printForcedPageBreak)}function ae(e,t){if(!(e instanceof HTMLElement))return;const o=(t||this._DOM.getComputedStyle(e)).display;return"inline"===o||"inline-block"===o||"inline-table"===o||"inline-flex"===o||"inline-grid"===o}function he(e,t){if(!(e instanceof HTMLElement))return;const o=(t||this._DOM.getComputedStyle(e)).display;return"inline-block"===o||"inline-table"===o||"inline-flex"===o||"inline-grid"===o}function ce(e,t){if(!(e instanceof HTMLElement))return;return"grid"===(t||this._DOM.getComputedStyle(e)).display}function de(e,t){if(!(e instanceof HTMLElement))return;const o=(t||this._DOM.getComputedStyle(e)).display;if("TABLE"!==this._DOM.getElementTagName(e)&&["table","inline-table"].includes(o))return!0;const i=e=>"table-row"===e,n=e=>"table-cell"===e;if(i(o)){const t=this._DOM.getChildren(e);for(const e of t)if(e instanceof HTMLElement&&n(this._DOM.getComputedStyle(e).display))return!0;return!1}if("table-row-group"===(r=o)||"table-header-group"===r||"table-footer-group"===r){const t=this._DOM.getChildren(e);for(const e of t){if(!(e instanceof HTMLElement))continue;if(!i(this._DOM.getComputedStyle(e).display))continue;const t=this._DOM.getChildren(e);for(const e of t)if(e instanceof HTMLElement&&n(this._DOM.getComputedStyle(e).display))return!0}return!1}var r;return!1}function ge(e,t){if(e instanceof HTMLElement) +var HTML2PDF4DOC;(()=>{"use strict";var e={d:(t,o)=>{for(var i in o)e.o(o,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:o[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{init:()=>Wi});var o={};e.r(o),e.d(o,{log:()=>F,logGroup:()=>N,logGroupEnd:()=>B,strictAssert:()=>k});var i={};e.r(i),e.d(i,{isAfterContentFlowStart:()=>ee,isComplexTextBlock:()=>oe,isContentFlowEnd:()=>te,isContentFlowStart:()=>Q,isFlexRow:()=>_e,isForcedPageBreak:()=>le,isGrid:()=>ce,isGridAutoFlowRow:()=>ue,isIMG:()=>z,isInline:()=>ae,isInlineBlock:()=>he,isLiNode:()=>q,isNeutral:()=>K,isNoBreak:()=>ne,isNoHanging:()=>re,isOBJECT:()=>U,isPRE:()=>pe,isPageStartElement:()=>J,isSTYLE:()=>j,isSVG:()=>V,isSelectorMatching:()=>G,isSignificantTextNode:()=>W,isSlice:()=>se,isSliced:()=>fe,isSlough:()=>me,isSyntheticTextWrapper:()=>ie,isTableLikeNode:()=>de,isTableNode:()=>ge,isWrappedTextGroup:()=>Z,isWrappedTextLine:()=>X,isWrappedTextNode:()=>Y});var n={};e.r(n),e.d(n,{explainHeuristicSelectorMismatch:()=>Te,filterHeuristicSelectorMatches:()=>Oe,hasNoSignificantSiblingNodes:()=>Me,hasSignificantLeadingText:()=>Pe,hasSignificantTrailingText:()=>Ce,isHeuristicSelector:()=>Se,resolveConfigSelectorConstraints:()=>we,validateHeuristicSelectorMatch:()=>Ee});var r={};e.r(r),e.d(r,{insertStyle:()=>ye});var s={};e.r(s),e.d(s,{isFirstChildOfFirstChild:()=>De,isLastChildOfLastChild:()=>Re,isLineChanged:()=>xe,isLineKept:()=>Ne,resolveFlowElement:()=>Fe,setInitStyle:()=>Be});var l={};e.r(l),e.d(l,{getBottom:()=>Ge,getBottomWithMargin:()=>We,getContentHeightByProbe:()=>Je,getEmptyNodeHeightByProbe:()=>Ue,getHeightWithMargin:()=>je,getLineHeight:()=>qe,getMaxWidth:()=>Ve,getNormalizedBottomWithMargin:()=>Ie,getNormalizedTop:()=>He,getTableEmptyRowHeight:()=>Ye,getTableEntries:()=>Ze,getTableRowHeight:()=>Ke,getTableRowShellHeightByTD:()=>Xe,getTop:()=>Le,getTopForPageStartCandidate:()=>Ae,getTopWithMargin:()=>ze,resolveRowBoundsGeneric:()=>Qe});var a={};e.r(a),e.d(a,{create:()=>et,createComplexTextBlock:()=>at,createForcedPageBreak:()=>dt,createNeutral:()=>tt,createNeutralBlock:()=>ot,createPrintPageBreak:()=>lt,createSignpost:()=>gt,createSliceWrapper:()=>ut,createTable:()=>pt,createTestNodeFrom:()=>ht,createTextGroup:()=>rt,createTextLine:()=>nt,createTextNodeWrapper:()=>it,createWithFlagNoBreak:()=>st,createWord:()=>ct});var h={};e.r(h),e.d(h,{prepareSplittedNode:()=>bt,splitByWordsGreedyWithSpacesFilter:()=>mt,splitTextByLinesGreedy:()=>_t,splitTextByWordsGreedy:()=>ft});var c={};e.r(c),e.d(c,{markBottomCut:()=>xt,markCleanBottomCut:()=>Dt,markCleanTopCut:()=>vt,markPageEndElement:()=>Ot,markPageNumber:()=>yt,markPageStartElement:()=>Et,markProcessed:()=>St,markSliceCuts:()=>Nt,markSliceCutsInRows:()=>Bt,markTopCut:()=>Rt,setFlagNoBreak:()=>Mt,setFlagNoHanging:()=>Pt,setFlagSlice:()=>Ct,unmarkPageStartElement:()=>Tt});var d={};e.r(d),e.d(d,{wrapNodeChildrenWithNeutralBlock:()=>Ft});var g={};e.r(g),e.d(g,{copyNodeWidth:()=>Lt,estimateInlineImgGapBelow:()=>Wt,fitElementWithinBoundaries:()=>At,fitElementWithinHeight:()=>Ht,lockNodesWidths:()=>Gt,lockTableWidths:()=>$t,scaleCellsToHeight:()=>It});var p={};e.r(p),e.d(p,{findAllForcedPageBreakInside:()=>Xt,findBetterForcedPageStarter:()=>zt,findBetterPageStart:()=>Vt,findFirstChildParent:()=>Kt,findFirstChildParentFromPage:()=>Ut,findLastChildParent:()=>Yt,findPreviousNonHangingsFromPage:()=>qt});var u={};e.r(u),e.d(u,{getFirstChildrenChain:()=>no,getLastChildrenChain:()=>ro,getPreparedChildren:()=>oo,getSplitChildren:()=>io});var _={};e.r(_),e.d(_,{isReplacedElement:()=>_o,resolveReplacedElement:()=>fo});var f={};e.r(f),e.d(f,{cloneAndCleanOutsideRange:()=>Eo,getSplitPoints:()=>bo,getSplitPointsPerCells:()=>wo,isFirstSliceEmpty:()=>Co,normalizeContentCuts:()=>Mo,sliceNodeBySplitPoints:()=>So,sliceNodeContentBySplitPoints:()=>Po});var m={};e.r(m),e.d(m,{shouldSkipFlowElement:()=>Do});var b={};e.r(b),e.d(b,{buildRowSlices:()=>xo,evaluateRowSplitPlacement:()=>Bo,paginationBuildBalancedRowSlices:()=>No,replaceCurrentRowsAfterRowSplit:()=>Fo,sliceCellsBySplitPoints:()=>Ro});var w={};e.r(w),e.d(w,{paginationApplyFullPageScaling:()=>Io,paginationScaleCellsToHeight:()=>Ao,paginationShouldScaleFullPage:()=>Ho});var S={};e.r(S),e.d(S,{applyRowSlicesToEntriesAfterRowSplit:()=>Lo,computeRowFlags:()=>$o});var M={};e.r(M),e.d(M,{paginationRefreshRowsAfterSplit:()=>Wo,validateSplitterAdapter:()=>Go});var P={};e.r(P),e.d(P,{paginationComputeCellShellHeights:()=>jo});var C={};e.r(C),e.d(C,{handleRowOverflow:()=>Uo,handleRowSplitFailure:()=>qo,scaleRowCellsToHeight:()=>Vo});var E={};e.r(E),e.d(E,{absorbShortTrailingSliceIfFits:()=>Yo,calculateFinalPartReclaimedHeight:()=>Ko});var T={};e.r(T),e.d(T,{paginationBuildRowEvaluationContext:()=>Zo,paginationCanAbsorbLastRow:()=>Jo});var O={};e.r(O),e.d(O,{paginationCalculateRowSplitBudget:()=>ii,paginationHandleRowSlicesPlacement:()=>ai,paginationProcessRowSplitResult:()=>si,paginationResolveAlreadySlicedRow:()=>oi,paginationResolveOverflowingRow:()=>ei,paginationResolveRowWithRowspan:()=>ti,paginationResolveSplittableRow:()=>li,paginationSplitRow:()=>ni});const y="html2pdf4doc",v="html2pdf";function D(e,t){if("string"!=typeof e)return e;if(!e.includes(y))return e;if(t){if(!e.includes(t))return e;const o=t.replaceAll(y,v);if(o===t)return e;const i=e.replaceAll(t,o);return i===e?e:`${e},${i}`}const o=e.replaceAll(y,v);return o===e?e:`${e},${o}`}const R={init:"[html2pdf4doc]",root:"html2pdf4doc-root",paperFlow:"html2pdf4doc-paper-flow",contentFlow:"html2pdf4doc-content-flow",overlayFlow:"html2pdf4doc-overlay-flow",pageDivider:"html2pdf4doc-page",pageStartMarker:"[html2pdf4doc-page-start]",pageEndMarker:"[html2pdf4doc-page-end]",pageMarker:"[html2pdf4doc-page]",contentFlowStart:"html2pdf4doc-content-flow-start",contentFlowEnd:"html2pdf4doc-content-flow-end",style:"[html2pdf4doc-style]",frontpageTemplate:"[html2pdf4doc-frontpage]",headerTemplate:"[html2pdf4doc-header]",footerTemplate:"[html2pdf4doc-footer]",frontpageElement:"html2pdf4doc-frontpage",frontpageContent:"html2pdf4doc-frontpage-content",headerContent:"html2pdf4doc-header",footerContent:"html2pdf4doc-footer",pageNumberRoot:"[html2pdf4doc-page-number]",pageNumberCurrent:"[html2pdf4doc-page-number-current]",pageNumberTotal:"[html2pdf4doc-page-number-total]",pageChrome:"html2pdf4doc-page-chrome",pageBodySpacer:"html2pdf4doc-page-body-spacer",pageHeader:"html2pdf4doc-page-header",pageFooter:"html2pdf4doc-page-footer",printPageBreak:"html2pdf4doc-print-page-break",runningSafety:"html2pdf4doc-print-running",virtualPaper:"html2pdf4doc-virtual-paper",virtualPaperTopMargin:"html2pdf4doc-virtual-paper-margin-top",virtualPaperBottomMargin:"html2pdf4doc-virtual-paper-margin-bottom",virtualPaperGap:"html2pdf4doc-virtual-paper-gap",printIgnore:"[html2pdf4doc-print-ignore]",printHide:"[html2pdf4doc-print-hide]",neutral:"html2pdf4doc-neutral",word:"html2pdf4doc-word",textNode:"html2pdf4doc-text-node",textLine:"html2pdf4doc-text-line",textGroup:"html2pdf4doc-text-group",complexTextBlock:"html2pdf4doc-complex-text-block",printForcedPageBreak:"html2pdf4doc-print-forced-page-break",split:"[html2pdf4doc-split]",processed:"[html2pdf4doc-processed]",flagNoBreak:"[html2pdf4doc-flag-no-break]",flagNoHanging:"[html2pdf4doc-flag-no-hanging]",flagSlice:"[html2pdf4doc-flag-slice]",topCutPart:".html2pdf4doc-top-cut",bottomCutPart:".html2pdf4doc-bottom-cut",cleanTopCut:".html2pdf4doc-clean-top-cut",cleanBottomCut:".html2pdf4doc-clean-bottom-cut",tocPageNumber:"html2pdf4doc-toc-page-number"},x="background:#eee;color:#888;padding: 0 1px 0 0;";function N(e,t="",o=!1){"boolean"==typeof t&&(o=t,t=""),!0===o?this._debug._&&console.groupCollapsed(`%c${e}`,t):this._debug._&&console.group(`%c${e}`,t)}function B(e){this._debug._&&console.log(`%c ▲ ${e} `,x),this._debug._&&console.groupEnd()}function F(e,...t){this._debug._&&console.log(`[${e}]`,...t)}function k(e,...t){this._assert&&console.assert(e,"⛔",...t)}class A{constructor({DOM:e,config:t}){this.document=e,this.body=e.body,this._debug=t.debugMode?{...t.debugConfig.DOM}:{},this._assert=!!t.consoleAssert,Object.assign(this,o)}createElement(e){return this.document.createElement(e)}createDocumentFragment(){return this.document.createDocumentFragment()}cloneNode(e){return e?.cloneNode(!0)}cloneNodeWrapper(e){return e?.cloneNode(!1)}insertBefore(e,...t){const o=t.filter(e=>null!=e);e.before(...o)}insertAfter(e,...t){const o=t.filter(e=>null!=e);e.after(...o)}insertAtEnd(e,...t){const o=t.filter(e=>null!=e);e.append(...o)}insertAtStart(e,...t){const o=t.filter(e=>null!=e);e.prepend(...o)}insertInsteadOf(e,...t){this.insertBefore(e,...t),e.remove()}wrap(e,t){return e.before(t),t.append(e),t}moveContent(e,t){for(;e.firstChild;)t.append(e.firstChild);this.strictAssert(""===this.getInnerHTML(e))}moveRowContent(e,t){if(!e||!t)return void(this._debug._&&console.warn("moveRowContent(): sourceTR or targetTR is missing"));const o=this.getElementTagName(e),i=this.getElementTagName(t);this.strictAssert("TR"===o,`moveRowContent(): source is not TR, got ${o}`),this.strictAssert("TR"===i,`moveRowContent(): target is not TR, got ${i}`);const n=[...this.getChildren(e)],r=[...this.getChildren(t)];n.length!==r.length&&this._debug._&&console.warn(`moveRowContent(): cells count mismatch: ${n.length} (source) vs ${r.length} (target)`);const s=Math.min(n.length,r.length);for(let e=0;e0,"getAll(selectors), selectors:",e),1===e.length?[...this.getAllElements(e[0],t)]:[...e].flatMap(e=>[...this.getAllElements(e,t)])}getElement(e,t=this.document){return this.strictAssert(e),t.querySelector(e)}getAllElements(e,t=this.document){return this.strictAssert(e),t.querySelectorAll(e)}getElementById(e,t=this.document){return t.getElementById(e)}getNodeType(e){return e.nodeType}getRightNeighbor(e){return e.nextElementSibling}getLeftNeighbor(e){return e.previousElementSibling}getParentNode(e){return e.parentElement}getNodeValue(e){return e.nodeValue}getNodeWholeText(e){return e.wholeText}getLastElementChild(e){return e.lastElementChild}getFirstElementChild(e){return e.firstElementChild}getChildNodes(e){return e.childNodes}getChildren(e){return e.children}getElementOffsetParent(e){return e.offsetParent}getComputedStyle(e){return window.getComputedStyle(e)}getElementBCR(e){return e.getBoundingClientRect()}getElementOffsetLeft(e){return e?.offsetLeft}getElementOffsetHeight(e){return e?.offsetHeight}getElementOffsetWidth(e){return e?.offsetWidth}getElementOffsetTop(e){return e?.offsetTop}getElementOffsetBottom(e){return e?.offsetTop+e?.offsetHeight||void 0}getElementTagName(e){return e.tagName}getDataId(e){return e.dataset.id}getAttribute(e,t){if(!e||!t)return void(this._debug._&&console.warn("getAttribute() must have 2 params"));const o=t.charAt(0);if("."!==o&&"#"!==o||this.log("getAttribute",`you're really sure ${t} is attribute selector?`),"["===o){this.strictAssert("]"===t.at(-1),`the ${t} selector is not OK.`);const o=t.substring(1,t.length-1);return e.getAttribute(o)}e.getAttribute(t)}setAttribute(e,t,o){if(!e||!t)return void(this._debug._&&console.warn("setAttribute() must have 2 params"));const i=t.charAt(0);if("."===i){const o=t.substring(1);return void e.classList.add(o)}if("#"===i){const o=t.substring(1);return void(e.id=o)}if("["===i){this.strictAssert("]"===t.at(-1),`the ${t} selector is not OK.`);const i=t.substring(1,t.length-1);return void e.setAttribute(i,o||"")}this.log("setAttribute",`you're really sure ${t} is a selector?`)}setStyles(e,t){Object.entries(t).forEach(([t,o])=>{Array.isArray(o)?this.setStyle(e,t,o[0],o[1]||""):this.setStyle(e,t,o)})}setStyle(e,t,o,i=""){const n=this._toKebab(t);null==o||""===o?e.style.removeProperty(n):e.style.setProperty(n,String(o),i)}_toKebab=e=>{if(e.includes("-"))return e;const t=e.match(/^(webkit|moz|ms|o)(?=[A-Z])/);return t&&(e="-"+t[1]+"-"+e.slice(t[1].length)),e.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())};addClasses(e,...t){e.classList.add(...t)}removeAttribute(e,t){if(!e||!t)return void(this._debug._&&console.warn("removeAttribute() must have 2 params"));const o=t.charAt(0);if(this.strictAssert(o.match(/[a-zA-Z#\[\.]/),`removeAttribute() expects a valid selector, but received ${t}`),"."===o){const o=t.substring(1);return void e.classList.remove(o)}if("#"===o){const o=t.substring(1);return void e.removeAttribute(o)}if("["===o){this.strictAssert("]"===t.at(-1),`the ${t} selector is not OK.`);const o=t.substring(1,t.length-1);return void e.removeAttribute(o)}e.removeAttribute(attr)}removeAllAttributes(e){for(;e.attributes.length>0;)e.removeAttribute(e.attributes[0].name)}removeClasses(e,...t){e.classList.remove(...t)}removeAllClasses(e){e.classList=""}removeAllStyles(e){e.style=""}getInnerHTML(e){if("string"==typeof e){const t=this.document.querySelector(e);return t?t.innerHTML:void 0}return e.innerHTML}setInnerHTML(e,t){if("string"==typeof e){const o=this.document.querySelector(e);o&&(o.innerHTML=t)}e.innerHTML=t}isDocumentBody(e){return"BODY"===e.tagName}isTextNode(e){return e.nodeType===Node.TEXT_NODE}isElementNode(e){return e.nodeType===Node.ELEMENT_NODE}hasClass(e,t){return e.classList.contains(t)}hasID(e,t){return e.id===t}hasAttribute(e,t){return e.hasAttribute(t)}}class H{constructor(e){this.config=e,this._printWidth=parseFloat(this.config.paperWidth),this._printLeft=parseFloat(this.config.printLeftMargin),this._printRight=parseFloat(this.config.printRightMargin),this._printContentWidth=this._printWidth-this._printLeft-this._printRight+"px",this._flowPreviewPaddingBottom="100px",this._chromeBorderSafeSpace="2px",this._ensureBFC="display: flow-root",this.charWidth="10px"}create(){return this._pageRule()+this._layoutStyles().screen+this._layoutStyles().print+this._chromeStyles().screen+this._chromeStyles().print+this._serviceElementsStyle().screen+this._serviceElementsStyle().print+this._cutEdgeStyle()+(this.config.debugMode?this._testScreenOnlyStyle():"")}_pageRule(){return`@page {\n size: A4;\n size: ${`${this.config.paperWidth} ${this.config.paperHeight}`};\n margin-left: ${this.config.printLeftMargin};\n margin-right: ${this.config.printRightMargin};\n margin-top: ${this.config.printTopMargin};\n margin-bottom: 0;\n}`}_layoutStyles(){return{screen:`\n${R.root} {\n --paper-color: ${this.config.paperColor};\n display: flow-root;\n position: relative;\n z-index: 1;\n width: ${this._printContentWidth};\n margin: 0 auto;\n font-size: ${this.config.printFontSize};\n padding-bottom: ${this._flowPreviewPaddingBottom};\n}\n\n${R.contentFlow} {\n display: block;\n}\n\n${R.paperFlow} {\n display: block;\n position: absolute;\n width: 100%;\n z-index: -1;\n padding-bottom: ${this._flowPreviewPaddingBottom};\n pointer-events: none;\n}\n\n${R.overlayFlow} {\n display: block;\n position: absolute;\n width: 100%;\n z-index: 2147483647;\n padding-bottom: ${this._flowPreviewPaddingBottom};\n pointer-events: none;\n}\n\n${R.virtualPaper} {\n display: grid;\n grid-template-columns: 1fr;\n grid-template-rows: minmax(min-content, max-content) minmax(min-content, max-content) 1fr minmax(min-content, max-content) minmax(min-content, max-content);\n place-items: stretch stretch;\n place-content: stretch stretch;\n width: ${this._printContentWidth};\n height: ${this.config.paperHeight};\n font-size: ${this.config.printFontSize};\n}\n\n${R.virtualPaper}::before {\n position: absolute;\n content: '';\n width: ${this.config.paperWidth};\n height: ${this.config.paperHeight};\n left: -${this.config.printLeftMargin};\n background: var(--paper-color, white);\n box-shadow: rgba(0, 0, 0, 0.1) 2px 2px 12px 0px;\n z-index: -1;\n}\n\n${R.pageChrome} {\n display: block;\n pointer-events: none;\n}\n\n${R.pageBodySpacer} {\n display: block;\n pointer-events: none;\n}\n\n${R.pageFooter},\n${R.pageHeader} {\n display: block;\n position: relative;\n pointer-events: auto;\n}\n\n${R.pageFooter}::before,\n${R.pageHeader}::before {\n content: '';\n position: absolute;\n inset: 0;\n z-index: -1;\n background: var(--paper-color, white);\n}\n\n${R.pageFooter}::before {\n top: ${this._chromeBorderSafeSpace};\n}\n\n${R.pageHeader}::before {\n bottom: ${this._chromeBorderSafeSpace};\n}\n\n${R.virtualPaperTopMargin} {\n display: block;\n height: ${this.config.printTopMargin};\n}\n\n${R.virtualPaperBottomMargin} {\n display: block;\n height: ${this.config.printBottomMargin};\n}\n\n${R.virtualPaperGap} {\n display: block;\n padding-top: ${this.config.virtualPagesGap};\n}\n\n${R.contentFlowStart},\n${R.contentFlowEnd},\n${R.pageDivider},\n${R.runningSafety} {\n ${this._ensureBFC};\n}\n `,print:`\n@media print {\n\n ${R.root},\n ${R.overlayFlow},\n ${R.paperFlow} {\n padding: 0;\n }\n\n ${R.paperFlow},\n ${R.printHide} {\n display: none !important;\n }\n\n ${R.printIgnore} {\n display: contents !important;\n }\n\n ${R.virtualPaperTopMargin},\n ${R.virtualPaperBottomMargin},\n ${R.virtualPaperGap} {\n display: none !important;\n }\n\n ${R.pageChrome},\n ${R.frontpageElement},\n ${R.pageBodySpacer} {\n break-inside: avoid;\n }\n}\n `}}_chromeStyles(){return{screen:`\n${R.headerContent},\n${R.footerContent} {\n display: block;\n font-size: small;\n}\n\n${R.headerContent} p,\n${R.footerContent} p {\n margin: 0;\n}\n\n${R.headerContent} {\n padding-bottom: ${this.config.headerMargin};\n padding-top: 10px; /* for page numbers */\n}\n\n${R.footerContent} {\n padding-top: ${this.config.footerMargin};\n min-height: 32px; /* for page numbers */\n}\n\n${R.tocPageNumber} {\n min-width: 3ch;\n display: flex;\n justify-content: flex-end;\n align-items: baseline;\n}\n\n${D(R.pageNumberRoot)} {\n display: flex;\n column-gap: 2px;\n position: absolute;\n right: 0;\n text-align: right;\n line-height: 1;\n}\n\n${D(`${R.headerContent} ${R.pageNumberRoot}`,R.pageNumberRoot)} {\n top: 0;\n}\n\n${D(`${R.footerContent} ${R.pageNumberRoot}`,R.pageNumberRoot)} {\n bottom: 0;\n}\n `,print:""}}_cutEdgeStyle(){return`\n${R.topCutPart} {\n margin-top: 0 !important;\n}\n${R.bottomCutPart} {\n margin-bottom: 0 !important;\n}\n${R.cleanTopCut} {\n margin-top: 0 !important;\n padding-top: 0 !important;\n border-top: none !important;\n}\n${R.cleanBottomCut} {\n margin-bottom: 0 !important;\n padding-bottom: 0 !important;\n border-bottom: none !important;\n}\n `}_serviceElementsStyle(){const e="display: inline";return{screen:`\n.null {\n display: inline;\n padding: 0;\n margin: 0;\n font: 0;\n color: transparent;\n line-height: 0;\n border: none;\n outline: none;\n background: none;\n background-color: transparent;\n}\n\n${R.word},\n${R.textNode},\n${R.textLine},\n${R.textGroup},\n${R.neutral},\n${R.neutral} span {\n display: inline;\n padding: 0;\n margin: 0;\n font: inherit;\n color: inherit;\n line-height: inherit;\n background: none;\n background-color: transparent;\n}\n\n${R.textGroup} {\n display: block;\n}\n\n${R.textLine} {\n display: inline-block;\n}\n\n${R.textGroup} ${R.textLine} {\n ${e};\n}\n\n${R.complexTextBlock} {\n display: block;\n}\n\n${R.complexTextBlock} ${R.complexTextBlock} {\n ${e};\n}\n\n${R.printPageBreak} {\n ${this._ensureBFC};\n}\n\n${R.printForcedPageBreak} {\n display: block;\n visibility: hidden;\n height: 0;\n overflow: hidden;\n}\n `,print:`\n@media print {\n\n ${R.printPageBreak} {\n break-after: page;\n }\n\n ${R.textLine} {\n ${e};\n }\n}\n `}}_testScreenOnlyStyle(){return`\n/* DEBUG PREVIEW */\n@media screen {\n\n ${R.contentFlow} {\n background:repeating-linear-gradient(\n -45deg,\n rgba(222, 222, 222, .1),\n rgba(222, 222, 222, .1) 10px,\n rgba(222, 222, 222, .2) 10px,\n rgba(222, 222, 222, .2) 20px\n );\n }\n\n ${R.overlayFlow} {\n background:repeating-linear-gradient(\n 45deg,\n rgba(222, 222, 222, 0),\n rgba(222, 222, 222, 0) 18px,\n rgba(0, 166, 255, 0.05) 18px,\n rgba(0, 166, 255, 0.05) 20px\n );\n }\n\n ${R.virtualPaperGap} {\n background: #ff000020;\n }\n\n ${R.pageFooter},\n ${R.pageHeader} {\n background: #fff1ff99;\n }\n ${R.pageBodySpacer} {\n background: #ffee0020;\n }\n ${R.runningSafety} {\n background: #f200ff;\n outline: 0.1px dashed #f200ff88;\n }\n ${R.frontpageElement} {\n background: #00fcff20;\n }\n\n ${R.neutral} {\n background: #00ffee10;\n }\n\n ${R.textNode} {\n background: #00ff0010;\n }\n\n ${R.textGroup},\n ${R.textLine} {\n background: #0000ff08;\n }\n}\n `}}class I{constructor({config:e,DOM:t,node:i,selector:n}){this.success=!1,Object.assign(this,o),this.root,this.paperFlow,this.contentFlow,this.overlayFlow,this.frontpageTemplate,this.headerTemplate,this.footerTemplate,this._initialRoot,this._contentRoot,this._config=e,this._debug=e.debugMode?{...e.debugConfig.layout}:{},this._assert=!!e.consoleAssert,this._DOM=t,this._selector=n,this._node=i,this._customInitialRootSelector=e.initialRoot,this._defaultInitialRootSelector=n.init}create(){if(this._getTemplates(),this._insertStyle(),this._DOM.getElement(`style${this._selector.style}`)){if(this._createLayout(),this._DOM.getParentNode(this.root)!==this._initialRoot||this._DOM.getElementOffsetParent(this.paperFlow)!==this.root||this._DOM.getElementOffsetParent(this.contentFlow)!==this.root||this._DOM.getElementOffsetParent(this.overlayFlow)!==this.root)return this.strictAssert(this._DOM.getParentNode(this.root)===this._initialRoot,"Failed to insert the layout root into the DOM."),this.strictAssert(this._DOM.getElementOffsetParent(this.paperFlow)===this.root,"Failed to insert the paperFlow element into the DOM."),void this.strictAssert(this._DOM.getElementOffsetParent(this.contentFlow)===this.root,"Failed to insert the contentFlow element into the DOM.");this.success=!0}else console.error("Failed to add print styles into the DOM.")}_getTemplates(){this.strictAssert(this._selector.frontpageTemplate,"frontpageTemplate selector is missing"),this.strictAssert(this._selector.headerTemplate,"headerTemplate selector is missing"),this.strictAssert(this._selector.footerTemplate,"footerTemplate selector is missing"),this.frontpageTemplate=this._DOM.getInnerHTML(D(this._selector.frontpageTemplate)),this.headerTemplate=this._DOM.getInnerHTML(D(this._selector.headerTemplate)),this.footerTemplate=this._DOM.getInnerHTML(D(this._selector.footerTemplate))}_insertStyle(){this._node.insertStyle(new H(this._config).create())}_createLayout(){this._getInitialRoot(),this._initialRoot?(this.log("create Layout","initial root:",this._initialRoot),this._createRoot(),this._createPaperFlow(),this._createContentFlow(),this._createOverlayFlow(),this._DOM.moveContent(this._initialRoot,this.contentFlow),this._DOM.insertAtEnd(this._initialRoot,this.root),this._DOM.insertAtEnd(this.root,this.paperFlow,this.overlayFlow,this.contentFlow),this._insertContentFlowStartAndEnd(this.contentFlow),this._ignoreUnprintableEnvironment(this.root)):console.error("Failed to initialize the root element.")}_insertContentFlowStartAndEnd(e){const t=this._node.create(this._selector.contentFlowStart),o=this._node.create(this._selector.contentFlowEnd);return this._DOM.insertAtStart(e,t),this._DOM.insertAtEnd(e,o),{contentFlowStart:t,contentFlowEnd:o}}_getInitialRoot(){let e=this._customInitialRootSelector?this._DOM.getElement(this._customInitialRootSelector):this._DOM.getElement(this._defaultInitialRootSelector);if(!e){if(!this._DOM.body)return void console.error("We expected to find the BODY tag.");e=this._DOM.body,console.warn(`The printable area is currently unspecified and encompasses the entire contents of the BODY tag. To restrict the printed content to a specific area, include ${this._defaultInitialRootSelector} in the root element of the desired printing area.`)}return this._initialRoot=e,e}_createRoot(){const e=this._node.create(this._selector.root);return this._DOM.setStyles(e,{visibility:"hidden"}),this.root=e,e}_createPaperFlow(){const e=this._node.create(this._selector.paperFlow);return this.paperFlow=e,e}_createOverlayFlow(){const e=this._node.create(this._selector.overlayFlow);return this.overlayFlow=e,e}_createContentFlow(){const e=this._node.create(this._selector.contentFlow);return this.contentFlow=e,e}_ignoreUnprintableEnvironment(e){if(e===this._DOM.body)return void this.strictAssert(!1,"misshapen root");let t=this._DOM.getParentNode(e);this._DOM.setAttribute(t,this._selector.printIgnore),this._DOM.getChildNodes(t).forEach(t=>{if(t!==e&&this._DOM.isElementNode(t))this._DOM.setAttribute(t,this._selector.printHide);else{if(!this._node.isSignificantTextNode(t))return;{const e=this._node.createTextNodeWrapper();this._DOM.wrap(t,e),this._DOM.setAttribute(e,this._selector.printHide)}}}),this._DOM.isDocumentBody(t)||this._ignoreUnprintableEnvironment(t)}}function L(e){return function(t){return t._config.debugMode&&t._debug[e]}}const $=L("selectors");function G(e,t){if(!e||!t)return void($(this)&&console.warn("isSelectorMatching() must have 2 params","\n element: ",e,"\n selector: ",t));const o=[t];if("string"==typeof t&&t.includes("html2pdf4doc")){const e=t.replaceAll("html2pdf4doc","html2pdf");e!==t&&o.push(e)}return o.some(t=>{const o=t.charAt(0);if("."===o){const o=t.substring(1);return this._DOM.hasClass(e,o)}if("#"===o){const o=t.substring(1);return this._DOM.hasID(e,o)}if("["===o){this.strictAssert("]"===t.at(-1),`the ${t} selector is not OK.`);const o=t.substring(1,t.length-1);return this._DOM.hasAttribute(e,o)}return this._DOM.getElementTagName(e)===t.toUpperCase()})}function W(e){return!!this._DOM.isTextNode(e)&&this._DOM.getNodeValue(e).trim().length>0}function j(e){return"STYLE"===this._DOM.getElementTagName(e)}function z(e){return"IMG"===this._DOM.getElementTagName(e)}function V(e){return"svg"===this._DOM.getElementTagName(e)}function U(e){return"OBJECT"===this._DOM.getElementTagName(e)}function q(e){return"LI"===this._DOM.getElementTagName(e)}function K(e){return this.isSelectorMatching(e,this._selector.neutral)}function Y(e){return this.isSelectorMatching(e,this._selector.textNode)}function X(e){return this.isSelectorMatching(e,this._selector.textLine)}function Z(e){return this.isSelectorMatching(e,this._selector.textGroup)}function J(e){return this.isSelectorMatching(e,this._selector.pageStartMarker)}function Q(e){return this.isSelectorMatching(e,this._selector.contentFlowStart)}function ee(e){const t=this._DOM.getLeftNeighbor(e);return this.isSelectorMatching(t,this._selector.contentFlowStart)}function te(e){return this.isSelectorMatching(e,this._selector.contentFlowEnd)}function oe(e){return this.isSelectorMatching(e,this._selector.complexTextBlock)}function ie(e){return this.isComplexTextBlock(e)||this.isWrappedTextNode(e)||this.isWrappedTextLine(e)||this.isWrappedTextGroup(e)}function ne(e,t){return this.isSelectorMatching(e,this._selector.flagNoBreak)||this.isWrappedTextLine(e)||this.isWrappedTextGroup(e)||this.isInlineBlock(e,t)||this.notSolved(e)}function re(e){return this.isSelectorMatching(e,this._selector.flagNoHanging)}function se(e){return this.isSelectorMatching(e,this._selector.flagSlice)}function le(e){return this.isSelectorMatching(e,this._selector.printForcedPageBreak)}function ae(e,t){if(!(e instanceof HTMLElement))return;const o=(t||this._DOM.getComputedStyle(e)).display;return"inline"===o||"inline-block"===o||"inline-table"===o||"inline-flex"===o||"inline-grid"===o}function he(e,t){if(!(e instanceof HTMLElement))return;const o=(t||this._DOM.getComputedStyle(e)).display;return"inline-block"===o||"inline-table"===o||"inline-flex"===o||"inline-grid"===o}function ce(e,t){if(!(e instanceof HTMLElement))return;return"grid"===(t||this._DOM.getComputedStyle(e)).display}function de(e,t){if(!(e instanceof HTMLElement))return;const o=(t||this._DOM.getComputedStyle(e)).display;if("TABLE"!==this._DOM.getElementTagName(e)&&["table","inline-table"].includes(o))return!0;const i=e=>"table-row"===e,n=e=>"table-cell"===e;if(i(o)){const t=this._DOM.getChildren(e);for(const e of t)if(e instanceof HTMLElement&&n(this._DOM.getComputedStyle(e).display))return!0;return!1}if("table-row-group"===(r=o)||"table-header-group"===r||"table-footer-group"===r){const t=this._DOM.getChildren(e);for(const e of t){if(!(e instanceof HTMLElement))continue;if(!i(this._DOM.getComputedStyle(e).display))continue;const t=this._DOM.getChildren(e);for(const e of t)if(e instanceof HTMLElement&&n(this._DOM.getComputedStyle(e).display))return!0}return!1}var r;return!1}function ge(e,t){if(e instanceof HTMLElement) //! const computedStyle = style || this._DOM.getComputedStyle(element); return"TABLE"===this._DOM.getElementTagName(e); //! || ['table', 'inline-table'].includes(computedStyle.display) -}function pe(e,t){if(!(e instanceof HTMLElement))return;const o=t||this._DOM.getComputedStyle(e);return["block"].includes(o.display)&&["pre","pre-wrap","pre-line","break-spaces","nowrap"].includes(o.whiteSpace)}function ue(e,t){if(!(e instanceof HTMLElement))return;const o=t||this._DOM.getComputedStyle(e),i=o.display,n=o.gridAutoFlow;return("grid"===i||"inline-grid"===i)&&"row"===n}function _e(e,t){if(!(e instanceof HTMLElement))return;const o=t||this._DOM.getComputedStyle(e),i=o.display;if("flex"!==i&&"inline-flex"!==i)return!1;return(o.flexDirection||"").startsWith("row")}function fe(e,t){const o=t||this._DOM.getComputedStyle(e);return this.isTableNode(e,o)||this.isTableLikeNode(e,o)||this.isGridAutoFlowRow(e,o)}function me(e){return this._DOM.hasAttribute(e,"slough-node")}const be=L("selectorHeuristics");function we(e,t,o){const i=[],n=new Set;return be(this)&&console.group(o),e.forEach(e=>{const o=this._DOM.getAllElements(e,t),r=this.isHeuristicSelector(e);be(this)&&r&&console.log("🪄 [heuristic selector]",e,`\n${o.length} elements found`);for(const t of o)r&&!this.validateHeuristicSelectorMatch(t,e)||n.has(t)||(n.add(t),i.push(t))}),be(this)&&console.log(o,i.length?i:"has no elements"),be(this)&&console.groupEnd(o),i}function Se(e){return/:(only-child|first-child|last-child)\b/.test(e)}function Me(e,{allowWhitespaceText:t=!0,ignoreComments:o=!0}={}){const i=e&&e.parentNode;if(!i)return!1;for(let n=i.firstChild;n;n=n.nextSibling)if(n!==e){if(n.nodeType===Node.ELEMENT_NODE)return!1;if(n.nodeType!==Node.TEXT_NODE){if(n.nodeType===Node.COMMENT_NODE){if(o)continue;return!1}return!1}if(!t)return!1;if(n.nodeValue&&""!==n.nodeValue.trim())return!1}return!0}function Pe(e){const t=e&&e.parentNode;if(!t)return!1;for(let o=t.firstChild;o&&o!==e;o=o.nextSibling){if(o.nodeType===Node.TEXT_NODE&&o.nodeValue&&""!==o.nodeValue.trim())return!0;if(o.nodeType!==Node.COMMENT_NODE&&o.nodeType!==Node.ELEMENT_NODE&&o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE)return!0}return!1}function Ce(e){const t=e&&e.parentNode;if(!t)return!1;let o=!1;for(let i=t.firstChild;i;i=i.nextSibling)if(o){if(i.nodeType===Node.TEXT_NODE&&i.nodeValue&&""!==i.nodeValue.trim())return!0;if(i.nodeType!==Node.COMMENT_NODE&&i.nodeType!==Node.ELEMENT_NODE&&i.nodeType!==Node.TEXT_NODE&&i.nodeType!==Node.COMMENT_NODE)return!0}else i===e&&(o=!0);return!1}function Ee(e,t){return/:only-child\b/.test(t)?this.hasNoSignificantSiblingNodes(e,{allowWhitespaceText:!0,ignoreComments:!0}):/:first-child\b/.test(t)?!this.hasSignificantLeadingText(e):!/:last-child\b/.test(t)||!this.hasSignificantTrailingText(e)}function Te(e,t){return/:only-child\b/.test(t)?"has significant sibling nodes (text/elements)":/:first-child\b/.test(t)?"has significant leading text":/:last-child\b/.test(t)?"has significant trailing text":"failed heuristic validation"}function Oe(e,t){return this.isHeuristicSelector(t)?e.filter(e=>this.validateHeuristicSelectorMatch(e,t)):e}function ye(e,t=""){const o=this._DOM.getElement("head"),i=this._DOM.body;if(!o&&!i)return void console.error("Check the structure of your document. We didn`t find HEAD and BODY tags. HTML2PDF4DOC expects valid HTML.");const n=this.create("style",e);n?(this._DOM.setAttribute(n,this._selector.style,t),o?this._DOM.insertAtEnd(o,n):i?this._DOM.insertBefore(i,n):this.strictAssert(!1,"We expected to find the HEAD and BODY tags.")):console.error("Failed to create print styles")}const ve=L("positioning");function De(e,t){if(!e||!this._DOM.getParentNode(e))return!1;let o=e;for(;this._DOM.getParentNode(o)&&o!==t;){if(this._DOM.getFirstElementChild(this._DOM.getParentNode(o))!==o)return!1;o=this._DOM.getParentNode(o)}return o===t}function Re(e,t){if(!e||!this._DOM.getParentNode(e))return!1;let o=e;for(;this._DOM.getParentNode(o)&&o!==t;){if(this._DOM.getParentNode(o)===t){let e=this._DOM.getRightNeighbor(o);for(;!this._DOM.getElementOffsetHeight(e)&&!this._DOM.getElementOffsetWidth(e);)if(e=this._DOM.getRightNeighbor(e),this.isContentFlowEnd(e))return!0;return this.isContentFlowEnd(e)}if(this._DOM.getLastElementChild(this._DOM.getParentNode(o))!==o)return!1;o=this._DOM.getParentNode(o)}return o===t}function xe(e,t){return this._DOM.getElementOffsetTop(t)-this._DOM.getElementOffsetBottom(e)>-2}function Ne(e,t){const o=this._DOM.getElementOffsetBottom(e),i=this._DOM.getElementOffsetTop(t),n=o-i,r=n>=2;return ve(this)&&console.group("isLineKept?"),ve(this)&&console.log("\n",r,"\n","\n currentBottom",o,[e],"\n nextTop",i,[t],"\n delta",n),ve(this)&&console.groupEnd("isLineKept?"),r}function Be(e,t,o){const i="[init-position]",n="[init-vertical-align]",r="relative",s=o||this._DOM.getComputedStyle(t),l=s.position,a=s.verticalAlign;if(e)l!=r&&(this._DOM.setStyles(t,{position:r}),this._DOM.setAttribute(t,i,l)),"top"!=a&&(this._DOM.setStyles(t,{"vertical-align":"top"}),this._DOM.setAttribute(t,n,a));else{const e=this._DOM.getAttribute(t,i),o=this._DOM.getAttribute(t,n);e&&(this._DOM.setStyles(t,{position:e}),this._DOM.removeAttribute(t,i)),o&&(this._DOM.setStyles(t,{"vertical-align":o}),this._DOM.removeAttribute(t,n))}}function Fe(e,{prefer:t="self"}={}){if(!e)return null;const o=e=>"last"===t?this._DOM.getLastElementChild(e):"first"===t||"self"===t?this._DOM.getFirstElementChild(e):null,i=new Set;let n=e;for(;n&&!i.has(n);){i.add(n);if(this._DOM.getElementOffsetParent(n))return n;const e=this._DOM.getComputedStyle(n);if(!e)return null;const t=e.display,r=e.visibility,s=e.position;if("none"===t||"collapse"===r||"fixed"===s)return null;if("contents"===t){const e=o.call(this,n);if(!e)return null;n=e;continue}return null}return null}const ke=L("getters");function He(e,t){return this.getTop(e,t)}function Ae(e,t,o){const i=o||this._DOM.getComputedStyle(t),n=parseFloat(i.paddingTop)||0;return this.getTop(e,t)-n}function Ie(e,t,o){const i=o||this._DOM.getComputedStyle(t),n=parseFloat(i.paddingTop)||0;return this.getBottomWithMargin(e,t)-n}function Le(e,t=null,o=0,i=null,n=[],r=null){if(!e)return void(ke(this)&&console.warn("[getTop] element must be provided, but was received:",e,"\nThe function returned:",void 0));if(!(e instanceof HTMLElement))return void this.strictAssert(0,"[getTop] element must be HTMLElement, but was received:",e,"\nThe function returned:",void 0);if(null===t)return this._DOM.getElementOffsetTop(e);if(!(t instanceof HTMLElement))return void this.strictAssert(0,"[getTop] root must be HTMLElement, but was received:",t,"\nThe function returned:",void 0);if(i=i||{element:e,root:t},0===o&&!t.contains(e))return void this.strictAssert(0,"[getTop] the provided root does not contain the element.",{element:e,root:t,paramSnapshot:i},"\nThe function returned:",void 0);if(!(r=r||$e.call(this,t,i)))return void(ke(this)&&console.warn("Root has no a usable offset reference; nothing else to measure against. \nThe function returned:",void 0,{element:e,paramSnapshot:i,offsetParent:l,traversal:s}));if(e===t)return o;const s=[...n,e],l=this._DOM.getElementOffsetParent(e);if(!l)return void(ke(this)&&console.warn("Element has no offset parent; offset chain is broken. \nThe function returned:",void 0,{element:e,paramSnapshot:i,offsetParent:l,traversal:s}));const a=this._DOM.getElementOffsetTop(e);return l===t?a+o:l===r.sharedOffsetParent?(r.sharedOffsetParentIsBody&&!r.warnedAboutBody&&(r.warnedAboutBody=!0,ke(this)&&console.warn("getTop(): reached document.body while measuring offsets. Layout likely lacks positioned ancestors.",{element:e,root:t,paramSnapshot:i})),a+o-r.rootOffsetFromSharedParent):this.getTop(l,t,o+a,i,s,r)}function $e(e,t){const o=this._DOM.getElementOffsetParent(e);if(!o)return ke(this)&&console.warn("[getTop*]: root has no offset parent; cannot build relative offsets.",{root:e,paramSnapshot:t}),null;const i=this._DOM.getElementOffsetTop(e);return"number"!=typeof i?(ke(this)&&console.warn("[getTop*]: root offsetTop is not a number.",{root:e,sharedOffsetParent:o,paramSnapshot:t}),null):{sharedOffsetParent:o,rootOffsetFromSharedParent:i,sharedOffsetParentIsBody:o===e.ownerDocument?.body,warnedAboutBody:!1}}function Ge(e,t=null){if(e){if(null===t)return this._DOM.getElementOffsetBottom(e);if(t)return this.getTop(e,t)+this._DOM.getElementOffsetHeight(e);ke(this)&&console.warn("root must be provided, but was received:",t,"\nThe function returned:",void 0)}else ke(this)&&console.warn("[getBottom] element must be provided, but was received:",e,"\nThe function returned:",void 0)}function We(e,t){if(!e)return;const o=this.getBottom(e,t);let i;const n=this.createNeutralBlock();this._DOM.insertAfter(e,n);const r=this.getTop(n,t);this._DOM.removeNode(n);if(r>=o)i=r;else{i=o+parseInt(this._DOM.getComputedStyle(e).marginBottom)}return i}function je(e){const t=parseInt(this._DOM.getComputedStyle(e).marginTop),o=parseInt(this._DOM.getComputedStyle(e).marginBottom);return this._DOM.getElementOffsetHeight(e)+t+o}function ze(e,t){const o=parseInt(this._DOM.getComputedStyle(e).marginTop);return this.getTop(e,t)-o}function Ve(e){const t=this.create();this._DOM.insertAtEnd(e,t);const o=this._DOM.getElementOffsetWidth(t);return this._DOM.removeNode(t),o}function Ue(e,t="",o=!0){const i=this.create();o&&this._DOM.setStyles(i,{overflow:"auto"});const n=this._DOM.cloneNodeWrapper(e);this._DOM.setInnerHTML(n,t),this._DOM.insertAtEnd(i,n),this._DOM.insertBefore(e,i);const r=this._DOM.getElementOffsetHeight(i);return this._DOM.removeNode(i),r}function qe(e){const t=this.createNeutral();this._DOM.setInnerHTML(t,"!"),this._DOM.setStyles(t,{display:"block"}),this._DOM.insertAtEnd(e,t);const o=this._DOM.getElementOffsetHeight(t);return this._DOM.removeNode(t),o}function Ke(e,t=0){const o=this._DOM.getElementOffsetTop(e),i=this._DOM.cloneNode(e),n="!
".repeat(t);[...i.children].forEach(e=>this._DOM.setInnerHTML(e,n)),this._DOM.insertBefore(e,i);const r=this._DOM.getElementOffsetTop(e);return this._DOM.removeNode(i),r-o}function Ye(e){const t=this._DOM.getElementOffsetTop(e),o=this._DOM.cloneNodeWrapper(e);this._DOM.insertBefore(e,o);const i=this._DOM.getElementOffsetTop(e);return this._DOM.removeNode(o),i-t}function Xe(e){const t=this._DOM.getElementOffsetTop(e),o=this._DOM.cloneNodeWrapper(e),i=e.children.length,n=[...e.children];this._DOM.insertBefore(e,o);const r=[];for(let s=0;sthis._DOM.removeNode(e))}return this._DOM.removeNode(o),r}function Ze(e){if(!(e instanceof HTMLElement)||"TABLE"!==e.tagName)throw new Error("Expected a element.");const t=[...e.children].reduce((e,t)=>{const o=t.tagName;return"TBODY"===o?{...e,rows:[...e.rows,...t.children]}:"CAPTION"===o?(this.setFlagNoBreak(t),{...e,caption:t}):"COLGROUP"===o?(this.setFlagNoBreak(t),{...e,colgroup:t}):"THEAD"===o?(this.setFlagNoBreak(t),{...e,thead:t}):"TFOOT"===o?(this.setFlagNoBreak(t),{...e,tfoot:t}):"TR"===o?{...e,rows:[...e.rows,...t]}:(ke(this)&&t&&console.warn("unexpected:",t),{...e,unexpected:[...e.unexpected,...t]})},{caption:null,thead:null,tfoot:null,rows:[],unexpected:[]});return t.unexpected.length>0&&ke(this)&&console.warn(`something unexpected is found in the table ${e}`),t}function Je(e,t){const o=t||this._DOM.getComputedStyle(e),i=this.createNeutralBlock();this._DOM.setStyles(i,{display:"block",padding:"0",margin:"0",border:"0",height:"0",clear:"both",visibility:"hidden",contain:"layout"}),this._DOM.insertAtEnd(e,i);const n=this.getNormalizedTop(i,e,o);return this._DOM.removeNode(i),n}function Qe(e,t,o="both"){const i="bottom"!==o,n="top"!==o;if(e instanceof HTMLElement){const r=i?this.getTop(e,t):void 0,s=n?this.getBottom(e,t):void 0;return i&&!Number.isFinite(r)?(this.strictAssert(!1,"[resolveRowBoundsGeneric] failed to measure top for HTMLElement",{row:e,root:t,want:o}),{top:void 0,bottom:void 0}):n&&!Number.isFinite(s)?(this.strictAssert(!1,"[resolveRowBoundsGeneric] failed to measure bottom for HTMLElement",{row:e,root:t,want:o}),{top:void 0,bottom:void 0}):"top"===o?{top:r,bottom:r}:"bottom"===o?{top:s,bottom:s}:{top:r,bottom:s}}if(Array.isArray(e)){let r=i?1/0:void 0,s=n?-1/0:void 0,l=!1,a=!1;return e.forEach(e=>{if(e instanceof HTMLElement){if(i){const o=this.getTop(e,t);Number.isFinite(o)&&(r=Math.min(r,o),l=!0)}if(n){const o=this.getBottom(e,t);Number.isFinite(o)&&(s=Math.max(s,o),a=!0)}}}),"top"===o?l?{top:r,bottom:r}:(this.strictAssert(!1,"[resolveRowBoundsGeneric] no valid top found in row array",{row:e,root:t,want:o}),{top:void 0,bottom:void 0}):"bottom"===o?a?{top:s,bottom:s}:(this.strictAssert(!1,"[resolveRowBoundsGeneric] no valid bottom found in row array",{row:e,root:t,want:o}),{top:void 0,bottom:void 0}):i&&!l?(this.strictAssert(!1,"[resolveRowBoundsGeneric] no valid top found in row array",{row:e,root:t,want:o}),{top:void 0,bottom:void 0}):n&&!a?(this.strictAssert(!1,"[resolveRowBoundsGeneric] no valid bottom found in row array",{row:e,root:t,want:o}),{top:void 0,bottom:void 0}):{top:r,bottom:s}}return this.strictAssert(!1,"[resolveRowBoundsGeneric] unexpected row payload",{row:e,root:t,want:o}),{top:void 0,bottom:void 0}}L("creators");function et(e,t){let o;if(e){const t=e.charAt(0);if(t.match(/[#\[\.]/))o=this._DOM.createElement("div"),this._DOM.setAttribute(o,e);else{if(!t.match(/[a-zA-Z]/))return void this.strictAssert(!1,"Expected valid html selector ot tag name, but received:",e);o=this._DOM.createElement(e)}}else o=this._DOM.createElement("div");return t&&this._DOM.setInnerHTML(o,t),o}function tt(){return this.create(this._selector.neutral)}function ot(){const e=this.createNeutral();return e.style.display="block",e.style.clear="both",e}function it(){return this.create(this._selector.textNode)}function nt(){return this.create(this._selector.textLine)}function rt(){return this.create(this._selector.textGroup)}function st(e){const t=this.create(this._selector.flagNoBreak);return e&&this._DOM.setStyles(t,e),t}function lt(){return this.create(this._selector.printPageBreak)}function at(){return this.create(this._selector.complexTextBlock)}function ht(e){const t=this._DOM.cloneNodeWrapper(e);return this._DOM.setAttribute(t,".test-node"),this._DOM.setStyles(t,{position:"absolute",background:"rgb(255 239 177)",width:this.getMaxWidth(e)+"px"}),t}function ct(e,t){const o=this.create(this._selector.word);return this._DOM.setInnerHTML(o,e),o.dataset.index=t,o}function dt(){return this.create(this._selector.printForcedPageBreak)}function gt(e,t){if(!t)return null;const o=this.create();return this._DOM.setStyles(o,{display:"flex",flexWrap:"nowrap",alignItems:"center",justifyContent:"center",textAlign:"center",fontSize:"8px",fontFamily:"sans-serif",letterSpacing:"1px",textTransform:"uppercase",height:t+"px"}),e&&this._DOM.setInnerHTML(o,e),this.setFlagNoBreak(o),o}function pt({wrapper:e,caption:t,colgroup:o,thead:i,tfoot:n,tbody:r}){const s=e||this.create("table"),l=this.create("TBODY");return t&&this._DOM.insertAtEnd(s,t),o&&this._DOM.insertAtEnd(s,o),i&&this._DOM.insertAtEnd(s,i),r&&this._DOM.insertAtEnd(l,...r),this._DOM.insertAtEnd(s,l),n&&this._DOM.insertAtEnd(s,n),s}function ut(e){const t=this._DOM.cloneNodeWrapper(e);return this.unmarkPageStartElement(t),this.setFlagNoBreak(t),t}L("splitters");function _t(e){return e.split(/(?<=\n)/)}function ft(e){return(this._DOM.getNodeValue(e)||this._DOM.getInnerHTML(e)).split(/(?<=\s|-)/)}function mt(e){return(this._DOM.getNodeValue(e)||this._DOM.getInnerHTML(e)).trim().split(/(?<=\s|-)/).filter(e=>" "!=e)}function bt(e){const t=e,o=this.splitTextByWordsGreedy(e),i=o.map(e=>{const t=this._DOM.createElement("span");return this._DOM.setInnerHTML(t,e+" "),t}),n=this.createTestNodeFrom(e);return this._DOM.insertAtEnd(n,...i),this._DOM.insertAtEnd(e,n),{splittedNode:t,nodeWords:o,nodeWordItems:i}}const wt=L("markers");function St(e,t){this._markupDebugMode&&this._DOM.setAttribute(e,this._selector.processed,"🏷️ "+t)}function Mt(e){this._DOM.setAttribute(e,this._selector.flagNoBreak)}function Pt(e,t){this._DOM.setAttribute(e,this._selector.flagNoHanging,t)}function Ct(e){this._DOM.setAttribute(e,this._selector.flagSlice)}function Et(e,t){this._DOM.setAttribute(e,this._selector.pageStartMarker,`${t}`)}function Tt(e){this._DOM.removeAttribute(e,this._selector.pageStartMarker)}function Ot(e,t){this._DOM.setAttribute(e,this._selector.pageEndMarker,`${t}`)}function yt(e,t){this._DOM.setAttribute(e,this._selector.pageMarker,`${t}`)}function vt(e){wt(this)&&console.log("[mark ⊤ cut]",e),e&&this._DOM.setAttribute(e,this._selector.cleanTopCut)}function Dt(e){wt(this)&&console.log("[mark ⊥ cut]",e),e&&this._DOM.setAttribute(e,this._selector.cleanBottomCut)}function Rt(e){wt(this)&&console.log("[mark ⊤ cut]",e),e&&this._DOM.setAttribute(e,this._selector.topCutPart)}function xt(e){wt(this)&&console.log("[mark ⊥ cut]",e),e&&this._DOM.setAttribute(e,this._selector.bottomCutPart)}function Nt(e){if(e&&e.length)if(1!==e.length)for(let t=0;t0,i=t0,n=t","color:blue",o),r=o,s=[...this._DOM.getChildren(o)]):Array.isArray(o)?(wt(this)&&console.log("%c[markSliceCutsInRows] It is an Array","color:blue",o),r=void 0,s=o):this.strictAssert(0,"we expected TR or an array of elements!"),!r&&!s.length){wt(this)&&console.log("%c[markSliceCutsInRows] There was no split","color:red",{rowWrapper:r,cellWrappers:s});break}i&&(r&&(wt(this)&&console.log("[markSliceCutsInRows] rowWrapper ⊥",r),this.markTopCut(r)),s.forEach(e=>{wt(this)&&console.log("[markSliceCutsInRows] cell 🖍️ ⊥",e),this.markTopCut(e)})),n&&(r&&(wt(this)&&console.log("[markSliceCutsInRows] rowWrapper ⊤",r),this.markBottomCut(r)),s.forEach(e=>{wt(this)&&console.log("[markSliceCutsInRows] cell 🖍️ ⊤",e),this.markBottomCut(e)}))}else wt(this)&&console.log("%c[markSliceCutsInRows] The rows were not passed. Doing nothing.","color:red")}L("wrappers");function Ft(e){const t=this._DOM.getChildren(e),o=this.createNeutralBlock();return this._DOM.insertAtStart(o,...t),this._DOM.insertAtStart(e,o),o}const kt=L("fitters");function Ht({element:e,height:t,width:o,vspace:i,hspace:n}){const r=i/t,s=n/o,l=ra&&(g||(g=this.wrapNodeChildrenWithNeutralBlock(s),d=this._DOM.getElementOffsetHeight(g)||d),this.fitElementWithinHeight(g,a),n=!0,kt(this)&&console.warn("💢 scaleCellsToHeight: resized cell content",{cell:s,target:a}))}return n}function Lt(e,t){this._DOM.setStyles(e,{"box-sizing":"border-box",width:`${this._DOM.getElementOffsetWidth(t)}px`,"min-width":`${this._DOM.getElementOffsetWidth(t)}px`})}function $t(e){this.copyNodeWidth(e,e),this._DOM.getAll("td",e).forEach(e=>this.copyNodeWidth(e,e))}function Gt(e){Array.isArray(e)&&e.forEach(e=>{e&&this.copyNodeWidth(e,e)})}function Wt(e,t={}){const{descentRatio:o=.22,normalLH:i=1.2,safety:n=1}=t,r=getComputedStyle(e),s=parseFloat(r.fontSize)||0;let l;if("normal"!==r.lineHeight&&r.lineHeight){const e=parseFloat(r.lineHeight);l=Number.isFinite(e)?e:i*s}else l=i*s;const a=(Math.max(0,(l-s)/2)+o*s)*n;return Math.ceil(a)}const jt=L("pageBreaks");function zt(e,t){let o=e;for(;;){const e=this.findFirstChildParent(o,t);if(!e||e===o)break;o=e}return o}function Vt(e,t,o){jt(this)&&console.group("➗ findBetterPageStart");let i=!1,n=!1,r=!1;const s=t?this.getTop(t,o):0;jt(this)&&console.log("Start calculations:",{pageStart:e,lastPageStart:t,root:o,topLimit:s});const l=this.findFirstChildParentFromPage(e,s,o);let a;if(l)a=l;else{a=this.getTop(e,o){if(this.isSTYLE(t))return to(this)&&console.info("🚸 (getPreparedChildren) ignore STYLE",[t]),e;if(this.isSignificantTextNode(t)){const o=this.createTextNodeWrapper();return this._DOM.wrap(t,o),e.push(o),to(this)&&console.info("🚸 (getPreparedChildren) wrap and return TEXT NODE",[t]),e}if(this._DOM.isElementNode(t)){if(this.shouldSkipFlowElement(t,{context:"getPreparedChildren"}))return e;if(!this._DOM.getElementOffsetParent(t)){const o=this.getPreparedChildren(t);return o.length>0&&e.push(...o),to(this)&&console.info("%c🚸 (getPreparedChildren) * no offset parent — unwrapped","color:green",o,[t]),e}return e.push(t),to(this)&&console.info("🚸 (getPreparedChildren) * normal node",[t]),e}return to(this)&&console.info("%c🚸 (getPreparedChildren) IGNORE whitespace / comment ...","color:red",[t]),e},[]),to(this)&&console.groupEnd("⚗️🚸 distill children"),to(this)&&console.info("🚸 distilled children",t);const o=ho.call(this,t),i=this.isInline(e);o&&(to(this)&&console.info("🚸 isVerticalFlowDisrupted in children of element",[e]),i?(to(this)&&console.info("🎒🚸 parent element is inline wrapper",[e]),t=[lo.call(this,e)]):t=so.call(this,t))}}return to(this)&&console.info("🚸 getPreparedChildren:",t),to(this)&&console.groupEnd("🚸 getPreparedChildren of"),t}function io(e,t,o,i){let n=[];if(this.isNoBreak(e))return to(this)&&console.info("🧡 isNoBreak",e),[];if(this.isComplexTextBlock(e))return to(this)&&console.info("💚 ComplexTextBlock",e),this._paragraph.split(e)||[];if(this.isWrappedTextNode(e))return to(this)&&console.info("💚 TextNode",e),this._paragraph.split(e)||[];if(!co.call(this,e))return to(this)&&console.info("🪲 getSplitChildren: empty node, return []",e),[];const r=this._DOM.getComputedStyle(e);if(this.isTableNode(e,r))to(this)&&console.info("💚 TABLE",e),n=this._table.split(e,t,o,i,r)||[];else if(this.isTableLikeNode(e,r))to(this)&&console.info("💚 TABLE like",e),n=this._tableLike.split(e,t,o,i,r)||[];else if(this.isPRE(e,r))to(this)&&console.info("💚 PRE",e),n=this._pre.split(e,t,o,i,r)||[];else if(this.isFlexRow(e,r)){to(this)&&console.info("🩷 Flex ROW",e);let t=this.getPreparedChildren(e);n=ao.call(this,t)}else this.isGridAutoFlowRow(e,r)?(to(this)&&console.info("💜 GRID"),n=this._grid.split(e,t,o,i)||[]):(to(this)&&console.info("💚 found some node - use main this.getPreparedChildren() for:",e),n=this.getPreparedChildren(e));return n}function no(e){const t=[];if(!e||!this||!this._DOM)return t;let o=e;for(;o;){let e=this._DOM.getFirstElementChild(o);for(;e&&this.shouldSkipFlowElement(e,{context:"getFirstChildren:firstChild"});)e=this._DOM.getRightNeighbor(e);if(!e)break;if(this.isSyntheticTextWrapper(e))break;t.push(e),o=e}return t}function ro(e){const t=[];if(!e||!this||!this._DOM)return t;let o=e;for(;o;){let e=this._DOM.getLastElementChild(o);for(;e&&this.shouldSkipFlowElement(e,{context:"getLastChildren:lastChild"});)e=this._DOM.getLeftNeighbor(e);if(!e)break;if(this.isSyntheticTextWrapper(e))break;t.push(e),o=e}return t}function so(e){let t=null;const o=[];return e.forEach(e=>{this.isInline(e)?(t||(t=lo.call(this,e),o.push(t)),this._DOM.insertAtEnd(t,e)):(t=null,o.push(e))}),o}function lo(e){const t=this.createComplexTextBlock();return this._DOM.wrap(e,t),t}function ao(e){const t=e.filter(e=>this._DOM.getElementOffsetHeight(e)>0);return t.length>0?t:e}function ho(e){return e.some((e,t,o)=>{const i=e,n=o[t+1];if(!n)return!1;return this._DOM.getElementOffsetBottom(i)>this._DOM.getElementOffsetTop(n)})}function co(e){let t=e.firstChild;for(;t;){if(this._DOM.isElementNode(t)){if(!this.shouldSkipFlowElement(t,{context:"hasRenderableChild"}))return!0}else if(this.isSignificantTextNode(t))return!0;t=t.nextSibling}return!1}const go=L("media"),po=new Set(["IMG","SVG","OBJECT","EMBED","IFRAME","VIDEO","AUDIO","CANVAS"]);function uo(e,t="self"){return"last"===t?this._DOM.getLastElementChild(e):this._DOM.getFirstElementChild(e)}function _o(e){if(!e)return!1;const t=this._DOM.getElementTagName(e);if(!t)return!1;if("INPUT"===t){return"image"===(this._DOM.getAttribute(e,"type")||"").toLowerCase()}return po.has(t)}function fo(e,{prefer:t="self"}={}){if(!e)return null;const o=new Set;let i=e;for(;i&&!o.has(i);){if(o.add(i),this.isReplacedElement(i))return i;if("function"==typeof this.resolveFlowElement){const e=this.resolveFlowElement(i,{prefer:t});if(e&&e!==i){if(this.isReplacedElement(e))return e;i=e;continue}}const e=[...this._DOM.getChildren(i)].filter(e=>{const t=this._DOM.getComputedStyle(e)?.display;return"none"!==t});if(1!==e.length)return go(this)&&console.info("🧭 resolveReplacedElement: branching or empty wrapper",i,e),null;i=uo.call(this,i,t)||e[0]}return null}const mo=L("slicers");function bo({rootNode:e,rootComputedStyle:t,children:o,firstPartHeight:i,fullPageHeight:n,firstChild:r,points:s=[]}){if(!o.length)return mo(this)&&console.log("🧶 [getSplitPoints] %c has no children, early returns []","font-weight:bold",{rootNode:e}),[];const l=t=>{const o=this.findBetterPageStart(t,s.at(-1),e);return s.length||o!==r?(mo(this)&&console.log("%c 🧼🧼🧼🧼 push(point) in registerPoint()","color:violet",{point:o,points:s,firstChild:r},s.length),s.push(o),!1):(mo(this)&&console.log("%c !points.length && point === children[0] && children[1]","color:red"),mo(this)&&console.log("%c 🅾️ push(null) in registerPoint()","color:red"),s.push(null),!0)};mo(this)&&console.group("🧶 getSplitPoints"),mo(this)&&console.log("points.length",s.length);const a=t||this._DOM.getComputedStyle(e),h=new WeakMap,c=e=>{let t=h.get(e);return t||(t=Object.create(null),h.set(e,t)),t},d=t=>{if(!t)return NaN;const o=c(t);return"top"in o||(o.top=this.getNormalizedTop(t,e,a)),o.top},g=t=>{if(!t)return NaN;const o=c(t);return"bottomWithMargin"in o||(o.bottomWithMargin=this.getNormalizedBottomWithMargin(t,e,a)),o.bottomWithMargin},p=e=>{if(!e)return 0;const t=c(e);return"offsetHeight"in t||(t.offsetHeight=this._DOM.getElementOffsetHeight(e)),t.offsetHeight};this.setInitStyle(!0,e,a);let u=!1;const _=()=>(u||(u=!0,mo(this)&&console.groupEnd(`walking through ${o.length} children`),this.setInitStyle(!1,e,t),mo(this)&&console.groupEnd("getSplitPoints")),s);mo(this)&&console.group(`walking through ${o.length} children`,o);for(let t=0;th))if(mo(this)&&console.log("[getSplitPoints]",`next overtook the floater : (nextElementTop) ${b} > ${h}`,{currentElement:u},"does current overflow? let's check.",{isNextElementTopFinite:w}),(this.isSVG(u)||this.isIMG(u))&&mo(this)&&console.log("%cIMAGE","color:red;text-weight:bold"),S=g(u),S<=h){if(w){mo(this)&&console.log("[getSplitPoints]",`current fits: (currentElementBottom) ${S} <= ${h}, 🍎 register nextElement as Point.`,{currentElement:u,nextElement:m});if(l(m))return mo(this)&&console.log("%cNULL CASE, return","color:red;text-weight:bold"),_();continue}mo(this)&&console.log("[getSplitPoints] nextElementTop not finite and current fits tail window",{currentElementBottom:S,floater:h,nextElement:m})}else mo(this)&&console.log(`🔪🥒 try to split overflowing current: (currentElementBottom > ) ${S} > ${h}`,{currentElement:u}),M=!0;if(!m){mo(this)&&console.log("%c[getSplitPoints] !nextElement","color:red"),mo(this)&&console.log("%c[getSplitPoints] * Try to split it. 🔪🥒","color:blue"),S=S??g(u);let t=u;if(u.parentElement&&e.contains(u.parentElement)){let o=u.parentElement;for(;o&&e.contains(o)&&o!==e&&!this._DOM.getRightNeighbor(o);)t=o,o=o.parentElement}const o=t===u?S:g(t);if(o<=h){mo(this)&&console.log("%c 🍕 [getSplitPoints] !nextElement branch fits with container shell","color:violet",{currentElementBottom:S,containerBottom:o,floater:h,containerElement:t});continue}M=!0}if(!M)continue;let P=[];const C=this.getSplitChildren(u,i,n,e);if(C.length){if(P=bo.call(this,{rootNode:e,rootComputedStyle:a,children:C,firstPartHeight:i,fullPageHeight:n,firstChild:r,points:s}),0===P.length){const e=Math.max(i,n),t=p(u),o=t>e&&(!P.length||1===P.length&&null===P[0]);if(mo(this)&&console.log("room (Math.max)",e),o){if(mo(this)&&console.warn("%c⚠️ UNSPLITTABLE OVERSIZED ELEMENT — SCALE IT","color:white; background:red; font-weight:bold;",u,`height: ${t}`),!s.length&&u===r)return mo(this)&&console.warn("🅾️ (1) points.push(null) in isUnbreakableOversized"),s.push(null),_();if(m){if(l(m))return _()}}else if(l(u))return _()}}else{mo(this)&&console.log("🍎 currentElementChildren.length == 0");const e=p(u);if(e>c&&(!P.length||1===P.length&&null===P[0])){if(mo(this)&&console.warn("%c⚠️ UNSPLITTABLE OVERSIZED ELEMENT — SCALE IT","color:white; background:red; font-weight:bold;",u,`height: ${e}`),mo(this)&&console.warn("🅾️ (2) points.push(null) in isUnbreakableOversized"),!s.length&&u===r)return s.push(null),_();if(m){mo(this)&&console.warn("🅾️🅾️🅾️🅾️🅾️🅾️🅾️🅾️ registerPoint(nextElement)");if(l(m))return _()}}else{if(l(u))return _()}}}return _()}function wo(e,t,o,i,n){mo(this)&&console.group("[✖️] getSplitPointsPerCells");const r=e.map((e,r)=>{mo(this)&&console.group(`(•) Split CELL.${r} in:`,n);let s=[];const l=o-(t[r]||0),a=i-(t[r]||0);let h=this.getSplitChildren(e,l,a,n);if(h.length){const t=h[0];mo(this)&&console.log("firstChild",t),s=this.getSplitPoints({rootNode:e,children:h,firstPartHeight:l,fullPageHeight:a,firstChild:t})}else mo(this)&&console.log(`(•) empty cell #${r}`);return mo(this)&&console.log(`(•) return splitPoints for CELL#${r}`,s),mo(this)&&console.groupEnd(),s}),s=r.some(Co);mo(this)&&console.log("🧽🧽🧽🧽🧽🧽🧽 isFirstPartEmptyInAnyCell",s);let l=r,a=!1;if(s){l=e.map((e,r)=>{mo(this)&&console.group(`(••) Split CELL.${r} in:`,n);const s=o-(t[r]||0),l=i-(t[r]||0),a=this.getSplitChildren(e,s,l,n),h=a[0];mo(this)&&console.log("firstChild",h);let c=[];return a.length&&(c=this.getSplitPoints({rootNode:e,children:a,firstPartHeight:l,fullPageHeight:l,firstChild:h})),mo(this)&&console.log(`(••) return splitPoints for CELL#${r}`,c),mo(this)&&console.groupEnd(),c}),mo(this)&&console.log("[••] splitPointsPerCell",l);for(let e=0;e0&&this.strictAssert(o.every(e=>null!==e),"sliceNodeBySplitPoints: splitPoints contains null — sanitize upstream before slicing"),this.strictAssert(o.every(e=>!e||e.nodeType===Node.ELEMENT_NODE&&(t===e||t.contains(e))),"sliceNodeBySplitPoints: split point is not an Element within rootNode");for(let e=0;e<=o.length;e++){const n=o[e-1]??null,r=o[e]??null,s=this.cloneAndCleanOutsideRange(t,n,r);this.normalizeContentCuts({slice:s,top:null!==n,bottom:null!==r}),this._DOM.getChildNodes(s).length>0&&i.push(s)}return mo(this)&&console.log(i),mo(this)&&console.groupEnd(`🔪 (${e}) sliceNodeBySplitPoints`),i}function Mo({slice:e,top:t=!1,bottom:o=!1}){if(e){if(t){const t=[...this.getFirstChildrenChain(e)];t.forEach(e=>this.markCleanTopCut(e)),mo(this)&&console.log("[normalizeContentCuts] topChain 👗",t)}if(o){const t=[...this.getLastChildrenChain(e)];t.forEach(e=>this.markCleanBottomCut(e)),mo(this)&&console.log("[normalizeContentCuts] bottomChain 👗",t)}}else mo(this)&&console.log("[normalizeContentCuts] no slice has been passed; return")}function Po({index:e,rootNode:t,splitPoints:o}){mo(this)&&console.group(`🔪 (${e}) sliceNodeContentBySplitPoints`);const i=[];for(let e=0;e<=o.length;e++){const n=o[e-1]??null,r=o[e]??null,s=this.cloneAndCleanOutsideRange(t,n,r);mo(this)&&console.log({slice:s});const l=this.createNeutralBlock();for(;s.firstChild;)l.appendChild(s.firstChild);l.childNodes.length>0&&i.push(l)}return mo(this)&&console.log(i),mo(this)&&console.groupEnd(`🔪 (${e}) sliceNodeContentBySplitPoints`),i}function Co(e){return!!Array.isArray(e)&&(e.length>0&&null===e[0])}function Eo(e,t,o){t&&t.setAttribute("split","start"),o&&o.setAttribute("split","end");let i=e.cloneNode(!0);if(t){let t=i.querySelector('[split="start"]'),o=t.previousElementSibling;for(;o;){let e=o;o=o.previousElementSibling,e.remove()}let n=t.parentElement;for(;n&&n!==e;){let e=n.previousElementSibling;for(;e;){let t=e;e=e.previousElementSibling,t.remove()}n=n.parentElement}t.removeAttribute("split")}if(o){let t=i.querySelector('[split="end"]'),o=t.nextElementSibling;for(;o;){let e=o;o=o.nextElementSibling,e.remove()}let n=t.parentElement;for(;n&&n!==e;){let e=n.nextElementSibling;for(;e;){let t=e;e=e.nextElementSibling,t.remove()}n=n.parentElement}t.remove()}return t&&t.removeAttribute("split"),o&&o.removeAttribute("split"),i}const To=L("flowfilters"),Oo="__html2pdf4docFlowFilter",yo=[{test:e=>"none"===e.display,cache:{reason:"display:none",message:"* display:none — skipped"}},{test:e=>"absolute"===e.position,cache:{reason:"position:absolute",message:"* position:absolute — skipped"}},{test:e=>"fixed"===e.position,cache:{reason:"position:fixed",message:"* position:fixed — skipped"}},{test:e=>"collapse"===e.visibility,cache:{reason:"visibility:collapse",message:"* visibility:collapse — skipped"}}];function vo(e,t,o,i,{cached:n}={cached:!1}){if(!To(e))return;const r=t?`(${t}) `:"",s=n?" (cached)":"";console.info(`🚸 ${r}${o.message}${s}`,[i])}function Do(e,{context:t="",computedStyle:o}={}){if(!(e&&this&&this._DOM&&this._DOM.isElementNode(e)))return!1;const i=e[Oo];if(i)return vo(this,t,i,e,{cached:!0}),!0;const n=o??this._DOM.getComputedStyle(e);if(!n)return!1;for(const o of yo)if(o.test(n))return e[Oo]=o.cache,vo(this,t,o.cache,e),!0;return!1}L("pagination");function Ro({cells:e,splitPointsPerCell:t,sliceCell:o}){return t.map((t,i)=>{const n=e[i];return o({cell:n,index:i,splitPoints:t})})}function xo({originalRow:e,originalCells:t,slicedCellsPerOriginal:o,beginRow:i,cloneCellFallback:n,handleCell:r,finalizeRow:s}){const l=Math.max(...o.map(e=>e.length)),a=[];for(let h=0;h{const i=o[t][h]||n(e);r({context:l,cellClone:i,originalCell:e,cellIndex:t})}),a.push(s({context:l}))}return a}function No({originalRow:e,originalCells:t,splitPointsPerCell:o,sliceCell:i,beginRow:n,cloneCellFallback:r,handleCell:s,finalizeRow:l}){if(!Array.isArray(o)||!o.length)return[];const a=this.sliceCellsBySplitPoints({cells:t,splitPointsPerCell:o,sliceCell:i});return this.buildRowSlices({originalRow:e,originalCells:t,slicedCellsPerOriginal:a,beginRow:n,cloneCellFallback:r,handleCell:s,finalizeRow:l})}function Bo({usedRemainingWindow:e,isFirstPartEmpty:t,firstSliceTop:o,firstSliceBottom:i,pageBottom:n,epsilon:r=.5}){return{placeOnCurrentPage:e&&!t,remainingWindowSpace:Math.max(0,n-o),exceedsWindow:i>n+r}}function Fo({currentRows:e,index:t,rowSlices:o}){return Array.isArray(e)?(e.splice(t,1,...o),e):[]}const ko=L("pagination");function Ho({cells:e,targetHeight:t,shells:o}){return!!(Array.isArray(e)&&e.length&&t>0)&&this.scaleCellsToHeight(e,t,o)}function Ao({needsScalingInFullPage:e,cells:t}){return Boolean(e&&Array.isArray(t)&&t.length)}function Io({needsScalingInFullPage:e,scaleCallback:t,payload:o}){if(!e)return!1;if("function"!=typeof t)return!1;const i=t(o||{});return!i&&this&&this._debug&&this._debug._&&ko(this)&&console.warn("[pagination.scaling] requested full-page scaling but callback reported no change",o),Boolean(i)}L("pagination");function Lo(e,t,o){e&&Array.isArray(e.rows)&&e.rows.splice(t,1,...o)}function $o({rows:e,DOM:t,cellTagFilter:o,guardCallback:i}){if(!Array.isArray(e))return{};let n=!1,r=!1,s=!1,l=null;e.forEach(e=>{const i=Array.isArray(e)?e:Array.from(t.getChildren(e)||[]);null==l&&(l=i.length),i.length!==l&&(s=!0),i.forEach(e=>{const i=t.getElementTagName(e);if(!o||o(i,e)){const t=parseInt(e.getAttribute?.("rowspan"));Number.isFinite(t)&&t>1&&(n=!0);const o=parseInt(e.getAttribute?.("colspan"));Number.isFinite(o)&&o>1&&(r=!0)}})});const a={hasRowspan:n,hasColspan:r,inconsistentCells:s};return i?.(a),a}L("pagination");function Go(e){if(!e||"object"!=typeof e)throw new Error("splitter kernel adapter must be an object.");if(!e.rows||"object"!=typeof e.rows)throw new Error("splitter kernel adapter must expose a rows provider.");if("function"!=typeof e.rows.replaceRow)throw new Error("splitter kernel adapter rows.replaceRow must be a function.")}function Wo(e,{rowIndex:t,rowSlices:o}){Go(e);const i=Number.isFinite(t)?t:0,n=Array.isArray(o)?o:[],r=e.rows;r.replaceRow({rowIndex:i,rowSlices:n}),r.syncEntries?.({rowIndex:i,rowSlices:n});const s=e.guards?.getConfig?.({rowIndex:i,rowSlices:n})??r.getGuardConfig?.({rowIndex:i,rowSlices:n})??null;let l=null;if(s){const t={rows:s.rows,DOM:s.DOM||this._DOM,cellTagFilter:s.cellTagFilter,guardCallback:s.guardCallback};Array.isArray(t.rows)&&t.DOM&&(l=this.computeRowFlags(t),e.guards?.onFlags?.({flags:l,rowIndex:i,rowSlices:n}))}return e.metrics?.refresh?.({rowIndex:i,rowSlices:n,flags:l}),r.onRowsChanged?.({rowIndex:i,rowSlices:n,flags:l}),{flags:l}}L("pagination");function jo({cells:e}){return Array.isArray(e)&&e.length?e.map(e=>{if(!e)return 0;const t=this._DOM.getComputedStyle(e),o=(parseFloat(t?.paddingTop)||0)+(parseFloat(t?.paddingBottom)||0)+(parseFloat(t?.borderTopWidth)||0)+(parseFloat(t?.borderBottomWidth)||0);return Number.isFinite(o)?Math.max(0,o):0}):[]}const zo=L("pagination");function Vo({ownerLabel:e,DOM:t,row:o,targetHeight:i,cachedShells:n,getRowShellHeightsCallback:r,scaleCellsToHeightCallback:s}){if(e||zo(this)&&console.warn("[scaleRowCellsToHeight] 👤 Owner wanted!",{owner:e}),!o)return zo(this)&&console.warn("[pagination.overflow] Missing row for scaling.",{owner:e}),!1;if("function"!=typeof s)return zo(this)&&console.warn("[pagination.overflow] scaleCellsToHeight callback is required.",{owner:e}),!1;const l=t,a=l&&"function"==typeof l.getChildren?l.getChildren(o):null;return s(a?[...a]:[],i,Array.isArray(n)?n:"function"==typeof r?r(o):[])}function Uo({ownerLabel:e,rowIndex:t,row:o,availableRowHeight:i,fullPageHeight:n,splitStartRowIndexes:r,reasonTail:s,reasonFull:l,registerPageStartCallback:a,scaleProblematicCellsCallback:h,debugLogger:c}){return e||zo(this)&&console.warn("[handleRowOverflow] 👤 Owner wanted!",{owner:e}),Array.isArray(r)?"function"!=typeof a?(zo(this)&&console.warn("[pagination.overflow] registerPageStart callback is required.",{owner:e}),t):i!1,isSlice:n=()=>!1}=t,{handleRowWithRowspan:r=()=>e.rowIndex,handleSplittableRow:s=()=>e.rowIndex,handleAlreadySlicedRow:l=()=>e.rowIndex}=o,{row:a}=e;return i(a,e)?r({evaluation:e}):n(a,e)?l({evaluation:e}):s({evaluation:e})}function ti({evaluation:e,splitStartRowIndexes:t,fullPageHeight:o,resolveOverflow:i,debug:n,afterResolve:r}){const{rowIndex:s,tailWindowHeight:l}=e;Qo(this)&&console.log("%c ⚠️ Row has ROWSPAN; use conservative fallback (no slicing)","color:DarkOrange; font-weight:bold");const a=i({rowIndex:s,evaluation:e,availableRowHeight:l,splitStartRowIndexes:t,fullPageHeight:o});return r?.({evaluation:e,tailWindowHeight:l,fullPageHeight:o,result:a}),a}function oi({evaluation:e,splitStartRowIndexes:t,resolveSplitFailure:o,fullPageHeight:i,debug:n}){const{rowIndex:r,row:s,tailWindowHeight:l,delta:a}=e;return Qo(this)&&console.log(`%c Row # ${r} is slice! but don't fit`,"color:DarkOrange; font-weight:bold",s),Qo(this)&&console.warn("%c SUPER BIG","background:red;color:white",a,{part:i}),o({evaluation:e,splitStartRowIndexes:t,availableRowHeight:l,fullPageHeight:i})}function ii({tailWindowHeight:e,minMeaningfulRowSpace:t,fullPartHeight:o,debug:i}){return ethis.sliceNodeBySplitPoints({index:t,rootNode:e,splitPoints:o})),f=l.beginRow||(({originalRow:t,sliceIndex:o})=>{const i=this._DOM.cloneNodeWrapper(t);return r?.({rowWrapper:i,rowIndex:e,sliceIndex:o,originalRow:t}),{rowWrapper:i}}),m=l.cloneCellFallback||(e=>this._DOM.cloneNodeWrapper(e)),b=l.handleCell||(({context:e,cellClone:t})=>{this._DOM.insertAtEnd(e.rowWrapper,t)}),w=l.finalizeRow||(({context:e})=>e.rowWrapper),S=[];if(g.some(e=>Array.isArray(e)&&e.length)){const e=this.paginationBuildBalancedRowSlices({originalRow:t,originalCells:h,splitPointsPerCell:g,sliceCell:_,beginRow:f,cloneCellFallback:m,handleCell:b,finalizeRow:w});S.push(...e)}else Qo(this)&&console.log("🔴 There is no Split");return S.length&&this.markSliceCutsInRows(S),n&&n._&&console.log("%c newRows \n","color:magenta; font-weight:bold",S),{newRows:S,isFirstPartEmptyInAnyTD:p,needsScalingInFullPage:u}}function ri({row:e,rowIndex:t,decorateRowSlice:o}){const i=Array.isArray(e),n=this;return{getParentContainer:()=>i?null:e,getOriginalCells:()=>i?[...e]:[...n._DOM.getChildren(e)],getShellHeights:({cells:t})=>i?[]:n.getTableRowShellHeightByTD(e),markOriginalRow:({cells:t})=>{i||n.setFlagSlice(e)},beginRow:({originalRow:e,sliceIndex:r})=>{if(i)return{cells:[]};const s=n._DOM.cloneNodeWrapper(e);return o?.({rowWrapper:s,rowIndex:t,sliceIndex:r,originalRow:e}),{rowWrapper:s}},cloneCellFallback:e=>n._DOM.cloneNodeWrapper(e),handleCell:({context:e,cellClone:t})=>{i?(n.setFlagSlice(t),e.cells.push(t)):n._DOM.insertAtEnd(e.rowWrapper,t)},finalizeRow:({context:e})=>i?e.cells:e.rowWrapper}}function si({evaluation:e,splitResult:t,splitStartRowIndexes:o,insufficientRemainingWindow:i,extraCapacity:n,fullPageHeight:r,debug:s,handlers:l={}}){const{newRows:a,isFirstPartEmptyInAnyTD:h,needsScalingInFullPage:c}=t||{},{rowIndex:d,row:g,isLastRow:p,tailWindowHeight:u}=e,{onReplaceRow:_,onAbsorbTail:f,onRefreshRows:m,onPlacement:b,onSplitFailure:w}=l;return Array.isArray(a)&&a.length?(_?.({evaluation:e,newRows:a}),p&&f?.({evaluation:e,newRows:a,extraCapacity:n}),m?.({evaluation:e,newRows:a,splitStartRowIndexes:o}),b?.({evaluation:e,newRows:a,insufficientRemainingWindow:i,isFirstPartEmptyInAnyTD:h,needsScalingInFullPage:c,splitStartRowIndexes:o})??e.rowIndex):(Qo(this)&&console.log(`%c The row is not split. (ROW.${d})`,"color:orange",g),w?.({evaluation:e,splitStartRowIndexes:o,availableRowHeight:u,fullPageHeight:r})??e.rowIndex)}function li({evaluation:e,splitStartRowIndexes:t,extraCapacity:o,fullPageHeight:i,minPartLines:n,debug:r,decorateRowSlice:s,onBudgetInfo:l,handlers:a={}}){if(!e||!e.row)return e?.rowIndex??0;const{row:h}=e,c=this.getTableRowHeight(h,n),d=this.paginationCalculateRowSplitBudget({tailWindowHeight:e.tailWindowHeight,minMeaningfulRowSpace:c,fullPartHeight:i,debug:r});l?.({evaluation:e,firstPartHeight:d.firstPartHeight,fullPartHeight:i});const g=a.getRowSliceAdapter,p=g?.({evaluation:e,row:h,rowIndex:e.rowIndex,decorateRowSlice:s}),u=this.paginationSplitRow({rowIndex:e.rowIndex,row:h,firstPartHeight:d.firstPartHeight,fullPageHeight:i,debug:r,decorateRowSlice:s,rowAdapter:p});return this.paginationProcessRowSplitResult({evaluation:e,splitResult:u,splitStartRowIndexes:t,insufficientRemainingWindow:d.insufficientRemainingWindow,extraCapacity:o,fullPageHeight:i,debug:r,handlers:a})}function ai({evaluation:e,table:t,newRows:o,insufficientRemainingWindow:i,isFirstPartEmptyInAnyTD:n,needsScalingInFullPage:r,splitStartRowIndexes:s,pageBottom:l,fullPageHeight:a,debug:h,resolveRowBounds:c,registerPageStartCallback:d,scaleProblematicSliceCallback:g,applyFullPageScalingCallback:p}){const{rowIndex:u}=e,_=Array.isArray(o)?o[0]:null;if(!_)return d?.({targetIndex:u,reason:"Row split produced empty first slice"}),u-1;const f="function"==typeof c?c:e=>this.resolveRowBoundsGeneric(e,t),{top:m,bottom:b}=f(_),w=this.evaluateRowSplitPlacement({usedRemainingWindow:!i,isFirstPartEmpty:n,firstSliceTop:m,firstSliceBottom:b,pageBottom:l,epsilon:0});return w.placeOnCurrentPage?(w.remainingWindowSpace>0&&g?.(_,w.remainingWindowSpace),d?.({targetIndex:u+1,reason:"Row split — next slice starts new page"})):(p?.({row:_,needsScalingInFullPage:r,fullPageHeight:a}),d?.({targetIndex:u,reason:"Empty first part — move row to next page"})),u-1}class hi{constructor({config:e,DOM:t,node:i,selector:n}){this._debug=e.debugMode?{...e.debugConfig.paragraph}:{},this._assert=!!e.consoleAssert,this._DOM=t,this._selector=n,this._node=i,this._minParagraphLeftLines=2,this._minParagraphDanglingLines=2,this._minParagraphBreakableLines=this._minParagraphLeftLines+this._minParagraphDanglingLines||2,Object.assign(this,o)}split(e){return this._splitComplexTextBlockIntoLines(e)}_estimateLineCount(e){return Math.ceil(this._DOM.getElementOffsetHeight(e)/this._node.getLineHeight(e))}_splitComplexTextBlockIntoLines(e){if(this._debug._&&console.group("_splitComplexTextBlockIntoLines",[e]),this._estimateLineCount(e){const t=this._node.getLineHeight(e),o=this._DOM.getElementOffsetHeight(e),i=this._DOM.getElementOffsetLeft(e),n=this._DOM.getElementOffsetTop(e);return{element:e,lines:Math.ceil(o/t),left:i,top:n,height:o,lineHeight:t,text:this._DOM.getInnerHTML(e)}});this._debug._&&console.log("\n🚸 nodeChildren",[...t],"\n🚸 extendedChildrenArray",[...o]);const i=o.flatMap(e=>e.lines>1&&!this._node.isNoBreak(e.element)?this._breakItIntoLines(e.element):e.element);this._debug._&&console.log("\n🚸🚸🚸\n partiallyLinedChildren",[...i]);const n=i.reduce((e,t,o,i)=>(e||(e=[]),"BR"===this._DOM.getElementTagName(t)?(e.length||e.push([]),e.at(-1).push(t),e.push([]),this._debug._&&console.log("br; push:",t),e):!e.length||this._node.isLineChanged(e.at(-1).at(-1),t)?(e.push([t]),this._debug._&&console.log("◼️ start new line:",t),e):0===e.at(-1).length||e.length&&this._node.isLineKept(e.at(-1).at(-1),t)?(this._debug._&&console.log("⬆ add to line:",t),e.at(-1).push(t),e):void this.strictAssert(!0,"groupedPartiallyLinedChildren: An unexpected case of splitting a complex paragraph into lines.","\nOn the element:",t)),[]);if(this._debug._&&console.log("🟡🟡🟡 groupedPartiallyLinedChildren \n",n.length,[...n]),n.length{let o;if(0==e.length)o=e[0],o.setAttribute("role","🚫"),this.strictAssert(0==e.length,"The string cannot be empty (_splitComplexTextBlockIntoLines)");else if(1==e.length)o=e[0];else{o=this._node.createTextGroup(),this._DOM.insertBefore(e[0],o),this._DOM.insertAtEnd(o,...e)}return o.dataset.child=t,o});return this.logGroupEnd("OK _splitComplexTextBlockIntoLines"),this._DOM.setAttribute(e,this._selector.split),l}_breakItIntoLines(e){if(this._debug._&&console.group("_breakItIntoLines",[e]),this._node.isNoBreak(e))return this.logGroupEnd("isNoBreak"),e;if(this._node.isWrappedTextNode(e)){const t=this._breakWrappedTextNodeIntoLines(e);return this.logGroupEnd("TextNode newLines"),t}return this.logGroupEnd("(recursive _breakItIntoLines)"),this._processNestedInlineElements(e)}_processNestedInlineElements(e){this._debug._&&console.group("_processNestedInlineElements",[e]);const t=this._getNestedInlineChildren(e).flatMap(e=>this._estimateLineCount(e)>1?this._breakItIntoLines(e):e),o=this._findNewLineStarts(t,e),i=o.map((i,n)=>{const r=t[i],s=t[o[n+1]];return this._node.cloneAndCleanOutsideRange(e,r,s)});return this._DOM.insertInsteadOf(e,...i),this.logGroupEnd("Nested Inline parts"),i}_getNestedInlineChildren(e){return[...this._DOM.getChildNodes(e)].reduce((e,t)=>{if(this._node.isSignificantTextNode(t)){const o=this._node.createTextNodeWrapper();return this._DOM.wrap(t,o),e.push(o),e}if(!this._DOM.getElementOffsetParent(t)){const o=this._node.getPreparedChildren(t);return o.length>0&&e.push(...o),e}if(this._DOM.isElementNode(t)){return this._getNestedInlineChildren(t).forEach(t=>e.push(t)),e}},[])}_makeWordsFromTextNode(e){const t=this._node.splitTextByWordsGreedy(e);this._debug._&&console.log("wordArray",t);const o=t.map((e,t)=>this._node.createWord(e+"",t));return this._debug._&&console.log("wrappedWordArray",o),{wordArray:t,wrappedWordArray:o}}_breakWrappedTextNodeIntoLines(e){e.classList.add("🔠_breakItIntoLines"),e.classList.add("🚫_must_be_removed");const{wordArray:t,wrappedWordArray:o}=this._makeWordsFromTextNode(e);this._DOM.setInnerHTML(e,""),this._DOM.insertAtEnd(e,...o);const i=this._findNewLineStarts(o,e),n=i.reduce((o,n,r)=>{const s=this._node.createTextLine(),l=i[r],a=i[r+1],h=t.slice(l,a).join("")+"";return this._DOM.setInnerHTML(s,h),this._DOM.insertBefore(e,s),o.push(s),o},[]);return e.remove(),n}_findNewLineStarts(e,t){const o=t.style.lineHeight;t.style.lineHeight=2;const i=e.reduce((t,o,i)=>{const n=i>0?e[i-1].offsetTop:void 0,r=i>0?e[i-1].offsetHeight:void 0,s=o.offsetTop;return i>0&&n+r<=s&&t.push(i),t},[0]);return t.style.lineHeight=o,i}}function ci(e){if(e)return"function"==typeof e.getDebug?e.getDebug():e.debug}function di(e,t,o="unknown case"){if(!e||"function"!=typeof e.getSplitBottom||"function"!=typeof e.setSplitBottom)throw new Error("updateSplitBottom: adapter must expose getSplitBottom() and setSplitBottom().");const i=e.getSplitBottom();let n;if("number"==typeof t)n=t;else{if(!(t instanceof HTMLElement))throw new Error("updateSplitBottom: unexpected value type: "+typeof t);if("function"!=typeof e.computeSplitBottomForElement)throw new Error("updateSplitBottom: adapter must implement computeSplitBottomForElement(element).");n=e.computeSplitBottomForElement(t)}e.setSplitBottom(n);const r=function(e){return e?"function"==typeof e.getSplitBottomLog?e.getSplitBottomLog():e.splitBottomLog||null:null}(e);Array.isArray(r)&&r.push(n);const s=ci(e);s&&s._&&console.log(`%c♻️ [${function(e){return e?.label||"👤 [paginator.label] element"}(e)}] update splitBottom (with ${t}) \n • ${o}`,"color: green; font-weight: bold","\n",i||"•••","->",n,r?`\n log: ${r}`:"")}function gi(e,t,o,i="register page start"){const n=function(e){return e?"function"==typeof e.getRows?e.getRows()||[]:e.rows||[]:[]}(e),r=n.length,s=function(e){return!!e&&("function"==typeof e.shouldAssert?e.shouldAssert():Boolean(e.assert))}(e),l=ci(e),a=Number.isInteger(t);if(s&&console.assert(a,`registerPageStartAt: index must be an integer, got: ${t}`),!a)return;if(s&&console.assert(r>0,"registerPageStartAt: no rows to register"),0===r)return;if(0===t)return l&&l._&&console.log("%c 📍 Row #0 forced to next page (no short first fragment)","color:green; font-weight:bold"),void((n[0]instanceof HTMLElement||"number"==typeof n[0])&&di(e,n[0],`${i} (index=0)`));let h=Math.max(1,Math.min(t,r-1));const c=o.at(-1);if(null!=c&&h<=c&&(h=c+1),h>=r)return void(l&&l._&&console.warn(`registerPageStartAt return: computed index (${h}) >= rowsLen (${r})`,"Last split index should not equal rows.length, or the original table will be empty."));o.push(h),l&&l._&&console.log(`%c 📍 Row # ${h} registered as page start`,"color:green; font-weight:bold");const d=n[h];(d instanceof HTMLElement||"number"==typeof d)&&di(e,d,i)}function pi({owner:e=null,currentRows:t=[]}={}){return{owner:e,currentRows:Array.isArray(t)?t:[],parts:[]}}function ui({entries:e,part:t,startIndex:o=null,endIndex:i=null,type:n="unknown",rows:r=[],meta:s}){if(!e||!t)return null;const l=function(e){if(e)return Array.isArray(e.parts)||(e.parts=[]),e.parts}(e);if(!l)return null;const a={part:t,type:n,startIndex:o,endIndex:i,rows:Array.isArray(r)?[...r]:[]};return s&&"object"==typeof s&&Object.keys(s).length&&(a.meta={...s}),l.push(a),a}class _i{constructor({config:e,DOM:t,node:i,selector:n}){this._debug=e.debugMode?{...e.debugConfig.table}:{},this._assert=!!e.consoleAssert,this._DOM=t,this._selector=n,this._node=i,this._splitLabelHeightFromConfig=e.splitLabelHeight,this._initConstants(),Object.assign(this,o),this._resetCurrent()}split(e,t,o,i,n){this._setCurrent(e,t,o,i);const r=this._splitCurrentTable();return this._resetCurrent(),r}_initConstants(){this._signpostHeight=parseFloat(this._splitLabelHeightFromConfig)||0,this._minPartLines=2}_resetCurrent(){this._currentTable=void 0,this._currentFirstPageBottom=void 0,this._currentFullPageHeight=void 0,this._currentRoot=void 0,this._currentTableEntries=void 0,this._currentTableRecordedParts=void 0,this._currentTableDistributedRows=void 0,this._currentTableFirstPartContentBottom=void 0,this._currentTableFullPartContentHeight=void 0,this._currentTableTfootHeight=void 0,this._currentTableSplitBottom=void 0,this._logSplitBottom_=[],this._currentRowShellCache=void 0,this._currentOverflowHelpers=void 0,this._currentTableHasRowspan=void 0,this._currentTableHasColspan=void 0,this._currentTableInconsistentCells=void 0,this._currentTableHasUnexpectedChildren=void 0}_setCurrent(e,t,o,i){this._currentTable=e,this._currentFirstPageBottom=t,this._currentFullPageHeight=o,this._currentRoot=i,this._currentRowShellCache=new WeakMap,this._currentOverflowHelpers=this._composeOverflowHelpers()}_prepareCurrentTableForSplitting(){this._lockCurrentTableWidths(),this._collectCurrentTableEntries(),this._updateCurrentTableDistributedRows(),this._currentTableRecordedParts=pi({owner:this._currentTable,currentRows:this._currentTableDistributedRows}),this._currentTableEntries&&(this._currentTableEntries.recordedParts=this._currentTableRecordedParts),this._currentTable.__html2pdf4docRecordedParts=this._currentTableRecordedParts,this._analyzeCurrentTableStructure(),this._collectCurrentTableMetrics()}_lockCurrentTableWidths(){this._node.lockTableWidths(this._currentTable)}_splitCurrentTable(){this._prepareCurrentTableForSplitting(),this._setCurrentTableFirstSplitBottom(),this._debug._&&console.group("%c📊 _splitCurrentTable()","color:green; background:#eee; padding:3px","\n•",this._currentTableFirstPartContentBottom,"(1st bottom)","\n•",this._currentTableFullPartContentHeight,"(full part height)",{table:this._currentTable,rows:[...this._currentTableDistributedRows],rowCount:this._currentTableDistributedRows.length,entries:this._currentTableEntries,root:this._currentRoot});const e=this._resolveCurrentTableDistributedRowsInPlace();if(this._debug._&&console.log("📊 updated table rows",{rows_new:[...this._currentTableDistributedRows],rowCount_new:this._currentTableDistributedRows.length,splitStartRowIndexes:e}),!e.length)return this.logGroupEnd("[_splitCurrentTable]: there are no splits (!splitStartRowIndexes.length)"),[];let t=this._createTableSlices({splitPoints:e,table:this._currentTable,tableEntries:this._currentTableEntries});return this._node.markSliceCuts([this._currentTable,...t]),this._signpostHeight&&(t=this._extendTableSlices(t)),this._DOM.insertAfter(this._currentTable,...t),this._debug._&&console.log("tableSlices",t),this._debug._&&console.log("[table.split] recordedParts",this._currentTableRecordedParts?.parts),this.logGroupEnd("[_splitCurrentTable]"),[this._currentTable,...t]}_resolveCurrentTableDistributedRowsInPlace(){let e=[];for(let t=0;tNumber.isInteger(e)&&e>0&&e<=this._currentTableDistributedRows.length),"splitStartRowIndexes contains invalid indexes"),this.strictAssert(e.every((e,t,o)=>0===t||e>o[t-1]),"splitStartRowIndexes must be strictly ascending and without duplicates"),this.strictAssert(e.at(-1)!==this._currentTableDistributedRows.length,"Last split index should not equal rows.length, or the original table will be empty."),e}_evaluateAndResolveRow(e,t){const o=e,i=this._currentTableDistributedRows.length;this._debug._&&console.groupCollapsed(`🔲 %c Check the Row # ${o} (from ${i})`,"");const n=this._node.paginationBuildRowEvaluationContext({rows:this._currentTableDistributedRows,rowIndex:e,table:this._currentTable,splitBottom:this._currentTableSplitBottom});if(!n?.row)return console.warn("[table.split] Missing row during evaluation.",{rowIndex:e}),this.logGroupEnd(`Row # ${o} (from ${i}) is checked`),e;if(this._debug._){const e=n.fitsCurrentWindow,t=e?"green":"orange",o=e?"<=":">";console.log(`%c📐 does row fit? %c ${e} %c :: ${n.nextMarker} ${o} ${this._currentTableSplitBottom} %c(Δ=${n.delta})`,"",`font-weight:bold;color:${t};`,"",`color:${t};`)}if(this._debug._&&console.info({row:n.row,rows:[...this._currentTableDistributedRows]}),n.fitsCurrentWindow)return this._debug._&&console.log(`%c ✓ Row # ${e}: PASS`,"color:green"),this.logGroupEnd(`Row # ${o} (from ${i}) is checked`),e;const r=this._node.calculateFinalPartReclaimedHeight({signpostHeight:this._signpostHeight,tfootHeight:this._currentTableTfootHeight});if(this._node.paginationCanAbsorbLastRow({evaluation:n,extraCapacity:r,splitBottom:this._currentTableSplitBottom,debug:this._debug}))return this._debug._&&console.log("🫟 last-row-fits-without-bottom-signpost: skip split"),this.logGroupEnd(`Row # ${o} (from ${i}) is checked`),e;const s=this._resolveOverflowingRow({evaluation:n,splitStartRowIndexes:t,extraCapacity:r});return this.logGroupEnd(`Row # ${o} (from ${i}) is checked`),s}_resolveOverflowingRow({evaluation:e,splitStartRowIndexes:t,extraCapacity:o}){return this._node.paginationResolveOverflowingRow({evaluation:e,utils:{rowHasSpan:e=>this._rowHasSpan(e),isSlice:e=>this._node.isSlice(e)},handlers:{handleRowWithRowspan:()=>this._node.paginationResolveRowWithRowspan({evaluation:e,splitStartRowIndexes:t,fullPageHeight:this._currentTableFullPartContentHeight,resolveOverflow:({evaluation:e,splitStartRowIndexes:t,availableRowHeight:o,fullPageHeight:i})=>this._forwardOverflowFallback({rowIndex:e.rowIndex,row:e.row,availableRowHeight:o,fullPageHeight:i,splitStartRowIndexes:t,reasonTail:"Row with ROWSPAN — move to next page",reasonFull:"Row with ROWSPAN — scaled TDs to full page",branch:"rowspan"}),debug:this._debug,afterResolve:({tailWindowHeight:e,fullPageHeight:t})=>{this._debug._&&e>=t&&console.warn("[table.fallback] ROWSPAN row required full-page scaling to fit.")}}),handleSplittableRow:()=>this._resolveSplittableRow({evaluation:e,splitStartRowIndexes:t,extraCapacity:o}),handleAlreadySlicedRow:()=>this._node.paginationResolveAlreadySlicedRow({evaluation:e,splitStartRowIndexes:t,fullPageHeight:this._currentTableFullPartContentHeight,debug:this._debug,resolveSplitFailure:({evaluation:e,splitStartRowIndexes:t,availableRowHeight:o,fullPageHeight:i})=>this._forwardOverflowFallback({rowIndex:e.rowIndex,row:e.row,availableRowHeight:o,fullPageHeight:i,splitStartRowIndexes:t,reasonTail:"Slice doesn't fit tail — move to next page",reasonFull:"Scaled TD content to fit full page",branch:"alreadySliced"})})}})}_resolveSplittableRow({evaluation:e,splitStartRowIndexes:t,extraCapacity:o}){const{rowIndex:i}=e;this._debug._&&console.group(`%c 🔳 Try to split the ROW ${i} %c (from ${this._currentTableDistributedRows.length})`,"color:magenta;","");const n=this._node.paginationResolveSplittableRow({evaluation:e,splitStartRowIndexes:t,extraCapacity:o,fullPageHeight:this._currentTableFullPartContentHeight,minPartLines:this._minPartLines,debug:this._debug,decorateRowSlice:({rowWrapper:e,rowIndex:t,sliceIndex:o})=>{this._DOM.setAttribute(e,`.splitted_row_${t}_part_${o}`)},onBudgetInfo:({evaluation:e,firstPartHeight:t,fullPartHeight:o})=>{this._debug._&&console.info({currRowTop:e.rowTop,"• splitBottom":this._currentTableSplitBottom,"• is row sliced?":!1,"remaining page space":e.tailWindowHeight,"first part height":t,"full part height":o})},handlers:{onReplaceRow:({evaluation:e,newRows:t})=>{this._replaceRowInDOM(e.row,t)},onAbsorbTail:({newRows:e,extraCapacity:t})=>{this._node.absorbShortTrailingSliceIfFits({slices:e,extraCapacity:t,ownerLabel:"table",debug:this._debug})},onRefreshRows:({evaluation:e,newRows:t})=>{this._node.paginationRefreshRowsAfterSplit(this._getSplitterAdapter(),{rowIndex:e.rowIndex,rowSlices:t})},onPlacement:({evaluation:e,newRows:o,insufficientRemainingWindow:i,isFirstPartEmptyInAnyTD:n,needsScalingInFullPage:r})=>this._node.paginationHandleRowSlicesPlacement({evaluation:e,table:this._currentTable,newRows:o,insufficientRemainingWindow:i,isFirstPartEmptyInAnyTD:n,needsScalingInFullPage:r,splitStartRowIndexes:t,pageBottom:this._currentTableSplitBottom,fullPageHeight:this._currentTableFullPartContentHeight,debug:this._debug,registerPageStartCallback:({targetIndex:e,reason:o})=>this._registerPageStartAt(e,t,o),scaleProblematicSliceCallback:(e,t)=>{t>0&&(this._debug._&&console.log("⚖️ scaleProblematicCellsToHeight"),this._scaleProblematicCellsToHeight(e,t,this._getRowShellHeights(e)))},applyFullPageScalingCallback:({row:e,needsScalingInFullPage:t,fullPageHeight:o})=>{this._node.paginationApplyFullPageScaling({needsScalingInFullPage:t&&Boolean(e),payload:{row:e,targetHeight:o},scaleCallback:({row:e,targetHeight:t})=>(this._debug._&&console.log("⚖️ scaleProblematicCellsToHeight"),this._scaleProblematicCellsToHeight(e,t,this._getRowShellHeights(e)))})}}),onSplitFailure:({evaluation:e,splitStartRowIndexes:t,availableRowHeight:o,fullPageHeight:i})=>this._forwardOverflowFallback({rowIndex:e.rowIndex,row:e.row,availableRowHeight:o,fullPageHeight:i,splitStartRowIndexes:t,reasonTail:"Split failed — move row to next page",reasonFull:"Scaled TDs to fit full-page",branch:"splitFailure"})}});return this.logGroupEnd(`🔳 Try to split the ROW ${i} (from ${this._currentTableDistributedRows.length})`),n}_collectCurrentTableEntries(){this._currentTableEntries=this._node.getTableEntries(this._currentTable)}_rowHasSpan(e){const t=[...this._DOM.getChildren(e)];for(const e of t){const t=this._DOM.getElementTagName(e);if("TD"!==t&&"TH"!==t)continue;const o=parseInt(e.getAttribute("rowspan"));if(Number.isFinite(o)&&o>1)return!0}return!1}_collectCurrentTableMetrics(){const e=this._node.getEmptyNodeHeightByProbe(this._currentTable,'',!1),t=this._node.getTopForPageStartCandidate(this._currentTable,this._currentRoot),o=(this._node.getTopWithMargin(this._currentTable,this._currentRoot),this._DOM.getElementOffsetHeight(this._currentTableEntries.caption)||0),i=this._DOM.getElementOffsetTop(this._currentTableDistributedRows[0],this._currentTable)-o||0;this._currentTableTfootHeight=this._DOM.getElementOffsetHeight(this._currentTableEntries.tfoot)||0,this._currentTableFirstPartContentBottom=this._currentFirstPageBottom-t-e-this._signpostHeight,this._currentTableFullPartContentHeight=this._currentFullPageHeight-o-i-this._currentTableTfootHeight-e-2*this._signpostHeight}_getDistributedRows(e){return[...e.rows,...e.tfoot?[e.tfoot]:[]]}_updateCurrentTableDistributedRows(){this._currentTableDistributedRows=this._getDistributedRows(this._currentTableEntries)}_analyzeCurrentTableStructure(){this._currentTableEntries;const e=this._currentTableDistributedRows||[],t=this._node.computeRowFlags({rows:e,DOM:this._DOM,cellTagFilter:(e,t)=>"TFOOT"!==this._DOM.getElementTagName(t.parentNode)&&("TD"===e||"TH"===e)});this._currentTableHasRowspan=t.hasRowspan,this._currentTableHasColspan=t.hasColspan,this._currentTableInconsistentCells=t.inconsistentCells,this._debug._&&(t.hasRowspan&&console.warn("[table.guard] ROWSPAN detected — slicing not implemented; applying conservative fallback.",{table:this._currentTable}),t.hasColspan&&console.warn("[table.guard] COLSPAN present — handled within-row slicing; monitor results.",{table:this._currentTable}),t.inconsistentCells&&console.warn("[table.guard] Inconsistent cell counts across rows — results may vary.",{table:this._currentTable}))}_updateCurrentTableEntriesAfterSplit(e,t){this._currentTableEntries.rows.splice(e,1,...t)}_setCurrentTableFirstSplitBottom(){this._node.getTop(this._currentTableDistributedRows[0],this._currentTable)>this._currentTableSplitBottom?(this._updateCurrentTableSplitBottom(this._currentTableFullPartContentHeight,"SPECIAL CASE: start immediately from the full height of the page"),this._debug._&&console.log("The Row 0 goes to the 2nd page")):this._updateCurrentTableSplitBottom(this._currentTableFirstPartContentBottom,"start with a short first part")}_getPaginatorAdapter(){return{label:"table",getSplitBottom:()=>this._currentTableSplitBottom,setSplitBottom:e=>{this._currentTableSplitBottom=e},computeSplitBottomForElement:e=>this._node.getTop(e,this._currentTable)+this._currentTableFullPartContentHeight,getRows:()=>this._currentTableDistributedRows,shouldAssert:()=>this._assert,getDebug:()=>this._debug,getSplitBottomLog:()=>this._logSplitBottom_}}_getSplitterAdapter(){const e=()=>({rows:this._currentTableDistributedRows||[],DOM:this._DOM,cellTagFilter:(e,t)=>{const o=t?.parentNode;return"TFOOT"!==(o?this._DOM.getElementTagName(o):void 0)&&("TD"===e||"TH"===e)}});return{label:"table",rows:{getCurrentRows:()=>this._currentTableDistributedRows||[],replaceRow:({rowIndex:e,rowSlices:t})=>{this._node.applyRowSlicesToEntriesAfterRowSplit(this._currentTableEntries,e,t)},syncEntries:()=>{this._updateCurrentTableDistributedRows(),this._currentTableRecordedParts&&(this._currentTableRecordedParts.currentRows=this._currentTableDistributedRows)},getGuardConfig:e,onRowsChanged:()=>{this._currentTableRecordedParts&&(this._currentTableRecordedParts.currentRows=this._currentTableDistributedRows)}},guards:{getConfig:e,onFlags:({flags:e})=>{e&&(this._currentTableHasRowspan=Boolean(e.hasRowspan),this._currentTableHasColspan=Boolean(e.hasColspan),this._currentTableInconsistentCells=Boolean(e.inconsistentCells))}}}}_updateCurrentTableSplitBottom(e,t="unknown case"){di(this._getPaginatorAdapter(),e,t)}_registerPageStartAt(e,t,o="register page start"){gi(this._getPaginatorAdapter(),e,t,o)}_composeOverflowHelpers(){const e=this._node.scaleCellsToHeight.bind(this._node),t=this._getRowShellHeights.bind(this),o={ownerLabel:"table",registerPageStartCallback:this._registerPageStartAt.bind(this),debugLogger:this._debug&&this._debug._?(e,t)=>console.log(e,t):void 0,scaleProblematicCellsCallback:(o,i,n)=>this._node.scaleRowCellsToHeight({ownerLabel:"table",DOM:this._DOM,row:o,targetHeight:i,cachedShells:n,getRowShellHeightsCallback:t,scaleCellsToHeightCallback:e})};return this._currentOverflowHelpers=o,o}_scaleProblematicCellsToHeight(e,t,o){return(this._currentOverflowHelpers||this._composeOverflowHelpers()).scaleProblematicCellsCallback(e,t,o)}_forwardOverflowFallback({rowIndex:e,row:t,availableRowHeight:o,fullPageHeight:i,splitStartRowIndexes:n,reasonTail:r,reasonFull:s,branch:l}){const a=this._currentOverflowHelpers||this._composeOverflowHelpers(),h={ownerLabel:`table:${l}`,rowIndex:e,row:t,availableRowHeight:o,fullPageHeight:i,splitStartRowIndexes:n,reasonTail:r,reasonFull:s,registerPageStartCallback:a.registerPageStartCallback,scaleProblematicCellsCallback:a.scaleProblematicCellsCallback,debugLogger:a.debugLogger};return this._debug._&&console.log(`%c[table.overflow] branch=${l} rowIndex=${e} tail=${o} full=${i}`,"color:orange; font-weight:bold",{reasonTail:r,reasonFull:s}),"splitFailure"===l?this._node.handleRowSplitFailure(h):this._node.handleRowOverflow(h)}_getRowShellHeights(e){if(!this._currentRowShellCache)return this._node.getTableRowShellHeightByTD(e);if(this._currentRowShellCache.has(e))return this._currentRowShellCache.get(e);const t=this._node.getTableRowShellHeightByTD(e);return this._currentRowShellCache.set(e,t),t}_createTableSlice({startId:e,endId:t,table:o,tableEntries:i}){this._debug._&&console.group(`[CREATE Table Slice] range: [${e}, ${t})`),this.strictAssert(Number.isInteger(e)&&(Number.isInteger(t)||t===1/0),`[createTableSlice] invalid bounds: startId=${e}, endId=${t}`);const n=i&&i.rows?i.rows.length:0;this.strictAssert(n>=0,`[createTableSlice]: invalid rows length: ${n}`),this.strictAssert(e>0&&t>0&&ethis._createTableSlice({startId:e,endId:i===n.length-1?1/0:n[i+1],table:t,tableEntries:o}))}_extendTableSlices(e){return e.reduce((e,t,o,i)=>{const n=0===o,r=o===i.length-1;return n&&e.push(this._createBottomSignpost()),e.push(this._node.createForcedPageBreak()),e.push(this._createTopSignpost()),e.push(t),!r&&e.push(this._createBottomSignpost()),e},[])}_createTopSignpost(){return this._node.createSignpost("(table continued)",this._signpostHeight)}_createBottomSignpost(){return this._node.createSignpost("(table continues on the next page)",this._signpostHeight)}_replaceRowInDOM(e,t){this._debug._&&this._DOM.setAttribute(e,".🚫_must_be_removed"),this._DOM.insertInsteadOf(e,...t)}}class fi{constructor({config:e,DOM:t,node:o,selector:i}){this._debug=e.debugMode?{...e.debugConfig.tableLike}:{},this._DOM=t,this._selector=i,this._node=o,this._minLeftLines=2,this._minDanglingLines=2,this._minBreakableLines=this._minLeftLines+this._minDanglingLines,this._minLeftRows=1,this._minDanglingRows=1,this._minBreakableRows=1,this._minPreFirstBlockLines=3,this._minPreLastBlockLines=3,this._minPreBreakableLines=this._minPreFirstBlockLines+this._minPreLastBlockLines,this._minBreakableGridRows=4,this._imageReductionRatio=.8,this._signpostHeight=parseFloat(e.splitLabelHeight)||0}split(e,t,o,i,n){const r=n||this._DOM.getComputedStyle(e);this._debug._&&console.log("root",i);const s=this._node.getPreparedChildren(e),l=this._node.getTop(e,i),a=this._node.getEmptyNodeHeightByProbe(e),h=o-a;let c=s,d=0,g=[],p=t-l-a;const u=r.position;"relative"!=u&&this._DOM.setStyles(e,{position:"relative"});for(let t=0;tp&&(t&&g.push(t),t&&(d+=1),p=t?this._node.getTop(o,e)+h:h)}if(this._DOM.setStyles(e,{position:u}),!g.length)return this._debug._&&console.log("splitters.length",g.length),[];g.push(null);const _=g.map((t,o,i)=>{const n=this._node.createSliceWrapper(e),r=i[o-1]||0,s=t||i[i.length];return this._DOM.insertAtEnd(n,...c.slice(r,s)),n});return this._node.markSliceCuts(_),this._DOM.replaceNodeContentsWith(e,..._),this._DOM.removeAllClasses(e),this._DOM.removeAllStyles(e),this._DOM.setStyles(e,{display:"contents"}),this._DOM.setAttribute(e,"[slough-node]",""),_}}class mi{constructor({config:e,DOM:t,node:i,selector:n}){this._debug=e.debugMode?{...e.debugConfig.grid}:{},this._assert=!!e.consoleAssert,Object.assign(this,o),this._DOM=t,this._selector=n,this._node=i,this._resetCurrent(),this._minBreakableGridRows=1,this._minGridRowContentLines=2,this._gridCellLineHeightCache=new WeakMap,this._gridComputedStyleCache=new WeakMap,this._signpostHeight=parseFloat(e.splitLabelHeight)||0}split(e,t,o,i,n){this._resetCurrent(),this._debug._&&console.group("%c split Grid Node","background:#00FFFF",e);const r=this._node.getPreparedChildren(e);this._node.lockNodesWidths(r);const s=n||this._getComputedStyleCached(e);if(!r.length)return this._node.setInitStyle(!1,e,s),this._debug._&&console.groupEnd(),[];this._node.setInitStyle(!0,e,s);const l=this._scanGridLayout(e,s);if(!l.safe)return this._debug._&&console.warn("[grid.split] skip unsafe layout",l),this._debug._&&console.warn("[grid.split] Unsupported grid layout detected; keeping original grid intact.",l),this._node.setInitStyle(!1,e,s),this._debug._&&console.groupEnd(),[];const a=[];let h=!1,c=!1;const d=new Set;let g=null,p=null,u=null;r.forEach(t=>{const o=this._getComputedStyleCached(t),i=parseInt(o.gridRowStart,10),n=Number.isFinite(i),r=this._node.getTop(t,e),s=this._node.getBottom(t,e);let l=!1;l=!a.length||(n&&null!=g?i!==g:null!=u?r>=u-.5:null==p||Math.abs(r-p)>.5),l?(a.push([t]),g=n?i:null,p=r,u=s):(a[a.length-1].push(t),n&&null==g&&(g=i),(null==p||ru)&&(u=s));const _=o.gridRowEnd||"",f=o.gridColumnEnd||"";h=h||_.includes("span"),c=c||f.includes("span"),n&&d.add(i)});const _=d.size>0&&Math.max(...d)>a.length;if(_)return this._debug._&&console.warn("[grid.split]","Unsupported implicit row gap detected; keeping grid unsplit.",{hasImplicitRowGaps:_}),this._node.setInitStyle(!1,e,s),this._debug._&&console.groupEnd(),[];if(h||c)return this._debug._&&console.warn("[grid.split]","Grid contains row/column spans; using fallback (move row to next page).",{hasRowSpan:h,hasColumnSpan:c}),this._debug._&&console.groupEnd(),this._fallbackMoveGridToNextPage({gridNode:e,nodeComputedStyle:s});this.log("grid.split","currentRows:",a);const f=this._node.getTop(e,i),m=this._node.getEmptyNodeHeightByProbe(e),b=t-f-m,w=o-m;if(this.log("grid.split",{firstPartHeight:b,fullPagePartHeight:w}),this._currentGridNode=e,this._currentGridRows=a,this._currentGridFullPartHeight=w,this._currentGridSplitLog=[],this._currentGridEntries=pi({owner:e,currentRows:a}),this._currentGridRecordedParts=this._currentGridEntries,this._currentGridNode.__html2pdf4docRecordedParts=this._currentGridRecordedParts,this._currentGridShellCache=new WeakMap,a.length0?Math.floor(t):1;let n=0;return()=>{if(n+=1,n<=i)return;const t={label:e,iterations:n,limit:i};throw o&&console.assert(!1,`\n\n ⛔ [${e}] ♾️ loop guard triggered`,t),new Error(`\n ⛔ [${e}] ♾️ loop guard triggered`)}}({label:"grid.split",limit:Math.max(1,6*(a.length||1)),assert:this._assert});this._updateCurrentGridSplitBottom(b,"start with initial window");for(let t=0;tthis._buildGridSplit({startId:i[o-1]||0,endId:t,node:e,entries:M})).filter(Boolean).map(e=>e.part),this._createAndInsertGridFinalSlice({node:e,entries:M,startId:C})];return this.log("grid.split",{splitStartRowIndexes:S,splits:E,recordedParts:this._currentGridRecordedParts?.parts}),this._node.setInitStyle(!1,e,s),this._resetCurrent(),this.logGroupEnd("split Grid Node"),E}_fallbackMoveGridToNextPage({gridNode:e,nodeComputedStyle:t}){return this._node.setInitStyle(!1,e,t),this._resetCurrent(),[]}_resetCurrent(){this._currentGridNode=void 0,this._currentGridRows=void 0,this._currentGridEntries=void 0,this._currentGridRecordedParts=void 0,this._currentGridSplitBottom=void 0,this._currentGridFullPartHeight=void 0,this._currentGridSplitLog=void 0,this._currentGridRowFlags=void 0,this._currentGridShellCache=void 0,this._gridCellLineHeightCache=new WeakMap,this._gridComputedStyleCache=new WeakMap}_getGridSplittableHandlers({evaluation:e,splitStartRowIndexes:t}){return{getRowSliceAdapter:({row:t})=>this._createGridRowSliceAdapter({row:t,rowIndex:e.rowIndex}),onReplaceRow:({newRows:t})=>{this._removeOriginalGridRowCells(e.row),this._node.paginationRefreshRowsAfterSplit(this._getSplitterAdapter(),{rowIndex:e.rowIndex,rowSlices:t})},onAbsorbTail:()=>{},onRefreshRows:({newRows:t})=>{this._node.paginationRefreshRowsAfterSplit(this._getSplitterAdapter(),{rowIndex:e.rowIndex,rowSlices:t})},onPlacement:({evaluation:e,newRows:o,insufficientRemainingWindow:i,isFirstPartEmptyInAnyTD:n,needsScalingInFullPage:r})=>this._node.paginationHandleRowSlicesPlacement({evaluation:e,table:this._currentGridNode,newRows:o,insufficientRemainingWindow:i,isFirstPartEmptyInAnyTD:n,needsScalingInFullPage:r,splitStartRowIndexes:t,pageBottom:this._currentGridSplitBottom,fullPageHeight:this._currentGridFullPartHeight,debug:this._debug,resolveRowBounds:e=>this._getRowBounds(e,this._currentGridNode),registerPageStartCallback:({targetIndex:e,reason:o})=>this._registerPageStartAt(e,t,o),scaleProblematicSliceCallback:(e,t)=>this._scaleGridCellsToHeight(e,t),applyFullPageScalingCallback:({row:e,needsScalingInFullPage:t,fullPageHeight:o})=>{this._node.paginationApplyFullPageScaling({needsScalingInFullPage:t&&Boolean(e),payload:{cells:e,targetHeight:o},scaleCallback:({cells:e,targetHeight:t})=>this._scaleGridCellsToHeight(e,t)})}}),onSplitFailure:({evaluation:e,splitStartRowIndexes:t,availableRowHeight:o,fullPageHeight:i})=>this._forwardGridOverflowFallback({evaluation:e,splitStartRowIndexes:t,availableRowHeight:o,fullPageHeight:i,branch:"splitFailure"})}}_forwardGridOverflowFallback({evaluation:e,splitStartRowIndexes:t,availableRowHeight:o,fullPageHeight:i=this._currentGridFullPartHeight,branch:n,reasonTail:r,reasonFull:s}){const l=this._composeGridOverflowHelpers(),a={ownerLabel:`grid:${n}`,gridNode:this._currentGridNode,evaluation:e,rowIndex:e.rowIndex,row:e.row,availableRowHeight:o,fullPageHeight:i,splitStartRowIndexes:t,reasonTail:r||("splitFailure"===n?"Grid split failed — move row to next page":"Grid slice overflow — move row to next page"),reasonFull:s||("splitFailure"===n?"Grid split failed — scaled cells to full page":"Grid slice overflow — scaled cells to full page"),registerPageStartCallback:l.registerPageStartCallback,scaleProblematicCellsCallback:l.scaleProblematicCellsCallback,debugLogger:l.debugLogger};return this._debug._&&console.log("[grid.overflow]",n,a),"splitFailure"===n?this._node.handleRowSplitFailure(a):this._node.handleRowOverflow(a)}_buildGridRowEvaluation({rows:e,rowIndex:t,gridNode:o,splitBottom:i}){if(!Array.isArray(e))return null;const n=e[t];if(!n)return null;const r=Array.isArray(n)?new Array(n.length):null,{top:s,bottom:l}=this._getRowBounds(n,o),a=e[t+1],h=a?this._getRowTop(a,o):l,c=h-i;return{rowIndex:t,row:n,rowTop:s,rowBottom:l,nextMarker:h,delta:c,tailWindowHeight:i-s,isLastRow:!a,fitsCurrentWindow:c<=0,cellStyles:r}}_composeGridOverflowHelpers(){return{registerPageStartCallback:this._registerPageStartAt.bind(this),scaleProblematicCellsCallback:(e,t)=>!!Array.isArray(e)&&this._scaleGridCellsToHeight(e,t),debugLogger:this._debug&&this._debug._?(e,t)=>console.log(e,t):void 0}}_resolveGridOverflowingRow({evaluation:e,splitStartRowIndexes:t}){return this._node.paginationResolveOverflowingRow({evaluation:e,utils:{rowHasSpan:()=>!1,isSlice:e=>this._isGridRowSlice(e)},handlers:{handleRowWithRowspan:()=>(this._debug._&&console.warn("[grid.split] ROWSPAN guard triggered unexpectedly.",{evaluation:e}),this._registerPageStartAt(e.rowIndex,t,"Grid ROWSPAN fallback — move row to next page"),e.rowIndex-1),handleSplittableRow:()=>this._resolveGridSplittableRow({evaluation:e,splitStartRowIndexes:t}),handleAlreadySlicedRow:()=>this._forwardGridOverflowFallback({evaluation:e,splitStartRowIndexes:t,branch:"alreadySliced"})}})}_resolveGridSplittableRow({evaluation:e,splitStartRowIndexes:t}){const{rowIndex:o}=e;this._debug._&&console.group("%c[grid.split] Stage5 — splittable row","color:#0080ff",{rowIndex:o,row:e.row,tailWindowHeight:e.tailWindowHeight});const i=this._estimateGridRowMeaningfulSpace({row:e.row,cellStyles:e.cellStyles,minContentLines:this._minGridRowContentLines});if(!(i>0))return console.warn("[grid.metrics] Meaningful row space is unavailable; falling back to overflow handler."),this._forwardGridOverflowFallback({evaluation:e,splitStartRowIndexes:t,availableRowHeight:e.tailWindowHeight,fullPageHeight:this._currentGridFullPartHeight,branch:"metricsMissing",reasonTail:"Grid row metrics missing — move row to next page",reasonFull:"Grid row metrics missing — scaled cells to full page"});const n=this._node.paginationCalculateRowSplitBudget({tailWindowHeight:e.tailWindowHeight,minMeaningfulRowSpace:i,fullPartHeight:this._currentGridFullPartHeight,debug:this._debug}),r=this._node.paginationSplitRow({rowIndex:o,row:e.row,firstPartHeight:n.firstPartHeight,fullPageHeight:this._currentGridFullPartHeight,debug:this._debug,decorateRowSlice:({rowWrapper:e,rowIndex:t,sliceIndex:o})=>{e instanceof HTMLElement&&this._DOM.setAttribute(e,`.grid_row_${t}_part_${o}`)},rowAdapter:this._createGridRowSliceAdapter({row:e.row,rowIndex:o,cellStyles:e.cellStyles})}),s=this._node.paginationProcessRowSplitResult({evaluation:e,splitResult:r,splitStartRowIndexes:t,insufficientRemainingWindow:n.insufficientRemainingWindow,extraCapacity:0,fullPageHeight:this._currentGridFullPartHeight,debug:this._debug,handlers:this._getGridSplittableHandlers({evaluation:e,splitStartRowIndexes:t})});return this.logGroupEnd("[grid.split] Stage5 — splittable row"),s}_createGridRowSliceAdapter({row:e,rowIndex:t,cellStyles:o}){if(!Array.isArray(e))return null;const i=this._currentGridNode,n=e[0]||null,r=this;return{getParentContainer:()=>i,getOriginalCells:()=>[...e],getShellHeights:()=>r._getGridShellHeights(e,o),markOriginalRow:({cells:e})=>{e.forEach(e=>r._node.setFlagSlice(e))},beginRow:()=>({fragment:r._DOM.createDocumentFragment(),cells:[]}),cloneCellFallback:e=>r._DOM.cloneNodeWrapper(e),handleCell:({context:e,cellClone:t})=>{r._node.setFlagSlice(t),e.fragment.append(t),e.cells.push(t)},finalizeRow:({context:e})=>(n&&r._DOM.insertBefore(n,e.fragment),e.cells)}}_removeOriginalGridRowCells(e){Array.isArray(e)&&e.forEach(e=>{e instanceof HTMLElement&&this._DOM.removeNode(e)})}_isGridRowSlice(e){if(Array.isArray(e)){const t=e.find(e=>e instanceof HTMLElement);return!!t&&this._node.isSlice(t)}return!!e&&this._node.isSlice(e)}_getPaginatorAdapter(){return{label:"grid",getSplitBottom:()=>this._currentGridSplitBottom,setSplitBottom:e=>{this._currentGridSplitBottom=e},computeSplitBottomForElement:e=>e&&this._currentGridNode?this._node.getTop(e,this._currentGridNode)+(this._currentGridFullPartHeight||0):this._currentGridSplitBottom||0,getRows:()=>Array.isArray(this._currentGridRows)?this._currentGridRows.map(e=>{if(!e)return null;if(e instanceof HTMLElement)return e;if(Array.isArray(e)){const t=e.find(e=>e instanceof HTMLElement);if(t)return t;const o=this._getRowTop(e,this._currentGridNode);return Number.isFinite(o)?o:null}const t=this._getRowTop(e,this._currentGridNode);return Number.isFinite(t)?t:null}):[],shouldAssert:()=>this._assert,getDebug:()=>this._debug,getSplitBottomLog:()=>this._currentGridSplitLog}}_getSplitterAdapter(){return{label:"grid",rows:{getCurrentRows:()=>this._currentGridRows||[],replaceRow:({rowIndex:e,rowSlices:t})=>{Array.isArray(this._currentGridRows)&&this._node.replaceCurrentRowsAfterRowSplit({currentRows:this._currentGridRows,index:e,rowSlices:t})},syncEntries:()=>{this._currentGridEntries&&(this._currentGridEntries.currentRows=this._currentGridRows),this._currentGridRecordedParts&&(this._currentGridRecordedParts.currentRows=this._currentGridRows)},getGuardConfig:()=>({rows:this._currentGridRows||[],DOM:this._DOM})},guards:{onFlags:({flags:e})=>{this._currentGridRowFlags=e}}}}_updateCurrentGridSplitBottom(e,t="unknown case"){di(this._getPaginatorAdapter(),e,t)}_registerPageStartAt(e,t,o="register page start"){gi(this._getPaginatorAdapter(),e,t,o)}_scaleGridCellsToHeight(e,t){if(!(Array.isArray(e)&&e.length&&t>0))return!1;const o=this._getGridShellHeights(e),i=this._debug._?e.map(e=>this._DOM.getElementOffsetHeight(e)):null,n=this._node.paginationScaleCellsToHeight({cells:e,targetHeight:t,shells:o});if(this._debug._){const r=e.map(e=>this._DOM.getElementOffsetHeight(e));console.log("[grid.scaleCells] target:",t,"shells:",o,"before:",i,"after:",r,"scaled:",n)}return n}_buildGridSplit({startId:e,endId:t,node:o,entries:i}){const n=i?.currentRows||this._currentGridRows||[];if(e===t)return this._debug._&&console.warn("[grid.split] _buildGridSplit: skip empty slice request",e,t),this.strictAssert(!1,"[grid.split] _buildGridSplit: empty slice encountered"),null;if(this._debug._){const o=n.slice(e,t);console.log(`=> [grid.split] _buildGridSplit: slice rows [${e}, ${t})`,o)}const r=this._createAndInsertGridSlice({startId:e,endId:t,node:o,entries:i}),s=this._collectGridTelemetryRows(n,e,t);return this._recordGridPart(r,{startId:e,endId:t,type:"slice",rows:s}),{part:r,telemetryRows:s}}_createAndInsertGridSlice({startId:e,endId:t,node:o,entries:i}){const n=this._DOM.cloneNodeWrapper(o);this._node.copyNodeWidth(n,o),this._node.setFlagNoBreak(n),e&&this._node.markTopCut(n),this._node.markBottomCut(n),o.before(n);const r=i?.currentRows||fallbackCurrentRows||[],s=this&&this._DOM&&"function"==typeof this._DOM.isElementNode?this._DOM.isElementNode.bind(this._DOM):null,l=r.slice(e,t).flat().map(e=>{if(!e)return null;if(s&&s(e))return e;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return e;const t=e.element;if(t){if(s&&s(t))return t;if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement)return t}return null}).filter(Boolean);return this._DOM.insertAtEnd(n,...l),n}_createAndInsertGridFinalSlice({node:e,entries:t,startId:o}){const i=e;this._node.markTopCut(i),this._node.setFlagNoBreak(i);const n=t?.currentRows||this._currentGridRows||[],r=this._collectGridTelemetryRows(n,o);return this._recordGridPart(i,{startId:o,endId:n.length,type:"final",rows:r}),i}_collectGridTelemetryRows(e,t,o){if(!Array.isArray(e))return[];return e.slice(t,"number"==typeof o?o:void 0).map((e,o)=>{const i=Array.isArray(e)?[...e]:[e];return{rowIndex:t+o,row:e,cells:i}})}_recordGridPart(e,t={}){const o=this._currentGridRecordedParts;if(!o||!e)return null;const{startId:i=null,endId:n=null,type:r="unknown",rows:s=[],meta:l}=t||{};return ui({entries:o,part:e,startIndex:i,endIndex:n,type:r,rows:s,meta:l})}_estimateGridRowMeaningfulSpace({row:e,cellStyles:t=null,minContentLines:o=this._minGridRowContentLines}){if(!Array.isArray(e)||0===e.length)return console.warn("[grid.metrics] Row payload missing while estimating split budget."),null;const i=this._getGridShellHeights(e,t),n=Array.isArray(t)?t:null,r=Math.max(1,o);let s=0;return e.forEach((e,t)=>{if(!(e instanceof HTMLElement))return void console.warn("[grid.metrics] Unexpected non-element cell in row; ignoring during split budget calculation.",{cell:e,index:t});let o=n?n[t]:null;o||(o=this._getComputedStyleCached(e),n&&(n[t]=o));const l=this._resolveGridCellLineHeight({cell:e,style:o}),a=(i?.[t]||0)+l*r;s=Math.max(s,a)}),s>0?s:(console.warn("[grid.metrics] Failed to measure meaningful row space."),null)}_resolveGridCellLineHeight({cell:e,style:t}){const o=this._gridCellLineHeightCache,i=o?.get(e);if(i>0)return i;t||(console.warn("[grid.metrics] style not passed for _resolveGridCellLineHeight",{cell:e}),t=this._getComputedStyleCached(e));let n=parseFloat(t?.lineHeight);if(n>0)return o?.set(e,n),n;const r=parseFloat(t?.fontSize);if(Number.isFinite(r)&&r>0){const t=1.2*r;return o?.set(e,t),t}if(n=this._node.getLineHeight(e),n>0)return o?.set(e,n),n;return o?.set(e,16),16}_getGridShellHeights(e,t=null){if(this._currentGridShellCache||(this._currentGridShellCache=new WeakMap),this._currentGridShellCache.has(e))return this._currentGridShellCache.get(e);const o=Array.isArray(e)?e:[e].filter(Boolean),i=this._computeGridCellShellHeights(o,t);return this._currentGridShellCache.set(e,i),i}_getComputedStyleCached(e){if(!e)return console.warn("[grid.split] the element was not passed to _getComputedStyleCached"),null;const t=this._gridComputedStyleCache;if(!t)return this._DOM.getComputedStyle(e);const o=t.get(e);if(o)return o;const i=this._DOM.getComputedStyle(e);return t.set(e,i),i}_computeGridCellShellHeights(e,t=null){return Array.isArray(e)&&e.length?e.map((e,o)=>{if(!e)return 0;let i=null;t?(i=t[o],i||(i=this._getComputedStyleCached(e),t[o]=i)):i=this._getComputedStyleCached(e);const n=parseFloat(i?.paddingTop)||0,r=parseFloat(i?.paddingBottom)||0,s=parseFloat(i?.borderTopWidth)||0,l=parseFloat(i?.borderBottomWidth)||0,a=parseFloat(i?.marginTop)||0,h=parseFloat(i?.marginBottom)||0,c=n+r+s+l,d=Math.max(0,a)+Math.max(0,h),g=Math.max(0,c);return Math.max(0,g+d)}):[]}_getRowBounds(e,t,o="both"){return this._node.resolveRowBoundsGeneric(e,t,o)}_getRowTop(e,t){return this._getRowBounds(e,t,"top").top}_getRowBottom(e,t){return this._getRowBounds(e,t,"bottom").bottom}_scanGridLayout(e,t){const o=t.gridAutoFlow||"";if(!o.startsWith("row"))return{safe:!1,reason:`grid-auto-flow=${o}`};if(o.includes("dense"))return{safe:!1,reason:"grid-auto-flow dense not supported yet"};if("none"!==(t.gridTemplateAreas||"none"))return{safe:!1,reason:"grid-template-areas present"};const i=t.gridTemplateColumns||"",n=t.gridTemplateRows||"",r=e=>e.includes("subgrid")||e.includes("auto-fit")||e.includes("auto-fill")||e.includes("fit-content");if(r(i)||r(n))return{safe:!1,reason:"complex track sizing (subgrid/auto-fit/fit-content)"};return/\[.*?\]/.test(i)||/\[.*?\]/.test(n)?{safe:!1,reason:"named grid lines detected"}:{safe:!0}}}const bi="background:#999;color:#FFF;padding: 0 4px;";class wi{constructor({config:e,DOM:t,node:i,selector:n}){this._debug=e.debugMode?{...e.debugConfig.pre}:{},this._assert=!!e.consoleAssert,Object.assign(this,o),this._DOM=t,this._selector=n,this._node=i,this._minPreFirstBlockLines=3,this._minPreLastBlockLines=3,this._minPreBreakableLines=this._minPreFirstBlockLines+this._minPreLastBlockLines,this._imageReductionRatio=.8,this._signpostHeight=parseFloat(e.splitLabelHeight)||0}_normalizeLinesInPlace(e){const t=e.splice(0,this._minPreFirstBlockLines).join(""),o=e.splice(-this._minPreLastBlockLines).join("");e.unshift(t),e.push(o)}_analyzeChildren(e){const t={},o=[...e].map(e=>{const o=this._DOM.getNodeType(e);return o===Node.TEXT_NODE?(t.text=!0,"text"):o===Node.ELEMENT_NODE?"BR"===this._DOM.getElementTagName(e)?(t.br=!0,"br"):this._node.isWrappedTextNode(e)?(t.wrappedText=!0,"wrappedText"):(t.node=!0,"node"):(t.other=!0,"other")});return{has:t,items:o}}split(e,t){this._debug._&&console.group("%c 🔲 PRE [split]","background:orange",{node:e});const o=()=>{this._debug._&&console.log("%c END 🔲 PRE [split]",bi),this._debug._&&console.groupEnd()},i=this._DOM.getChildNodes(e);if(this._debug._&&console.log("_children:",i.length,i),0==i.length)return this._debug._&&console.log("%c END _splitPreNode (not breakable)",bi),o(),[];let n=[];const r=this._analyzeChildren(i);if(this._debug._&&console.log("_childrenTypes:",r.items.length,r),this.strictAssert(!r.has.wrappedText,"Expected to be dealing with unprocessed PRE child nodes, but have wrappedText!",r),this.strictAssert(!(r.has.text&&r.has.wrappedText),"PRE children has text and wrappedText simultaneously",r),r.has.br&&this._debug._&&console.warn("PRE children has BR"),r.has.node){const t=this._DOM.getInnerHTML(e),o=this._node.splitTextByLinesGreedy(t);n.push(...o)}else for(const e of i){if(this._DOM.isTextNode(e)){const t=this._DOM.getNodeValue(e),o=this._node.splitTextByLinesGreedy(t);n.push(...o);continue}if(this._node.isWrappedTextNode(e)){const t=this._DOM.getInnerHTML(e),o=this._node.splitTextByLinesGreedy(t);n.push(...o);continue}}if(this._debug._&&console.log("_lines:",n),n.length{const t=this._node.createWithFlagNoBreak();return this._DOM.setInnerHTML(t,e),t});return this._debug._&&console.log("linesFromNode",s),this._DOM.replaceNodeContentsWith(e,...s),o(),s}slice(e,t,o,i,n){const r=n||this._DOM.getComputedStyle(e),s=["%c_SLICE PreNode\n","color:white"];this._debug._&&console.group("%c_✂️ slice PRE","background:cyan",{node:e,pageBottom:t,fullPageHeight:o});const l=()=>{this._debug._&&console.log("%c END ✂️ slice PRE",bi),this._debug._&&console.groupEnd()},a=e=>isNaN(parseFloat(e))?0:Math.ceil(parseFloat(e)),h=(a(r.marginTop),a(r.marginBottom),a(r.paddingTop)),c=a(r.paddingBottom),d=a(r.borderTopWidth),g=a(r.borderBottomWidth),p=a(r.lineHeight),u=this._node.getTop(e,i),_=h+c+d+g;if(this._DOM.getElementOffsetHeight(e)<_+p*this._minPreBreakableLines)return this._debug._&&console.log("%c END ✂️ slice (small node)",bi),l(),[];const f=this._DOM.getChildNodes(e);if(0==f.length)return this._debug._&&console.log("%c END ✂️ slice (not breakable)",bi),l(),[];if(f.length>1)return this._debug._&&console.log("%c END ✂️ slice TODO!",bi),l(),[];{if(this._DOM.isElementNode(f[0])){const e=f[0];return this._debug._&&console.warn("is Element Node",e),this._debug._&&console.log("%c END ✂️ slice ???????",bi),l(),[]}this._node.isWrappedTextNode(f[0])&&this._debug._&&console.warn(`is TEXT Node: ${f[0]}`);const i=f[0].wholeText,n=this._node.splitTextByLinesGreedy(i);if(n.length{const t=this._node.createWithFlagNoBreak();return this._DOM.setInnerHTML(t,e),t});this._debug._&&console.log("linesFromNode",c),this._DOM.replaceNodeContentsWith(e,...c);const p=0,m=p+d,b=p+g;let w=t-u-b-_; +}function pe(e,t){if(!(e instanceof HTMLElement))return;const o=t||this._DOM.getComputedStyle(e);return["block"].includes(o.display)&&["pre","pre-wrap","pre-line","break-spaces","nowrap"].includes(o.whiteSpace)}function ue(e,t){if(!(e instanceof HTMLElement))return;const o=t||this._DOM.getComputedStyle(e),i=o.display,n=o.gridAutoFlow;return("grid"===i||"inline-grid"===i)&&"row"===n}function _e(e,t){if(!(e instanceof HTMLElement))return;const o=t||this._DOM.getComputedStyle(e),i=o.display;if("flex"!==i&&"inline-flex"!==i)return!1;return(o.flexDirection||"").startsWith("row")}function fe(e,t){const o=t||this._DOM.getComputedStyle(e);return this.isTableNode(e,o)||this.isTableLikeNode(e,o)||this.isGridAutoFlowRow(e,o)}function me(e){return this._DOM.hasAttribute(e,"slough-node")}const be=L("selectorHeuristics");function we(e,t,o){const i=[],n=new Set;return be(this)&&console.group(o),e.forEach(e=>{const o=this._DOM.getAllElements(e,t),r=this.isHeuristicSelector(e);be(this)&&r&&console.log("🪄 [heuristic selector]",e,`\n${o.length} elements found`);for(const t of o)r&&!this.validateHeuristicSelectorMatch(t,e)||n.has(t)||(n.add(t),i.push(t))}),be(this)&&console.log(o,i.length?i:"has no elements"),be(this)&&console.groupEnd(o),i}function Se(e){return/:(only-child|first-child|last-child)\b/.test(e)}function Me(e,{allowWhitespaceText:t=!0,ignoreComments:o=!0}={}){const i=e&&e.parentNode;if(!i)return!1;for(let n=i.firstChild;n;n=n.nextSibling)if(n!==e){if(n.nodeType===Node.ELEMENT_NODE)return!1;if(n.nodeType!==Node.TEXT_NODE){if(n.nodeType===Node.COMMENT_NODE){if(o)continue;return!1}return!1}if(!t)return!1;if(n.nodeValue&&""!==n.nodeValue.trim())return!1}return!0}function Pe(e){const t=e&&e.parentNode;if(!t)return!1;for(let o=t.firstChild;o&&o!==e;o=o.nextSibling){if(o.nodeType===Node.TEXT_NODE&&o.nodeValue&&""!==o.nodeValue.trim())return!0;if(o.nodeType!==Node.COMMENT_NODE&&o.nodeType!==Node.ELEMENT_NODE&&o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE)return!0}return!1}function Ce(e){const t=e&&e.parentNode;if(!t)return!1;let o=!1;for(let i=t.firstChild;i;i=i.nextSibling)if(o){if(i.nodeType===Node.TEXT_NODE&&i.nodeValue&&""!==i.nodeValue.trim())return!0;if(i.nodeType!==Node.COMMENT_NODE&&i.nodeType!==Node.ELEMENT_NODE&&i.nodeType!==Node.TEXT_NODE&&i.nodeType!==Node.COMMENT_NODE)return!0}else i===e&&(o=!0);return!1}function Ee(e,t){return/:only-child\b/.test(t)?this.hasNoSignificantSiblingNodes(e,{allowWhitespaceText:!0,ignoreComments:!0}):/:first-child\b/.test(t)?!this.hasSignificantLeadingText(e):!/:last-child\b/.test(t)||!this.hasSignificantTrailingText(e)}function Te(e,t){return/:only-child\b/.test(t)?"has significant sibling nodes (text/elements)":/:first-child\b/.test(t)?"has significant leading text":/:last-child\b/.test(t)?"has significant trailing text":"failed heuristic validation"}function Oe(e,t){return this.isHeuristicSelector(t)?e.filter(e=>this.validateHeuristicSelectorMatch(e,t)):e}function ye(e,t=""){const o=this._DOM.getElement("head"),i=this._DOM.body;if(!o&&!i)return void console.error("Check the structure of your document. We didn`t find HEAD and BODY tags. HTML2PDF4DOC expects valid HTML.");const n=this.create("style",e);n?(this._DOM.setAttribute(n,this._selector.style,t),o?this._DOM.insertAtEnd(o,n):i?this._DOM.insertBefore(i,n):this.strictAssert(!1,"We expected to find the HEAD and BODY tags.")):console.error("Failed to create print styles")}const ve=L("positioning");function De(e,t){if(!e||!this._DOM.getParentNode(e))return!1;let o=e;for(;this._DOM.getParentNode(o)&&o!==t;){if(this._DOM.getFirstElementChild(this._DOM.getParentNode(o))!==o)return!1;o=this._DOM.getParentNode(o)}return o===t}function Re(e,t){if(!e||!this._DOM.getParentNode(e))return!1;let o=e;for(;this._DOM.getParentNode(o)&&o!==t;){if(this._DOM.getParentNode(o)===t){let e=this._DOM.getRightNeighbor(o);for(;!this._DOM.getElementOffsetHeight(e)&&!this._DOM.getElementOffsetWidth(e);)if(e=this._DOM.getRightNeighbor(e),this.isContentFlowEnd(e))return!0;return this.isContentFlowEnd(e)}if(this._DOM.getLastElementChild(this._DOM.getParentNode(o))!==o)return!1;o=this._DOM.getParentNode(o)}return o===t}function xe(e,t){return this._DOM.getElementOffsetTop(t)-this._DOM.getElementOffsetBottom(e)>-2}function Ne(e,t){const o=this._DOM.getElementOffsetBottom(e),i=this._DOM.getElementOffsetTop(t),n=o-i,r=n>=2;return ve(this)&&console.group("isLineKept?"),ve(this)&&console.log("\n",r,"\n","\n currentBottom",o,[e],"\n nextTop",i,[t],"\n delta",n),ve(this)&&console.groupEnd("isLineKept?"),r}function Be(e,t,o){const i="[init-position]",n="[init-vertical-align]",r="relative",s=o||this._DOM.getComputedStyle(t),l=s.position,a=s.verticalAlign;if(e)l!=r&&(this._DOM.setStyles(t,{position:r}),this._DOM.setAttribute(t,i,l)),"top"!=a&&(this._DOM.setStyles(t,{"vertical-align":"top"}),this._DOM.setAttribute(t,n,a));else{const e=this._DOM.getAttribute(t,i),o=this._DOM.getAttribute(t,n);e&&(this._DOM.setStyles(t,{position:e}),this._DOM.removeAttribute(t,i)),o&&(this._DOM.setStyles(t,{"vertical-align":o}),this._DOM.removeAttribute(t,n))}}function Fe(e,{prefer:t="self"}={}){if(!e)return null;const o=e=>"last"===t?this._DOM.getLastElementChild(e):"first"===t||"self"===t?this._DOM.getFirstElementChild(e):null,i=new Set;let n=e;for(;n&&!i.has(n);){i.add(n);if(this._DOM.getElementOffsetParent(n))return n;const e=this._DOM.getComputedStyle(n);if(!e)return null;const t=e.display,r=e.visibility,s=e.position;if("none"===t||"collapse"===r||"fixed"===s)return null;if("contents"===t){const e=o.call(this,n);if(!e)return null;n=e;continue}return null}return null}const ke=L("getters");function Ae(e,t){return this.getTop(e,t)}function He(e,t,o){const i=o||this._DOM.getComputedStyle(t),n=parseFloat(i.paddingTop)||0;return this.getTop(e,t)-n}function Ie(e,t,o){const i=o||this._DOM.getComputedStyle(t),n=parseFloat(i.paddingTop)||0;return this.getBottomWithMargin(e,t)-n}function Le(e,t=null,o=0,i=null,n=[],r=null){if(!e)return void(ke(this)&&console.warn("[getTop] element must be provided, but was received:",e,"\nThe function returned:",void 0));if(!(e instanceof HTMLElement))return void this.strictAssert(0,"[getTop] element must be HTMLElement, but was received:",e,"\nThe function returned:",void 0);if(null===t)return this._DOM.getElementOffsetTop(e);if(!(t instanceof HTMLElement))return void this.strictAssert(0,"[getTop] root must be HTMLElement, but was received:",t,"\nThe function returned:",void 0);if(i=i||{element:e,root:t},0===o&&!t.contains(e))return void this.strictAssert(0,"[getTop] the provided root does not contain the element.",{element:e,root:t,paramSnapshot:i},"\nThe function returned:",void 0);if(!(r=r||$e.call(this,t,i)))return void(ke(this)&&console.warn("Root has no a usable offset reference; nothing else to measure against. \nThe function returned:",void 0,{element:e,paramSnapshot:i,offsetParent:l,traversal:s}));if(e===t)return o;const s=[...n,e],l=this._DOM.getElementOffsetParent(e);if(!l)return void(ke(this)&&console.warn("Element has no offset parent; offset chain is broken. \nThe function returned:",void 0,{element:e,paramSnapshot:i,offsetParent:l,traversal:s}));const a=this._DOM.getElementOffsetTop(e);return l===t?a+o:l===r.sharedOffsetParent?(r.sharedOffsetParentIsBody&&!r.warnedAboutBody&&(r.warnedAboutBody=!0,ke(this)&&console.warn("getTop(): reached document.body while measuring offsets. Layout likely lacks positioned ancestors.",{element:e,root:t,paramSnapshot:i})),a+o-r.rootOffsetFromSharedParent):this.getTop(l,t,o+a,i,s,r)}function $e(e,t){const o=this._DOM.getElementOffsetParent(e);if(!o)return ke(this)&&console.warn("[getTop*]: root has no offset parent; cannot build relative offsets.",{root:e,paramSnapshot:t}),null;const i=this._DOM.getElementOffsetTop(e);return"number"!=typeof i?(ke(this)&&console.warn("[getTop*]: root offsetTop is not a number.",{root:e,sharedOffsetParent:o,paramSnapshot:t}),null):{sharedOffsetParent:o,rootOffsetFromSharedParent:i,sharedOffsetParentIsBody:o===e.ownerDocument?.body,warnedAboutBody:!1}}function Ge(e,t=null){if(e){if(null===t)return this._DOM.getElementOffsetBottom(e);if(t)return this.getTop(e,t)+this._DOM.getElementOffsetHeight(e);ke(this)&&console.warn("root must be provided, but was received:",t,"\nThe function returned:",void 0)}else ke(this)&&console.warn("[getBottom] element must be provided, but was received:",e,"\nThe function returned:",void 0)}function We(e,t){if(!e)return;const o=this.getBottom(e,t);let i;const n=this.createNeutralBlock();this._DOM.insertAfter(e,n);const r=this.getTop(n,t);this._DOM.removeNode(n);if(r>=o)i=r;else{i=o+parseInt(this._DOM.getComputedStyle(e).marginBottom)}return i}function je(e){const t=parseInt(this._DOM.getComputedStyle(e).marginTop),o=parseInt(this._DOM.getComputedStyle(e).marginBottom);return this._DOM.getElementOffsetHeight(e)+t+o}function ze(e,t){const o=parseInt(this._DOM.getComputedStyle(e).marginTop);return this.getTop(e,t)-o}function Ve(e){const t=this.create();this._DOM.insertAtEnd(e,t);const o=this._DOM.getElementOffsetWidth(t);return this._DOM.removeNode(t),o}function Ue(e,t="",o=!0){const i=this.create();o&&this._DOM.setStyles(i,{overflow:"auto"});const n=this._DOM.cloneNodeWrapper(e);this._DOM.setInnerHTML(n,t),this._DOM.insertAtEnd(i,n),this._DOM.insertBefore(e,i);const r=this._DOM.getElementOffsetHeight(i);return this._DOM.removeNode(i),r}function qe(e){const t=this.createNeutral();this._DOM.setInnerHTML(t,"!"),this._DOM.setStyles(t,{display:"block"}),this._DOM.insertAtEnd(e,t);const o=this._DOM.getElementOffsetHeight(t);return this._DOM.removeNode(t),o}function Ke(e,t=0){const o=this._DOM.getElementOffsetTop(e),i=this._DOM.cloneNode(e),n="!
".repeat(t);[...i.children].forEach(e=>this._DOM.setInnerHTML(e,n)),this._DOM.insertBefore(e,i);const r=this._DOM.getElementOffsetTop(e);return this._DOM.removeNode(i),r-o}function Ye(e){const t=this._DOM.getElementOffsetTop(e),o=this._DOM.cloneNodeWrapper(e);this._DOM.insertBefore(e,o);const i=this._DOM.getElementOffsetTop(e);return this._DOM.removeNode(o),i-t}function Xe(e){const t=this._DOM.getElementOffsetTop(e),o=this._DOM.cloneNodeWrapper(e),i=e.children.length,n=[...e.children];this._DOM.insertBefore(e,o);const r=[];for(let s=0;sthis._DOM.removeNode(e))}return this._DOM.removeNode(o),r}function Ze(e){if(!(e instanceof HTMLElement)||"TABLE"!==e.tagName)throw new Error("Expected a
element.");const t=[...e.children].reduce((e,t)=>{const o=t.tagName;return"TBODY"===o?{...e,rows:[...e.rows,...t.children]}:"CAPTION"===o?(this.setFlagNoBreak(t),{...e,caption:t}):"COLGROUP"===o?(this.setFlagNoBreak(t),{...e,colgroup:t}):"THEAD"===o?(this.setFlagNoBreak(t),{...e,thead:t}):"TFOOT"===o?(this.setFlagNoBreak(t),{...e,tfoot:t}):"TR"===o?{...e,rows:[...e.rows,...t]}:(ke(this)&&t&&console.warn("unexpected:",t),{...e,unexpected:[...e.unexpected,...t]})},{caption:null,thead:null,tfoot:null,rows:[],unexpected:[]});return t.unexpected.length>0&&ke(this)&&console.warn(`something unexpected is found in the table ${e}`),t}function Je(e,t){const o=t||this._DOM.getComputedStyle(e),i=this.createNeutralBlock();this._DOM.setStyles(i,{display:"block",padding:"0",margin:"0",border:"0",height:"0",clear:"both",visibility:"hidden",contain:"layout"}),this._DOM.insertAtEnd(e,i);const n=this.getNormalizedTop(i,e,o);return this._DOM.removeNode(i),n}function Qe(e,t,o="both"){const i="bottom"!==o,n="top"!==o;if(e instanceof HTMLElement){const r=i?this.getTop(e,t):void 0,s=n?this.getBottom(e,t):void 0;return i&&!Number.isFinite(r)?(this.strictAssert(!1,"[resolveRowBoundsGeneric] failed to measure top for HTMLElement",{row:e,root:t,want:o}),{top:void 0,bottom:void 0}):n&&!Number.isFinite(s)?(this.strictAssert(!1,"[resolveRowBoundsGeneric] failed to measure bottom for HTMLElement",{row:e,root:t,want:o}),{top:void 0,bottom:void 0}):"top"===o?{top:r,bottom:r}:"bottom"===o?{top:s,bottom:s}:{top:r,bottom:s}}if(Array.isArray(e)){let r=i?1/0:void 0,s=n?-1/0:void 0,l=!1,a=!1;return e.forEach(e=>{if(e instanceof HTMLElement){if(i){const o=this.getTop(e,t);Number.isFinite(o)&&(r=Math.min(r,o),l=!0)}if(n){const o=this.getBottom(e,t);Number.isFinite(o)&&(s=Math.max(s,o),a=!0)}}}),"top"===o?l?{top:r,bottom:r}:(this.strictAssert(!1,"[resolveRowBoundsGeneric] no valid top found in row array",{row:e,root:t,want:o}),{top:void 0,bottom:void 0}):"bottom"===o?a?{top:s,bottom:s}:(this.strictAssert(!1,"[resolveRowBoundsGeneric] no valid bottom found in row array",{row:e,root:t,want:o}),{top:void 0,bottom:void 0}):i&&!l?(this.strictAssert(!1,"[resolveRowBoundsGeneric] no valid top found in row array",{row:e,root:t,want:o}),{top:void 0,bottom:void 0}):n&&!a?(this.strictAssert(!1,"[resolveRowBoundsGeneric] no valid bottom found in row array",{row:e,root:t,want:o}),{top:void 0,bottom:void 0}):{top:r,bottom:s}}return this.strictAssert(!1,"[resolveRowBoundsGeneric] unexpected row payload",{row:e,root:t,want:o}),{top:void 0,bottom:void 0}}L("creators");function et(e,t){let o;if(e){const t=e.charAt(0);if(t.match(/[#\[\.]/))o=this._DOM.createElement("div"),this._DOM.setAttribute(o,e);else{if(!t.match(/[a-zA-Z]/))return void this.strictAssert(!1,"Expected valid html selector ot tag name, but received:",e);o=this._DOM.createElement(e)}}else o=this._DOM.createElement("div");return t&&this._DOM.setInnerHTML(o,t),o}function tt(){return this.create(this._selector.neutral)}function ot(){const e=this.createNeutral();return e.style.display="block",e.style.clear="both",e}function it(){return this.create(this._selector.textNode)}function nt(){return this.create(this._selector.textLine)}function rt(){return this.create(this._selector.textGroup)}function st(e){const t=this.create(this._selector.flagNoBreak);return e&&this._DOM.setStyles(t,e),t}function lt(){return this.create(this._selector.printPageBreak)}function at(){return this.create(this._selector.complexTextBlock)}function ht(e){const t=this._DOM.cloneNodeWrapper(e);return this._DOM.setAttribute(t,".test-node"),this._DOM.setStyles(t,{position:"absolute",background:"rgb(255 239 177)",width:this.getMaxWidth(e)+"px"}),t}function ct(e,t){const o=this.create(this._selector.word);return this._DOM.setInnerHTML(o,e),o.dataset.index=t,o}function dt(){return this.create(this._selector.printForcedPageBreak)}function gt(e,t){if(!t)return null;const o=this.create();return this._DOM.setStyles(o,{display:"flex",flexWrap:"nowrap",alignItems:"center",justifyContent:"center",textAlign:"center",fontSize:"8px",fontFamily:"sans-serif",letterSpacing:"1px",textTransform:"uppercase",height:t+"px"}),e&&this._DOM.setInnerHTML(o,e),this.setFlagNoBreak(o),o}function pt({wrapper:e,caption:t,colgroup:o,thead:i,tfoot:n,tbody:r}){const s=e||this.create("table"),l=this.create("TBODY");return t&&this._DOM.insertAtEnd(s,t),o&&this._DOM.insertAtEnd(s,o),i&&this._DOM.insertAtEnd(s,i),r&&this._DOM.insertAtEnd(l,...r),this._DOM.insertAtEnd(s,l),n&&this._DOM.insertAtEnd(s,n),s}function ut(e){const t=this._DOM.cloneNodeWrapper(e);return this.unmarkPageStartElement(t),this.setFlagNoBreak(t),t}L("splitters");function _t(e){return e.split(/(?<=\n)/)}function ft(e){return(this._DOM.getNodeValue(e)||this._DOM.getInnerHTML(e)).split(/(?<=\s|-)/)}function mt(e){return(this._DOM.getNodeValue(e)||this._DOM.getInnerHTML(e)).trim().split(/(?<=\s|-)/).filter(e=>" "!=e)}function bt(e){const t=e,o=this.splitTextByWordsGreedy(e),i=o.map(e=>{const t=this._DOM.createElement("span");return this._DOM.setInnerHTML(t,e+" "),t}),n=this.createTestNodeFrom(e);return this._DOM.insertAtEnd(n,...i),this._DOM.insertAtEnd(e,n),{splittedNode:t,nodeWords:o,nodeWordItems:i}}const wt=L("markers");function St(e,t){this._markupDebugMode&&this._DOM.setAttribute(e,this._selector.processed,"🏷️ "+t)}function Mt(e){this._DOM.setAttribute(e,this._selector.flagNoBreak)}function Pt(e,t){this._DOM.setAttribute(e,this._selector.flagNoHanging,t)}function Ct(e){this._DOM.setAttribute(e,this._selector.flagSlice)}function Et(e,t){this._DOM.setAttribute(e,this._selector.pageStartMarker,`${t}`)}function Tt(e){this._DOM.removeAttribute(e,this._selector.pageStartMarker)}function Ot(e,t){this._DOM.setAttribute(e,this._selector.pageEndMarker,`${t}`)}function yt(e,t){this._DOM.setAttribute(e,this._selector.pageMarker,`${t}`)}function vt(e){wt(this)&&console.log("[mark ⊤ cut]",e),e&&this._DOM.setAttribute(e,this._selector.cleanTopCut)}function Dt(e){wt(this)&&console.log("[mark ⊥ cut]",e),e&&this._DOM.setAttribute(e,this._selector.cleanBottomCut)}function Rt(e){wt(this)&&console.log("[mark ⊤ cut]",e),e&&this._DOM.setAttribute(e,this._selector.topCutPart)}function xt(e){wt(this)&&console.log("[mark ⊥ cut]",e),e&&this._DOM.setAttribute(e,this._selector.bottomCutPart)}function Nt(e){if(e&&e.length)if(1!==e.length)for(let t=0;t0,i=t0,n=t","color:blue",o),r=o,s=[...this._DOM.getChildren(o)]):Array.isArray(o)?(wt(this)&&console.log("%c[markSliceCutsInRows] It is an Array","color:blue",o),r=void 0,s=o):this.strictAssert(0,"we expected TR or an array of elements!"),!r&&!s.length){wt(this)&&console.log("%c[markSliceCutsInRows] There was no split","color:red",{rowWrapper:r,cellWrappers:s});break}i&&(r&&(wt(this)&&console.log("[markSliceCutsInRows] rowWrapper ⊥",r),this.markTopCut(r)),s.forEach(e=>{wt(this)&&console.log("[markSliceCutsInRows] cell 🖍️ ⊥",e),this.markTopCut(e)})),n&&(r&&(wt(this)&&console.log("[markSliceCutsInRows] rowWrapper ⊤",r),this.markBottomCut(r)),s.forEach(e=>{wt(this)&&console.log("[markSliceCutsInRows] cell 🖍️ ⊤",e),this.markBottomCut(e)}))}else wt(this)&&console.log("%c[markSliceCutsInRows] The rows were not passed. Doing nothing.","color:red")}L("wrappers");function Ft(e){const t=this._DOM.getChildren(e),o=this.createNeutralBlock();return this._DOM.insertAtStart(o,...t),this._DOM.insertAtStart(e,o),o}const kt=L("fitters");function At({element:e,height:t,width:o,vspace:i,hspace:n}){const r=i/t,s=n/o,l=ra&&(g||(g=this.wrapNodeChildrenWithNeutralBlock(s),d=this._DOM.getElementOffsetHeight(g)||d),this.fitElementWithinHeight(g,a),n=!0,kt(this)&&console.warn("💢 scaleCellsToHeight: resized cell content",{cell:s,target:a}))}return n}function Lt(e,t){this._DOM.setStyles(e,{"box-sizing":"border-box",width:`${this._DOM.getElementOffsetWidth(t)}px`,"min-width":`${this._DOM.getElementOffsetWidth(t)}px`})}function $t(e){this.copyNodeWidth(e,e),this._DOM.getAll("td",e).forEach(e=>this.copyNodeWidth(e,e))}function Gt(e){Array.isArray(e)&&e.forEach(e=>{e&&this.copyNodeWidth(e,e)})}function Wt(e,t={}){const{descentRatio:o=.22,normalLH:i=1.2,safety:n=1}=t,r=getComputedStyle(e),s=parseFloat(r.fontSize)||0;let l;if("normal"!==r.lineHeight&&r.lineHeight){const e=parseFloat(r.lineHeight);l=Number.isFinite(e)?e:i*s}else l=i*s;const a=(Math.max(0,(l-s)/2)+o*s)*n;return Math.ceil(a)}const jt=L("pageBreaks");function zt(e,t){let o=e;for(;;){const e=this.findFirstChildParent(o,t);if(!e||e===o)break;o=e}return o}function Vt(e,t,o){jt(this)&&console.group("➗ findBetterPageStart");let i=!1,n=!1,r=!1;const s=t?this.getTop(t,o):0;jt(this)&&console.log("Start calculations:",{pageStart:e,lastPageStart:t,root:o,topLimit:s});const l=this.findFirstChildParentFromPage(e,s,o);let a;if(l)a=l;else{a=this.getTop(e,o){if(this.isSTYLE(t))return to(this)&&console.info("🚸 (getPreparedChildren) ignore STYLE",[t]),e;if(this.isSignificantTextNode(t)){const o=this.createTextNodeWrapper();return this._DOM.wrap(t,o),e.push(o),to(this)&&console.info("🚸 (getPreparedChildren) wrap and return TEXT NODE",[t]),e}if(this._DOM.isElementNode(t)){if(this.shouldSkipFlowElement(t,{context:"getPreparedChildren"}))return e;if(!this._DOM.getElementOffsetParent(t)){const o=this.getPreparedChildren(t);return o.length>0&&e.push(...o),to(this)&&console.info("%c🚸 (getPreparedChildren) * no offset parent — unwrapped","color:green",o,[t]),e}return e.push(t),to(this)&&console.info("🚸 (getPreparedChildren) * normal node",[t]),e}return to(this)&&console.info("%c🚸 (getPreparedChildren) IGNORE whitespace / comment ...","color:red",[t]),e},[]),to(this)&&console.groupEnd("⚗️🚸 distill children"),to(this)&&console.info("🚸 distilled children",t);const o=ho.call(this,t),i=this.isInline(e);o&&(to(this)&&console.info("🚸 isVerticalFlowDisrupted in children of element",[e]),i?(to(this)&&console.info("🎒🚸 parent element is inline wrapper",[e]),t=[lo.call(this,e)]):t=so.call(this,t))}}return to(this)&&console.info("🚸 getPreparedChildren:",t),to(this)&&console.groupEnd("🚸 getPreparedChildren of"),t}function io(e,t,o,i){let n=[];if(this.isNoBreak(e))return to(this)&&console.info("🧡 isNoBreak",e),[];if(this.isComplexTextBlock(e))return to(this)&&console.info("💚 ComplexTextBlock",e),this._paragraph.split(e)||[];if(this.isWrappedTextNode(e))return to(this)&&console.info("💚 TextNode",e),this._paragraph.split(e)||[];if(!co.call(this,e))return to(this)&&console.info("🪲 getSplitChildren: empty node, return []",e),[];const r=this._DOM.getComputedStyle(e);if(this.isTableNode(e,r))to(this)&&console.info("💚 TABLE",e),n=this._table.split(e,t,o,i,r)||[];else if(this.isTableLikeNode(e,r))to(this)&&console.info("💚 TABLE like",e),n=this._tableLike.split(e,t,o,i,r)||[];else if(this.isPRE(e,r))to(this)&&console.info("💚 PRE",e),n=this._pre.split(e,t,o,i,r)||[];else if(this.isFlexRow(e,r)){to(this)&&console.info("🩷 Flex ROW",e);let t=this.getPreparedChildren(e);n=ao.call(this,t)}else this.isGridAutoFlowRow(e,r)?(to(this)&&console.info("💜 GRID"),n=this._grid.split(e,t,o,i)||[]):(to(this)&&console.info("💚 found some node - use main this.getPreparedChildren() for:",e),n=this.getPreparedChildren(e));return n}function no(e){const t=[];if(!e||!this||!this._DOM)return t;let o=e;for(;o;){let e=this._DOM.getFirstElementChild(o);for(;e&&this.shouldSkipFlowElement(e,{context:"getFirstChildren:firstChild"});)e=this._DOM.getRightNeighbor(e);if(!e)break;if(this.isSyntheticTextWrapper(e))break;t.push(e),o=e}return t}function ro(e){const t=[];if(!e||!this||!this._DOM)return t;let o=e;for(;o;){let e=this._DOM.getLastElementChild(o);for(;e&&this.shouldSkipFlowElement(e,{context:"getLastChildren:lastChild"});)e=this._DOM.getLeftNeighbor(e);if(!e)break;if(this.isSyntheticTextWrapper(e))break;t.push(e),o=e}return t}function so(e){let t=null;const o=[];return e.forEach(e=>{this.isInline(e)?(t||(t=lo.call(this,e),o.push(t)),this._DOM.insertAtEnd(t,e)):(t=null,o.push(e))}),o}function lo(e){const t=this.createComplexTextBlock();return this._DOM.wrap(e,t),t}function ao(e){const t=e.filter(e=>this._DOM.getElementOffsetHeight(e)>0);return t.length>0?t:e}function ho(e){return e.some((e,t,o)=>{const i=e,n=o[t+1];if(!n)return!1;return this._DOM.getElementOffsetBottom(i)>this._DOM.getElementOffsetTop(n)})}function co(e){let t=e.firstChild;for(;t;){if(this._DOM.isElementNode(t)){if(!this.shouldSkipFlowElement(t,{context:"hasRenderableChild"}))return!0}else if(this.isSignificantTextNode(t))return!0;t=t.nextSibling}return!1}const go=L("media"),po=new Set(["IMG","SVG","OBJECT","EMBED","IFRAME","VIDEO","AUDIO","CANVAS"]);function uo(e,t="self"){return"last"===t?this._DOM.getLastElementChild(e):this._DOM.getFirstElementChild(e)}function _o(e){if(!e)return!1;const t=this._DOM.getElementTagName(e);if(!t)return!1;if("INPUT"===t){return"image"===(this._DOM.getAttribute(e,"type")||"").toLowerCase()}return po.has(t)}function fo(e,{prefer:t="self"}={}){if(!e)return null;const o=new Set;let i=e;for(;i&&!o.has(i);){if(o.add(i),this.isReplacedElement(i))return i;if("function"==typeof this.resolveFlowElement){const e=this.resolveFlowElement(i,{prefer:t});if(e&&e!==i){if(this.isReplacedElement(e))return e;i=e;continue}}const e=[...this._DOM.getChildren(i)].filter(e=>{const t=this._DOM.getComputedStyle(e)?.display;return"none"!==t});if(1!==e.length)return go(this)&&console.info("🧭 resolveReplacedElement: branching or empty wrapper",i,e),null;i=uo.call(this,i,t)||e[0]}return null}const mo=L("slicers");function bo({rootNode:e,rootComputedStyle:t,children:o,firstPartHeight:i,fullPageHeight:n,firstChild:r,points:s=[]}){if(!o.length)return mo(this)&&console.log("🧶 [getSplitPoints] %c has no children, early returns []","font-weight:bold",{rootNode:e}),[];const l=t=>{const o=this.findBetterPageStart(t,s.at(-1),e);return s.length||o!==r?(mo(this)&&console.log("%c 🧼🧼🧼🧼 push(point) in registerPoint()","color:violet",{point:o,points:s,firstChild:r},s.length),s.push(o),!1):(mo(this)&&console.log("%c !points.length && point === children[0] && children[1]","color:red"),mo(this)&&console.log("%c 🅾️ push(null) in registerPoint()","color:red"),s.push(null),!0)};mo(this)&&console.group("🧶 getSplitPoints"),mo(this)&&console.log("points.length",s.length);const a=t||this._DOM.getComputedStyle(e),h=new WeakMap,c=e=>{let t=h.get(e);return t||(t=Object.create(null),h.set(e,t)),t},d=t=>{if(!t)return NaN;const o=c(t);return"top"in o||(o.top=this.getNormalizedTop(t,e,a)),o.top},g=t=>{if(!t)return NaN;const o=c(t);return"bottomWithMargin"in o||(o.bottomWithMargin=this.getNormalizedBottomWithMargin(t,e,a)),o.bottomWithMargin},p=e=>{if(!e)return 0;const t=c(e);return"offsetHeight"in t||(t.offsetHeight=this._DOM.getElementOffsetHeight(e)),t.offsetHeight};this.setInitStyle(!0,e,a);let u=!1;const _=()=>(u||(u=!0,mo(this)&&console.groupEnd(`walking through ${o.length} children`),this.setInitStyle(!1,e,t),mo(this)&&console.groupEnd("getSplitPoints")),s);mo(this)&&console.group(`walking through ${o.length} children`,o);for(let t=0;th))if(mo(this)&&console.log("[getSplitPoints]",`next overtook the floater : (nextElementTop) ${b} > ${h}`,{currentElement:u},"does current overflow? let's check.",{isNextElementTopFinite:w}),(this.isSVG(u)||this.isIMG(u))&&mo(this)&&console.log("%cIMAGE","color:red;text-weight:bold"),S=g(u),S<=h){if(w){mo(this)&&console.log("[getSplitPoints]",`current fits: (currentElementBottom) ${S} <= ${h}, 🍎 register nextElement as Point.`,{currentElement:u,nextElement:m});if(l(m))return mo(this)&&console.log("%cNULL CASE, return","color:red;text-weight:bold"),_();continue}mo(this)&&console.log("[getSplitPoints] nextElementTop not finite and current fits tail window",{currentElementBottom:S,floater:h,nextElement:m})}else mo(this)&&console.log(`🔪🥒 try to split overflowing current: (currentElementBottom > ) ${S} > ${h}`,{currentElement:u}),M=!0;if(!m){mo(this)&&console.log("%c[getSplitPoints] !nextElement","color:red"),mo(this)&&console.log("%c[getSplitPoints] * Try to split it. 🔪🥒","color:blue"),S=S??g(u);let t=u;if(u.parentElement&&e.contains(u.parentElement)){let o=u.parentElement;for(;o&&e.contains(o)&&o!==e&&!this._DOM.getRightNeighbor(o);)t=o,o=o.parentElement}const o=t===u?S:g(t);if(o<=h){mo(this)&&console.log("%c 🍕 [getSplitPoints] !nextElement branch fits with container shell","color:violet",{currentElementBottom:S,containerBottom:o,floater:h,containerElement:t});continue}M=!0}if(!M)continue;let P=[];const C=this.getSplitChildren(u,i,n,e);if(C.length){if(P=bo.call(this,{rootNode:e,rootComputedStyle:a,children:C,firstPartHeight:i,fullPageHeight:n,firstChild:r,points:s}),0===P.length){const e=Math.max(i,n),t=p(u),o=t>e&&(!P.length||1===P.length&&null===P[0]);if(mo(this)&&console.log("room (Math.max)",e),o){if(mo(this)&&console.warn("%c⚠️ UNSPLITTABLE OVERSIZED ELEMENT — SCALE IT","color:white; background:red; font-weight:bold;",u,`height: ${t}`),!s.length&&u===r)return mo(this)&&console.warn("🅾️ (1) points.push(null) in isUnbreakableOversized"),s.push(null),_();if(m){if(l(m))return _()}}else if(l(u))return _()}}else{mo(this)&&console.log("🍎 currentElementChildren.length == 0");const e=p(u);if(e>c&&(!P.length||1===P.length&&null===P[0])){if(mo(this)&&console.warn("%c⚠️ UNSPLITTABLE OVERSIZED ELEMENT — SCALE IT","color:white; background:red; font-weight:bold;",u,`height: ${e}`),mo(this)&&console.warn("🅾️ (2) points.push(null) in isUnbreakableOversized"),!s.length&&u===r)return s.push(null),_();if(m){mo(this)&&console.warn("🅾️🅾️🅾️🅾️🅾️🅾️🅾️🅾️ registerPoint(nextElement)");if(l(m))return _()}}else{if(l(u))return _()}}}return _()}function wo(e,t,o,i,n){mo(this)&&console.group("[✖️] getSplitPointsPerCells");const r=e.map((e,r)=>{mo(this)&&console.group(`(•) Split CELL.${r} in:`,n);let s=[];const l=o-(t[r]||0),a=i-(t[r]||0);let h=this.getSplitChildren(e,l,a,n);if(h.length){const t=h[0];mo(this)&&console.log("firstChild",t),s=this.getSplitPoints({rootNode:e,children:h,firstPartHeight:l,fullPageHeight:a,firstChild:t})}else mo(this)&&console.log(`(•) empty cell #${r}`);return mo(this)&&console.log(`(•) return splitPoints for CELL#${r}`,s),mo(this)&&console.groupEnd(),s}),s=r.some(Co);mo(this)&&console.log("🧽🧽🧽🧽🧽🧽🧽 isFirstPartEmptyInAnyCell",s);let l=r,a=!1;if(s){l=e.map((e,r)=>{mo(this)&&console.group(`(••) Split CELL.${r} in:`,n);const s=o-(t[r]||0),l=i-(t[r]||0),a=this.getSplitChildren(e,s,l,n),h=a[0];mo(this)&&console.log("firstChild",h);let c=[];return a.length&&(c=this.getSplitPoints({rootNode:e,children:a,firstPartHeight:l,fullPageHeight:l,firstChild:h})),mo(this)&&console.log(`(••) return splitPoints for CELL#${r}`,c),mo(this)&&console.groupEnd(),c}),mo(this)&&console.log("[••] splitPointsPerCell",l);for(let e=0;e0&&this.strictAssert(o.every(e=>null!==e),"sliceNodeBySplitPoints: splitPoints contains null — sanitize upstream before slicing"),this.strictAssert(o.every(e=>!e||e.nodeType===Node.ELEMENT_NODE&&(t===e||t.contains(e))),"sliceNodeBySplitPoints: split point is not an Element within rootNode");for(let e=0;e<=o.length;e++){const n=o[e-1]??null,r=o[e]??null,s=this.cloneAndCleanOutsideRange(t,n,r);this.normalizeContentCuts({slice:s,top:null!==n,bottom:null!==r}),this._DOM.getChildNodes(s).length>0&&i.push(s)}return mo(this)&&console.log(i),mo(this)&&console.groupEnd(`🔪 (${e}) sliceNodeBySplitPoints`),i}function Mo({slice:e,top:t=!1,bottom:o=!1}){if(e){if(t){const t=[...this.getFirstChildrenChain(e)];t.forEach(e=>this.markCleanTopCut(e)),mo(this)&&console.log("[normalizeContentCuts] topChain 👗",t)}if(o){const t=[...this.getLastChildrenChain(e)];t.forEach(e=>this.markCleanBottomCut(e)),mo(this)&&console.log("[normalizeContentCuts] bottomChain 👗",t)}}else mo(this)&&console.log("[normalizeContentCuts] no slice has been passed; return")}function Po({index:e,rootNode:t,splitPoints:o}){mo(this)&&console.group(`🔪 (${e}) sliceNodeContentBySplitPoints`);const i=[];for(let e=0;e<=o.length;e++){const n=o[e-1]??null,r=o[e]??null,s=this.cloneAndCleanOutsideRange(t,n,r);mo(this)&&console.log({slice:s});const l=this.createNeutralBlock();for(;s.firstChild;)l.appendChild(s.firstChild);l.childNodes.length>0&&i.push(l)}return mo(this)&&console.log(i),mo(this)&&console.groupEnd(`🔪 (${e}) sliceNodeContentBySplitPoints`),i}function Co(e){return!!Array.isArray(e)&&(e.length>0&&null===e[0])}function Eo(e,t,o){t&&t.setAttribute("split","start"),o&&o.setAttribute("split","end");let i=e.cloneNode(!0);if(t){let t=i.querySelector('[split="start"]'),o=t.previousElementSibling;for(;o;){let e=o;o=o.previousElementSibling,e.remove()}let n=t.parentElement;for(;n&&n!==e;){let e=n.previousElementSibling;for(;e;){let t=e;e=e.previousElementSibling,t.remove()}n=n.parentElement}t.removeAttribute("split")}if(o){let t=i.querySelector('[split="end"]'),o=t.nextElementSibling;for(;o;){let e=o;o=o.nextElementSibling,e.remove()}let n=t.parentElement;for(;n&&n!==e;){let e=n.nextElementSibling;for(;e;){let t=e;e=e.nextElementSibling,t.remove()}n=n.parentElement}t.remove()}return t&&t.removeAttribute("split"),o&&o.removeAttribute("split"),i}const To=L("flowfilters"),Oo="__html2pdf4docFlowFilter",yo=[{test:e=>"none"===e.display,cache:{reason:"display:none",message:"* display:none — skipped"}},{test:e=>"absolute"===e.position,cache:{reason:"position:absolute",message:"* position:absolute — skipped"}},{test:e=>"fixed"===e.position,cache:{reason:"position:fixed",message:"* position:fixed — skipped"}},{test:e=>"collapse"===e.visibility,cache:{reason:"visibility:collapse",message:"* visibility:collapse — skipped"}}];function vo(e,t,o,i,{cached:n}={cached:!1}){if(!To(e))return;const r=t?`(${t}) `:"",s=n?" (cached)":"";console.info(`🚸 ${r}${o.message}${s}`,[i])}function Do(e,{context:t="",computedStyle:o}={}){if(!(e&&this&&this._DOM&&this._DOM.isElementNode(e)))return!1;const i=e[Oo];if(i)return vo(this,t,i,e,{cached:!0}),!0;const n=o??this._DOM.getComputedStyle(e);if(!n)return!1;for(const o of yo)if(o.test(n))return e[Oo]=o.cache,vo(this,t,o.cache,e),!0;return!1}L("pagination");function Ro({cells:e,splitPointsPerCell:t,sliceCell:o}){return t.map((t,i)=>{const n=e[i];return o({cell:n,index:i,splitPoints:t})})}function xo({originalRow:e,originalCells:t,slicedCellsPerOriginal:o,beginRow:i,cloneCellFallback:n,handleCell:r,finalizeRow:s}){const l=Math.max(...o.map(e=>e.length)),a=[];for(let h=0;h{const i=o[t][h]||n(e);r({context:l,cellClone:i,originalCell:e,cellIndex:t})}),a.push(s({context:l}))}return a}function No({originalRow:e,originalCells:t,splitPointsPerCell:o,sliceCell:i,beginRow:n,cloneCellFallback:r,handleCell:s,finalizeRow:l}){if(!Array.isArray(o)||!o.length)return[];const a=this.sliceCellsBySplitPoints({cells:t,splitPointsPerCell:o,sliceCell:i});return this.buildRowSlices({originalRow:e,originalCells:t,slicedCellsPerOriginal:a,beginRow:n,cloneCellFallback:r,handleCell:s,finalizeRow:l})}function Bo({usedRemainingWindow:e,isFirstPartEmpty:t,firstSliceTop:o,firstSliceBottom:i,pageBottom:n,epsilon:r=.5}){return{placeOnCurrentPage:e&&!t,remainingWindowSpace:Math.max(0,n-o),exceedsWindow:i>n+r}}function Fo({currentRows:e,index:t,rowSlices:o}){return Array.isArray(e)?(e.splice(t,1,...o),e):[]}const ko=L("pagination");function Ao({cells:e,targetHeight:t,shells:o}){return!!(Array.isArray(e)&&e.length&&t>0)&&this.scaleCellsToHeight(e,t,o)}function Ho({needsScalingInFullPage:e,cells:t}){return Boolean(e&&Array.isArray(t)&&t.length)}function Io({needsScalingInFullPage:e,scaleCallback:t,payload:o}){if(!e)return!1;if("function"!=typeof t)return!1;const i=t(o||{});return!i&&this&&this._debug&&this._debug._&&ko(this)&&console.warn("[pagination.scaling] requested full-page scaling but callback reported no change",o),Boolean(i)}L("pagination");function Lo(e,t,o){e&&Array.isArray(e.rows)&&e.rows.splice(t,1,...o)}function $o({rows:e,DOM:t,cellTagFilter:o,guardCallback:i}){if(!Array.isArray(e))return{};let n=!1,r=!1,s=!1,l=null;e.forEach(e=>{const i=Array.isArray(e)?e:Array.from(t.getChildren(e)||[]);null==l&&(l=i.length),i.length!==l&&(s=!0),i.forEach(e=>{const i=t.getElementTagName(e);if(!o||o(i,e)){const t=parseInt(e.getAttribute?.("rowspan"));Number.isFinite(t)&&t>1&&(n=!0);const o=parseInt(e.getAttribute?.("colspan"));Number.isFinite(o)&&o>1&&(r=!0)}})});const a={hasRowspan:n,hasColspan:r,inconsistentCells:s};return i?.(a),a}L("pagination");function Go(e){if(!e||"object"!=typeof e)throw new Error("splitter kernel adapter must be an object.");if(!e.rows||"object"!=typeof e.rows)throw new Error("splitter kernel adapter must expose a rows provider.");if("function"!=typeof e.rows.replaceRow)throw new Error("splitter kernel adapter rows.replaceRow must be a function.")}function Wo(e,{rowIndex:t,rowSlices:o}){Go(e);const i=Number.isFinite(t)?t:0,n=Array.isArray(o)?o:[],r=e.rows;r.replaceRow({rowIndex:i,rowSlices:n}),r.syncEntries?.({rowIndex:i,rowSlices:n});const s=e.guards?.getConfig?.({rowIndex:i,rowSlices:n})??r.getGuardConfig?.({rowIndex:i,rowSlices:n})??null;let l=null;if(s){const t={rows:s.rows,DOM:s.DOM||this._DOM,cellTagFilter:s.cellTagFilter,guardCallback:s.guardCallback};Array.isArray(t.rows)&&t.DOM&&(l=this.computeRowFlags(t),e.guards?.onFlags?.({flags:l,rowIndex:i,rowSlices:n}))}return e.metrics?.refresh?.({rowIndex:i,rowSlices:n,flags:l}),r.onRowsChanged?.({rowIndex:i,rowSlices:n,flags:l}),{flags:l}}L("pagination");function jo({cells:e}){return Array.isArray(e)&&e.length?e.map(e=>{if(!e)return 0;const t=this._DOM.getComputedStyle(e),o=(parseFloat(t?.paddingTop)||0)+(parseFloat(t?.paddingBottom)||0)+(parseFloat(t?.borderTopWidth)||0)+(parseFloat(t?.borderBottomWidth)||0);return Number.isFinite(o)?Math.max(0,o):0}):[]}const zo=L("pagination");function Vo({ownerLabel:e,DOM:t,row:o,targetHeight:i,cachedShells:n,getRowShellHeightsCallback:r,scaleCellsToHeightCallback:s}){if(e||zo(this)&&console.warn("[scaleRowCellsToHeight] 👤 Owner wanted!",{owner:e}),!o)return zo(this)&&console.warn("[pagination.overflow] Missing row for scaling.",{owner:e}),!1;if("function"!=typeof s)return zo(this)&&console.warn("[pagination.overflow] scaleCellsToHeight callback is required.",{owner:e}),!1;const l=t,a=l&&"function"==typeof l.getChildren?l.getChildren(o):null;return s(a?[...a]:[],i,Array.isArray(n)?n:"function"==typeof r?r(o):[])}function Uo({ownerLabel:e,rowIndex:t,row:o,availableRowHeight:i,fullPageHeight:n,splitStartRowIndexes:r,reasonTail:s,reasonFull:l,registerPageStartCallback:a,scaleProblematicCellsCallback:h,debugLogger:c}){return e||zo(this)&&console.warn("[handleRowOverflow] 👤 Owner wanted!",{owner:e}),Array.isArray(r)?"function"!=typeof a?(zo(this)&&console.warn("[pagination.overflow] registerPageStart callback is required.",{owner:e}),t):i!1,isSlice:n=()=>!1}=t,{handleRowWithRowspan:r=()=>e.rowIndex,handleSplittableRow:s=()=>e.rowIndex,handleAlreadySlicedRow:l=()=>e.rowIndex}=o,{row:a}=e;return i(a,e)?r({evaluation:e}):n(a,e)?l({evaluation:e}):s({evaluation:e})}function ti({evaluation:e,splitStartRowIndexes:t,fullPageHeight:o,resolveOverflow:i,debug:n,afterResolve:r}){const{rowIndex:s,tailWindowHeight:l}=e;Qo(this)&&console.log("%c ⚠️ Row has ROWSPAN; use conservative fallback (no slicing)","color:DarkOrange; font-weight:bold");const a=i({rowIndex:s,evaluation:e,availableRowHeight:l,splitStartRowIndexes:t,fullPageHeight:o});return r?.({evaluation:e,tailWindowHeight:l,fullPageHeight:o,result:a}),a}function oi({evaluation:e,splitStartRowIndexes:t,resolveSplitFailure:o,fullPageHeight:i,debug:n}){const{rowIndex:r,row:s,tailWindowHeight:l,delta:a}=e;return Qo(this)&&console.log(`%c Row # ${r} is slice! but don't fit`,"color:DarkOrange; font-weight:bold",s),Qo(this)&&console.warn("%c SUPER BIG","background:red;color:white",a,{part:i}),o({evaluation:e,splitStartRowIndexes:t,availableRowHeight:l,fullPageHeight:i})}function ii({tailWindowHeight:e,minMeaningfulRowSpace:t,fullPartHeight:o,debug:i}){return ethis.sliceNodeBySplitPoints({index:t,rootNode:e,splitPoints:o})),f=l.beginRow||(({originalRow:t,sliceIndex:o})=>{const i=this._DOM.cloneNodeWrapper(t);return r?.({rowWrapper:i,rowIndex:e,sliceIndex:o,originalRow:t}),{rowWrapper:i}}),m=l.cloneCellFallback||(e=>this._DOM.cloneNodeWrapper(e)),b=l.handleCell||(({context:e,cellClone:t})=>{this._DOM.insertAtEnd(e.rowWrapper,t)}),w=l.finalizeRow||(({context:e})=>e.rowWrapper),S=[];if(g.some(e=>Array.isArray(e)&&e.length)){const e=this.paginationBuildBalancedRowSlices({originalRow:t,originalCells:h,splitPointsPerCell:g,sliceCell:_,beginRow:f,cloneCellFallback:m,handleCell:b,finalizeRow:w});S.push(...e)}else Qo(this)&&console.log("🔴 There is no Split");return S.length&&this.markSliceCutsInRows(S),n&&n._&&console.log("%c newRows \n","color:magenta; font-weight:bold",S),{newRows:S,isFirstPartEmptyInAnyTD:p,needsScalingInFullPage:u}}function ri({row:e,rowIndex:t,decorateRowSlice:o}){const i=Array.isArray(e),n=this;return{getParentContainer:()=>i?null:e,getOriginalCells:()=>i?[...e]:[...n._DOM.getChildren(e)],getShellHeights:({cells:t})=>i?[]:n.getTableRowShellHeightByTD(e),markOriginalRow:({cells:t})=>{i||n.setFlagSlice(e)},beginRow:({originalRow:e,sliceIndex:r})=>{if(i)return{cells:[]};const s=n._DOM.cloneNodeWrapper(e);return o?.({rowWrapper:s,rowIndex:t,sliceIndex:r,originalRow:e}),{rowWrapper:s}},cloneCellFallback:e=>n._DOM.cloneNodeWrapper(e),handleCell:({context:e,cellClone:t})=>{i?(n.setFlagSlice(t),e.cells.push(t)):n._DOM.insertAtEnd(e.rowWrapper,t)},finalizeRow:({context:e})=>i?e.cells:e.rowWrapper}}function si({evaluation:e,splitResult:t,splitStartRowIndexes:o,insufficientRemainingWindow:i,extraCapacity:n,fullPageHeight:r,debug:s,handlers:l={}}){const{newRows:a,isFirstPartEmptyInAnyTD:h,needsScalingInFullPage:c}=t||{},{rowIndex:d,row:g,isLastRow:p,tailWindowHeight:u}=e,{onReplaceRow:_,onAbsorbTail:f,onRefreshRows:m,onPlacement:b,onSplitFailure:w}=l;return Array.isArray(a)&&a.length?(_?.({evaluation:e,newRows:a}),p&&f?.({evaluation:e,newRows:a,extraCapacity:n}),m?.({evaluation:e,newRows:a,splitStartRowIndexes:o}),b?.({evaluation:e,newRows:a,insufficientRemainingWindow:i,isFirstPartEmptyInAnyTD:h,needsScalingInFullPage:c,splitStartRowIndexes:o})??e.rowIndex):(Qo(this)&&console.log(`%c The row is not split. (ROW.${d})`,"color:orange",g),w?.({evaluation:e,splitStartRowIndexes:o,availableRowHeight:u,fullPageHeight:r})??e.rowIndex)}function li({evaluation:e,splitStartRowIndexes:t,extraCapacity:o,fullPageHeight:i,minPartLines:n,debug:r,decorateRowSlice:s,onBudgetInfo:l,handlers:a={}}){if(!e||!e.row)return e?.rowIndex??0;const{row:h}=e,c=this.getTableRowHeight(h,n),d=this.paginationCalculateRowSplitBudget({tailWindowHeight:e.tailWindowHeight,minMeaningfulRowSpace:c,fullPartHeight:i,debug:r});l?.({evaluation:e,firstPartHeight:d.firstPartHeight,fullPartHeight:i});const g=a.getRowSliceAdapter,p=g?.({evaluation:e,row:h,rowIndex:e.rowIndex,decorateRowSlice:s}),u=this.paginationSplitRow({rowIndex:e.rowIndex,row:h,firstPartHeight:d.firstPartHeight,fullPageHeight:i,debug:r,decorateRowSlice:s,rowAdapter:p});return this.paginationProcessRowSplitResult({evaluation:e,splitResult:u,splitStartRowIndexes:t,insufficientRemainingWindow:d.insufficientRemainingWindow,extraCapacity:o,fullPageHeight:i,debug:r,handlers:a})}function ai({evaluation:e,table:t,newRows:o,insufficientRemainingWindow:i,isFirstPartEmptyInAnyTD:n,needsScalingInFullPage:r,splitStartRowIndexes:s,pageBottom:l,fullPageHeight:a,debug:h,resolveRowBounds:c,registerPageStartCallback:d,scaleProblematicSliceCallback:g,applyFullPageScalingCallback:p}){const{rowIndex:u}=e,_=Array.isArray(o)?o[0]:null;if(!_)return d?.({targetIndex:u,reason:"Row split produced empty first slice"}),u-1;const f="function"==typeof c?c:e=>this.resolveRowBoundsGeneric(e,t),{top:m,bottom:b}=f(_),w=this.evaluateRowSplitPlacement({usedRemainingWindow:!i,isFirstPartEmpty:n,firstSliceTop:m,firstSliceBottom:b,pageBottom:l,epsilon:0});return w.placeOnCurrentPage?(w.remainingWindowSpace>0&&g?.(_,w.remainingWindowSpace),d?.({targetIndex:u+1,reason:"Row split — next slice starts new page"})):(p?.({row:_,needsScalingInFullPage:r,fullPageHeight:a}),d?.({targetIndex:u,reason:"Empty first part — move row to next page"})),u-1}class hi{constructor({config:e,DOM:t,node:i,selector:n}){this._debug=e.debugMode?{...e.debugConfig.paragraph}:{},this._assert=!!e.consoleAssert,this._DOM=t,this._selector=n,this._node=i,this._minParagraphLeftLines=2,this._minParagraphDanglingLines=2,this._minParagraphBreakableLines=this._minParagraphLeftLines+this._minParagraphDanglingLines||2,Object.assign(this,o)}split(e){return this._splitComplexTextBlockIntoLines(e)}_estimateLineCount(e){return Math.ceil(this._DOM.getElementOffsetHeight(e)/this._node.getLineHeight(e))}_splitComplexTextBlockIntoLines(e){if(this._debug._&&console.group("_splitComplexTextBlockIntoLines",[e]),this._estimateLineCount(e){const t=this._node.getLineHeight(e),o=this._DOM.getElementOffsetHeight(e),i=this._DOM.getElementOffsetLeft(e),n=this._DOM.getElementOffsetTop(e);return{element:e,lines:Math.ceil(o/t),left:i,top:n,height:o,lineHeight:t,text:this._DOM.getInnerHTML(e)}});this._debug._&&console.log("\n🚸 nodeChildren",[...t],"\n🚸 extendedChildrenArray",[...o]);const i=o.flatMap(e=>e.lines>1&&!this._node.isNoBreak(e.element)?this._breakItIntoLines(e.element):e.element);this._debug._&&console.log("\n🚸🚸🚸\n partiallyLinedChildren",[...i]);const n=i.reduce((e,t,o,i)=>(e||(e=[]),"BR"===this._DOM.getElementTagName(t)?(e.length||e.push([]),e.at(-1).push(t),e.push([]),this._debug._&&console.log("br; push:",t),e):!e.length||this._node.isLineChanged(e.at(-1).at(-1),t)?(e.push([t]),this._debug._&&console.log("◼️ start new line:",t),e):0===e.at(-1).length||e.length&&this._node.isLineKept(e.at(-1).at(-1),t)?(this._debug._&&console.log("⬆ add to line:",t),e.at(-1).push(t),e):void this.strictAssert(!0,"groupedPartiallyLinedChildren: An unexpected case of splitting a complex paragraph into lines.","\nOn the element:",t)),[]);if(this._debug._&&console.log("🟡🟡🟡 groupedPartiallyLinedChildren \n",n.length,[...n]),n.length{let o;if(0==e.length)o=e[0],o.setAttribute("role","🚫"),this.strictAssert(0==e.length,"The string cannot be empty (_splitComplexTextBlockIntoLines)");else if(1==e.length)o=e[0];else{o=this._node.createTextGroup(),this._DOM.insertBefore(e[0],o),this._DOM.insertAtEnd(o,...e)}return o.dataset.child=t,o});return this.logGroupEnd("OK _splitComplexTextBlockIntoLines"),this._DOM.setAttribute(e,this._selector.split),l}_breakItIntoLines(e){if(this._debug._&&console.group("_breakItIntoLines",[e]),this._node.isNoBreak(e))return this.logGroupEnd("isNoBreak"),e;if(this._node.isWrappedTextNode(e)){const t=this._breakWrappedTextNodeIntoLines(e);return this.logGroupEnd("TextNode newLines"),t}return this.logGroupEnd("(recursive _breakItIntoLines)"),this._processNestedInlineElements(e)}_processNestedInlineElements(e){this._debug._&&console.group("_processNestedInlineElements",[e]);const t=this._getNestedInlineChildren(e).flatMap(e=>this._estimateLineCount(e)>1?this._breakItIntoLines(e):e),o=this._findNewLineStarts(t,e),i=o.map((i,n)=>{const r=t[i],s=t[o[n+1]];return this._node.cloneAndCleanOutsideRange(e,r,s)});return this._DOM.insertInsteadOf(e,...i),this.logGroupEnd("Nested Inline parts"),i}_getNestedInlineChildren(e){return[...this._DOM.getChildNodes(e)].reduce((e,t)=>{if(this._node.isSignificantTextNode(t)){const o=this._node.createTextNodeWrapper();return this._DOM.wrap(t,o),e.push(o),e}if(!this._DOM.getElementOffsetParent(t)){const o=this._node.getPreparedChildren(t);return o.length>0&&e.push(...o),e}if(this._DOM.isElementNode(t)){return this._getNestedInlineChildren(t).forEach(t=>e.push(t)),e}},[])}_makeWordsFromTextNode(e){const t=this._node.splitTextByWordsGreedy(e);this._debug._&&console.log("wordArray",t);const o=t.map((e,t)=>this._node.createWord(e+"",t));return this._debug._&&console.log("wrappedWordArray",o),{wordArray:t,wrappedWordArray:o}}_breakWrappedTextNodeIntoLines(e){e.classList.add("🔠_breakItIntoLines"),e.classList.add("🚫_must_be_removed");const{wordArray:t,wrappedWordArray:o}=this._makeWordsFromTextNode(e);this._DOM.setInnerHTML(e,""),this._DOM.insertAtEnd(e,...o);const i=this._findNewLineStarts(o,e),n=i.reduce((o,n,r)=>{const s=this._node.createTextLine(),l=i[r],a=i[r+1],h=t.slice(l,a).join("")+"";return this._DOM.setInnerHTML(s,h),this._DOM.insertBefore(e,s),o.push(s),o},[]);return e.remove(),n}_findNewLineStarts(e,t){const o=t.style.lineHeight;t.style.lineHeight=2;const i=e.reduce((t,o,i)=>{const n=i>0?e[i-1].offsetTop:void 0,r=i>0?e[i-1].offsetHeight:void 0,s=o.offsetTop;return i>0&&n+r<=s&&t.push(i),t},[0]);return t.style.lineHeight=o,i}}function ci(e){if(e)return"function"==typeof e.getDebug?e.getDebug():e.debug}function di(e,t,o="unknown case"){if(!e||"function"!=typeof e.getSplitBottom||"function"!=typeof e.setSplitBottom)throw new Error("updateSplitBottom: adapter must expose getSplitBottom() and setSplitBottom().");const i=e.getSplitBottom();let n;if("number"==typeof t)n=t;else{if(!(t instanceof HTMLElement))throw new Error("updateSplitBottom: unexpected value type: "+typeof t);if("function"!=typeof e.computeSplitBottomForElement)throw new Error("updateSplitBottom: adapter must implement computeSplitBottomForElement(element).");n=e.computeSplitBottomForElement(t)}e.setSplitBottom(n);const r=function(e){return e?"function"==typeof e.getSplitBottomLog?e.getSplitBottomLog():e.splitBottomLog||null:null}(e);Array.isArray(r)&&r.push(n);const s=ci(e);s&&s._&&console.log(`%c♻️ [${function(e){return e?.label||"👤 [paginator.label] element"}(e)}] update splitBottom (with ${t}) \n • ${o}`,"color: green; font-weight: bold","\n",i||"•••","->",n,r?`\n log: ${r}`:"")}function gi(e,t,o,i="register page start"){const n=function(e){return e?"function"==typeof e.getRows?e.getRows()||[]:e.rows||[]:[]}(e),r=n.length,s=function(e){return!!e&&("function"==typeof e.shouldAssert?e.shouldAssert():Boolean(e.assert))}(e),l=ci(e),a=Number.isInteger(t);if(s&&console.assert(a,`registerPageStartAt: index must be an integer, got: ${t}`),!a)return;if(s&&console.assert(r>0,"registerPageStartAt: no rows to register"),0===r)return;if(0===t)return l&&l._&&console.log("%c 📍 Row #0 forced to next page (no short first fragment)","color:green; font-weight:bold"),void((n[0]instanceof HTMLElement||"number"==typeof n[0])&&di(e,n[0],`${i} (index=0)`));let h=Math.max(1,Math.min(t,r-1));const c=o.at(-1);if(null!=c&&h<=c&&(h=c+1),h>=r)return void(l&&l._&&console.warn(`registerPageStartAt return: computed index (${h}) >= rowsLen (${r})`,"Last split index should not equal rows.length, or the original table will be empty."));o.push(h),l&&l._&&console.log(`%c 📍 Row # ${h} registered as page start`,"color:green; font-weight:bold");const d=n[h];(d instanceof HTMLElement||"number"==typeof d)&&di(e,d,i)}function pi({owner:e=null,currentRows:t=[]}={}){return{owner:e,currentRows:Array.isArray(t)?t:[],parts:[]}}function ui({entries:e,part:t,startIndex:o=null,endIndex:i=null,type:n="unknown",rows:r=[],meta:s}){if(!e||!t)return null;const l=function(e){if(e)return Array.isArray(e.parts)||(e.parts=[]),e.parts}(e);if(!l)return null;const a={part:t,type:n,startIndex:o,endIndex:i,rows:Array.isArray(r)?[...r]:[]};return s&&"object"==typeof s&&Object.keys(s).length&&(a.meta={...s}),l.push(a),a}class _i{constructor({config:e,DOM:t,node:i,selector:n}){this._debug=e.debugMode?{...e.debugConfig.table}:{},this._assert=!!e.consoleAssert,this._DOM=t,this._selector=n,this._node=i,this._splitLabelHeightFromConfig=e.splitLabelHeight,this._initConstants(),Object.assign(this,o),this._resetCurrent()}split(e,t,o,i,n){this._setCurrent(e,t,o,i);const r=this._splitCurrentTable();return this._resetCurrent(),r}_initConstants(){this._signpostHeight=parseFloat(this._splitLabelHeightFromConfig)||0,this._minPartLines=2}_resetCurrent(){this._currentTable=void 0,this._currentFirstPageBottom=void 0,this._currentFullPageHeight=void 0,this._currentRoot=void 0,this._currentTableEntries=void 0,this._currentTableRecordedParts=void 0,this._currentTableDistributedRows=void 0,this._currentTableFirstPartContentBottom=void 0,this._currentTableFullPartContentHeight=void 0,this._currentTableTfootHeight=void 0,this._currentTableSplitBottom=void 0,this._logSplitBottom_=[],this._currentRowShellCache=void 0,this._currentOverflowHelpers=void 0,this._currentTableHasRowspan=void 0,this._currentTableHasColspan=void 0,this._currentTableInconsistentCells=void 0,this._currentTableHasUnexpectedChildren=void 0}_setCurrent(e,t,o,i){this._currentTable=e,this._currentFirstPageBottom=t,this._currentFullPageHeight=o,this._currentRoot=i,this._currentRowShellCache=new WeakMap,this._currentOverflowHelpers=this._composeOverflowHelpers()}_prepareCurrentTableForSplitting(){this._lockCurrentTableWidths(),this._collectCurrentTableEntries(),this._updateCurrentTableDistributedRows(),this._currentTableRecordedParts=pi({owner:this._currentTable,currentRows:this._currentTableDistributedRows}),this._currentTableEntries&&(this._currentTableEntries.recordedParts=this._currentTableRecordedParts),this._currentTable.__html2pdf4docRecordedParts=this._currentTableRecordedParts,this._analyzeCurrentTableStructure(),this._collectCurrentTableMetrics()}_lockCurrentTableWidths(){this._node.lockTableWidths(this._currentTable)}_splitCurrentTable(){this._prepareCurrentTableForSplitting(),this._setCurrentTableFirstSplitBottom(),this._debug._&&console.group("%c📊 _splitCurrentTable()","color:green; background:#eee; padding:3px","\n•",this._currentTableFirstPartContentBottom,"(1st bottom)","\n•",this._currentTableFullPartContentHeight,"(full part height)",{table:this._currentTable,rows:[...this._currentTableDistributedRows],rowCount:this._currentTableDistributedRows.length,entries:this._currentTableEntries,root:this._currentRoot});const e=this._resolveCurrentTableDistributedRowsInPlace();if(this._debug._&&console.log("📊 updated table rows",{rows_new:[...this._currentTableDistributedRows],rowCount_new:this._currentTableDistributedRows.length,splitStartRowIndexes:e}),!e.length)return this.logGroupEnd("[_splitCurrentTable]: there are no splits (!splitStartRowIndexes.length)"),[];let t=this._createTableSlices({splitPoints:e,table:this._currentTable,tableEntries:this._currentTableEntries});return this._node.markSliceCuts([this._currentTable,...t]),this._signpostHeight&&(t=this._extendTableSlices(t)),this._DOM.insertAfter(this._currentTable,...t),this._debug._&&console.log("tableSlices",t),this._debug._&&console.log("[table.split] recordedParts",this._currentTableRecordedParts?.parts),this.logGroupEnd("[_splitCurrentTable]"),[this._currentTable,...t]}_resolveCurrentTableDistributedRowsInPlace(){let e=[];for(let t=0;tNumber.isInteger(e)&&e>0&&e<=this._currentTableDistributedRows.length),"splitStartRowIndexes contains invalid indexes"),this.strictAssert(e.every((e,t,o)=>0===t||e>o[t-1]),"splitStartRowIndexes must be strictly ascending and without duplicates"),this.strictAssert(e.at(-1)!==this._currentTableDistributedRows.length,"Last split index should not equal rows.length, or the original table will be empty."),e}_evaluateAndResolveRow(e,t){const o=e,i=this._currentTableDistributedRows.length;this._debug._&&console.groupCollapsed(`🔲 %c Check the Row # ${o} (from ${i})`,"");const n=this._node.paginationBuildRowEvaluationContext({rows:this._currentTableDistributedRows,rowIndex:e,table:this._currentTable,splitBottom:this._currentTableSplitBottom});if(!n?.row)return console.warn("[table.split] Missing row during evaluation.",{rowIndex:e}),this.logGroupEnd(`Row # ${o} (from ${i}) is checked`),e;if(this._debug._){const e=n.fitsCurrentWindow,t=e?"green":"orange",o=e?"<=":">";console.log(`%c📐 does row fit? %c ${e} %c :: ${n.nextMarker} ${o} ${this._currentTableSplitBottom} %c(Δ=${n.delta})`,"",`font-weight:bold;color:${t};`,"",`color:${t};`)}if(this._debug._&&console.info({row:n.row,rows:[...this._currentTableDistributedRows]}),n.fitsCurrentWindow)return this._debug._&&console.log(`%c ✓ Row # ${e}: PASS`,"color:green"),this.logGroupEnd(`Row # ${o} (from ${i}) is checked`),e;const r=this._node.calculateFinalPartReclaimedHeight({signpostHeight:this._signpostHeight,tfootHeight:this._currentTableTfootHeight});if(this._node.paginationCanAbsorbLastRow({evaluation:n,extraCapacity:r,splitBottom:this._currentTableSplitBottom,debug:this._debug}))return this._debug._&&console.log("🫟 last-row-fits-without-bottom-signpost: skip split"),this.logGroupEnd(`Row # ${o} (from ${i}) is checked`),e;const s=this._resolveOverflowingRow({evaluation:n,splitStartRowIndexes:t,extraCapacity:r});return this.logGroupEnd(`Row # ${o} (from ${i}) is checked`),s}_resolveOverflowingRow({evaluation:e,splitStartRowIndexes:t,extraCapacity:o}){return this._node.paginationResolveOverflowingRow({evaluation:e,utils:{rowHasSpan:e=>this._rowHasSpan(e),isSlice:e=>this._node.isSlice(e)},handlers:{handleRowWithRowspan:()=>this._node.paginationResolveRowWithRowspan({evaluation:e,splitStartRowIndexes:t,fullPageHeight:this._currentTableFullPartContentHeight,resolveOverflow:({evaluation:e,splitStartRowIndexes:t,availableRowHeight:o,fullPageHeight:i})=>this._forwardOverflowFallback({rowIndex:e.rowIndex,row:e.row,availableRowHeight:o,fullPageHeight:i,splitStartRowIndexes:t,reasonTail:"Row with ROWSPAN — move to next page",reasonFull:"Row with ROWSPAN — scaled TDs to full page",branch:"rowspan"}),debug:this._debug,afterResolve:({tailWindowHeight:e,fullPageHeight:t})=>{this._debug._&&e>=t&&console.warn("[table.fallback] ROWSPAN row required full-page scaling to fit.")}}),handleSplittableRow:()=>this._resolveSplittableRow({evaluation:e,splitStartRowIndexes:t,extraCapacity:o}),handleAlreadySlicedRow:()=>this._node.paginationResolveAlreadySlicedRow({evaluation:e,splitStartRowIndexes:t,fullPageHeight:this._currentTableFullPartContentHeight,debug:this._debug,resolveSplitFailure:({evaluation:e,splitStartRowIndexes:t,availableRowHeight:o,fullPageHeight:i})=>this._forwardOverflowFallback({rowIndex:e.rowIndex,row:e.row,availableRowHeight:o,fullPageHeight:i,splitStartRowIndexes:t,reasonTail:"Slice doesn't fit tail — move to next page",reasonFull:"Scaled TD content to fit full page",branch:"alreadySliced"})})}})}_resolveSplittableRow({evaluation:e,splitStartRowIndexes:t,extraCapacity:o}){const{rowIndex:i}=e;this._debug._&&console.group(`%c 🔳 Try to split the ROW ${i} %c (from ${this._currentTableDistributedRows.length})`,"color:magenta;","");const n=this._node.paginationResolveSplittableRow({evaluation:e,splitStartRowIndexes:t,extraCapacity:o,fullPageHeight:this._currentTableFullPartContentHeight,minPartLines:this._minPartLines,debug:this._debug,decorateRowSlice:({rowWrapper:e,rowIndex:t,sliceIndex:o})=>{this._DOM.setAttribute(e,`.splitted_row_${t}_part_${o}`)},onBudgetInfo:({evaluation:e,firstPartHeight:t,fullPartHeight:o})=>{this._debug._&&console.info({currRowTop:e.rowTop,"• splitBottom":this._currentTableSplitBottom,"• is row sliced?":!1,"remaining page space":e.tailWindowHeight,"first part height":t,"full part height":o})},handlers:{onReplaceRow:({evaluation:e,newRows:t})=>{this._replaceRowInDOM(e.row,t)},onAbsorbTail:({newRows:e,extraCapacity:t})=>{this._node.absorbShortTrailingSliceIfFits({slices:e,extraCapacity:t,ownerLabel:"table",debug:this._debug})},onRefreshRows:({evaluation:e,newRows:t})=>{this._node.paginationRefreshRowsAfterSplit(this._getSplitterAdapter(),{rowIndex:e.rowIndex,rowSlices:t})},onPlacement:({evaluation:e,newRows:o,insufficientRemainingWindow:i,isFirstPartEmptyInAnyTD:n,needsScalingInFullPage:r})=>this._node.paginationHandleRowSlicesPlacement({evaluation:e,table:this._currentTable,newRows:o,insufficientRemainingWindow:i,isFirstPartEmptyInAnyTD:n,needsScalingInFullPage:r,splitStartRowIndexes:t,pageBottom:this._currentTableSplitBottom,fullPageHeight:this._currentTableFullPartContentHeight,debug:this._debug,registerPageStartCallback:({targetIndex:e,reason:o})=>this._registerPageStartAt(e,t,o),scaleProblematicSliceCallback:(e,t)=>{t>0&&(this._debug._&&console.log("⚖️ scaleProblematicCellsToHeight"),this._scaleProblematicCellsToHeight(e,t,this._getRowShellHeights(e)))},applyFullPageScalingCallback:({row:e,needsScalingInFullPage:t,fullPageHeight:o})=>{this._node.paginationApplyFullPageScaling({needsScalingInFullPage:t&&Boolean(e),payload:{row:e,targetHeight:o},scaleCallback:({row:e,targetHeight:t})=>(this._debug._&&console.log("⚖️ scaleProblematicCellsToHeight"),this._scaleProblematicCellsToHeight(e,t,this._getRowShellHeights(e)))})}}),onSplitFailure:({evaluation:e,splitStartRowIndexes:t,availableRowHeight:o,fullPageHeight:i})=>this._forwardOverflowFallback({rowIndex:e.rowIndex,row:e.row,availableRowHeight:o,fullPageHeight:i,splitStartRowIndexes:t,reasonTail:"Split failed — move row to next page",reasonFull:"Scaled TDs to fit full-page",branch:"splitFailure"})}});return this.logGroupEnd(`🔳 Try to split the ROW ${i} (from ${this._currentTableDistributedRows.length})`),n}_collectCurrentTableEntries(){this._currentTableEntries=this._node.getTableEntries(this._currentTable)}_rowHasSpan(e){const t=[...this._DOM.getChildren(e)];for(const e of t){const t=this._DOM.getElementTagName(e);if("TD"!==t&&"TH"!==t)continue;const o=parseInt(e.getAttribute("rowspan"));if(Number.isFinite(o)&&o>1)return!0}return!1}_collectCurrentTableMetrics(){const e=this._node.getEmptyNodeHeightByProbe(this._currentTable,'',!1),t=this._node.getTopForPageStartCandidate(this._currentTable,this._currentRoot),o=(this._node.getTopWithMargin(this._currentTable,this._currentRoot),this._DOM.getElementOffsetHeight(this._currentTableEntries.caption)||0),i=this._DOM.getElementOffsetTop(this._currentTableDistributedRows[0],this._currentTable)-o||0;this._currentTableTfootHeight=this._DOM.getElementOffsetHeight(this._currentTableEntries.tfoot)||0,this._currentTableFirstPartContentBottom=this._currentFirstPageBottom-t-e-this._signpostHeight,this._currentTableFullPartContentHeight=this._currentFullPageHeight-o-i-this._currentTableTfootHeight-e-2*this._signpostHeight}_getDistributedRows(e){return[...e.rows,...e.tfoot?[e.tfoot]:[]]}_updateCurrentTableDistributedRows(){this._currentTableDistributedRows=this._getDistributedRows(this._currentTableEntries)}_analyzeCurrentTableStructure(){this._currentTableEntries;const e=this._currentTableDistributedRows||[],t=this._node.computeRowFlags({rows:e,DOM:this._DOM,cellTagFilter:(e,t)=>"TFOOT"!==this._DOM.getElementTagName(t.parentNode)&&("TD"===e||"TH"===e)});this._currentTableHasRowspan=t.hasRowspan,this._currentTableHasColspan=t.hasColspan,this._currentTableInconsistentCells=t.inconsistentCells,this._debug._&&(t.hasRowspan&&console.warn("[table.guard] ROWSPAN detected — slicing not implemented; applying conservative fallback.",{table:this._currentTable}),t.hasColspan&&console.warn("[table.guard] COLSPAN present — handled within-row slicing; monitor results.",{table:this._currentTable}),t.inconsistentCells&&console.warn("[table.guard] Inconsistent cell counts across rows — results may vary.",{table:this._currentTable}))}_updateCurrentTableEntriesAfterSplit(e,t){this._currentTableEntries.rows.splice(e,1,...t)}_setCurrentTableFirstSplitBottom(){this._node.getTop(this._currentTableDistributedRows[0],this._currentTable)>this._currentTableSplitBottom?(this._updateCurrentTableSplitBottom(this._currentTableFullPartContentHeight,"SPECIAL CASE: start immediately from the full height of the page"),this._debug._&&console.log("The Row 0 goes to the 2nd page")):this._updateCurrentTableSplitBottom(this._currentTableFirstPartContentBottom,"start with a short first part")}_getPaginatorAdapter(){return{label:"table",getSplitBottom:()=>this._currentTableSplitBottom,setSplitBottom:e=>{this._currentTableSplitBottom=e},computeSplitBottomForElement:e=>this._node.getTop(e,this._currentTable)+this._currentTableFullPartContentHeight,getRows:()=>this._currentTableDistributedRows,shouldAssert:()=>this._assert,getDebug:()=>this._debug,getSplitBottomLog:()=>this._logSplitBottom_}}_getSplitterAdapter(){const e=()=>({rows:this._currentTableDistributedRows||[],DOM:this._DOM,cellTagFilter:(e,t)=>{const o=t?.parentNode;return"TFOOT"!==(o?this._DOM.getElementTagName(o):void 0)&&("TD"===e||"TH"===e)}});return{label:"table",rows:{getCurrentRows:()=>this._currentTableDistributedRows||[],replaceRow:({rowIndex:e,rowSlices:t})=>{this._node.applyRowSlicesToEntriesAfterRowSplit(this._currentTableEntries,e,t)},syncEntries:()=>{this._updateCurrentTableDistributedRows(),this._currentTableRecordedParts&&(this._currentTableRecordedParts.currentRows=this._currentTableDistributedRows)},getGuardConfig:e,onRowsChanged:()=>{this._currentTableRecordedParts&&(this._currentTableRecordedParts.currentRows=this._currentTableDistributedRows)}},guards:{getConfig:e,onFlags:({flags:e})=>{e&&(this._currentTableHasRowspan=Boolean(e.hasRowspan),this._currentTableHasColspan=Boolean(e.hasColspan),this._currentTableInconsistentCells=Boolean(e.inconsistentCells))}}}}_updateCurrentTableSplitBottom(e,t="unknown case"){di(this._getPaginatorAdapter(),e,t)}_registerPageStartAt(e,t,o="register page start"){gi(this._getPaginatorAdapter(),e,t,o)}_composeOverflowHelpers(){const e=this._node.scaleCellsToHeight.bind(this._node),t=this._getRowShellHeights.bind(this),o={ownerLabel:"table",registerPageStartCallback:this._registerPageStartAt.bind(this),debugLogger:this._debug&&this._debug._?(e,t)=>console.log(e,t):void 0,scaleProblematicCellsCallback:(o,i,n)=>this._node.scaleRowCellsToHeight({ownerLabel:"table",DOM:this._DOM,row:o,targetHeight:i,cachedShells:n,getRowShellHeightsCallback:t,scaleCellsToHeightCallback:e})};return this._currentOverflowHelpers=o,o}_scaleProblematicCellsToHeight(e,t,o){return(this._currentOverflowHelpers||this._composeOverflowHelpers()).scaleProblematicCellsCallback(e,t,o)}_forwardOverflowFallback({rowIndex:e,row:t,availableRowHeight:o,fullPageHeight:i,splitStartRowIndexes:n,reasonTail:r,reasonFull:s,branch:l}){const a=this._currentOverflowHelpers||this._composeOverflowHelpers(),h={ownerLabel:`table:${l}`,rowIndex:e,row:t,availableRowHeight:o,fullPageHeight:i,splitStartRowIndexes:n,reasonTail:r,reasonFull:s,registerPageStartCallback:a.registerPageStartCallback,scaleProblematicCellsCallback:a.scaleProblematicCellsCallback,debugLogger:a.debugLogger};return this._debug._&&console.log(`%c[table.overflow] branch=${l} rowIndex=${e} tail=${o} full=${i}`,"color:orange; font-weight:bold",{reasonTail:r,reasonFull:s}),"splitFailure"===l?this._node.handleRowSplitFailure(h):this._node.handleRowOverflow(h)}_getRowShellHeights(e){if(!this._currentRowShellCache)return this._node.getTableRowShellHeightByTD(e);if(this._currentRowShellCache.has(e))return this._currentRowShellCache.get(e);const t=this._node.getTableRowShellHeightByTD(e);return this._currentRowShellCache.set(e,t),t}_createTableSlice({startId:e,endId:t,table:o,tableEntries:i}){this._debug._&&console.group(`[CREATE Table Slice] range: [${e}, ${t})`),this.strictAssert(Number.isInteger(e)&&(Number.isInteger(t)||t===1/0),`[createTableSlice] invalid bounds: startId=${e}, endId=${t}`);const n=i&&i.rows?i.rows.length:0;this.strictAssert(n>=0,`[createTableSlice]: invalid rows length: ${n}`),this.strictAssert(e>0&&t>0&&ethis._createTableSlice({startId:e,endId:i===n.length-1?1/0:n[i+1],table:t,tableEntries:o}))}_extendTableSlices(e){return e.reduce((e,t,o,i)=>{const n=0===o,r=o===i.length-1;return n&&e.push(this._createBottomSignpost()),e.push(this._node.createForcedPageBreak()),e.push(this._createTopSignpost()),e.push(t),!r&&e.push(this._createBottomSignpost()),e},[])}_createTopSignpost(){return this._node.createSignpost("(table continued)",this._signpostHeight)}_createBottomSignpost(){return this._node.createSignpost("(table continues on the next page)",this._signpostHeight)}_replaceRowInDOM(e,t){this._debug._&&this._DOM.setAttribute(e,".🚫_must_be_removed"),this._DOM.insertInsteadOf(e,...t)}}class fi{constructor({config:e,DOM:t,node:o,selector:i}){this._debug=e.debugMode?{...e.debugConfig.tableLike}:{},this._DOM=t,this._selector=i,this._node=o,this._minLeftLines=2,this._minDanglingLines=2,this._minBreakableLines=this._minLeftLines+this._minDanglingLines,this._minLeftRows=1,this._minDanglingRows=1,this._minBreakableRows=1,this._minPreFirstBlockLines=3,this._minPreLastBlockLines=3,this._minPreBreakableLines=this._minPreFirstBlockLines+this._minPreLastBlockLines,this._minBreakableGridRows=4,this._imageReductionRatio=.8,this._signpostHeight=parseFloat(e.splitLabelHeight)||0}split(e,t,o,i,n){const r=n||this._DOM.getComputedStyle(e);this._debug._&&console.log("root",i);const s=this._node.getPreparedChildren(e),l=this._node.getTop(e,i),a=this._node.getEmptyNodeHeightByProbe(e),h=o-a;let c=s,d=0,g=[],p=t-l-a;const u=r.position;"relative"!=u&&this._DOM.setStyles(e,{position:"relative"});for(let t=0;tp&&(t&&g.push(t),t&&(d+=1),p=t?this._node.getTop(o,e)+h:h)}if(this._DOM.setStyles(e,{position:u}),!g.length)return this._debug._&&console.log("splitters.length",g.length),[];g.push(null);const _=g.map((t,o,i)=>{const n=this._node.createSliceWrapper(e),r=i[o-1]||0,s=t||i[i.length];return this._DOM.insertAtEnd(n,...c.slice(r,s)),n});return this._node.markSliceCuts(_),this._DOM.replaceNodeContentsWith(e,..._),this._DOM.removeAllClasses(e),this._DOM.removeAllStyles(e),this._DOM.setStyles(e,{display:"contents"}),this._DOM.setAttribute(e,"[slough-node]",""),_}}class mi{constructor({config:e,DOM:t,node:i,selector:n}){this._debug=e.debugMode?{...e.debugConfig.grid}:{},this._assert=!!e.consoleAssert,Object.assign(this,o),this._DOM=t,this._selector=n,this._node=i,this._resetCurrent(),this._minBreakableGridRows=1,this._minGridRowContentLines=2,this._gridCellLineHeightCache=new WeakMap,this._gridComputedStyleCache=new WeakMap,this._signpostHeight=parseFloat(e.splitLabelHeight)||0}split(e,t,o,i,n){this._resetCurrent(),this._debug._&&console.group("%c split Grid Node","background:#00FFFF",e);const r=this._node.getPreparedChildren(e);this._node.lockNodesWidths(r);const s=n||this._getComputedStyleCached(e);if(!r.length)return this._node.setInitStyle(!1,e,s),this._debug._&&console.groupEnd(),[];this._node.setInitStyle(!0,e,s);const l=this._scanGridLayout(e,s);if(!l.safe)return this._debug._&&console.warn("[grid.split] skip unsafe layout",l),this._debug._&&console.warn("[grid.split] Unsupported grid layout detected; keeping original grid intact.",l),this._node.setInitStyle(!1,e,s),this._debug._&&console.groupEnd(),[];const a=[];let h=!1,c=!1;const d=new Set;let g=null,p=null,u=null;r.forEach(t=>{const o=this._getComputedStyleCached(t),i=parseInt(o.gridRowStart,10),n=Number.isFinite(i),r=this._node.getTop(t,e),s=this._node.getBottom(t,e);let l=!1;l=!a.length||(n&&null!=g?i!==g:null!=u?r>=u-.5:null==p||Math.abs(r-p)>.5),l?(a.push([t]),g=n?i:null,p=r,u=s):(a[a.length-1].push(t),n&&null==g&&(g=i),(null==p||ru)&&(u=s));const _=o.gridRowEnd||"",f=o.gridColumnEnd||"";h=h||_.includes("span"),c=c||f.includes("span"),n&&d.add(i)});const _=d.size>0&&Math.max(...d)>a.length;if(_)return this._debug._&&console.warn("[grid.split]","Unsupported implicit row gap detected; keeping grid unsplit.",{hasImplicitRowGaps:_}),this._node.setInitStyle(!1,e,s),this._debug._&&console.groupEnd(),[];if(h||c)return this._debug._&&console.warn("[grid.split]","Grid contains row/column spans; using fallback (move row to next page).",{hasRowSpan:h,hasColumnSpan:c}),this._debug._&&console.groupEnd(),this._fallbackMoveGridToNextPage({gridNode:e,nodeComputedStyle:s});this.log("grid.split","currentRows:",a);const f=this._node.getTop(e,i),m=this._node.getEmptyNodeHeightByProbe(e),b=t-f-m,w=o-m;if(this.log("grid.split",{firstPartHeight:b,fullPagePartHeight:w}),this._currentGridNode=e,this._currentGridRows=a,this._currentGridFullPartHeight=w,this._currentGridSplitLog=[],this._currentGridEntries=pi({owner:e,currentRows:a}),this._currentGridRecordedParts=this._currentGridEntries,this._currentGridNode.__html2pdf4docRecordedParts=this._currentGridRecordedParts,this._currentGridShellCache=new WeakMap,a.length0?Math.floor(t):1;let n=0;return()=>{if(n+=1,n<=i)return;const t={label:e,iterations:n,limit:i};throw o&&console.assert(!1,`\n\n ⛔ [${e}] ♾️ loop guard triggered`,t),new Error(`\n ⛔ [${e}] ♾️ loop guard triggered`)}}({label:"grid.split",limit:Math.max(1,6*(a.length||1)),assert:this._assert});this._updateCurrentGridSplitBottom(b,"start with initial window");for(let t=0;tthis._buildGridSplit({startId:i[o-1]||0,endId:t,node:e,entries:M})).filter(Boolean).map(e=>e.part),this._createAndInsertGridFinalSlice({node:e,entries:M,startId:C})];return this.log("grid.split",{splitStartRowIndexes:S,splits:E,recordedParts:this._currentGridRecordedParts?.parts}),this._node.setInitStyle(!1,e,s),this._resetCurrent(),this.logGroupEnd("split Grid Node"),E}_fallbackMoveGridToNextPage({gridNode:e,nodeComputedStyle:t}){return this._node.setInitStyle(!1,e,t),this._resetCurrent(),[]}_resetCurrent(){this._currentGridNode=void 0,this._currentGridRows=void 0,this._currentGridEntries=void 0,this._currentGridRecordedParts=void 0,this._currentGridSplitBottom=void 0,this._currentGridFullPartHeight=void 0,this._currentGridSplitLog=void 0,this._currentGridRowFlags=void 0,this._currentGridShellCache=void 0,this._gridCellLineHeightCache=new WeakMap,this._gridComputedStyleCache=new WeakMap}_getGridSplittableHandlers({evaluation:e,splitStartRowIndexes:t}){return{getRowSliceAdapter:({row:t})=>this._createGridRowSliceAdapter({row:t,rowIndex:e.rowIndex}),onReplaceRow:({newRows:t})=>{this._removeOriginalGridRowCells(e.row),this._node.paginationRefreshRowsAfterSplit(this._getSplitterAdapter(),{rowIndex:e.rowIndex,rowSlices:t})},onAbsorbTail:()=>{},onRefreshRows:({newRows:t})=>{this._node.paginationRefreshRowsAfterSplit(this._getSplitterAdapter(),{rowIndex:e.rowIndex,rowSlices:t})},onPlacement:({evaluation:e,newRows:o,insufficientRemainingWindow:i,isFirstPartEmptyInAnyTD:n,needsScalingInFullPage:r})=>this._node.paginationHandleRowSlicesPlacement({evaluation:e,table:this._currentGridNode,newRows:o,insufficientRemainingWindow:i,isFirstPartEmptyInAnyTD:n,needsScalingInFullPage:r,splitStartRowIndexes:t,pageBottom:this._currentGridSplitBottom,fullPageHeight:this._currentGridFullPartHeight,debug:this._debug,resolveRowBounds:e=>this._getRowBounds(e,this._currentGridNode),registerPageStartCallback:({targetIndex:e,reason:o})=>this._registerPageStartAt(e,t,o),scaleProblematicSliceCallback:(e,t)=>this._scaleGridCellsToHeight(e,t),applyFullPageScalingCallback:({row:e,needsScalingInFullPage:t,fullPageHeight:o})=>{this._node.paginationApplyFullPageScaling({needsScalingInFullPage:t&&Boolean(e),payload:{cells:e,targetHeight:o},scaleCallback:({cells:e,targetHeight:t})=>this._scaleGridCellsToHeight(e,t)})}}),onSplitFailure:({evaluation:e,splitStartRowIndexes:t,availableRowHeight:o,fullPageHeight:i})=>this._forwardGridOverflowFallback({evaluation:e,splitStartRowIndexes:t,availableRowHeight:o,fullPageHeight:i,branch:"splitFailure"})}}_forwardGridOverflowFallback({evaluation:e,splitStartRowIndexes:t,availableRowHeight:o,fullPageHeight:i=this._currentGridFullPartHeight,branch:n,reasonTail:r,reasonFull:s}){const l=this._composeGridOverflowHelpers(),a={ownerLabel:`grid:${n}`,gridNode:this._currentGridNode,evaluation:e,rowIndex:e.rowIndex,row:e.row,availableRowHeight:o,fullPageHeight:i,splitStartRowIndexes:t,reasonTail:r||("splitFailure"===n?"Grid split failed — move row to next page":"Grid slice overflow — move row to next page"),reasonFull:s||("splitFailure"===n?"Grid split failed — scaled cells to full page":"Grid slice overflow — scaled cells to full page"),registerPageStartCallback:l.registerPageStartCallback,scaleProblematicCellsCallback:l.scaleProblematicCellsCallback,debugLogger:l.debugLogger};return this._debug._&&console.log("[grid.overflow]",n,a),"splitFailure"===n?this._node.handleRowSplitFailure(a):this._node.handleRowOverflow(a)}_buildGridRowEvaluation({rows:e,rowIndex:t,gridNode:o,splitBottom:i}){if(!Array.isArray(e))return null;const n=e[t];if(!n)return null;const r=Array.isArray(n)?new Array(n.length):null,{top:s,bottom:l}=this._getRowBounds(n,o),a=e[t+1],h=a?this._getRowTop(a,o):l,c=h-i;return{rowIndex:t,row:n,rowTop:s,rowBottom:l,nextMarker:h,delta:c,tailWindowHeight:i-s,isLastRow:!a,fitsCurrentWindow:c<=0,cellStyles:r}}_composeGridOverflowHelpers(){return{registerPageStartCallback:this._registerPageStartAt.bind(this),scaleProblematicCellsCallback:(e,t)=>!!Array.isArray(e)&&this._scaleGridCellsToHeight(e,t),debugLogger:this._debug&&this._debug._?(e,t)=>console.log(e,t):void 0}}_resolveGridOverflowingRow({evaluation:e,splitStartRowIndexes:t}){return this._node.paginationResolveOverflowingRow({evaluation:e,utils:{rowHasSpan:()=>!1,isSlice:e=>this._isGridRowSlice(e)},handlers:{handleRowWithRowspan:()=>(this._debug._&&console.warn("[grid.split] ROWSPAN guard triggered unexpectedly.",{evaluation:e}),this._registerPageStartAt(e.rowIndex,t,"Grid ROWSPAN fallback — move row to next page"),e.rowIndex-1),handleSplittableRow:()=>this._resolveGridSplittableRow({evaluation:e,splitStartRowIndexes:t}),handleAlreadySlicedRow:()=>this._forwardGridOverflowFallback({evaluation:e,splitStartRowIndexes:t,branch:"alreadySliced"})}})}_resolveGridSplittableRow({evaluation:e,splitStartRowIndexes:t}){const{rowIndex:o}=e;this._debug._&&console.group("%c[grid.split] Stage5 — splittable row","color:#0080ff",{rowIndex:o,row:e.row,tailWindowHeight:e.tailWindowHeight});const i=this._estimateGridRowMeaningfulSpace({row:e.row,cellStyles:e.cellStyles,minContentLines:this._minGridRowContentLines});if(!(i>0))return console.warn("[grid.metrics] Meaningful row space is unavailable; falling back to overflow handler."),this._forwardGridOverflowFallback({evaluation:e,splitStartRowIndexes:t,availableRowHeight:e.tailWindowHeight,fullPageHeight:this._currentGridFullPartHeight,branch:"metricsMissing",reasonTail:"Grid row metrics missing — move row to next page",reasonFull:"Grid row metrics missing — scaled cells to full page"});const n=this._node.paginationCalculateRowSplitBudget({tailWindowHeight:e.tailWindowHeight,minMeaningfulRowSpace:i,fullPartHeight:this._currentGridFullPartHeight,debug:this._debug}),r=this._node.paginationSplitRow({rowIndex:o,row:e.row,firstPartHeight:n.firstPartHeight,fullPageHeight:this._currentGridFullPartHeight,debug:this._debug,decorateRowSlice:({rowWrapper:e,rowIndex:t,sliceIndex:o})=>{e instanceof HTMLElement&&this._DOM.setAttribute(e,`.grid_row_${t}_part_${o}`)},rowAdapter:this._createGridRowSliceAdapter({row:e.row,rowIndex:o,cellStyles:e.cellStyles})}),s=this._node.paginationProcessRowSplitResult({evaluation:e,splitResult:r,splitStartRowIndexes:t,insufficientRemainingWindow:n.insufficientRemainingWindow,extraCapacity:0,fullPageHeight:this._currentGridFullPartHeight,debug:this._debug,handlers:this._getGridSplittableHandlers({evaluation:e,splitStartRowIndexes:t})});return this.logGroupEnd("[grid.split] Stage5 — splittable row"),s}_createGridRowSliceAdapter({row:e,rowIndex:t,cellStyles:o}){if(!Array.isArray(e))return null;const i=this._currentGridNode,n=e[0]||null,r=this;return{getParentContainer:()=>i,getOriginalCells:()=>[...e],getShellHeights:()=>r._getGridShellHeights(e,o),markOriginalRow:({cells:e})=>{e.forEach(e=>r._node.setFlagSlice(e))},beginRow:()=>({fragment:r._DOM.createDocumentFragment(),cells:[]}),cloneCellFallback:e=>r._DOM.cloneNodeWrapper(e),handleCell:({context:e,cellClone:t})=>{r._node.setFlagSlice(t),e.fragment.append(t),e.cells.push(t)},finalizeRow:({context:e})=>(n&&r._DOM.insertBefore(n,e.fragment),e.cells)}}_removeOriginalGridRowCells(e){Array.isArray(e)&&e.forEach(e=>{e instanceof HTMLElement&&this._DOM.removeNode(e)})}_isGridRowSlice(e){if(Array.isArray(e)){const t=e.find(e=>e instanceof HTMLElement);return!!t&&this._node.isSlice(t)}return!!e&&this._node.isSlice(e)}_getPaginatorAdapter(){return{label:"grid",getSplitBottom:()=>this._currentGridSplitBottom,setSplitBottom:e=>{this._currentGridSplitBottom=e},computeSplitBottomForElement:e=>e&&this._currentGridNode?this._node.getTop(e,this._currentGridNode)+(this._currentGridFullPartHeight||0):this._currentGridSplitBottom||0,getRows:()=>Array.isArray(this._currentGridRows)?this._currentGridRows.map(e=>{if(!e)return null;if(e instanceof HTMLElement)return e;if(Array.isArray(e)){const t=e.find(e=>e instanceof HTMLElement);if(t)return t;const o=this._getRowTop(e,this._currentGridNode);return Number.isFinite(o)?o:null}const t=this._getRowTop(e,this._currentGridNode);return Number.isFinite(t)?t:null}):[],shouldAssert:()=>this._assert,getDebug:()=>this._debug,getSplitBottomLog:()=>this._currentGridSplitLog}}_getSplitterAdapter(){return{label:"grid",rows:{getCurrentRows:()=>this._currentGridRows||[],replaceRow:({rowIndex:e,rowSlices:t})=>{Array.isArray(this._currentGridRows)&&this._node.replaceCurrentRowsAfterRowSplit({currentRows:this._currentGridRows,index:e,rowSlices:t})},syncEntries:()=>{this._currentGridEntries&&(this._currentGridEntries.currentRows=this._currentGridRows),this._currentGridRecordedParts&&(this._currentGridRecordedParts.currentRows=this._currentGridRows)},getGuardConfig:()=>({rows:this._currentGridRows||[],DOM:this._DOM})},guards:{onFlags:({flags:e})=>{this._currentGridRowFlags=e}}}}_updateCurrentGridSplitBottom(e,t="unknown case"){di(this._getPaginatorAdapter(),e,t)}_registerPageStartAt(e,t,o="register page start"){gi(this._getPaginatorAdapter(),e,t,o)}_scaleGridCellsToHeight(e,t){if(!(Array.isArray(e)&&e.length&&t>0))return!1;const o=this._getGridShellHeights(e),i=this._debug._?e.map(e=>this._DOM.getElementOffsetHeight(e)):null,n=this._node.paginationScaleCellsToHeight({cells:e,targetHeight:t,shells:o});if(this._debug._){const r=e.map(e=>this._DOM.getElementOffsetHeight(e));console.log("[grid.scaleCells] target:",t,"shells:",o,"before:",i,"after:",r,"scaled:",n)}return n}_buildGridSplit({startId:e,endId:t,node:o,entries:i}){const n=i?.currentRows||this._currentGridRows||[];if(e===t)return this._debug._&&console.warn("[grid.split] _buildGridSplit: skip empty slice request",e,t),this.strictAssert(!1,"[grid.split] _buildGridSplit: empty slice encountered"),null;if(this._debug._){const o=n.slice(e,t);console.log(`=> [grid.split] _buildGridSplit: slice rows [${e}, ${t})`,o)}const r=this._createAndInsertGridSlice({startId:e,endId:t,node:o,entries:i}),s=this._collectGridTelemetryRows(n,e,t);return this._recordGridPart(r,{startId:e,endId:t,type:"slice",rows:s}),{part:r,telemetryRows:s}}_createAndInsertGridSlice({startId:e,endId:t,node:o,entries:i}){const n=this._DOM.cloneNodeWrapper(o);this._node.copyNodeWidth(n,o),this._node.setFlagNoBreak(n),e&&this._node.markTopCut(n),this._node.markBottomCut(n),o.before(n);const r=i?.currentRows||fallbackCurrentRows||[],s=this&&this._DOM&&"function"==typeof this._DOM.isElementNode?this._DOM.isElementNode.bind(this._DOM):null,l=r.slice(e,t).flat().map(e=>{if(!e)return null;if(s&&s(e))return e;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return e;const t=e.element;if(t){if(s&&s(t))return t;if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement)return t}return null}).filter(Boolean);return this._DOM.insertAtEnd(n,...l),n}_createAndInsertGridFinalSlice({node:e,entries:t,startId:o}){const i=e;this._node.markTopCut(i),this._node.setFlagNoBreak(i);const n=t?.currentRows||this._currentGridRows||[],r=this._collectGridTelemetryRows(n,o);return this._recordGridPart(i,{startId:o,endId:n.length,type:"final",rows:r}),i}_collectGridTelemetryRows(e,t,o){if(!Array.isArray(e))return[];return e.slice(t,"number"==typeof o?o:void 0).map((e,o)=>{const i=Array.isArray(e)?[...e]:[e];return{rowIndex:t+o,row:e,cells:i}})}_recordGridPart(e,t={}){const o=this._currentGridRecordedParts;if(!o||!e)return null;const{startId:i=null,endId:n=null,type:r="unknown",rows:s=[],meta:l}=t||{};return ui({entries:o,part:e,startIndex:i,endIndex:n,type:r,rows:s,meta:l})}_estimateGridRowMeaningfulSpace({row:e,cellStyles:t=null,minContentLines:o=this._minGridRowContentLines}){if(!Array.isArray(e)||0===e.length)return console.warn("[grid.metrics] Row payload missing while estimating split budget."),null;const i=this._getGridShellHeights(e,t),n=Array.isArray(t)?t:null,r=Math.max(1,o);let s=0;return e.forEach((e,t)=>{if(!(e instanceof HTMLElement))return void console.warn("[grid.metrics] Unexpected non-element cell in row; ignoring during split budget calculation.",{cell:e,index:t});let o=n?n[t]:null;o||(o=this._getComputedStyleCached(e),n&&(n[t]=o));const l=this._resolveGridCellLineHeight({cell:e,style:o}),a=(i?.[t]||0)+l*r;s=Math.max(s,a)}),s>0?s:(console.warn("[grid.metrics] Failed to measure meaningful row space."),null)}_resolveGridCellLineHeight({cell:e,style:t}){const o=this._gridCellLineHeightCache,i=o?.get(e);if(i>0)return i;t||(console.warn("[grid.metrics] style not passed for _resolveGridCellLineHeight",{cell:e}),t=this._getComputedStyleCached(e));let n=parseFloat(t?.lineHeight);if(n>0)return o?.set(e,n),n;const r=parseFloat(t?.fontSize);if(Number.isFinite(r)&&r>0){const t=1.2*r;return o?.set(e,t),t}if(n=this._node.getLineHeight(e),n>0)return o?.set(e,n),n;return o?.set(e,16),16}_getGridShellHeights(e,t=null){if(this._currentGridShellCache||(this._currentGridShellCache=new WeakMap),this._currentGridShellCache.has(e))return this._currentGridShellCache.get(e);const o=Array.isArray(e)?e:[e].filter(Boolean),i=this._computeGridCellShellHeights(o,t);return this._currentGridShellCache.set(e,i),i}_getComputedStyleCached(e){if(!e)return console.warn("[grid.split] the element was not passed to _getComputedStyleCached"),null;const t=this._gridComputedStyleCache;if(!t)return this._DOM.getComputedStyle(e);const o=t.get(e);if(o)return o;const i=this._DOM.getComputedStyle(e);return t.set(e,i),i}_computeGridCellShellHeights(e,t=null){return Array.isArray(e)&&e.length?e.map((e,o)=>{if(!e)return 0;let i=null;t?(i=t[o],i||(i=this._getComputedStyleCached(e),t[o]=i)):i=this._getComputedStyleCached(e);const n=parseFloat(i?.paddingTop)||0,r=parseFloat(i?.paddingBottom)||0,s=parseFloat(i?.borderTopWidth)||0,l=parseFloat(i?.borderBottomWidth)||0,a=parseFloat(i?.marginTop)||0,h=parseFloat(i?.marginBottom)||0,c=n+r+s+l,d=Math.max(0,a)+Math.max(0,h),g=Math.max(0,c);return Math.max(0,g+d)}):[]}_getRowBounds(e,t,o="both"){return this._node.resolveRowBoundsGeneric(e,t,o)}_getRowTop(e,t){return this._getRowBounds(e,t,"top").top}_getRowBottom(e,t){return this._getRowBounds(e,t,"bottom").bottom}_scanGridLayout(e,t){const o=t.gridAutoFlow||"";if(!o.startsWith("row"))return{safe:!1,reason:`grid-auto-flow=${o}`};if(o.includes("dense"))return{safe:!1,reason:"grid-auto-flow dense not supported yet"};if("none"!==(t.gridTemplateAreas||"none"))return{safe:!1,reason:"grid-template-areas present"};const i=t.gridTemplateColumns||"",n=t.gridTemplateRows||"",r=e=>e.includes("subgrid")||e.includes("auto-fit")||e.includes("auto-fill")||e.includes("fit-content");if(r(i)||r(n))return{safe:!1,reason:"complex track sizing (subgrid/auto-fit/fit-content)"};return/\[.*?\]/.test(i)||/\[.*?\]/.test(n)?{safe:!1,reason:"named grid lines detected"}:{safe:!0}}}const bi="background:#999;color:#FFF;padding: 0 4px;";class wi{constructor({config:e,DOM:t,node:i,selector:n}){this._debug=e.debugMode?{...e.debugConfig.pre}:{},this._assert=!!e.consoleAssert,Object.assign(this,o),this._DOM=t,this._selector=n,this._node=i,this._minPreFirstBlockLines=3,this._minPreLastBlockLines=3,this._minPreBreakableLines=this._minPreFirstBlockLines+this._minPreLastBlockLines,this._imageReductionRatio=.8,this._signpostHeight=parseFloat(e.splitLabelHeight)||0}_normalizeLinesInPlace(e){const t=e.splice(0,this._minPreFirstBlockLines).join(""),o=e.splice(-this._minPreLastBlockLines).join("");e.unshift(t),e.push(o)}_analyzeChildren(e){const t={},o=[...e].map(e=>{const o=this._DOM.getNodeType(e);return o===Node.TEXT_NODE?(t.text=!0,"text"):o===Node.ELEMENT_NODE?"BR"===this._DOM.getElementTagName(e)?(t.br=!0,"br"):this._node.isWrappedTextNode(e)?(t.wrappedText=!0,"wrappedText"):(t.node=!0,"node"):(t.other=!0,"other")});return{has:t,items:o}}split(e,t){this._debug._&&console.group("%c 🔲 PRE [split]","background:orange",{node:e});const o=()=>{this._debug._&&console.log("%c END 🔲 PRE [split]",bi),this._debug._&&console.groupEnd()},i=this._DOM.getChildNodes(e);if(this._debug._&&console.log("_children:",i.length,i),0==i.length)return this._debug._&&console.log("%c END _splitPreNode (not breakable)",bi),o(),[];let n=[];const r=this._analyzeChildren(i);if(this._debug._&&console.log("_childrenTypes:",r.items.length,r),this.strictAssert(!r.has.wrappedText,"Expected to be dealing with unprocessed PRE child nodes, but have wrappedText!",r),this.strictAssert(!(r.has.text&&r.has.wrappedText),"PRE children has text and wrappedText simultaneously",r),r.has.br&&this._debug._&&console.warn("PRE children has BR"),r.has.node){const t=this._DOM.getInnerHTML(e),o=this._node.splitTextByLinesGreedy(t);n.push(...o)}else for(const e of i){if(this._DOM.isTextNode(e)){const t=this._DOM.getNodeValue(e),o=this._node.splitTextByLinesGreedy(t);n.push(...o);continue}if(this._node.isWrappedTextNode(e)){const t=this._DOM.getInnerHTML(e),o=this._node.splitTextByLinesGreedy(t);n.push(...o);continue}}if(this._debug._&&console.log("_lines:",n),n.length{const t=this._node.createWithFlagNoBreak();return this._DOM.setInnerHTML(t,e),t});return this._debug._&&console.log("linesFromNode",s),this._DOM.replaceNodeContentsWith(e,...s),o(),s}slice(e,t,o,i,n){const r=n||this._DOM.getComputedStyle(e),s=["%c_SLICE PreNode\n","color:white"];this._debug._&&console.group("%c_✂️ slice PRE","background:cyan",{node:e,pageBottom:t,fullPageHeight:o});const l=()=>{this._debug._&&console.log("%c END ✂️ slice PRE",bi),this._debug._&&console.groupEnd()},a=e=>isNaN(parseFloat(e))?0:Math.ceil(parseFloat(e)),h=(a(r.marginTop),a(r.marginBottom),a(r.paddingTop)),c=a(r.paddingBottom),d=a(r.borderTopWidth),g=a(r.borderBottomWidth),p=a(r.lineHeight),u=this._node.getTop(e,i),_=h+c+d+g;if(this._DOM.getElementOffsetHeight(e)<_+p*this._minPreBreakableLines)return this._debug._&&console.log("%c END ✂️ slice (small node)",bi),l(),[];const f=this._DOM.getChildNodes(e);if(0==f.length)return this._debug._&&console.log("%c END ✂️ slice (not breakable)",bi),l(),[];if(f.length>1)return this._debug._&&console.log("%c END ✂️ slice TODO!",bi),l(),[];{if(this._DOM.isElementNode(f[0])){const e=f[0];return this._debug._&&console.warn("is Element Node",e),this._debug._&&console.log("%c END ✂️ slice ???????",bi),l(),[]}this._node.isWrappedTextNode(f[0])&&this._debug._&&console.warn(`is TEXT Node: ${f[0]}`);const i=f[0].wholeText,n=this._node.splitTextByLinesGreedy(i);if(n.length{const t=this._node.createWithFlagNoBreak();return this._DOM.setInnerHTML(t,e),t});this._debug._&&console.log("linesFromNode",c),this._DOM.replaceNodeContentsWith(e,...c);const p=0,m=p+d,b=p+g;let w=t-u-b-_; //! For firstPartSpace we need all margins & preWrapperHeight. //! For firstPartSpaceForSPlitting we only need selected amendments. const S=o-_-m;this._debug._&&console.log({pageBottom:t,nodeTop:u,preWrapperHeight:_,topCutLineAmend:m,bottomCutLineAmend:b,fullPageHeight:o},{firstPartSpace:w,fullPageSpace:S});let M=0,P=[],C=w;const E=r.position;"relative"!=E&&this._DOM.setStyles(e,{position:"relative"});for(let t=0;tC&&(this._debug._&&console.log(`start a new page: currentBottom (${i}) > floater(${C})`,o),t&&P.push(t),t&&(M+=1),C=t?this._node.getTop(o,e)+S:S)}if(this._DOM.setStyles(e,{position:E}),!P.length)return this._debug._&&console.log("%c END ✂️ slice - NO SPLIITERS",bi),l(),[];this._debug._&&console.log(...s,"splitters",P);const T=P.map((t,o,i)=>{const n=this._node.createSliceWrapper(e),r=t,s=o===i.length-1?1/0:i[o+1],l=c.slice(r,s);return this._DOM.insertAtEnd(n,...l),n});return this._node.markSliceCuts([e,...T]),this._debug._&&console.log(...s,"newPreElementsArray",T),this._DOM.insertAfter(e,...T),this._debug._&&console.log("%c END ✂️ slice PRE",bi),l(),[e,...T]}}}class Si{constructor({config:e,DOM:t,selector:y}){this._config=e,this._DOM=t,this._selector=y,this._debug=e.debugMode?{...e.debugConfig.node}:{},this._assert=!!e.consoleAssert,this._markupDebugMode=this._config.markupDebugMode,Object.assign(this,o),Object.assign(this,i),Object.assign(this,n),Object.assign(this,r),Object.assign(this,s),Object.assign(this,l),Object.assign(this,a),Object.assign(this,h),Object.assign(this,c),Object.assign(this,d),Object.assign(this,g),Object.assign(this,p),Object.assign(this,u),Object.assign(this,_),Object.assign(this,f),Object.assign(this,m),Object.assign(this,b),Object.assign(this,w),Object.assign(this,S),Object.assign(this,M),Object.assign(this,P),Object.assign(this,C),Object.assign(this,E),Object.assign(this,T),Object.assign(this,O),this._paragraph=new hi({config:this._config,DOM:this._DOM,selector:this._selector,node:this}),this._pre=new wi({config:this._config,DOM:this._DOM,selector:this._selector,node:this}),this._table=new _i({config:this._config,DOM:this._DOM,selector:this._selector,node:this}),this._grid=new mi({config:this._config,DOM:this._DOM,selector:this._selector,node:this}),this._tableLike=new fi({config:this._config,DOM:this._DOM,selector:this._selector,node:this})}clearTemplates(e){this._DOM.getAll("template",e).forEach(e=>this._DOM.removeNode(e))}notSolved(e){this._DOM.getElementTagName(e);return!1}}function Mi(e){return e?.length?e?.split(/\s+/).filter(Boolean):[]}const Pi="#66CC00",Ci=`color: ${Pi};font-weight:bold`,Ei=`border:1px solid ${Pi};background:#EEEEEE;color:${Pi};`,Ti="background:#999;color:#FFF;padding: 0 4px;";class Oi{constructor({config:e,DOM:t,node:i,selector:n,layout:r,referenceWidth:s,referenceHeight:l}){Object.assign(this,o),this._debug=e.debugMode?{...e.debugConfig.pages}:{},this._assert=!!e.consoleAssert,this._selector=n,this._node=i,this._configSelectors={noHanging:e.noHangingSelectors,pageBreakBefore:e.pageBreakBeforeSelectors,pageBreakAfter:e.pageBreakAfterSelectors,forcedPageBreak:e.forcedPageBreakSelectors,noBreak:e.noBreakSelectors,garbage:e.garbageSelectors},this._DOM=t,this._root=r.root,this._contentFlow=r.contentFlow,this._referenceWidth=s,this._referenceHeight=l,this._minLeftLines=2,this._minDanglingLines=2,this._minBreakableLines=this._minLeftLines+this._minDanglingLines,this._minLeftRows=1,this._minDanglingRows=1,this._minBreakableRows=1,this._minPreFirstBlockLines=3,this._minPreLastBlockLines=3,this._minPreBreakableLines=this._minPreFirstBlockLines+this._minPreLastBlockLines,this._minBreakableGridRows=4,this._imageReductionRatio=.8,this._signpostHeight=parseFloat(e.splitLabelHeight)||0,this._commonLineHeight=this._node.getLineHeight(this._root),this._minimumBreakableHeight=this._commonLineHeight*this._minBreakableLines,this._contentFlowEnd,this._contentFlowLastChild,this.pages=[]}calculate(){return this._removeGarbageElements(),this._prepareConfigSelectorConstraints(),this._calculatePageStarts(),this._resolvePageEnds(),this._debug._&&console.log("%c ✔ Pages.calculate()",Ei,this.pages),this.pages}_removeGarbageElements(){const e=Mi(this._configSelectors.garbage);if(e.length){this._node.resolveConfigSelectorConstraints(e,this._contentFlow).forEach(e=>{this._DOM.removeNode(e)})}}_prepareConfigSelectorConstraints(){this._debug._&&console.groupCollapsed("🗂️ prepare config selector constraints");const e=Mi(this._configSelectors.noHanging),t=Mi(this._configSelectors.pageBreakBefore),o=Mi(this._configSelectors.pageBreakAfter),i=Mi(this._configSelectors.forcedPageBreak),n=Mi(this._configSelectors.noBreak);this._prepareNoHangingElements(e),this._prepareForcedPageBreakElements({beforeSelectors:t,afterSelectors:o,forcedSelectors:i}),this._prepareNoBreakElements(n);this._debug._&&console.groupEnd("🗂️ prepare config selector constraints")}_prepareNoHangingElements(e){if(e.length){const t=this._node.resolveConfigSelectorConstraints(e,this._contentFlow,"noHangings");t.forEach(e=>{this._node.setFlagNoHanging(e);const t=this._node.findLastChildParent(e,this._contentFlow);t&&this._node.setFlagNoHanging(t,"parent")}),this._debug._&&t.length&&console.log("✓ noHangings got the flag")}}_prepareNoBreakElements(e){if(e.length){const t=this._node.resolveConfigSelectorConstraints(e,this._contentFlow,"noBreaks");t.forEach(e=>this._node.setFlagNoBreak(e)),this._debug._&&t.length&&console.log("✓ noBreaks got the flag")}}_prepareForcedPageBreakElements({beforeSelectors:e,afterSelectors:t,forcedSelectors:o}){const i=e.length?this._node.resolveConfigSelectorConstraints(e,this._contentFlow,"pageStarters"):[],n=t.length?this._node.resolveConfigSelectorConstraints(t,this._contentFlow,"pageEnders"):[],r=this._node.resolveConfigSelectorConstraints(o,this._contentFlow,"forcedPageStarters");if(i.length){const e=i[0],t=this._node.findFirstChildParent(e,this._contentFlow)||e;this._node.isAfterContentFlowStart(t)&&i.shift()}if(n.length){const e=n.at(-1),t=this._node.findLastChildParent(e,this._contentFlow)||e,o=this._DOM.getRightNeighbor(t);this._node.isContentFlowEnd(o)&&n.pop()}i.length&&i.forEach(e=>{const t=this._node.findBetterForcedPageStarter(e,this._contentFlow);this.strictAssert(t,"findBetterForcedPageStarter should return an element. Returns:",t),this._DOM.insertBefore(t,this._node.createForcedPageBreak()),this._debug._&&console.log("📄⤵️ pageStarters • inserted before",{candidate:t,element:e})}),r&&r.forEach(e=>{if(!this._node.isForcedPageBreak(e)){const t=this._node.findBetterForcedPageStarter(e,this._contentFlow);this.strictAssert(t,"findBetterForcedPageStarter should return an element. Returns:",t),this._DOM.insertBefore(t,this._node.createForcedPageBreak()),this._debug._&&console.log("📄⤵️⤵️ forcedPageStarters • inserted before",{candidate:t,element:e})}}),n.length&&n.forEach(e=>{const t=this._node.findLastChildParent(e,this._contentFlow);t&&(e=t),this._node.isForcedPageBreak(this._DOM.getRightNeighbor(e))||(this._DOM.insertAfter(e,this._node.createForcedPageBreak()),this._debug._&&console.log("📄⤴️ pageEnders • inserted after",{element:e}))})}_registerFirstPage(){this._registerPageStart({element:this._DOM.getElement(this._selector.contentFlowStart,this._contentFlow),context:"register First Page"})}_isContentFlowShort(){const e=this._DOM.getElement(this._selector.contentFlowEnd,this._contentFlow),t=this._node.getBottom(e,this._root),o=tthis._registerPageStart({element:e,context:"All Forced Page Break Inside _contentFlow"}))}_calculatePageStarts(){if(this._registerFirstPage(),this._isContentFlowShort())return void this._resolveForcedPBInsideContentFlow();const e=this._node.getPreparedChildren(this._contentFlow);this._contentFlowEnd=e.at(-1),this._contentFlowLastChild=e.at(-2),this._debug._&&console.groupCollapsed("%c🚸 children(contentFlow)",Ei),this._debug._&&console.log(e),this._debug._&&console.groupEnd("%c🚸 children(contentFlow)",Ei),this._parseNodes({array:e})}_resolvePageEnds(){for(let e=1;e"),"📄",this.pages.length,{currentElement:i}),this._debug._parseNode&&console.log({previousElement:o,currentElement:i,nextElement:n,isFirstChild:e,isLastChild:t,arrayTopParent:r,arrayBottomParent:s}),!n)return this._node.markProcessed(i,"content-flow-end"),this._debug._parseNode&&console.log("%c END _parseNode (!nextElement)",Ti),void(this._debug._parseNode&&console.groupEnd());const a=this._node.getBottom(i,this._root),h=s?this._node.getBottom(s,this._root):void 0;let c=h;const d=this._node.getTop(i,this._root);if(void 0!==h&&h-a>=this._referenceHeight){if(c=void 0,this._debug._parseNode&&console.log("🪁 Tail: We got a tail from the lower shells of the last child. Giving up our “last child” rule here and will try to insert a page break at the end of some parent. ",{arrayParentBottomEdge:h,currentParentBottomEdge:c,currentElementBottom:a,pageBottom:this.pages.at(-1).pageBottom},{currentElement:i,arrayBottomParent:s}),a<=this.pages.at(-1).pageBottom){this._debug._parseNode&&console.log("🪁 Tail: currentElementBottom <= this.pages.at(-1).pageBottom");const e=[];let t=i;for(this._debug._parseNode&&console.log("🪁 Tail: currentElement",i);t&&t!==s;)e.push({element:t,bottom:this._node.getBottom(t,this._root)}),t=t.parentElement;if(t!==s)throw new Error('"bottom" parent not found in the ancestor chain');e.push({element:s,bottom:h}),this._debug._parseNode&&console.log("🪁 Tail: _parents",e),this._debug._parseNode&&console.log("🪁 Tail: current PageBottom",this.pages.at(-1).pageBottom);for(let t=0;tthis.pages.at(-1).pageBottom){this._debug._parseNode&&console.log("🪁 Tail: _parents[i].bottom > this.pages.at(-1).pageBottom",e[t].bottom,">",this.pages.at(-1).pageBottom,e[t].element);const o=this._node.createNeutral();if(o.classList.add("service"),this._DOM.insertAtEnd(e[t].element,o),this._registerPageStart({element:o,context:"_isTailLongerThanPage"}),this._debug._parseNode&&console.log("_registerPageStart",o),this._node.markProcessed(o,"node is ForcedPageBreak"),this._debug._parseNode&&console.log(this.pages.at(-1).pageBottom,h),!(h>this.pages.at(-1).pageBottom))return this._debug._parseNode&&console.log("%c END _parseNode (bottom Tail of parents)",Ti),void(this._debug._parseNode&&console.groupEnd());this._debug._&&console.log("🧧 • arrayParentBottomEdge > this.pages.at(-1).pageBottom")}return this._debug._parseNode&&console.log("%c END _parseNode (bottom Tail of parents)",Ti),void(this._debug._parseNode&&console.groupEnd())}this._debug._parseNode&&console.log("🪁 Tail: currentElementBottom > this.pages.at(-1).pageBottom","DOING NOTHING")} //! currentParentBottomEdge is refreshed right before, so descendants see live parent boundaries. -const g=c??a;if(this._debug._parseNode&&console.log("[_parseNode]",{currentBlockBottom:g,currentParentBottomEdge:c,currentElementBottom:a}),this.pages.at(-1).pageStart===i&&(this._node.isNoBreak(i)||g<=this.pages.at(-1).pageBottom))return this._node.markProcessed(i,"node is already registered and fits in the page"),this._debug._parseNode&&console.log("%c END _parseNode (node is already registered and fits in the next page)",Ti),void(this._debug._parseNode&&console.groupEnd());if(d>=this.pages.at(-1).pageBottom&&a-d){const t=e&&Boolean(r)?this._node.getTopForPageStartCandidate(r,this._root):void 0,o=Boolean(t)&&d-t>=this._referenceHeight;if(o)this._debug._parseNode&&console.log("🪁 beginning Tail",{parentTop:t,currentParentBottomEdge:c,currentElementTop:d,pageBottom:this.pages.at(-1).pageBottom},{currentElement:i,arrayTopParent:r});else{const e=this._DOM.getComputedStyle(i)?.display||"";if(e.includes("inline")||"contents"===e)return this._debug._parseNode&&console.log("🧅 current in thin wrapper"),this._registerPageStart({element:i,improveResult:!0,context:"🧅 current in thin wrapper"}),this._debug._parseNode&&console.log("%c END _parseNode (registered new page start)",Ti),void(this._debug._parseNode&&console.groupEnd())}this._registerPageStart({element:i,improveResult:!o,context:"currentElementTop >= this.pages.at(-1).pageBottom"})}if(this._node.isForcedPageBreak(i))return this._registerPageStart({element:i,context:"currentElement is ForcedPageBreak"}),this._node.markProcessed(i,"node is ForcedPageBreak"),this._debug._parseNode&&console.log("%c END _parseNode (isForcedPageBreak)",Ti),void(this._debug._parseNode&&console.groupEnd());this.strictAssert(this._DOM.getElementOffsetParent(i),"it is expected that the element has an offset parent",i);const p=this._node.getTop(n,this._root);if(this._debug._parseNode&&console.log(...l,"• pageBottom",this.pages.at(-1).pageBottom,"\n","• nextElementTop",p),p<=this.pages.at(-1).pageBottom)return this._debug._parseNode&&console.log("nextElementTop <= this.pages.at(-1).pageBottom",p,"<=",this.pages.at(-1).pageBottom),this._node.markProcessed(i,"node fits"),this._node.findAllForcedPageBreakInside(i).forEach(e=>{this._node.markProcessed(e,"node is ForcedPageBreak (inside a node that fits)"),this._registerPageStart({element:e,context:"All Forced Page Break Inside currentElement"})}),this._debug._parseNode&&console.log("%c END _parseNode (node pass)",Ti),void(this._debug._parseNode&&console.groupEnd());{if(this._debug._parseNode&&console.log("nextElementTop > this.pages.at(-1).pageBottom",p,">",this.pages.at(-1).pageBottom),g<=this.pages.at(-1).pageBottom)return this._debug._parseNode&&console.log("currentBlockBottom <= this.pages.at(-1).pageBottom",g,"<=",this.pages.at(-1).pageBottom,"\n register nextElement as pageStart"),this._node.isNoHanging(i)?(this._debug._parseNode&&console.log("currentElement fits / last, and _isNoHanging => move it to the next page"),this._node.markProcessed(i,"it fits & last & _isNoHanging => move it to the next page"),this._registerPageStart({element:i,improveResult:!0,context:"currentElement is NoHanging"}),this._debug._parseNode&&console.log("%c END _parseNode (isNoHanging)",Ti),void(this._debug._parseNode&&console.groupEnd())):(this._registerPageStart({element:n,type:"next",context:"currentBlockBottom <= PgBtt && nextElementTop > PgBtt"}),this._node.markProcessed(i,"fits, its bottom falls exactly on the cut"),this._node.markProcessed(n,"starts new page, its top is exactly on the cut"),this._debug._parseNode&&console.log("%c END _parseNode (currentElement fits, register the next element)",Ti),void(this._debug._parseNode&&console.groupEnd()));const t=this._node.resolveReplacedElement(i,{prefer:"first"});if(t){const o=this._node.isSVG(t),s=o?this._node.createSignpost(t):t,l=this._node.getTop(s,this._root),a=this._node.getBottom(s,this._root),d=e&&r?this._node.getTop(r,this._root):void 0,g=r||this._DOM.getParentNode(s),p=this._node.estimateInlineImgGapBelow(g);let u=this.pages.at(-1).pageBottom-l-p;u-=h?h-a:0;const _=this._DOM.getElementOffsetHeight(s),f=this._DOM.getElementOffsetWidth(s);if(this._debug._parseNode&&console.log("🖼️🖼️🖼️🖼️🖼️🖼️ (if mediaElement)",t,{_imageParent:g,arrayTopParent:r,arrayParentBottomEdge:h,availableImageNodeSpace:u,currentParentBottomEdge:c,currentElement:i,currentImage:s,currentImageHeight:_,currentImageWidth:f,isSvgMedia:o,imgGapBelow:p,parentTopForImage:d}),f>this._referenceWidth&&this._debug._parseNode&&console.warn("%c IMAGE is too wide","color: red"),_this._imageReductionRatio)return this._debug._parseNode&&console.log("Register next elements; 🖼️🖼️🖼️ IMG RESIZE to availableImageNodeSpace:",u,i),this._node.markProcessed(i,`IMG with ratio ${m}, and next starts on next`),this._node.fitElementWithinBoundaries({element:t,height:_,width:f,vspace:u,hspace:this._referenceWidth}),this._registerPageStart({element:n,type:"next",context:"current IMG was RESIZED to availableImageNodeSpace"}),this._debug._parseNode&&console.log("%c END _parseNode 🖼️ IMG scaled",Ti),void(this._debug._parseNode&&console.groupEnd());this._node.markProcessed(i,"IMG starts on next");const b=o?s:t;this._registerPageStart({element:b,improveResult:!0,context:"move IMG it to next page"}),this._debug._parseNode&&console.log("🖼️ register Page Start",i);let w=this.pages.at(-1).pageBottom-l-p;const S=h?null:this._node.findLastChildParent(i,this._contentFlow),M=h||this._node.getBottom(S||i,this._root);return M>a&&(w-=M-a),_>w&&(this._node.fitElementWithinBoundaries({element:t,height:_,width:f,vspace:w,hspace:this._referenceWidth}),this._node.markProcessed(i,"IMG starts on next and resized"),this._debug._parseNode&&console.log("🖼️ ..and fit it to full page",i)),this._debug._parseNode&&console.log("%c END",Ti),void(this._debug._parseNode&&console.groupEnd())}if(i.style.height){this._debug._parseNode&&console.log("🥁 currentElement has HEIGHT",i.style.height);const e=this.pages.at(-1).pageBottom-d,t=p-d,o=e/t,r=this._referenceHeight/t;return this._debug._parseNode&&console.log("\n🥁 currentElementTop",d,"\n🥁 pageBottom",this.pages.at(-1).pageBottom,"\n🥁 availableSpace",e,"\n🥁 currentElementContextualHeight",t,"\n🥁 availableSpaceFactor",o,"\n🥁 fullPageFactor",r),this.strictAssert(o<1),o>.8?(this._debug._parseNode&&console.log("🥁 availableSpaceFactor > 0.8: ",o),this._DOM.setStyles(i,{transform:`scale(${o})`,"transform-origin":"top center"}),this._registerPageStart({element:n,type:"next",context:"IMMEDIATELY scale currentElement to the remaining space; availableSpaceFactor > 0.8; currentElement.style.height"}),this._node.markProcessed(i,"processed as a image, has been scaled down within 20%, the next one starts a new page"),this._node.markProcessed(n,"the previous one was scaled down within 20%, and this one starts a new page."),this._debug._parseNode&&console.log("%c END _parseNode (has height & scale)",Ti),void(this._debug._parseNode&&console.groupEnd())):(r<1&&(this._debug._parseNode&&console.log("🥁 fullPageFactor < 1: ",r),this._node.markProcessed(i,"processed as a image, has been scaled down, and starts new page"),this._DOM.setStyles(i,{transform:`scale(${r})`,"transform-origin":"top center"})),this._debug._parseNode&&console.log("🥁 _registerPageStart",i),this._registerPageStart({element:i,improveResult:!0,context:'has height & processed "as a image", has been scaled down, and starts new page'}),this._node.markProcessed(i,"processed as a image, starts new page"),this._debug._parseNode&&console.log("%c END _parseNode (has height & put on next page)",Ti),void(this._debug._parseNode&&console.groupEnd()))}if(this._debug._parseNode&&console.log("split or not? \n","currentBlockBottom",g),this._debug._parseNode&&console.log("currentParentBottomEdge || currentElementBottom",{currentParentBottomEdge:c,currentElementBottom:a},"currentBlockBottom > this.pages.at(-1).pageBottom",g,">",this.pages.at(-1).pageBottom),this._DOM.getElementOffsetHeight(i) this.pages.at(-1).pageBottom"}),this._node.markProcessed(i,"starts new page, #fewLines"),this._debug._parseNode&&console.log("%c END _parseNode #fewLines",Ti),void(this._debug._parseNode&&console.groupEnd());const u=this._node.getSplitChildren(i,this.pages.at(-1).pageBottom,this._referenceHeight,this._root);this._debug._parseNode&&console.log("try to break it and loop the children:",u);if(u.length){const e=r||i,t=s||i,l=this._node.isSliced(i)||this._node.isSlough(i);this._debug._parseNode&&console.log({isSlicedParent:l,arrayTopParent:r}),this._parseNodes({array:u,previous:o,next:n,arrayTopParent:l?void 0:e,arrayBottomParent:l?void 0:t}),this._node.markProcessed(i,"getSplitChildren and _parseNodes")}else this._debug._parseNode&&console.log(...l,"_registerPageStart (from _parseNode): \n",i),this._registerPageStart({element:i,improveResult:!0,context:"does not fit, has no children, register it (or parents if improved)"}),this._node.markProcessed(i,"doesn't fit, has no children, register it or parents")}this._debug._parseNode&&console.log("%c END _parseNode [•••]",Ti,{currentElement:i}),this._debug._parseNode&&console.groupEnd()}}class yi{constructor({config:e,DOM:t,node:o,selector:i,layout:n}){this._debug=e.debugMode?{...e.debugConfig.paper}:{},this._DOM=t,this._selector=i,this._node=o,this._frontpageTemplate=n.frontpageTemplate,this._headerTemplate=n.headerTemplate,this._footerTemplate=n.footerTemplate,this._pageChromeSelector=i?.pageChrome||".pageChrome",this._pageBodySpacerSelector=i?.pageBodySpacer||".pageBodySpacer",this._pageHeaderSelector=i?.pageHeader||".pageHeader",this._pageFooterSelector=i?.pageFooter||".pageFooter",this._headerContentSelector=i?.headerContent||".headerContent",this._footerContentSelector=i?.footerContent||".footerContent",this._frontpageElementSelector=i?.frontpageElement||".frontpageElement",this._frontpageContentSelector=i?.frontpageContent||".frontpageContent",this._virtualPaperSelector=i?.virtualPaper||".virtualPaper",this._virtualPaperTopMarginSelector=i?.virtualPaperTopMargin||".virtualPaperTopMargin",this._virtualPaperBottomMarginSelector=i?.virtualPaperBottomMargin||".virtualPaperBottomMargin",this._pageNumberRootSelector=i?.pageNumberRoot?D(i.pageNumberRoot):void 0,this._pageNumberCurrentSelector=i?.pageNumberCurrent?D(i.pageNumberCurrent):void 0,this._pageNumberTotalSelector=i?.pageNumberTotal?D(i.pageNumberTotal):void 0,this._paperHeight,this._frontpageFactor,this.headerHeight,this.footerHeight,this.bodyHeight,this.bodyWidth,this._calculatePaperParams()}createPageChrome({pageNumber:e,pageCount:t}){const o=this._node.create(this._pageChromeSelector);this._node.markPageNumber(o,e);const i=this._composePageElements({pageNumber:e,pageCount:t});return this._DOM.insertAtEnd(o,i),o}_composePageElements({pageNumber:e,pageCount:t}){const o=this._DOM.createDocumentFragment(),i=this._createPageBodySpacer(this.bodyHeight);this._node.markPageNumber(i,e);const n=this._createPageHeader(this._headerTemplate),r=this._createPageFooter(this._footerTemplate);return this._DOM.insertAtEnd(o,this.createVirtualTopMargin(),n,i,r,this.createVirtualBottomMargin()),e&&t&&(this._setPageNumber(n,e,t),this._setPageNumber(r,e,t)),o}createFrontpage(){if(!this._frontpageTemplate)return void(this._debug&&console.warn("[paper • createFrontpage()] called without a template"));const e=this._node.create(this._frontpageElementSelector);this._DOM.setStyles(e,{height:this.bodyHeight+"px",display:"inline-block",width:"100%","vertical-align":"top"});const t=this._createFrontpageContent(this._frontpageTemplate,this._frontpageFactor);return this._DOM.setStyles(t,{display:"flow-root","transform-origin":"top center",height:"100%"}),this._DOM.insertAtStart(e,t),e}createVirtualTopMargin(){return this._node.create(this._virtualPaperTopMarginSelector)}createVirtualBottomMargin(){return this._node.create(this._virtualPaperBottomMarginSelector)}createVirtualPaper(e){const t=this._node.create(this._virtualPaperSelector);return e&&this._DOM.insertAtEnd(t,this.createVirtualTopMargin(),e,this.createVirtualBottomMargin()),t}_createFrontpageContent(e,t){const o=this._node.create(this._frontpageContentSelector);return e&&this._DOM.setInnerHTML(o,e),t&&this._DOM.setStyles(o,{transform:`scale(${t})`}),o}_createPageBodySpacer(e,t){const o=this._node.create(this._pageBodySpacerSelector);return this._DOM.setStyles(o,{height:e+"px"}),t&&this._DOM.insertAtEnd(o,t),o}_createPageHeader(e){const t=this._node.create(this._pageHeaderSelector);if(e){const o=this._node.create(this._headerContentSelector);this._DOM.setInnerHTML(o,e),this._DOM.insertAtEnd(t,o)}return t}_createPageFooter(e){const t=this._node.create(this._pageFooterSelector);if(e){const o=this._node.create(this._footerContentSelector);this._DOM.setInnerHTML(o,e),this._DOM.insertAtEnd(t,o)}return t}_setPageNumber(e,t,o){const i=this._pageNumberRootSelector?this._DOM.getElement(this._pageNumberRootSelector,e):this._pageNumberRootSelector;if(i){const e=this._DOM.getElement(this._pageNumberCurrentSelector,i),n=this._DOM.getElement(this._pageNumberTotalSelector,i);this._DOM.setInnerHTML(e,t),this._DOM.setInnerHTML(n,o)}}_calculatePaperParams(){const e=this._createPageBodySpacer(),t=this._createPageHeader(this._headerTemplate),o=this._createPageFooter(this._footerTemplate),i=this._node.create(this._virtualPaperSelector);this._DOM.insertAtEnd(i,this.createVirtualTopMargin(),t,e,o,this.createVirtualBottomMargin());const n=this._node.create("#workbench");this._DOM.setStyles(n,{position:"absolute",left:"-3000px"}),this._DOM.insertAtEnd(n,i),this._DOM.insertAtStart(this._DOM.body,n);const r=this._DOM.getElementBCR(i).height,s=this._DOM.getElementBCR(t).height||0,l=this._DOM.getElementBCR(o).height||0,a=this._DOM.getElementBCR(e).height,h=this._DOM.getElementBCR(e).width,c=this._createFrontpageContent(this._frontpageTemplate);this._DOM.insertAtStart(e,c);const d=this._DOM.getElementBCR(e).height,g=d>a?a/d:1;this._DOM.removeNode(n),s>.2*r&&console.warn("It seems that your custom header is too high"),l>.15*r&&console.warn("It seems that your custom footer is too high"),g<1&&console.warn("It seems that your frontpage content is too large. We made it smaller to fit on the page. Check out how it looks! It might make sense to fix this with styles or reduce the text amount."),this._paperHeight=r,this.headerHeight=s,this.footerHeight=l,this.bodyHeight=a,this.bodyWidth=h,this._frontpageFactor=g}}class vi{constructor({config:e,DOM:t,selector:i,node:n,pages:r,layout:s,paper:l}){this._config=e,this._debug=e.debugMode?{...e.debugConfig.preview}:{},this._assert=!!e.consoleAssert,Object.assign(this,o),this._accumulatedAssertions={},this._DOM=t,this._selector=i,this._node=n,this._virtualPaperGapSelector=i.virtualPaperGap,this._runningSafetySelector=i.runningSafety,this._printPageBreakSelector=i.printPageBreak,this._pageDivider=i.pageDivider,this._virtualPaper=i.virtualPaper,this._virtualPaperTopMargin=i.virtualPaperTopMargin,this._pageBodySpacer=i.pageBodySpacer,this._pages=r,this._root=s.root,this._contentFlow=s.contentFlow,this._paperFlow=s.paperFlow,this._overlayFlow=s.overlayFlow,this._paper=l,this._hasFrontPage=!!s.frontpageTemplate}create(){return this._processFrontPage(),this._processPages(),(!0===this._config.mask||"true"===this._config.mask)&&this._addMask(),this._makeRootVisible(),this._accumulatedAssertions}_addMask(){const e=parseInt(this._config.virtualPagesGap),t=parseInt(this._config.paperHeight),o=parseInt(this._config.printTopMargin),i=parseInt(this._config.printBottomMargin),n=parseInt(this._config.headerMargin),r=parseInt(this._config.footerMargin),s=this._paper.headerHeight,l=this._paper.footerHeight,a=this._paper.bodyHeight,h=s?Math.ceil(n/2):0,c=l?Math.ceil(r/2):0,d=s-h,g=l-c,p=a+h+c,u=o+d,_=t+e;this.strictAssert(t===p+d+o+g+i,"Paper size calculation params do not match");const f=function({maskStep:e,maskWindow:t,maskFirstShift:o}){return`\n -webkit-mask-image: linear-gradient(\n black 0,\n black ${t}px,\n transparent ${t}px,\n transparent ${e}px\n );\n mask-image: linear-gradient(\n black 0,\n black ${t}px,\n transparent ${t}px,\n transparent ${e}px\n );\n -webkit-mask-repeat: no-repeat;\n mask-repeat: no-repeat;\n -webkit-mask-size: 100% ${e}px;\n mask-size: 100% ${e}px;\n -webkit-mask-position: 100% ${o}px;\n mask-position: 100% ${o}px;\n -webkit-mask-repeat: repeat-y;\n mask-repeat: repeat-y;\n -webkit-mask-origin: border-box;\n mask-origin: border-box;\n `}({maskFirstShift:u,maskStep:_,maskWindow:p}),m=`\n @media screen {\n ${this._selector.contentFlow} {\n ${f}\n }\n }\n @media print {\n ${this._selector.root}::after {\n /* Safety placeholder for the bottom margin of the paper.\n Remove if the margins at the bottom of the page are replaced with padding.\n Placed under the footer.\n */\n --paper-color: ${this._config.paperColor};\n background: var(--paper-color, white);\n content: '';\n position: fixed;\n pointer-events: none;\n z-index: 11;\n inset: 0;\n top: unset;\n height: ${i+l}px;\n }\n }`;this._node.insertStyle(m,"mask")}_makeRootVisible(){this._DOM.setStyles(this._root,{visibility:"visible"})}_processFrontPage(){if(this._hasFrontPage){const e=this._paper.createFrontpage();this._DOM.insertAtStart(this._contentFlow,e),this._pages.unshift({pageStart:e,pageEnd:e}),this._pages[1].prevPageEnd=e}}_processPages(){for(let e=0;e0&&this._debug._&&console.warn(`[preview] There is no page end element before ${e}. Perhaps it's a 'beginningTail'.`)}_createPageBreaker(e,t){const o=this._node.create(this._pageDivider);return this._DOM.setAttribute(o,"[page]",`${e+1}`),t&&this._paper.footerHeight&&this._DOM.setStyles(o,{marginTop:this._paper.footerHeight+"px"}),this._paper.headerHeight&&this._DOM.setStyles(o,{paddingBottom:this._paper.headerHeight+"px"}),o}_updatePageNumberElementAttrValue(e){this._hasFrontPage&&this._node.markPageStartElement(this._pages[e].pageStart,`${e+1}`),this._node.markPageEndElement(this._pages[e].pageEnd,`${e+1}`)}_insertPaper(e,t,o){o?this._DOM.insertAtEnd(e,o,t):this._DOM.insertAtEnd(e,t)}_createVirtualPaperGap(){return this._node.create(this._virtualPaperGapSelector)}_createVirtualPaperTopMargin(){return this._paper.createVirtualTopMargin()}_createVirtualPaperBottomMargin(){return this._paper.createVirtualBottomMargin()}_insertFrontpageSpacer(e,t){const o=this._node.create();return this._DOM.setStyles(o,{paddingBottom:t+"px"}),this._DOM.setAttribute(o,".printFrontpageSpacer"),this._DOM.insertAtStart(e,o),o}_insertHeaderSpacer(e,t){const o=this._DOM.createDocumentFragment(),i=this._node.create(this._runningSafetySelector);this._DOM.insertAtEnd(o,this._createVirtualPaperTopMargin(),i),this._DOM.insertAtEnd(e,o)}_insertFooterSpacer({target:e,footerHeight:t,pageSeparator:o,paperSeparator:i,pageIndex:n}){const r=this._DOM.createDocumentFragment(),s=this._createVirtualPaperGap(),l=this._node.create(this._runningSafetySelector);this._DOM.insertAtEnd(r,l,this._createVirtualPaperBottomMargin(),this._node.create(this._printPageBreakSelector),s),this._DOM.insertAtStart(e,r),this._balanceFooter({balancingFooter:l,contentSeparator:s,pageSeparator:o,paperSeparator:i,pageIndex:n})}_balanceFooter({balancingFooter:e,contentSeparator:t,pageSeparator:o,paperSeparator:i,pageIndex:n}){const r=this._node.getTop(o,this._root),s=this._node.getTop(i,this._root),l=this._node.getTop(t,this._root);this.strictAssert(s==r,"balancers in paper layers are misaligned",{pageIndex:n,balancingFooter:e,contentSeparator:t,pageSeparator:o,paperSeparator:i,paperSeparatorTop:s,pageSeparatorTop:r});const a=r-l;this._debug._&&console.log({balancingFooter:e,contentSeparatorTop:l,paperSeparatorTop:s,pageSeparatorTop:r}),this._DOM.setStyles(e,{"margin-bottom":a+"px"});a<-1&&(this._debug._&&console.warn(`[pages: ${n}-${n+1}] balancer is negative: ${a} < 0. Submitted to the Validator.`,t),this._accumulatedAssertions[n]={balancer:a,contentSeparator:t,pageNumber:n})}}class Di{constructor({config:e,DOM:t,selector:o,node:i,layout:n}){this._globalDebugMode=e.debugMode,this._debug=e.debugMode?{...e.debugConfig.toc}:{},this._assert=!!e.consoleAssert,this._DOM=t,this._node=i,this._tocPageNumberSelector=e.tocPageNumberSelector,this._root=n.root,this._contentFlow=n.contentFlow,this._pageDividerSelector=o.pageDivider}render(){this._globalDebugMode&&console.time("Processing TOC"),this._debug._&&console.log(`\n📑 TOC: I am here!\n\ntocPageNumberSelector:\n • ${this._tocPageNumberSelector}\n pageDividerSelector:\n • ${this._pageDividerSelector}\n `);const e=this._DOM.getAll(this._tocPageNumberSelector,this._contentFlow);if(this._debug._&&console.log("📑 tocPageNumberBoxes",e.length),!e.length)return void(this._debug._&&console.log("📑 no valid toc"));const t=this._DOM.getAll(this._pageDividerSelector,this._contentFlow).reduce((e,t,o)=>{const i=this._node.getTop(t,this._root)-1,n=this._DOM.getAttribute(t,"[page]");return e[i]=n,e},{});this._debug._&&console.log("📑 dataFromPagesMarkers",t);const o=e.reduce((e,t)=>{const o=this._DOM.getDataId(t),i=this._DOM.getElementById(o),n=this._node.getTop(i,this._root);return e[n]={box:t,id:o,targetTop:n},e},{});this._debug._&&console.log("📑 dataFromTOC",o);const i={...t,...o};let n=0;this._debug._&&console.groupCollapsed("Processing obj");for(const e in i){const t=i[e];this._debug._&&console.log(`Processing ${e}: ${t}`),"string"==typeof t?n=t:(t.page=n,this._DOM.setInnerHTML(t.box,n))}this._debug._&&console.groupEnd("Processing obj"),this._debug._&&console.log("📑 tocObject",i),this._globalDebugMode&&console.timeEnd("Processing TOC")}}class Ri{constructor({config:e,DOM:t,selector:i,node:n,layout:r,pages:s,previewValidations:l}){this._config=e,this._selector=i,this._DOM=t,this._node=n,this._layout=r,this._root=r.root,this._pageCount=s.length,this._accumulatedAssertions=l,this._assert=!!e.consoleAssert,Object.assign(this,o)}init(){this._config.debugMode&&console.log("🐙 i am Validator!");const e=this._collectPageOverflowAssertions();for(const[t,o]of Object.entries(e))this._accumulatedAssertions[t]={...this._accumulatedAssertions[t]||{},...o};this.strictAssert(0===Object.keys(this._accumulatedAssertions).length,"Page overflow detected:",this._accumulatedAssertions)}_collectPageOverflowAssertions(){const e=`${this._selector.paperFlow} ${this._selector.virtualPaperGap}`,t=`${this._selector.contentFlow} ${this._selector.virtualPaperGap}`,o=(this._selector.contentFlow,this._selector.contentFlowEnd,`${this._selector.contentFlow} ${this._selector.pageEndMarker}`),i=`${this._selector.pageChrome} ${this._selector.pageBodySpacer}`,n={},r=[...this._DOM.getAllElements(e)],s=[...this._DOM.getAllElements(t)];this._assertElementsCount(this._pageCount-1,{paperGapElements:r,pageGapElements:s});const l=r.map(e=>this._node.getTop(e,this._root)),a=s.map(e=>this._node.getTop(e,this._root));for(let e=0;ee?this._node.getBottom(e,this._root):void 0),u=d.map(e=>e?this._node.getBottom(e,this._root):void 0);for(let e=0;e{e<=.1&&(clearInterval(t),this._preloader.remove()),this._preloader.style.opacity=e,e-=.1*e},50);this._debugMode&&console.log("%c Preloader removed ",xi)}_insertStyle(){const e=document.querySelector("head"),t=document.createElement("style");t.append(document.createTextNode(this._css())),t.setAttribute("data-preloader-style",""),e.append(t)}_css(){return`\n /* PRELOADER */\n .lds-dual-ring {\n position: absolute;\n z-index: 99999;\n top: 0; left: 0; bottom: 0; right: 0;\n background: ${this._preloaderBackground};\n display: flex;\n justify-content: center;\n align-items: center;\n }\n /*\n .lds-dual-ring:after {\n content: " ";\n display: block;\n width: 64px;\n height: 64px;\n margin: 8px;\n border-radius: 50%;\n border: 6px solid #eee;\n border-color: #eee transparent #eee transparent;\n animation: lds-dual-ring 1.2s linear infinite;\n }\n @keyframes lds-dual-ring {\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n }\n */\n `}_resolveTarget(e){const t=(e.preloaderTarget||"").trim();return t&&document.querySelector(t)}}class Bi{constructor(e){this._debugMode=e.debugMode}run(){let e=[...document.querySelectorAll("object")];this._debugMode&&console.log(e);let t=[];return e.forEach(e=>{const o=new Promise(t=>{e.addEventListener("load",o=>{this._debugMode&&console.log("⏰ EVENT: object load",e.clientHeight,e.clientWidth,e),t()})});t.push(o)}),Promise.all(t)}}const Fi=e=>!0===e||"true"===e;function ki(e){const t=Array.isArray(e)?[]:{};return Object.entries(e).forEach(([e,o])=>{t[e]=!o||"object"!=typeof o||ki(o)}),t}const Hi={DOM:{_:!1},layout:{_:!1},pages:{_:!1,_parseNode:!1,_parseNodes:!1,_registerPageStart:!1},paper:{_:!1},preview:{_:!1},toc:{_:!1},node:{_:!1,children:!1,creators:!1,flowFilters:!1,fitters:!1,getters:!1,markers:!1,pageBreaks:!1,positioning:!1,selectors:!1,selectorHeuristics:!1,slicers:!1,splitters:!1,wrappers:!1,pagination:!1},paragraph:{_:!1},grid:{_:!1},pre:{_:!1},table:{_:!1},tableLike:{_:!1},testSignals:{forcedModeLog:!1}};function Ai(e){const t=function(e){let t={debugMode:!1,forcedDebugMode:!1,consoleAssert:!1,markupDebugMode:!1,preloader:!1,preloaderTarget:"",preloaderBackground:"",mask:!0,noHangingSelectors:"",forcedPageBreakSelectors:"",pageBreakBeforeSelectors:"",pageBreakAfterSelectors:"",noBreakSelectors:"",tocPageNumberSelector:"html2pdf4doc-toc-page-number",printLeftMargin:"21mm",printRightMargin:"21mm",printTopMargin:"12mm",printBottomMargin:"12mm",printFontSize:"12pt",paperColor:"white",paperWidth:"210mm",paperHeight:"297mm",headerMargin:"16px",footerMargin:"16px",virtualPagesGap:"16px",splitLabelHeight:"24px"};const o={paperWidth:"210mm",paperHeight:"297mm"},i={paperWidth:"148.5mm",paperHeight:"210mm"};switch((e=function(e){const t={...e};for(const e in t){const o=t[e];if("string"==typeof o){const i=o.toLowerCase();"true"===i||"1"===i?t[e]=!0:"false"!==i&&"0"!==i&&""!==i||(t[e]=!1)}}return t}(e)).printPaperSize){case"A5":case"a5":t={...t,...i};break;default:t={...t,...o}}t={...t,initialRoot:D(R.init),tocPageNumberSelector:D(R.tocPageNumber),...e},console.info("[HTML2PDF4DOC] Config:",t);const n={printLeftMargin:t.printLeftMargin,printRightMargin:t.printRightMargin,printTopMargin:t.printTopMargin,printBottomMargin:t.printBottomMargin,printFontSize:t.printFontSize,paperWidth:t.paperWidth,paperHeight:t.paperHeight,headerMargin:t.headerMargin,footerMargin:t.footerMargin,virtualPagesGap:t.virtualPagesGap},r=document.createElement("div");return r.style="\n position:absolute;\n z-index:1000;\n left: 200%;\n ",document.body.append(r),Object.entries(n).forEach(([e,t])=>{r.style.width=t,n[e]=`${Math.trunc(r.getBoundingClientRect().width)}px`}),r.remove(),t={...t,...n},t.noHangingSelectors=t.noHangingSelectors+" H1 H2 H3 H4 H5 H6",t.forcedPageBreakSelectors=t.forcedPageBreakSelectors+" "+D(R.printForcedPageBreak),t.debugMode&&console.info("Config with converted units:",t),t}(e);t.forcedDebugMode&&(t.debugMode=!0,t.consoleAssert=!0,t.markupDebugMode=!0);const o=t.forcedDebugMode?ki(Hi):Hi;return{...t,debugConfig:o}}const Ii="color:Gray;border:1px solid;";console.info("[HTML2PDF4DOC] Version:","0.3.0");const Li=document.currentScript.dataset,$i=new class{constructor(e){this.params=function(e={}){const t={...e};return[["printWidth","paperWidth","data-print-width","data-paper-width"],["printHeight","paperHeight","data-print-height","data-paper-height"]].forEach(([e,o,i,n])=>{Object.prototype.hasOwnProperty.call(t,e)&&(console.warn(`[HTML2PDF4DOC] Config option "${i}" is deprecated. Use "${n}" instead.`),Object.prototype.hasOwnProperty.call(t,o)||(t[o]=t[e]),delete t[e])}),t}(e),this.forcedDebugMode=Fi(e.forcedDebugMode),this.debugMode=Fi(e.debugMode)||this.forcedDebugMode,this.preloader=e.preloader,this.selector=R,this.config}async render(){console.time("[HTML2PDF4DOC] Total time"),this.debugMode&&console.log("🏁 document.readyState",document.readyState),document.addEventListener("readystatechange",e=>{this.debugMode&&console.log("🏁 readystatechange",document.readyState)}),this.debugMode&&console.time("⏱️ await DOMContentLoaded time"),await new Promise(e=>{window.addEventListener("DOMContentLoaded",t=>{this.debugMode&&console.log("⏰ EVENT: DOMContentLoaded"),e()})}),this.debugMode&&console.timeEnd("⏱️ await DOMContentLoaded time"),this.debugMode&&console.time("⏱️ create Preloader time");const e=new Ni(this.params);"true"===this.preloader&&e.create(),this.debugMode&&console.timeEnd("⏱️ create Preloader time"),this.debugMode&&console.time("⏱️ Config time"),this.debugMode&&console.groupCollapsed("%c config ",Ii+"color:LightGray"),this.config=Ai(this.params),this.debugMode&&console.groupEnd(),this.debugMode&&console.info("⚙️ Current config with debugConfig:",this.config),this.debugMode&&console.timeEnd("⏱️ Config time"),this.config.debugConfig.testSignals.forcedModeLog&&console.info("[HTML2PDF4DOC] 🛠️ Forced debug mode is active."),this.config.consoleAssert&&console.info("[HTML2PDF4DOC] 🧧 Assertions enabled."),this.debugMode&&console.time("⏱️ DOM helpers init time");const t=new H({DOM:window.document,config:this.config});this.debugMode&&console.timeEnd("⏱️ DOM helpers init time"),this.debugMode&&console.time("⏱️ node helpers init time");const o=new Si({config:this.config,DOM:t,selector:this.selector});this.debugMode&&console.timeEnd("⏱️ node helpers init time"),this.debugMode&&console.time("⏱️ await window load time"),await new Promise(e=>{window.addEventListener("load",t=>{this.debugMode&&console.log("⏰ EVENT: window load"),e()})}),this.debugMode&&console.timeEnd("⏱️ await window load time"),this.debugMode&&console.time("⏱️ Layout time"),this.debugMode&&console.groupCollapsed("%c Layout ",Ii);const i=new I({config:this.config,DOM:t,selector:this.selector,node:o});if(i.create(),this.debugMode&&console.groupEnd(),this.debugMode&&console.timeEnd("⏱️ Layout time"),!i.success)return void(this.debugMode&&console.error("Failed to create layout.\n\nWe have to interrupt the process of creating PDF preview."));this.debugMode&&console.info("%c calculate Paper params ",Ii),this.debugMode&&console.time("⏱️ Paper time");const n=new yi({config:this.config,DOM:t,selector:this.selector,node:o,layout:i});if(this.debugMode&&console.timeEnd("⏱️ Paper time"),!n||!n.bodyHeight||!n.bodyWidth)return void(this.debugMode&&console.error("Failed to create paper calculations.\n\nWe have to interrupt the process of creating PDF preview."));this.debugMode&&console.time("⏱️ Preprocess time"),this.debugMode&&console.groupCollapsed("%c Preprocess ",Ii),await new Bi(this.config).run(),this.debugMode&&console.groupEnd(),this.debugMode&&console.timeEnd("⏱️ Preprocess time"),this.debugMode&&console.time("⏱️ Pages time"),this.debugMode&&console.group("%c Pages ",Ii);const r=new Oi({config:this.config,DOM:t,selector:this.selector,node:o,layout:i,referenceHeight:n.bodyHeight,referenceWidth:n.bodyWidth}).calculate();this.debugMode&&console.groupEnd(),this.debugMode&&console.timeEnd("⏱️ Pages time"),this.debugMode&&console.time("⏱️ Preview time"),this.debugMode&&console.groupCollapsed("%c Preview ",Ii);const s=new vi({config:this.config,DOM:t,selector:this.selector,node:o,layout:i,paper:n,pages:r}).create();this.debugMode&&console.groupEnd(),this.debugMode&&console.timeEnd("⏱️ Preview time"),this.debugMode&&console.time("⏱️ Toc time"),new Di({config:this.config,DOM:t,selector:this.selector,node:o,layout:i}).render(),this.debugMode&&console.timeEnd("⏱️ Toc time"),this.debugMode&&console.time("⏱️ Validator time"),new Ri({config:this.config,DOM:t,selector:this.selector,node:o,layout:i,pages:r,previewValidations:s}).init(),this.debugMode&&console.timeEnd("⏱️ Validator time"),t.setAttribute(i.root,"[success]"),t.setAttribute(i.root,"[pages]",r.length),e.remove(),console.info("[HTML2PDF4DOC] Page count:",r.length),console.timeEnd("[HTML2PDF4DOC] Total time")}}(Li),Gi="manual"===Li.init;function Wi(){Gi&&$i.render()}Gi&&console.info("HTML2PDF4DOC in manual initialization mode"),!Gi&&$i.render(),HTML2PDF4DOC=t})(); \ No newline at end of file +const g=c??a;if(this._debug._parseNode&&console.log("[_parseNode]",{currentBlockBottom:g,currentParentBottomEdge:c,currentElementBottom:a}),this.pages.at(-1).pageStart===i&&(this._node.isNoBreak(i)||g<=this.pages.at(-1).pageBottom))return this._node.markProcessed(i,"node is already registered and fits in the page"),this._debug._parseNode&&console.log("%c END _parseNode (node is already registered and fits in the next page)",Ti),void(this._debug._parseNode&&console.groupEnd());if(d>=this.pages.at(-1).pageBottom&&a-d){const t=e&&Boolean(r)?this._node.getTopForPageStartCandidate(r,this._root):void 0,o=Boolean(t)&&d-t>=this._referenceHeight;if(o)this._debug._parseNode&&console.log("🪁 beginning Tail",{parentTop:t,currentParentBottomEdge:c,currentElementTop:d,pageBottom:this.pages.at(-1).pageBottom},{currentElement:i,arrayTopParent:r});else{const e=this._DOM.getComputedStyle(i)?.display||"";if(e.includes("inline")||"contents"===e)return this._debug._parseNode&&console.log("🧅 current in thin wrapper"),this._registerPageStart({element:i,improveResult:!0,context:"🧅 current in thin wrapper"}),this._debug._parseNode&&console.log("%c END _parseNode (registered new page start)",Ti),void(this._debug._parseNode&&console.groupEnd())}this._registerPageStart({element:i,improveResult:!o,context:"currentElementTop >= this.pages.at(-1).pageBottom"})}if(this._node.isForcedPageBreak(i))return this._registerPageStart({element:i,context:"currentElement is ForcedPageBreak"}),this._node.markProcessed(i,"node is ForcedPageBreak"),this._debug._parseNode&&console.log("%c END _parseNode (isForcedPageBreak)",Ti),void(this._debug._parseNode&&console.groupEnd());this.strictAssert(this._DOM.getElementOffsetParent(i),"it is expected that the element has an offset parent",i);const p=this._node.getTop(n,this._root);if(this._debug._parseNode&&console.log(...l,"• pageBottom",this.pages.at(-1).pageBottom,"\n","• nextElementTop",p),p<=this.pages.at(-1).pageBottom)return this._debug._parseNode&&console.log("nextElementTop <= this.pages.at(-1).pageBottom",p,"<=",this.pages.at(-1).pageBottom),this._node.markProcessed(i,"node fits"),this._node.findAllForcedPageBreakInside(i).forEach(e=>{this._node.markProcessed(e,"node is ForcedPageBreak (inside a node that fits)"),this._registerPageStart({element:e,context:"All Forced Page Break Inside currentElement"})}),this._debug._parseNode&&console.log("%c END _parseNode (node pass)",Ti),void(this._debug._parseNode&&console.groupEnd());{if(this._debug._parseNode&&console.log("nextElementTop > this.pages.at(-1).pageBottom",p,">",this.pages.at(-1).pageBottom),g<=this.pages.at(-1).pageBottom)return this._debug._parseNode&&console.log("currentBlockBottom <= this.pages.at(-1).pageBottom",g,"<=",this.pages.at(-1).pageBottom,"\n register nextElement as pageStart"),this._node.isNoHanging(i)?(this._debug._parseNode&&console.log("currentElement fits / last, and _isNoHanging => move it to the next page"),this._node.markProcessed(i,"it fits & last & _isNoHanging => move it to the next page"),this._registerPageStart({element:i,improveResult:!0,context:"currentElement is NoHanging"}),this._debug._parseNode&&console.log("%c END _parseNode (isNoHanging)",Ti),void(this._debug._parseNode&&console.groupEnd())):(this._registerPageStart({element:n,type:"next",context:"currentBlockBottom <= PgBtt && nextElementTop > PgBtt"}),this._node.markProcessed(i,"fits, its bottom falls exactly on the cut"),this._node.markProcessed(n,"starts new page, its top is exactly on the cut"),this._debug._parseNode&&console.log("%c END _parseNode (currentElement fits, register the next element)",Ti),void(this._debug._parseNode&&console.groupEnd()));const t=this._node.resolveReplacedElement(i,{prefer:"first"});if(t){const o=this._node.isSVG(t),s=o?this._node.createSignpost(t):t,l=this._node.getTop(s,this._root),a=this._node.getBottom(s,this._root),d=e&&r?this._node.getTop(r,this._root):void 0,g=r||this._DOM.getParentNode(s),p=this._node.estimateInlineImgGapBelow(g);let u=this.pages.at(-1).pageBottom-l-p;u-=h?h-a:0;const _=this._DOM.getElementOffsetHeight(s),f=this._DOM.getElementOffsetWidth(s);if(this._debug._parseNode&&console.log("🖼️🖼️🖼️🖼️🖼️🖼️ (if mediaElement)",t,{_imageParent:g,arrayTopParent:r,arrayParentBottomEdge:h,availableImageNodeSpace:u,currentParentBottomEdge:c,currentElement:i,currentImage:s,currentImageHeight:_,currentImageWidth:f,isSvgMedia:o,imgGapBelow:p,parentTopForImage:d}),f>this._referenceWidth&&this._debug._parseNode&&console.warn("%c IMAGE is too wide","color: red"),_this._imageReductionRatio)return this._debug._parseNode&&console.log("Register next elements; 🖼️🖼️🖼️ IMG RESIZE to availableImageNodeSpace:",u,i),this._node.markProcessed(i,`IMG with ratio ${m}, and next starts on next`),this._node.fitElementWithinBoundaries({element:t,height:_,width:f,vspace:u,hspace:this._referenceWidth}),this._registerPageStart({element:n,type:"next",context:"current IMG was RESIZED to availableImageNodeSpace"}),this._debug._parseNode&&console.log("%c END _parseNode 🖼️ IMG scaled",Ti),void(this._debug._parseNode&&console.groupEnd());this._node.markProcessed(i,"IMG starts on next");const b=o?s:t;this._registerPageStart({element:b,improveResult:!0,context:"move IMG it to next page"}),this._debug._parseNode&&console.log("🖼️ register Page Start",i);let w=this.pages.at(-1).pageBottom-l-p;const S=h?null:this._node.findLastChildParent(i,this._contentFlow),M=h||this._node.getBottom(S||i,this._root);return M>a&&(w-=M-a),_>w&&(this._node.fitElementWithinBoundaries({element:t,height:_,width:f,vspace:w,hspace:this._referenceWidth}),this._node.markProcessed(i,"IMG starts on next and resized"),this._debug._parseNode&&console.log("🖼️ ..and fit it to full page",i)),this._debug._parseNode&&console.log("%c END",Ti),void(this._debug._parseNode&&console.groupEnd())}if(i.style.height){this._debug._parseNode&&console.log("🥁 currentElement has HEIGHT",i.style.height);const e=this.pages.at(-1).pageBottom-d,t=p-d,o=e/t,r=this._referenceHeight/t;return this._debug._parseNode&&console.log("\n🥁 currentElementTop",d,"\n🥁 pageBottom",this.pages.at(-1).pageBottom,"\n🥁 availableSpace",e,"\n🥁 currentElementContextualHeight",t,"\n🥁 availableSpaceFactor",o,"\n🥁 fullPageFactor",r),this.strictAssert(o<1),o>.8?(this._debug._parseNode&&console.log("🥁 availableSpaceFactor > 0.8: ",o),this._DOM.setStyles(i,{transform:`scale(${o})`,"transform-origin":"top center"}),this._registerPageStart({element:n,type:"next",context:"IMMEDIATELY scale currentElement to the remaining space; availableSpaceFactor > 0.8; currentElement.style.height"}),this._node.markProcessed(i,"processed as a image, has been scaled down within 20%, the next one starts a new page"),this._node.markProcessed(n,"the previous one was scaled down within 20%, and this one starts a new page."),this._debug._parseNode&&console.log("%c END _parseNode (has height & scale)",Ti),void(this._debug._parseNode&&console.groupEnd())):(r<1&&(this._debug._parseNode&&console.log("🥁 fullPageFactor < 1: ",r),this._node.markProcessed(i,"processed as a image, has been scaled down, and starts new page"),this._DOM.setStyles(i,{transform:`scale(${r})`,"transform-origin":"top center"})),this._debug._parseNode&&console.log("🥁 _registerPageStart",i),this._registerPageStart({element:i,improveResult:!0,context:'has height & processed "as a image", has been scaled down, and starts new page'}),this._node.markProcessed(i,"processed as a image, starts new page"),this._debug._parseNode&&console.log("%c END _parseNode (has height & put on next page)",Ti),void(this._debug._parseNode&&console.groupEnd()))}if(this._debug._parseNode&&console.log("split or not? \n","currentBlockBottom",g),this._debug._parseNode&&console.log("currentParentBottomEdge || currentElementBottom",{currentParentBottomEdge:c,currentElementBottom:a},"currentBlockBottom > this.pages.at(-1).pageBottom",g,">",this.pages.at(-1).pageBottom),this._DOM.getElementOffsetHeight(i) this.pages.at(-1).pageBottom"}),this._node.markProcessed(i,"starts new page, #fewLines"),this._debug._parseNode&&console.log("%c END _parseNode #fewLines",Ti),void(this._debug._parseNode&&console.groupEnd());const u=this._node.getSplitChildren(i,this.pages.at(-1).pageBottom,this._referenceHeight,this._root);this._debug._parseNode&&console.log("try to break it and loop the children:",u);if(u.length){const e=r||i,t=s||i,l=this._node.isSliced(i)||this._node.isSlough(i);this._debug._parseNode&&console.log({isSlicedParent:l,arrayTopParent:r}),this._parseNodes({array:u,previous:o,next:n,arrayTopParent:l?void 0:e,arrayBottomParent:l?void 0:t}),this._node.markProcessed(i,"getSplitChildren and _parseNodes")}else this._debug._parseNode&&console.log(...l,"_registerPageStart (from _parseNode): \n",i),this._registerPageStart({element:i,improveResult:!0,context:"does not fit, has no children, register it (or parents if improved)"}),this._node.markProcessed(i,"doesn't fit, has no children, register it or parents")}this._debug._parseNode&&console.log("%c END _parseNode [•••]",Ti,{currentElement:i}),this._debug._parseNode&&console.groupEnd()}}class yi{constructor({config:e,DOM:t,node:o,selector:i,layout:n}){this._debug=e.debugMode?{...e.debugConfig.paper}:{},this._DOM=t,this._selector=i,this._node=o,this._frontpageTemplate=n.frontpageTemplate,this._headerTemplate=n.headerTemplate,this._footerTemplate=n.footerTemplate,this._pageChromeSelector=i?.pageChrome||".pageChrome",this._pageBodySpacerSelector=i?.pageBodySpacer||".pageBodySpacer",this._pageHeaderSelector=i?.pageHeader||".pageHeader",this._pageFooterSelector=i?.pageFooter||".pageFooter",this._headerContentSelector=i?.headerContent||".headerContent",this._footerContentSelector=i?.footerContent||".footerContent",this._frontpageElementSelector=i?.frontpageElement||".frontpageElement",this._frontpageContentSelector=i?.frontpageContent||".frontpageContent",this._virtualPaperSelector=i?.virtualPaper||".virtualPaper",this._virtualPaperTopMarginSelector=i?.virtualPaperTopMargin||".virtualPaperTopMargin",this._virtualPaperBottomMarginSelector=i?.virtualPaperBottomMargin||".virtualPaperBottomMargin",this._pageNumberRootSelector=i?.pageNumberRoot?D(i.pageNumberRoot):void 0,this._pageNumberCurrentSelector=i?.pageNumberCurrent?D(i.pageNumberCurrent):void 0,this._pageNumberTotalSelector=i?.pageNumberTotal?D(i.pageNumberTotal):void 0,this._paperHeight,this._frontpageFactor,this.headerHeight,this.footerHeight,this.bodyHeight,this.bodyWidth,this._calculatePaperParams()}createPageChrome({pageNumber:e,pageCount:t}){const o=this._node.create(this._pageChromeSelector);this._node.markPageNumber(o,e);const i=this._composePageElements({pageNumber:e,pageCount:t});return this._DOM.insertAtEnd(o,i),o}_composePageElements({pageNumber:e,pageCount:t}){const o=this._DOM.createDocumentFragment(),i=this._createPageBodySpacer(this.bodyHeight);this._node.markPageNumber(i,e);const n=this._createPageHeader(this._headerTemplate),r=this._createPageFooter(this._footerTemplate);return this._DOM.insertAtEnd(o,this.createVirtualTopMargin(),n,i,r,this.createVirtualBottomMargin()),e&&t&&(this._setPageNumber(n,e,t),this._setPageNumber(r,e,t)),o}createFrontpage(){if(!this._frontpageTemplate)return void(this._debug&&console.warn("[paper • createFrontpage()] called without a template"));const e=this._node.create(this._frontpageElementSelector);this._DOM.setStyles(e,{height:this.bodyHeight+"px",display:"inline-block",width:"100%","vertical-align":"top"});const t=this._createFrontpageContent(this._frontpageTemplate,this._frontpageFactor);return this._DOM.setStyles(t,{display:"flow-root","transform-origin":"top center",height:"100%"}),this._DOM.insertAtStart(e,t),e}createVirtualTopMargin(){return this._node.create(this._virtualPaperTopMarginSelector)}createVirtualBottomMargin(){return this._node.create(this._virtualPaperBottomMarginSelector)}createVirtualPaper(e){const t=this._node.create(this._virtualPaperSelector);return e&&this._DOM.insertAtEnd(t,this.createVirtualTopMargin(),e,this.createVirtualBottomMargin()),t}_createFrontpageContent(e,t){const o=this._node.create(this._frontpageContentSelector);return e&&this._DOM.setInnerHTML(o,e),t&&this._DOM.setStyles(o,{transform:`scale(${t})`}),o}_createPageBodySpacer(e,t){const o=this._node.create(this._pageBodySpacerSelector);return this._DOM.setStyles(o,{height:e+"px"}),t&&this._DOM.insertAtEnd(o,t),o}_createPageHeader(e){const t=this._node.create(this._pageHeaderSelector);if(e){const o=this._node.create(this._headerContentSelector);this._DOM.setInnerHTML(o,e),this._DOM.insertAtEnd(t,o)}return t}_createPageFooter(e){const t=this._node.create(this._pageFooterSelector);if(e){const o=this._node.create(this._footerContentSelector);this._DOM.setInnerHTML(o,e),this._DOM.insertAtEnd(t,o)}return t}_setPageNumber(e,t,o){const i=this._pageNumberRootSelector?this._DOM.getElement(this._pageNumberRootSelector,e):this._pageNumberRootSelector;if(i){const e=this._DOM.getElement(this._pageNumberCurrentSelector,i),n=this._DOM.getElement(this._pageNumberTotalSelector,i);this._DOM.setInnerHTML(e,t),this._DOM.setInnerHTML(n,o)}}_calculatePaperParams(){const e=this._createPageBodySpacer(),t=this._createPageHeader(this._headerTemplate),o=this._createPageFooter(this._footerTemplate),i=this._node.create(this._virtualPaperSelector);this._DOM.insertAtEnd(i,this.createVirtualTopMargin(),t,e,o,this.createVirtualBottomMargin());const n=this._node.create("#workbench");this._DOM.setStyles(n,{position:"absolute",left:"-3000px"}),this._DOM.insertAtEnd(n,i),this._DOM.insertAtStart(this._DOM.body,n);const r=this._DOM.getElementBCR(i).height,s=this._DOM.getElementBCR(t).height||0,l=this._DOM.getElementBCR(o).height||0,a=this._DOM.getElementBCR(e).height,h=this._DOM.getElementBCR(e).width,c=this._createFrontpageContent(this._frontpageTemplate);this._DOM.insertAtStart(e,c);const d=this._DOM.getElementBCR(e).height,g=d>a?a/d:1;this._DOM.removeNode(n),s>.2*r&&console.warn("It seems that your custom header is too high"),l>.15*r&&console.warn("It seems that your custom footer is too high"),g<1&&console.warn("It seems that your frontpage content is too large. We made it smaller to fit on the page. Check out how it looks! It might make sense to fix this with styles or reduce the text amount."),this._paperHeight=r,this.headerHeight=s,this.footerHeight=l,this.bodyHeight=a,this.bodyWidth=h,this._frontpageFactor=g}}class vi{constructor({config:e,DOM:t,selector:i,node:n,pages:r,layout:s,paper:l}){this._config=e,this._debug=e.debugMode?{...e.debugConfig.preview}:{},this._assert=!!e.consoleAssert,Object.assign(this,o),this._accumulatedAssertions={},this._DOM=t,this._selector=i,this._node=n,this._virtualPaperGapSelector=i.virtualPaperGap,this._runningSafetySelector=i.runningSafety,this._printPageBreakSelector=i.printPageBreak,this._pageDivider=i.pageDivider,this._virtualPaper=i.virtualPaper,this._virtualPaperTopMargin=i.virtualPaperTopMargin,this._pageBodySpacer=i.pageBodySpacer,this._pages=r,this._root=s.root,this._contentFlow=s.contentFlow,this._paperFlow=s.paperFlow,this._overlayFlow=s.overlayFlow,this._paper=l,this._hasFrontPage=!!s.frontpageTemplate}create(){return this._processFrontPage(),this._processPages(),(!0===this._config.mask||"true"===this._config.mask)&&this._addMask(),this._makeRootVisible(),this._accumulatedAssertions}_addMask(){const e=parseInt(this._config.virtualPagesGap),t=parseInt(this._config.paperHeight),o=parseInt(this._config.printTopMargin),i=parseInt(this._config.printBottomMargin),n=parseInt(this._config.headerMargin),r=parseInt(this._config.footerMargin),s=this._paper.headerHeight,l=this._paper.footerHeight,a=this._paper.bodyHeight,h=s?Math.ceil(n/2):0,c=l?Math.ceil(r/2):0,d=s-h,g=l-c,p=a+h+c,u=o+d,_=t+e;this.strictAssert(t===p+d+o+g+i,"Paper size calculation params do not match");const f=function({maskStep:e,maskWindow:t,maskFirstShift:o}){return`\n -webkit-mask-image: linear-gradient(\n black 0,\n black ${t}px,\n transparent ${t}px,\n transparent ${e}px\n );\n mask-image: linear-gradient(\n black 0,\n black ${t}px,\n transparent ${t}px,\n transparent ${e}px\n );\n -webkit-mask-repeat: no-repeat;\n mask-repeat: no-repeat;\n -webkit-mask-size: 100% ${e}px;\n mask-size: 100% ${e}px;\n -webkit-mask-position: 100% ${o}px;\n mask-position: 100% ${o}px;\n -webkit-mask-repeat: repeat-y;\n mask-repeat: repeat-y;\n -webkit-mask-origin: border-box;\n mask-origin: border-box;\n `}({maskFirstShift:u,maskStep:_,maskWindow:p}),m=`\n @media screen {\n ${this._selector.contentFlow} {\n ${f}\n }\n }\n @media print {\n ${this._selector.root}::after {\n /* Safety placeholder for the bottom margin of the paper.\n Remove if the margins at the bottom of the page are replaced with padding.\n Placed under the footer.\n */\n --paper-color: ${this._config.paperColor};\n background: var(--paper-color, white);\n content: '';\n position: fixed;\n pointer-events: none;\n z-index: 11;\n inset: 0;\n top: unset;\n height: ${i+l}px;\n }\n }`;this._node.insertStyle(m,"mask")}_makeRootVisible(){this._DOM.setStyles(this._root,{visibility:"visible"})}_processFrontPage(){if(this._hasFrontPage){const e=this._paper.createFrontpage();this._DOM.insertAtStart(this._contentFlow,e),this._pages.unshift({pageStart:e,pageEnd:e}),this._pages[1].prevPageEnd=e}}_processPages(){for(let e=0;e0&&this._debug._&&console.warn(`[preview] There is no page end element before ${e}. Perhaps it's a 'beginningTail'.`)}_createPageBreaker(e,t){const o=this._node.create(this._pageDivider);return this._DOM.setAttribute(o,"[page]",`${e+1}`),t&&this._paper.footerHeight&&this._DOM.setStyles(o,{marginTop:this._paper.footerHeight+"px"}),this._paper.headerHeight&&this._DOM.setStyles(o,{paddingBottom:this._paper.headerHeight+"px"}),o}_updatePageNumberElementAttrValue(e){this._hasFrontPage&&this._node.markPageStartElement(this._pages[e].pageStart,`${e+1}`),this._node.markPageEndElement(this._pages[e].pageEnd,`${e+1}`)}_insertPaper(e,t,o){o?this._DOM.insertAtEnd(e,o,t):this._DOM.insertAtEnd(e,t)}_createVirtualPaperGap(){return this._node.create(this._virtualPaperGapSelector)}_createVirtualPaperTopMargin(){return this._paper.createVirtualTopMargin()}_createVirtualPaperBottomMargin(){return this._paper.createVirtualBottomMargin()}_insertFrontpageSpacer(e,t){const o=this._node.create();return this._DOM.setStyles(o,{paddingBottom:t+"px"}),this._DOM.setAttribute(o,".printFrontpageSpacer"),this._DOM.insertAtStart(e,o),o}_insertHeaderSpacer(e,t){const o=this._DOM.createDocumentFragment(),i=this._node.create(this._runningSafetySelector);this._DOM.insertAtEnd(o,this._createVirtualPaperTopMargin(),i),this._DOM.insertAtEnd(e,o)}_insertFooterSpacer({target:e,footerHeight:t,pageSeparator:o,paperSeparator:i,pageIndex:n}){const r=this._DOM.createDocumentFragment(),s=this._createVirtualPaperGap(),l=this._node.create(this._runningSafetySelector);this._DOM.insertAtEnd(r,l,this._createVirtualPaperBottomMargin(),this._node.create(this._printPageBreakSelector),s),this._DOM.insertAtStart(e,r),this._balanceFooter({balancingFooter:l,contentSeparator:s,pageSeparator:o,paperSeparator:i,pageIndex:n})}_balanceFooter({balancingFooter:e,contentSeparator:t,pageSeparator:o,paperSeparator:i,pageIndex:n}){const r=this._node.getTop(o,this._root),s=this._node.getTop(i,this._root),l=this._node.getTop(t,this._root);this.strictAssert(s==r,"balancers in paper layers are misaligned",{pageIndex:n,balancingFooter:e,contentSeparator:t,pageSeparator:o,paperSeparator:i,paperSeparatorTop:s,pageSeparatorTop:r});const a=r-l;this._debug._&&console.log({balancingFooter:e,contentSeparatorTop:l,paperSeparatorTop:s,pageSeparatorTop:r}),this._DOM.setStyles(e,{"margin-bottom":a+"px"});a<-1&&(this._debug._&&console.warn(`[pages: ${n}-${n+1}] balancer is negative: ${a} < 0. Submitted to the Validator.`,t),this._accumulatedAssertions[n]={balancer:a,contentSeparator:t,pageNumber:n})}}class Di{constructor({config:e,DOM:t,selector:o,node:i,layout:n}){this._globalDebugMode=e.debugMode,this._debug=e.debugMode?{...e.debugConfig.toc}:{},this._assert=!!e.consoleAssert,this._DOM=t,this._node=i,this._tocPageNumberSelector=e.tocPageNumberSelector,this._root=n.root,this._contentFlow=n.contentFlow,this._pageDividerSelector=o.pageDivider}render(){this._globalDebugMode&&console.time("Processing TOC"),this._debug._&&console.log(`\n📑 TOC: I am here!\n\ntocPageNumberSelector:\n • ${this._tocPageNumberSelector}\n pageDividerSelector:\n • ${this._pageDividerSelector}\n `);const e=this._DOM.getAll(this._tocPageNumberSelector,this._contentFlow);if(this._debug._&&console.log("📑 tocPageNumberBoxes",e.length),!e.length)return void(this._debug._&&console.log("📑 no valid toc"));const t=this._DOM.getAll(this._pageDividerSelector,this._contentFlow).reduce((e,t,o)=>{const i=this._node.getTop(t,this._root)-1,n=this._DOM.getAttribute(t,"[page]");return e[i]=n,e},{});this._debug._&&console.log("📑 dataFromPagesMarkers",t);const o=e.reduce((e,t)=>{const o=this._DOM.getDataId(t),i=this._DOM.getElementById(o),n=this._node.getTop(i,this._root);return e[n]={box:t,id:o,targetTop:n},e},{});this._debug._&&console.log("📑 dataFromTOC",o);const i={...t,...o};let n=0;this._debug._&&console.groupCollapsed("Processing obj");for(const e in i){const t=i[e];this._debug._&&console.log(`Processing ${e}: ${t}`),"string"==typeof t?n=t:(t.page=n,this._DOM.setInnerHTML(t.box,n))}this._debug._&&console.groupEnd("Processing obj"),this._debug._&&console.log("📑 tocObject",i),this._globalDebugMode&&console.timeEnd("Processing TOC")}}class Ri{constructor({config:e,DOM:t,selector:i,node:n,layout:r,pages:s,previewValidations:l}){this._config=e,this._selector=i,this._DOM=t,this._node=n,this._layout=r,this._root=r.root,this._pageCount=s.length,this._accumulatedAssertions=l,this._assert=!!e.consoleAssert,Object.assign(this,o)}init(){this._config.debugMode&&console.log("🐙 i am Validator!");const e=this._collectPageOverflowAssertions();for(const[t,o]of Object.entries(e))this._accumulatedAssertions[t]={...this._accumulatedAssertions[t]||{},...o};this.strictAssert(0===Object.keys(this._accumulatedAssertions).length,"Page overflow detected:",this._accumulatedAssertions)}_collectPageOverflowAssertions(){const e=`${this._selector.paperFlow} ${this._selector.virtualPaperGap}`,t=`${this._selector.contentFlow} ${this._selector.virtualPaperGap}`,o=(this._selector.contentFlow,this._selector.contentFlowEnd,`${this._selector.contentFlow} ${this._selector.pageEndMarker}`),i=`${this._selector.pageChrome} ${this._selector.pageBodySpacer}`,n={},r=[...this._DOM.getAllElements(e)],s=[...this._DOM.getAllElements(t)];this._assertElementsCount(this._pageCount-1,{paperGapElements:r,pageGapElements:s});const l=r.map(e=>this._node.getTop(e,this._root)),a=s.map(e=>this._node.getTop(e,this._root));for(let e=0;ee?this._node.getBottom(e,this._root):void 0),u=d.map(e=>e?this._node.getBottom(e,this._root):void 0);for(let e=0;e{e<=.1&&(clearInterval(t),this._preloader.remove()),this._preloader.style.opacity=e,e-=.1*e},50);this._debugMode&&console.log("%c Preloader removed ",xi)}_insertStyle(){const e=document.querySelector("head"),t=document.createElement("style");t.append(document.createTextNode(this._css())),t.setAttribute("data-preloader-style",""),e.append(t)}_css(){return`\n /* PRELOADER */\n .lds-dual-ring {\n position: absolute;\n z-index: 99999;\n top: 0; left: 0; bottom: 0; right: 0;\n background: ${this._preloaderBackground};\n display: flex;\n justify-content: center;\n align-items: center;\n }\n /*\n .lds-dual-ring:after {\n content: " ";\n display: block;\n width: 64px;\n height: 64px;\n margin: 8px;\n border-radius: 50%;\n border: 6px solid #eee;\n border-color: #eee transparent #eee transparent;\n animation: lds-dual-ring 1.2s linear infinite;\n }\n @keyframes lds-dual-ring {\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n }\n */\n `}_resolveTarget(e){const t=(e.preloaderTarget||"").trim();return t&&document.querySelector(t)}}class Bi{constructor(e){this._debugMode=e.debugMode}run(){let e=[...document.querySelectorAll("object")];this._debugMode&&console.log(e);let t=[];return e.forEach(e=>{const o=new Promise(t=>{e.addEventListener("load",o=>{this._debugMode&&console.log("⏰ EVENT: object load",e.clientHeight,e.clientWidth,e),t()})});t.push(o)}),Promise.all(t)}}const Fi=e=>!0===e||"true"===e;function ki(e){const t=Array.isArray(e)?[]:{};return Object.entries(e).forEach(([e,o])=>{t[e]=!o||"object"!=typeof o||ki(o)}),t}const Ai={DOM:{_:!1},layout:{_:!1},pages:{_:!1,_parseNode:!1,_parseNodes:!1,_registerPageStart:!1},paper:{_:!1},preview:{_:!1},toc:{_:!1},node:{_:!1,children:!1,creators:!1,flowFilters:!1,fitters:!1,getters:!1,markers:!1,pageBreaks:!1,positioning:!1,selectors:!1,selectorHeuristics:!1,slicers:!1,splitters:!1,wrappers:!1,pagination:!1},paragraph:{_:!1},grid:{_:!1},pre:{_:!1},table:{_:!1},tableLike:{_:!1},testSignals:{forcedModeLog:!1}};function Hi(e){const t=function(e){let t={debugMode:!1,forcedDebugMode:!1,consoleAssert:!1,markupDebugMode:!1,preloader:!1,preloaderTarget:"",preloaderBackground:"",mask:!0,noHangingSelectors:"",forcedPageBreakSelectors:"",pageBreakBeforeSelectors:"",pageBreakAfterSelectors:"",noBreakSelectors:"",tocPageNumberSelector:"html2pdf4doc-toc-page-number",printLeftMargin:"21mm",printRightMargin:"21mm",printTopMargin:"12mm",printBottomMargin:"12mm",printFontSize:"12pt",paperColor:"white",paperWidth:"210mm",paperHeight:"297mm",headerMargin:"16px",footerMargin:"16px",virtualPagesGap:"16px",splitLabelHeight:"24px"};const o={paperWidth:"210mm",paperHeight:"297mm"},i={paperWidth:"148.5mm",paperHeight:"210mm"};switch((e=function(e){const t={...e};for(const e in t){const o=t[e];if("string"==typeof o){const i=o.toLowerCase();"true"===i||"1"===i?t[e]=!0:"false"!==i&&"0"!==i&&""!==i||(t[e]=!1)}}return t}(e)).printPaperSize){case"A5":case"a5":t={...t,...i};break;default:t={...t,...o}}t={...t,initialRoot:D(R.init),tocPageNumberSelector:D(R.tocPageNumber),...e},console.info("[HTML2PDF4DOC] Config:",t);const n={printLeftMargin:t.printLeftMargin,printRightMargin:t.printRightMargin,printTopMargin:t.printTopMargin,printBottomMargin:t.printBottomMargin,printFontSize:t.printFontSize,paperWidth:t.paperWidth,paperHeight:t.paperHeight,headerMargin:t.headerMargin,footerMargin:t.footerMargin,virtualPagesGap:t.virtualPagesGap},r=document.createElement("div");return r.style="\n position:absolute;\n z-index:1000;\n left: 200%;\n ",document.body.append(r),Object.entries(n).forEach(([e,t])=>{r.style.width=t,n[e]=`${Math.trunc(r.getBoundingClientRect().width)}px`}),r.remove(),t={...t,...n},t.noHangingSelectors=t.noHangingSelectors+" H1 H2 H3 H4 H5 H6",t.forcedPageBreakSelectors=t.forcedPageBreakSelectors+" "+D(R.printForcedPageBreak),t.debugMode&&console.info("Config with converted units:",t),t}(e);t.forcedDebugMode&&(t.debugMode=!0,t.consoleAssert=!0,t.markupDebugMode=!0);const o=t.forcedDebugMode?ki(Ai):Ai;return{...t,debugConfig:o}}const Ii="color:Gray;border:1px solid;";console.info("[HTML2PDF4DOC] Version:","0.3.0");const Li=document.currentScript.dataset,$i=new class{constructor(e){this.params=function(e={}){const t={...e};return[["printWidth","paperWidth","data-print-width","data-paper-width"],["printHeight","paperHeight","data-print-height","data-paper-height"]].forEach(([e,o,i,n])=>{Object.prototype.hasOwnProperty.call(t,e)&&(console.warn(`[HTML2PDF4DOC] Config option "${i}" is deprecated. Use "${n}" instead.`),Object.prototype.hasOwnProperty.call(t,o)||(t[o]=t[e]),delete t[e])}),t}(e),this.forcedDebugMode=Fi(e.forcedDebugMode),this.debugMode=Fi(e.debugMode)||this.forcedDebugMode,this.preloader=e.preloader,this.selector=R,this.config}async render(){console.time("[HTML2PDF4DOC] Total time"),this.debugMode&&console.log("🏁 document.readyState",document.readyState),document.addEventListener("readystatechange",e=>{this.debugMode&&console.log("🏁 readystatechange",document.readyState)}),this.debugMode&&console.time("⏱️ await DOMContentLoaded time"),await new Promise(e=>{window.addEventListener("DOMContentLoaded",t=>{this.debugMode&&console.log("⏰ EVENT: DOMContentLoaded"),e()})}),this.debugMode&&console.timeEnd("⏱️ await DOMContentLoaded time"),this.debugMode&&console.time("⏱️ create Preloader time");const e=new Ni(this.params);"true"===this.preloader&&e.create(),this.debugMode&&console.timeEnd("⏱️ create Preloader time"),this.debugMode&&console.time("⏱️ Config time"),this.debugMode&&console.groupCollapsed("%c config ",Ii+"color:LightGray"),this.config=Hi(this.params),this.debugMode&&console.groupEnd(),this.debugMode&&console.info("⚙️ Current config with debugConfig:",this.config),this.debugMode&&console.timeEnd("⏱️ Config time"),this.config.debugConfig.testSignals.forcedModeLog&&console.info("[HTML2PDF4DOC] 🛠️ Forced debug mode is active."),this.config.consoleAssert&&console.info("[HTML2PDF4DOC] 🧧 Assertions enabled."),this.debugMode&&console.time("⏱️ DOM helpers init time");const t=new A({DOM:window.document,config:this.config});this.debugMode&&console.timeEnd("⏱️ DOM helpers init time"),this.debugMode&&console.time("⏱️ node helpers init time");const o=new Si({config:this.config,DOM:t,selector:this.selector});this.debugMode&&console.timeEnd("⏱️ node helpers init time"),this.debugMode&&console.time("⏱️ await window load time"),await new Promise(e=>{window.addEventListener("load",t=>{this.debugMode&&console.log("⏰ EVENT: window load"),e()})}),this.debugMode&&console.timeEnd("⏱️ await window load time"),this.debugMode&&console.time("⏱️ Layout time"),this.debugMode&&console.groupCollapsed("%c Layout ",Ii);const i=new I({config:this.config,DOM:t,selector:this.selector,node:o});if(i.create(),this.debugMode&&console.groupEnd(),this.debugMode&&console.timeEnd("⏱️ Layout time"),!i.success)return void(this.debugMode&&console.error("Failed to create layout.\n\nWe have to interrupt the process of creating PDF preview."));this.debugMode&&console.info("%c calculate Paper params ",Ii),this.debugMode&&console.time("⏱️ Paper time");const n=new yi({config:this.config,DOM:t,selector:this.selector,node:o,layout:i});if(this.debugMode&&console.timeEnd("⏱️ Paper time"),!n||!n.bodyHeight||!n.bodyWidth)return void(this.debugMode&&console.error("Failed to create paper calculations.\n\nWe have to interrupt the process of creating PDF preview."));this.debugMode&&console.time("⏱️ Preprocess time"),this.debugMode&&console.groupCollapsed("%c Preprocess ",Ii),await new Bi(this.config).run(),this.debugMode&&console.groupEnd(),this.debugMode&&console.timeEnd("⏱️ Preprocess time"),this.debugMode&&console.time("⏱️ Pages time"),this.debugMode&&console.group("%c Pages ",Ii);const r=new Oi({config:this.config,DOM:t,selector:this.selector,node:o,layout:i,referenceHeight:n.bodyHeight,referenceWidth:n.bodyWidth}).calculate();this.debugMode&&console.groupEnd(),this.debugMode&&console.timeEnd("⏱️ Pages time"),this.debugMode&&console.time("⏱️ Preview time"),this.debugMode&&console.groupCollapsed("%c Preview ",Ii);const s=new vi({config:this.config,DOM:t,selector:this.selector,node:o,layout:i,paper:n,pages:r}).create();this.debugMode&&console.groupEnd(),this.debugMode&&console.timeEnd("⏱️ Preview time"),this.debugMode&&console.time("⏱️ Toc time"),new Di({config:this.config,DOM:t,selector:this.selector,node:o,layout:i}).render(),this.debugMode&&console.timeEnd("⏱️ Toc time"),this.debugMode&&console.time("⏱️ Validator time"),new Ri({config:this.config,DOM:t,selector:this.selector,node:o,layout:i,pages:r,previewValidations:s}).init(),this.debugMode&&console.timeEnd("⏱️ Validator time"),t.setAttribute(i.root,"[success]"),t.setAttribute(i.root,"[pages]",r.length),e.remove(),console.info("[HTML2PDF4DOC] Page count:",r.length),console.timeEnd("[HTML2PDF4DOC] Total time")}}(Li),Gi="manual"===Li.init;function Wi(){Gi&&$i.render()}Gi&&console.info("HTML2PDF4DOC in manual initialization mode"),!Gi&&$i.render(),HTML2PDF4DOC=t})(); \ No newline at end of file diff --git a/submodules/html2pdf b/submodules/html2pdf index 49104f2..5698cba 160000 --- a/submodules/html2pdf +++ b/submodules/html2pdf @@ -1 +1 @@ -Subproject commit 49104f26eb65ffc446b5649efc3e012976601643 +Subproject commit 5698cbae92e040add0b5216673b8687cdb609052 diff --git a/tests/integration/40_sdoc_only_child_does_not_break_page_when_surrounded_by_text_nodes/test.py b/tests/integration/40_sdoc_only_child_does_not_break_page_when_surrounded_by_text_nodes/test.py index dd1fc62..0730dd3 100644 --- a/tests/integration/40_sdoc_only_child_does_not_break_page_when_surrounded_by_text_nodes/test.py +++ b/tests/integration/40_sdoc_only_child_does_not_break_page_when_surrounded_by_text_nodes/test.py @@ -13,25 +13,30 @@ # NOTE: The replace() calls are needed because of the portability issues. # +page2_text_normalized = ( + reader.pages[2].extract_text().replace("leo.StrictDoc", "leo.\nStrictDoc") +) assert ( - reader.pages[2].extract_text() + page2_text_normalized == """\ 1. Section 1 Vivamus consectetur mollis varius. Quisque posuere venenatis nulla, sit amet pulvinar metus vestibulum sed. Sed at libero nec justo leo. StrictDoc Documentation Test document -3/4 -2025-12-21\ +2025-12-21 3/4\ """ -), reader.pages[2].extract_text().replace(".StrictDoc", "\nStrictDoc") +), page2_text_normalized + +page3_text_normalized = ( + reader.pages[3].extract_text().replace("cStrictDoc", "c\nStrictDoc") +) assert ( - reader.pages[3].extract_text() + page3_text_normalized == """\ 2. Section 2 Lorem ipsum dolor sit amet, c StrictDoc Documentation Test document -4/4 -2025-12-21\ +2025-12-21 4/4\ """ -), reader.pages[3].extract_text().replace("cStrictDoc", "c\nStrictDoc") +), page3_text_normalized