revise 2.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +4 -1
  3. package/assets/historyMaterializeWorker-C4uxcZEh.js +607 -3
  4. package/backend.js +3 -1
  5. package/chunks/{AgentPageRenderer-BIf_Fza8.js → AgentPageRenderer-BFB0arQL.js} +1 -1
  6. package/chunks/{AgentPageRenderer-DT9sNxEn.js → AgentPageRenderer-Dn6SaRjW.js} +1 -1
  7. package/chunks/AttachmentDocumentImporter-BHDJAdky.js +1 -0
  8. package/chunks/AttachmentDocumentImporter-CxOZqzt1.js +1 -0
  9. package/chunks/BidiText-C8PBPSQY.js +160 -0
  10. package/chunks/ColorParserFull-BKH72fK8.js +446 -1
  11. package/chunks/DocumentMutator-4vBJQ74L.js +31 -0
  12. package/chunks/{DocumentScrubber-DrgzBlx4.js → DocumentScrubber-COPepQKE.js} +1 -1
  13. package/chunks/{DocumentScrubber-W0EfGmL-.js → DocumentScrubber-Cf_QqHhF.js} +1 -1
  14. package/chunks/DocumentScrubber-DS4LFDKS.js +18 -0
  15. package/chunks/DocumentStylesheet-byN5dtC6.js +7 -1
  16. package/chunks/DocxConverter-BCEB7jWY.js +1083 -0
  17. package/chunks/{DocxConverter-CGYMfz-j.js → DocxConverter-C3NflpDr.js} +2 -2
  18. package/chunks/{DocxConverter-DabDLfsu.js → DocxConverter-D9ZNn4nX.js} +2 -2
  19. package/chunks/{DocxGraft-B6W7fbh4.js → DocxGraft-Ba63IRP4.js} +1 -1
  20. package/chunks/DocxGraft-DjERgl-z.js +7 -0
  21. package/chunks/{DocxGraft-Cj7v78BO.js → DocxGraft-cYlmw4Ab.js} +1 -1
  22. package/chunks/{FileImporter-CjUX2S4s.js → FileImporter-CHXj9sNX.js} +1 -1
  23. package/chunks/{FileImporter-DtkbI6rF.js → FileImporter-DetvRoJc.js} +1 -1
  24. package/chunks/HorizontalRuleOrnaments-gmUZ3R7Q.js +3 -1
  25. package/chunks/HtmlConverter-Sd9t49vH.js +267 -0
  26. package/chunks/ListNumbering-Qlu6AuRZ.js +23 -1
  27. package/chunks/MarkdownConverter-BdJgh8xt.js +57 -0
  28. package/chunks/MathRenderer-B0Y1h1JU.js +36 -7
  29. package/chunks/{OdtConverter-Cnda9T0q.js → OdtConverter-BKtyx012.js} +1 -1
  30. package/chunks/{OdtConverter-WdwwXKVM.js → OdtConverter-Ce9j8PRt.js} +1 -1
  31. package/chunks/OdtConverter-D709qfYb.js +31 -0
  32. package/chunks/ParagraphDiffAnalysis-DrmStvmz.js +36 -0
  33. package/chunks/PdfConverter-BA8XLTAM.js +21 -0
  34. package/chunks/PdfConverter-CkDClffR.js +438 -0
  35. package/chunks/PdfConverter-CxLxd-LJ.js +21 -0
  36. package/chunks/{PdfImportService-Dj1-3L2B.js → PdfImportService-CQCgsRX1.js} +2 -2
  37. package/chunks/{PdfImportService-OE9G383I.js → PdfImportService-xl7fstr-.js} +2 -2
  38. package/chunks/{RtfConverter-D-oqPWNl.js → RtfConverter-BZOnMUGH.js} +1 -1
  39. package/chunks/{RtfConverter-D9zhE07-.js → RtfConverter-Bs81AfXt.js} +1 -1
  40. package/chunks/RtfConverter-DfuE5olb.js +45 -0
  41. package/chunks/TableBorders-Cdkc62cX.js +30 -0
  42. package/chunks/TableGrid-DbroRucl.js +12 -0
  43. package/chunks/TextFileDecoder--rsVs3NR.js +9 -2
  44. package/chunks/{TxtConverter-BYazsp6P.js → TxtConverter-C-oiFUAp.js} +5 -2
  45. package/chunks/UnicodeUtils-CXtusU4g.js +10 -0
  46. package/chunks/XmlConverter-C0FnrVYk.js +70 -0
  47. package/chunks/XmlConverter-CQa8baOF.js +2 -0
  48. package/chunks/XmlConverter-DjEYaIyf.js +2 -0
  49. package/chunks/_commonjsHelpers-DaMA6jEr.js +2 -1
  50. package/chunks/_revise-sdk-lazy-harfbuzz-CDWdjF9f.js +1 -1
  51. package/chunks/_revise-sdk-lazy-harfbuzz-X8gnYTZL.js +1 -1
  52. package/chunks/ar-BdmGnaKI.js +14 -0
  53. package/chunks/backend-BIhAX-Gi.js +484 -0
  54. package/chunks/base64-Qx0OzT4p.js +196 -0
  55. package/chunks/browser-module-CFmqfGkE.js +1791 -3
  56. package/chunks/{browser-module-BbaxnHNK.js → browser-module-CYGCfEyx.js} +1 -1
  57. package/chunks/{browser-module-D2ixluMg.js → browser-module-DgvTMhpA.js} +1 -1
  58. package/chunks/bundle.min-DRpfgV69.js +779 -5
  59. package/chunks/capture-BAJ2in5p.js +9 -0
  60. package/chunks/carrier-C5VZRMxZ.js +6 -0
  61. package/chunks/de-DldIXRFC.js +14 -0
  62. package/chunks/es-CnyKlSPK.js +14 -0
  63. package/chunks/footnoteFlatten-Bekh8ZfM.js +6 -0
  64. package/chunks/graftExport-CRRm1Oe_.js +82 -0
  65. package/chunks/html2canvas.esm-CntiHiYW.js +994 -2
  66. package/chunks/index-B1idHquf.js +1094 -0
  67. package/chunks/index-BWdRWxoH.js +1796 -13
  68. package/chunks/index-C-4H81OE.js +378 -0
  69. package/chunks/index-iZC8xN0t.js +378 -0
  70. package/chunks/{index.es-mTU7Sl3w.js → index.es-Bwt05m_b.js} +1 -1
  71. package/chunks/index.es-CI0QPo8w.js +780 -5
  72. package/chunks/{index.es-B97tjxvW.js → index.es-DAQD57G4.js} +1 -1
  73. package/chunks/{jspdf.es.min-Mykp4BZO.js → jspdf.es.min-CnNRolk9.js} +1 -1
  74. package/chunks/jspdf.es.min-DU74zN8b.js +1747 -32
  75. package/chunks/{jspdf.es.min-DGiD4mlU.js → jspdf.es.min-DlTF8uTw.js} +1 -1
  76. package/chunks/jszip.min-CPW0h1Kx.js +476 -2
  77. package/chunks/katex-DWj8TvwO.js +1209 -8
  78. package/chunks/pdf-BLWDCiFF.js +1826 -10
  79. package/chunks/{pseudoLocale-C90lXrPg.js → pseudoLocale-BoJwIubw.js} +1 -1
  80. package/chunks/{pseudoLocale-UA_TkGrH.js → pseudoLocale-DWAm7Dpa.js} +1 -1
  81. package/chunks/purify.es-BwLardii.js +107 -2
  82. package/chunks/serverDocumentSession-DASrQAbW.js +15 -0
  83. package/chunks/signatures-CBF7NZUy.js +17 -0
  84. package/chunks/tree-sitter-D6zWWUMP.js +1 -1
  85. package/chunks/web-tree-sitter-BXGZGnNj.js +2 -1
  86. package/full.js +1 -1
  87. package/index.d.ts +31 -12
  88. package/index.js +1 -1
  89. package/package.json +1 -1
  90. package/root.js +2 -2
  91. package/serverToolContract.d.ts +21 -3
  92. package/serverToolInputs.generated.d.ts +23 -2
  93. package/style.css +1 -1
  94. package/chunks/AttachmentDocumentImporter-BUavYRxO.js +0 -1
  95. package/chunks/AttachmentDocumentImporter-DGwfDJSH.js +0 -1
  96. package/chunks/BidiText-D7LYTAUL.js +0 -1
  97. package/chunks/DocumentMutator-CjN7Kk-X.js +0 -31
  98. package/chunks/DocumentScrubber-C9ZZEcYW.js +0 -1
  99. package/chunks/DocxConverter-Be3uPNcD.js +0 -11
  100. package/chunks/DocxGraft-Duvo2cpy.js +0 -1
  101. package/chunks/HtmlConverter-ikXImzTY.js +0 -61
  102. package/chunks/MarkdownConverter-CFrcLyO_.js +0 -17
  103. package/chunks/OdtConverter-BFT_P8SI.js +0 -1
  104. package/chunks/PdfConverter-D7UM58vc.js +0 -21
  105. package/chunks/PdfConverter-TB-QPw29.js +0 -21
  106. package/chunks/PdfConverter-wVP63986.js +0 -21
  107. package/chunks/RtfConverter-DZgwU-_R.js +0 -14
  108. package/chunks/TableBorders-BorZS8aZ.js +0 -1
  109. package/chunks/TableGrid-DVWaRZv0.js +0 -1
  110. package/chunks/ar-C8zx2RwP.js +0 -8
  111. package/chunks/backend-MFpDFVrD.js +0 -1
  112. package/chunks/base64-BNMNG-lN.js +0 -1
  113. package/chunks/capture-qC26xmfy.js +0 -1
  114. package/chunks/carrier-BWONvrA7.js +0 -1
  115. package/chunks/de-ByQFqecF.js +0 -8
  116. package/chunks/es-PHpJXv5S.js +0 -8
  117. package/chunks/footnoteFlatten-Bdnn_bz1.js +0 -1
  118. package/chunks/graftExport-CP3h2T88.js +0 -2
  119. package/chunks/index-CjeGoI2g.js +0 -351
  120. package/chunks/index-D7V8zn4w.js +0 -36
  121. package/chunks/index-DyOcu9mD.js +0 -351
  122. package/chunks/serverDocumentSession-CRZSb5SO.js +0 -11
  123. package/chunks/signatures-CsL_TjvW.js +0 -1
@@ -0,0 +1,21 @@
1
+ import{aZ as Ft,a_ as ne,a$ as re,an as se,a7 as bt,b0 as Pt,I as le,b1 as ce,b2 as Ht,b3 as Nt,b4 as Gt,b5 as Ut,af as zt,b6 as Kt,b7 as Rt,b8 as jt,av as Yt,b9 as he,ba as ge,bb as de,bc as fe,B as me,bd as Pe,be as ue,bf as pe,bg as Te,bh as xe,bi as be,bj as ye,bk as _e,aN as $t,bl as tt,bm as Vt,bn as Fe,bo as Se,bp as St,bq as Le,br as we,bs as Oe,Y as Ce,Z as ke,bt as Zt,bu as Me,bv as Et,bw as Lt,aD as It,K as Ne,bx as Jt,by as Re,bz as vt,bA as qt,bB as Qt,bC as Ee,bD as Ie,bE as ve,al as Be,bF as Bt,aU as De,a0 as Xe,bG as Ae,bH as We,aH as He,bI as Ge,bJ as dt,bK as te,A as ee,bL as Ue,bM as ze,bN as Ke,bO as ae,bP as ie,bQ as je,bR as Ye,bS as $e,bT as Ve,bU as Ze,bV as Je,bW as qe,au as Qe,V as wt,bX as ta,ab as ea,ac as aa,bY as Dt,bZ as ia,b_ as oa,b$ as na,c0 as ra,c1 as sa,c2 as Xt,c3 as la,c4 as oe,aV as ca,c5 as ha}from"./index-iZC8xN0t.js";const Mt=new Map;ne(()=>Mt.clear());function ga(it){const t=String.fromCharCode(...it.subarray(0,4));return it[0]===0&&it[1]===1&&it[2]===0&&it[3]===0||t==="true"||t==="OTTO"}function da(it){let t="";for(let e=0;e<it.length;e+=32768)t+=String.fromCharCode(...it.subarray(e,e+32768));return btoa(t)}async function fa(it){try{const t=await fetch(Ft(`fonts/${encodeURIComponent(it)}`),{credentials:"omit"});if(!t.ok)return null;const e=new Uint8Array(await t.arrayBuffer());return ga(e)?da(e):null}catch{return null}}async function ma(it){let t=Mt.get(it);return t||(t=fa(it),Mt.set(it,t),t.then(e=>{e===null&&Mt.delete(it)})),t}const J=it=>({normal:it,bold:it}),Pa={japanese:{family:"NotoSansJP",probeCodePoint:12354,charRegex:/[\p{Script=Hiragana}\p{Script=Katakana}]/u,files:J("NotoSansJP-Regular.ttf")},korean:{family:"NotoSansKR",probeCodePoint:54620,charRegex:/\p{Script=Hangul}/u,files:J("NotoSansKR-Regular.ttf")},devanagari:{family:"NotoSansDevanagari",probeCodePoint:2309,charRegex:/\p{Script=Devanagari}/u,files:J("NotoSansDevanagari-Regular.ttf"),shape:!0},bengali:{family:"NotoSansBengali",probeCodePoint:2437,charRegex:/\p{Script=Bengali}/u,files:J("NotoSansBengali-Regular.ttf"),shape:!0},gurmukhi:{family:"NotoSansGurmukhi",probeCodePoint:2565,charRegex:/\p{Script=Gurmukhi}/u,files:J("NotoSansGurmukhi-Regular.ttf"),shape:!0},gujarati:{family:"NotoSansGujarati",probeCodePoint:2693,charRegex:/\p{Script=Gujarati}/u,files:J("NotoSansGujarati-Regular.ttf"),shape:!0},oriya:{family:"NotoSansOriya",probeCodePoint:2821,charRegex:/\p{Script=Oriya}/u,files:J("NotoSansOriya-Regular.ttf"),shape:!0},tamil:{family:"NotoSansTamil",probeCodePoint:2949,charRegex:/\p{Script=Tamil}/u,files:J("NotoSansTamil-Regular.ttf"),shape:!0},telugu:{family:"NotoSansTelugu",probeCodePoint:3077,charRegex:/\p{Script=Telugu}/u,files:J("NotoSansTelugu-Regular.ttf"),shape:!0},kannada:{family:"NotoSansKannada",probeCodePoint:3205,charRegex:/\p{Script=Kannada}/u,files:J("NotoSansKannada-Regular.ttf"),shape:!0},malayalam:{family:"NotoSansMalayalam",probeCodePoint:3333,charRegex:/\p{Script=Malayalam}/u,files:J("NotoSansMalayalam-Regular.ttf"),shape:!0},sinhala:{family:"NotoSansSinhala",probeCodePoint:3461,charRegex:/\p{Script=Sinhala}/u,files:J("NotoSansSinhala-Regular.ttf"),shape:!0},thai:{family:"NotoSansThai",probeCodePoint:3585,charRegex:/\p{Script=Thai}/u,files:J("NotoSansThai-Regular.ttf"),shape:!0},lao:{family:"NotoSansLao",probeCodePoint:3713,charRegex:/\p{Script=Lao}/u,files:J("NotoSansLao-Regular.ttf"),shape:!0},khmer:{family:"NotoSansKhmer",probeCodePoint:6016,charRegex:/\p{Script=Khmer}/u,files:J("NotoSansKhmer-Regular.ttf"),shape:!0},myanmar:{family:"NotoSansMyanmar",probeCodePoint:4096,charRegex:/\p{Script=Myanmar}/u,files:J("NotoSansMyanmar-Regular.ttf"),shape:!0},tibetan:{family:"NotoSerifTibetan",probeCodePoint:3904,charRegex:/\p{Script=Tibetan}/u,files:J("NotoSerifTibetan-Regular.ttf"),shape:!0},ethiopic:{family:"NotoSansEthiopic",probeCodePoint:4608,charRegex:/\p{Script=Ethiopic}/u,files:J("NotoSansEthiopic-Regular.ttf")},armenian:{family:"NotoSansArmenian",probeCodePoint:1329,charRegex:/\p{Script=Armenian}/u,files:J("NotoSansArmenian-Regular.ttf")},georgian:{family:"NotoSansGeorgian",probeCodePoint:4304,charRegex:/\p{Script=Georgian}/u,files:J("NotoSansGeorgian-Regular.ttf")},syriac:{family:"NotoSansSyriac",probeCodePoint:1808,charRegex:/\p{Script=Syriac}/u,files:J("NotoSansSyriac-Regular.ttf"),shape:!0},thaana:{family:"NotoSansThaana",probeCodePoint:1920,charRegex:/\p{Script=Thaana}/u,files:J("NotoSansThaana-Regular.ttf"),shape:!0},arabic:{family:"NotoNaskhArabic",probeCodePoint:1575,charRegex:/[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/,files:{normal:"NotoNaskhArabic-Regular.ttf",bold:"NotoNaskhArabic-Bold.ttf"}},hebrew:{family:"NotoSansHebrew",probeCodePoint:1488,charRegex:/[\u0590-\u05FF\uFB1D-\uFB4F]/,files:{normal:"NotoSansHebrew-Regular.ttf",bold:"NotoSansHebrew-Bold.ttf"}},cjkExtensionB:{family:"HanExtBSubset",probeCodePoint:131079,charRegex:/[\u{20000}-\u{207FF}]/u,files:J("HanExtBSubset-Regular.ttf"),shape:!0},han:{family:"NotoSansSC",probeCodePoint:20013,charRegex:/[\p{Script=Han}\p{Script=Bopomofo}\u3000-\u303F\uFE30-\uFE4F\uFF00-\uFFEF]/u,files:J("NotoSansSC-Regular.ttf")},emoji:{family:"NotoEmoji",probeCodePoint:128512,charRegex:/[\p{Extended_Pictographic}\p{Regional_Indicator}]/u,files:J("NotoEmoji-Regular.ttf"),shape:!0},arrows:{family:"NotoSansSymbols",probeCodePoint:8592,charRegex:/[\u2190-\u21FF]/u,files:J("NotoSansSymbols-Regular.ttf")},symbols:{family:"NotoSansSymbols2",probeCodePoint:9728,charRegex:/[\u2300-\u23FF\u2460-\u24FF\u25A0-\u27BF\u2B00-\u2BFF\u{1F000}-\u{1F2FF}]/u,files:J("NotoSansSymbols2-Regular.ttf"),shape:!0}},E=class st{static async ensureAllLatexRendered(t){const e=[],a=new Set,i=(o,l)=>{const n=`${l}:${o}`;!a.has(n)&&o.trim()&&(a.add(n),e.push({content:o,displayMode:l}))},r=o=>{if(!o||typeof o!="object")return;if(Array.isArray(o)){o.forEach(r);return}const l=o;l.type==="math"&&l.content?i(l.content,l.displayMode!=="inline"):l.type==="text"&&l.marks?.latex&&l.text&&i(l.text,!1),r(l.children)};r(t.children),r(t.chrome),r(t.notes),await Promise.all(e.map(o=>le(o.content,o.displayMode)))}static getLatexSvgFromCache(t,e){return ce(t,e)}static async svgToPng(t,e,a,i=3){return new Promise(r=>{const o=new Image,l="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(t);o.onload=()=>{try{const n=document.createElement("canvas");n.width=e*i,n.height=a*i;const h=n.getContext("2d");if(!h){r(null);return}h.scale(i,i),h.drawImage(o,0,0,e,a),r(n.toDataURL("image/png"))}catch(n){console.error("Failed to convert SVG to PNG:",n),r(null)}},o.onerror=()=>{r(null)},o.src=l})}static async loadFontFile(t,e=!0){const a=Ft(`fonts/${t}`),i=this.fontFileData.get(a);if(i!==void 0)return i;const r=await ma(t);let o=r??null;try{if(r===void 0){const l=await fetch(Ft(`fonts/${t}`));if(l.ok){const n=await l.arrayBuffer();Ht(new Uint8Array(n))==="ttf"&&(o=this.arrayBufferToBase64(n))}}}catch{}return o||(o=await this.readFontFromDisk(t)),!o&&e&&console.warn(`Failed to load font ${t}; PDF export used a fallback font. Embedded editors: if revise.io is unreachable, mirror the fonts and call setAssetBaseUrl().`),this.fontFileData.set(a,o),o}static async readFontFromDisk(t){try{const{readFile:e}=await import("./__vite-browser-external-l0sNRNKZ.js"),{join:a}=await import("./__vite-browser-external-l0sNRNKZ.js"),i=[a(process.cwd(),"public","fonts",t),a(process.cwd(),"frontend","public","fonts",t),a(process.cwd(),"..","frontend","public","fonts",t),a(process.cwd(),"..","..","frontend","public","fonts",t)];for(const r of i)try{return(await e(r)).toString("base64")}catch{}}catch{}return null}static async loadSourceCodePro(t){const e=await this.loadFontFile("SourceCodePro-Regular.ttf",!1);return e?(t.addFileToVFS("SourceCodePro-Regular.ttf",e),t.addFont("SourceCodePro-Regular.ttf","SourceCodePro","normal"),!0):!1}static async loadKaTeXMain(t){const e=[{file:"KaTeX_Main-Regular.ttf",style:"normal"},{file:"KaTeX_Main-Bold.ttf",style:"bold"},{file:"KaTeX_Main-Italic.ttf",style:"italic"},{file:"KaTeX_Main-BoldItalic.ttf",style:"bolditalic"}],a=await Promise.all(e.map(async i=>{const r=await this.loadFontFile(i.file);return r?{...i,base64:r}:null}));for(const i of a)i&&(t.addFileToVFS(i.file,i.base64),t.addFont(i.file,"KaTeX_Main",i.style));return a[0]!==null}static async embedBundledGenreFonts(t,e,a){this.bundledGenreFamilies.clear();const i=new Set,r=o=>{const l=this.mapFontFamilyToStandard(o);this.BUNDLED_GENRE_FONTS[l]&&i.add(l)};r(a);for(const o of Nt(e))r(o.value);for(const o of i){const l=this.BUNDLED_GENRE_FONTS[o],n=await Promise.all(Object.entries(l.files).map(async([h,s])=>({style:h,file:s,base64:await this.loadFontFile(s)})));if(!n.some(h=>!h.base64)){for(const{style:h,file:s,base64:g}of n)t.addFileToVFS(s,g),t.addFont(s,l.family,h);this.bundledGenreFamilies.set(o,l.family)}}}static documentFallbackScripts(t){const e=new Set,a=Object.keys(this.SCRIPT_FALLBACK_FONTS),i=r=>{if(e.size===a.length||!r||typeof r!="object")return;if(Array.isArray(r)){r.forEach(i);return}const o=r;if(typeof o.text=="string"&&o.text)for(const l of a)!e.has(l)&&this.SCRIPT_FALLBACK_FONTS[l].charRegex.test(o.text)&&e.add(l);i(o.children)};return i(t.children),i(t.chrome),i(t.notes),e}static splitDocumentFallbackRuns(t,e){const a=Object.entries(this.SCRIPT_FALLBACK_FONTS),i=s=>{const g=a.filter(([,P])=>P.charRegex.test(s)).map(([P])=>P);if(g.length>1&&e){const P=s.codePointAt(0)??0,c=g.find(d=>e(d,P));if(c)return c}return g[0]},r=/[\p{Letter}\p{Number}]/u,o=this.SCRIPT_FALLBACK_FONTS.japanese.charRegex,l=this.SCRIPT_FALLBACK_FONTS.korean.charRegex,n=s=>{const g=s.text??"";if(!g)return[{...s}];const P=[];let c="",d=null;for(const f of g.split(/(\s+)/)){const T=o.test(f)?"japanese":l.test(f)?"korean":null;for(const m of f){let x=i(m);if(x==="han"&&T&&(x=T),!x&&r.test(m)&&(x="base"),!x){d?d.text+=m:c+=m;continue}!d||d.key!==x?(d&&P.push(d),d={key:x,text:c+m},c=""):d.text+=m}}return d?(d.text+=c,P.push(d)):P.push({key:"base",text:c}),P.map(f=>{if(f.key==="base")return{...s,text:f.text};const T=this.SCRIPT_FALLBACK_FONTS[f.key];return{...s,text:f.text,marks:{...s.marks,fontFamily:T.family}}})},h=s=>Array.isArray(s)?s.flatMap(g=>g&&typeof g=="object"&&g.type==="text"?n(g):[h(g)]):!s||typeof s!="object"?s:Object.fromEntries(Object.entries(s).map(([g,P])=>[g,h(P)]));return h(t)}static async loadFallbackCoverage(t){const e=Object.entries(this.SCRIPT_FALLBACK_FONTS),a=new Set,i=new Set,r=l=>{if(!l||typeof l!="object")return;if(Array.isArray(l)){l.forEach(r);return}const n=l;if(typeof n.text=="string")for(const h of n.text){if(i.has(h)||h.charCodeAt(0)<128)continue;i.add(h);const s=e.filter(([,g])=>g.charRegex.test(h));s.length>1&&s.forEach(([g])=>a.add(g))}r(n.children)};r(t.children),r(t.chrome),r(t.notes);const o=new Map;for(const l of a){const n=this.SCRIPT_FALLBACK_FONTS[l].files.normal;let h=this.fallbackCharsetCache.get(n);if(h===void 0){h=null;const s=await this.loadFontFile(n,!1);if(s)try{const g=(await import("./browser-module-CYGCfEyx.js")).create(Gt(s));h=new Set(g.characterSet??[])}catch{h=null}this.fallbackCharsetCache.set(n,h)}h&&o.set(l,h)}return(l,n)=>{const h=o.get(l);return h?h.has(n):!0}}static async embedScriptFallbackFonts(t,e){this.scriptFallbackFamilies.clear(),this.shapingFonts.clear();for(const a of this.documentFallbackScripts(e)){const i=await this.registerScriptFallbackFace(t,a);i&&this.scriptFallbackFamilies.set(a,i)}}static async registerScriptFallbackFace(t,e){const a=this.SCRIPT_FALLBACK_FONTS[e];if(!a)return null;const i=await this.loadFontFile(a.files.normal);if(!i)return null;const r=await this.loadFontFile(a.files.bold,!1);t.addFileToVFS(a.files.normal,i),r&&a.files.bold!==a.files.normal&&t.addFileToVFS(a.files.bold,r);const o=r?a.files.bold:a.files.normal;if(t.addFont(a.files.normal,a.family,"normal"),t.addFont(o,a.family,"bold"),t.addFont(a.files.normal,a.family,"italic"),t.addFont(o,a.family,"bolditalic"),a.shape&&!this.shapingFonts.has(a.family))try{const[l,n]=await Promise.all([import("./browser-module-CYGCfEyx.js"),import("./_revise-sdk-lazy-harfbuzz-X8gnYTZL.js")]),h=n,s=h.loadHarfBuzz?await h.loadHarfBuzz():n,g=Gt(i),P=l.create(g),c=new s.Blob(g),d=new s.Face(c),f=new s.Font(d);this.shapingFonts.set(a.family,{unitsPerEm:d.upem,notdefPathCommands:P.getGlyph(0).path.commands,layout:T=>{const m=new s.Buffer;m.addText(T),m.guessSegmentProperties(),s.shape(f,m);const x=m.getGlyphInfosAndPositions(),F=x.map(b=>({xAdvance:b.xAdvance??0,yAdvance:b.yAdvance??0,xOffset:b.xOffset??0,yOffset:b.yOffset??0}));return{glyphs:x.map(b=>P.getGlyph(b.codepoint)),positions:F,advanceWidth:F.reduce((b,B)=>b+B.xAdvance,0)}}})}catch(l){console.warn(`Failed to initialize PDF shaping for ${a.family}:`,l)}return a.family}static fontCoversCodePoint(t,e,a){const i=`${e}:${a}`;let r=this.scriptFontCoverageCache.get(i);if(r===void 0){let o;try{o=t.getFont(e,"normal")}catch{o=void 0}r=!!o?.metadata?.cmap?.unicode?.codeMap?.[a],this.scriptFontCoverageCache.set(i,r)}return r}static fontCoversMatchedChars(t,e,a,i){let r=!1;for(const o of a)if(i.test(o)&&(r=!0,!this.fontCoversCodePoint(t,e,o.codePointAt(0)??0)))return!1;return r}static scriptFallbackFor(t,e,a){if(!e||this.scriptFallbackFamilies.size===0)return null;let i=null;for(const[r,o]of Object.entries(this.SCRIPT_FALLBACK_FONTS)){const l=this.scriptFallbackFamilies.get(r);if(l&&o.charRegex.test(e)&&!this.fontCoversCodePoint(t,a,o.probeCodePoint)&&!this.fontCoversMatchedChars(t,a,e,o.charRegex)){if(this.fontCoversMatchedChars(t,l,e,o.charRegex))return l;i??(i=l)}}return i}static async registerDocumentFonts(t,e,a){await this.embedLocalFonts(t,e),await this.embedBundledGenreFonts(t,e,a),await this.embedScriptFallbackFonts(t,e);const i=this.documentUsesSourceCodePro(e)?await this.loadSourceCodePro(t):!1;return this.inlineCodeFontFamily=i?"SourceCodePro":"courier",this.documentUsesKaTeXMain(e)&&await this.loadKaTeXMain(t),{hasSourceCodePro:i}}static async registerCurrentPdfFonts(t,e){for(const[a,i]of this.bundledGenreFamilies){const r=this.BUNDLED_GENRE_FONTS[a];if(!r||r.family!==i)continue;const o=await Promise.all(Object.entries(r.files).map(async([l,n])=>({style:l,file:n,base64:await this.loadFontFile(n)})));for(const{style:l,file:n,base64:h}of o)h&&(t.addFileToVFS(n,h),t.addFont(n,i,l))}for(const a of this.scriptFallbackFamilies.keys())await this.registerScriptFallbackFace(t,a);e&&await this.loadSourceCodePro(t)}static documentUsesKaTeXMain(t){return Nt(t).some(e=>{const a=e.family.toLowerCase();return a.includes("katex")||a.includes("computer modern")||a.includes("computermodern")})}static documentUsesSourceCodePro(t){const e=[...t.children];for(;e.length>0;){const a=e.pop();if(!a||typeof a!="object")continue;const i=a;if(i.type==="code"||i.type==="text"&&typeof i.marks=="object"&&i.marks!==null&&i.marks.code===!0)return!0;Array.isArray(i.children)&&e.push(...i.children)}return!1}static createCanvasTextContext(){if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");if(!t)return null;let e=null;return{measureText:a=>({width:Ut(a,e,i=>t.measureText(i).width)}),setFont:a=>{t.font=a,e=null},setMarkAdjustments:a=>{e=a}}}static resolveIndentStepPx(t){return this.resolvePdfLayoutMetrics(t).indentStepPx}static getDefaultPdfLayoutMetrics(){const t=zt(void 0),e=Math.max(1,this.PAGE_WIDTH-this.MARGIN_LEFT-this.MARGIN_RIGHT);return{orientation:"portrait",pageWidthPt:this.PAGE_WIDTH,pageHeightPt:this.PAGE_HEIGHT,marginTopPt:this.MARGIN_TOP,marginRightPt:this.MARGIN_RIGHT,marginBottomPt:this.MARGIN_BOTTOM,marginLeftPt:this.MARGIN_LEFT,contentWidthPt:e,fullContentWidthPt:e,pageMarginLeftPt:this.MARGIN_LEFT,columnCount:1,columnGapPt:Rt(t.columnGapTwips),columnStridePt:Kt(e,Rt(t.columnGapTwips)),blockSpacingPt:t.blockSpacingPx*this.PX_TO_PT,indentStepPx:t.indentStepPx,showPageNumbers:t.showPageNumbers,pageBorders:t.pageBorders,pageNumberPosition:t.pageNumberPosition,pageNumberStart:t.pageNumberStart,pageNumberFormat:t.pageNumberFormat,hyphenationEnabled:t.hyphenationEnabled,lineNumbering:t.lineNumbering}}static resolvePdfLayoutMetrics(t){return this.resolvePdfMetricsFromSettings(t?.pageLayout,t?.pageLayout,!1)}static resolvePdfMetricsFromSettings(t,e,a=!1){const i=jt(e,t),r=t,{pageWidth:o,pageHeight:l}=Yt(i),n=o*this.PX_TO_PT,h=l*this.PX_TO_PT,s=i.marginTopPx*this.PX_TO_PT,g=i.marginRightPx*this.PX_TO_PT,P=i.marginBottomPx*this.PX_TO_PT,c=i.marginLeftPx*this.PX_TO_PT,d=Math.max(1,n-c-g),f=Math.max(1,i.columnCount),T=Rt(i.columnGapTwips),m=he(d,f,T);return{orientation:i.orientation,pageWidthPt:n,pageHeightPt:h,marginTopPt:s,marginRightPt:g,marginBottomPt:P,marginLeftPt:c,contentWidthPt:m,fullContentWidthPt:d,pageMarginLeftPt:c,columnCount:f,columnGapPt:T,columnStridePt:Kt(m,T),...f>1?{columnFlow:{index:0,topPt:s,pageOffset:0}}:{},blockSpacingPt:i.blockSpacingPx*this.PX_TO_PT,indentStepPx:i.indentStepPx,showPageNumbers:i.showPageNumbers,pageBorders:i.pageBorders,pageNumberPosition:i.pageNumberPosition,pageNumberStart:i.pageNumberStart,pageNumberStartExplicit:a&&r?.pageNumberStart!==void 0,pageNumberFormat:i.pageNumberFormat,hyphenationEnabled:i.hyphenationEnabled,lineNumbering:i.lineNumbering}}static physicalPageMetrics(t){return{...t,marginLeftPt:t.pageMarginLeftPt,contentWidthPt:t.fullContentWidthPt,columnFlow:void 0,reservedInsetForPage:void 0}}static computeEngineLayout(t){if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");if(!e)return null;const a=zt(t.pageLayout),i=Yt(a),r=ge({pageWidth:i.pageWidth,pageHeight:i.pageHeight,pageMargin:a.marginLeftPx,pageMarginTop:a.marginTopPx,pageMarginRight:a.marginRightPx,pageMarginBottom:a.marginBottomPx,pageMarginLeft:a.marginLeftPx,availableWidth:Math.max(1,i.pageWidth-a.marginLeftPx-a.marginRightPx),textStartY:a.marginTopPx,indentStepPx:a.indentStepPx,blockSpacingPx:a.blockSpacingPx,hyphenationEnabled:a.hyphenationEnabled,lineNumbering:a.lineNumbering,columnCount:a.columnCount,columnGapPx:de(a.columnGapTwips),pageless:!1});try{return fe(t,me(e),r)}catch{return null}}static computeColumnBalanceTargets(t,e){const a=new Map,i=e.filter(g=>g.type==="section-break"),r=new Set;if(i.forEach((g,P)=>{const c=jt(t.pageLayout,g.layout);Pe(Math.max(1,c.columnCount),g.breakType==="continuous")&&r.add(P)}),r.size===0)return a;const o=this.computeEngineLayout(t);if(!o?.pageGeometries||o.pageGeometries.length===0)return a;const l=new Map(o.pageGeometries.map(g=>[g.pageIndex+1,g.pageTop])),n=(g,P)=>{if(!g||typeof g!="object")return;if(Array.isArray(g)){g.forEach(d=>n(d,P));return}const c=g;typeof c.id=="string"&&c.id&&P.add(c.id),n(c.children,P)},h=new Map;let s=0;for(const g of e){if(g.type==="section-break"){s+=1;continue}let P=h.get(s);P||(P=new Set,h.set(s,P)),n(g,P)}for(const g of r){const P=h.get(g);if(!P||P.size===0)continue;const c=o.fragments.filter(x=>!x.isChrome&&typeof x.pageNumber=="number"&&P.has(x.blockId));if(c.length===0)continue;let d=Number.POSITIVE_INFINITY,f=0;for(const x of c)d=Math.min(d,x.pageNumber),f=Math.max(f,x.pageNumber);const T=l.get(f);if(T===void 0)continue;let m=0;for(const x of c)x.pageNumber===f&&(m=Math.max(m,x.bounds.y+x.bounds.height-T));m<=0||a.set(g,{pageOffset:f-d,bottomPt:m*this.PX_TO_PT+this.COLUMN_BALANCE_SLACK_PT})}return a}static advancePdfColumnOrPage(t,e){const a=e.columnFlow;return!a||e.columnCount<=1?(t.addPage(),!0):a.index<e.columnCount-1?(a.index+=1,e.marginLeftPt=e.pageMarginLeftPt+a.index*e.columnStridePt,!1):(a.index=0,e.marginLeftPt=e.pageMarginLeftPt,t.addPage([e.pageWidthPt,e.pageHeightPt],e.orientation),a.topPt=e.marginTopPt,a.pageOffset+=1,!0)}static advancePdfFlowRegion(t,e){const a=this.advancePdfColumnOrPage(t,e);return{x:e.marginLeftPt,y:a?e.marginTopPt:e.columnFlow?.topPt??e.marginTopPt}}static declaredSpacingPx(t,e){const a=t?.[e];return typeof a=="number"&&Number.isFinite(a)?Math.max(0,a):void 0}static pdfSpaceBeforePt(t,e,a){const i=ue(a,t)??st.declaredSpacingPx(t,"spaceBefore");return i!==void 0?i*st.PX_TO_PT:e.blockSpacingPt}static pdfSpaceAfterPt(t,e){const a=pe(t,e)??st.declaredSpacingPx(t,"spaceAfter");return a!==void 0?a*st.PX_TO_PT:0}static syncPdfColumnOffset(t){const e=t.columnFlow;!e||t.columnCount<=1||(t.marginLeftPt=t.pageMarginLeftPt+e.index*t.columnStridePt)}static getPdfReservedInsetPt(t,e){return e.reservedInsetForPage?.get(this.getPdfCurrentPage(t))??0}static getPdfWritableBottomPt(t,e){return e.pageHeightPt-e.marginBottomPt-this.getPdfReservedInsetPt(t,e)}static getPdfFlowBottom(t,e){const a=this.getPdfWritableBottomPt(t,e),i=e.columnFlow;return!i?.balance||e.columnCount<=1||i.pageOffset!==i.balance.pageOffset?a:Math.min(a,i.balance.bottomPt)}static getPdfPageCount(t){return typeof t.getNumberOfPages=="function"?t.getNumberOfPages():typeof t.internal?.getNumberOfPages=="function"?t.internal.getNumberOfPages():1}static getPdfCurrentPage(t){return t.getCurrentPageInfo?.().pageNumber??this.getPdfPageCount(t)}static createPdfPageNumbering(t,e,a){const i=[...e?.keys()??[]].sort((n,h)=>n-h),r=n=>{let h=t;for(const s of i){if(s>n)break;h=e.get(s)}return h},o=[],l=n=>{const h=Math.max(1,Math.floor(n));for(let s=o.length+1;s<=h;s++){const g=r(s);o.push(s===1||a?.has(s)&&g.pageNumberStartExplicit?g.pageNumberStart:o[s-2]+1)}return o[h-1]};return{metricsForPage:r,numberForPage:l,labelForPage:n=>Te(l(n),r(n).pageNumberFormat)}}static async renderHeaderFooterChrome(t,e,a,i,r,o){const l=this.getPdfPageCount(t),n=d=>{if(!r)return a;let f=a,T=0;for(const[m,x]of r)m<=d&&m>T&&(f=x,T=m);return f},h=d=>{if(!o)return 0;let f=0,T=0;for(const[m,x]of o)m<=d&&m>T&&(f=x,T=m);return f},s=d=>{if(!o)return 1;let f=1;for(const[T]of o)T<=d&&T>f&&(f=T);return f},g=this.createPdfPageNumbering(a,r,o).labelForPage,P=(d,f)=>{if(e.chrome&&e.chrome.length>0)return ta(e.chrome,d,f,h(f));const T=d==="header"?e.headers:e.footers;if(!T)return;const m=f===s(f)&&T.first?"first":f%2===0&&T.even?"even":"default",x=T[m];if(x)return ea(d,m,aa(x),i)},c=async(d,f,T)=>{const m=n(T),x=d.children.slice(0,3).map((M,I)=>{const u=Dt[I];return{...M,...u&&!M.align?{align:u}:{},children:M.children.map(p=>p.type!=="text"||!p.marks?.field?p:p.marks.field==="page"?{...p,text:g(T)}:{...p,text:String(l)})}});for(;x.length<3;){const M=x.length;x.push({type:"paragraph",id:`${d.id}-pdf-column-${M}`,children:[{type:"text",text:""}],...Dt[M]?{align:Dt[M]}:{}})}const F=this.createLayoutForWrapping(m.contentWidthPt,m.indentStepPx,m),b=this.createCanvasTextContext(),B=b?ia(d,b,F,e,x).map(M=>M*this.PX_TO_PT):[m.contentWidthPt/3,m.contentWidthPt/3,m.contentWidthPt/3],N=f?Math.max(10*this.PX_TO_PT,m.marginTopPt/2):m.pageHeightPt-Math.max(10*this.PX_TO_PT,m.marginBottomPt/2);let v=m.marginLeftPt;for(let M=0;M<3;M++){const I=x[M],u=B[M],p=this.measureParagraphLineAdvances(I,u,m.indentStepPx,m).reduce((C,D)=>C+D,0),S=N-p/2,w={...m,marginTopPt:S,marginLeftPt:v,marginRightPt:Math.max(0,m.pageWidthPt-v-u),contentWidthPt:Math.max(1,u)};await this.renderParagraph(t,I,S,u,i,1e9,m.indentStepPx,w),v+=u}};for(let d=0;d<l;d++){const f=d+1;t.setPage(f);const T=P("header",f),m=P("footer",f);T&&await c(T,!0,f),m&&await c(m,!1,f)}this.renderPageNumbers(t,a,i,n,g,(d,f)=>!!P(f,d));for(let d=1;d<=l;d++){const f=n(d),T=xe(f.pageBorders,f.pageWidthPt,f.pageHeightPt,{top:f.marginTopPt,right:f.marginRightPt,bottom:f.marginBottomPt,left:f.pageMarginLeftPt},d===s(d));if(!T.length)continue;t.setPage(d);const m=t.internal?.pages?.[d],x=m?.length??0;t.saveGraphicsState(),t.setLineCap?.("square");for(const F of T){t.setDrawColor(F.color),t.setLineWidth(F.style==="double"?F.widthPt/3:F.widthPt),t.setLineDashPattern(F.style==="dotted"?[F.widthPt,F.widthPt*2]:F.style==="dashed"?[F.widthPt*4,F.widthPt*2]:[],0);for(const b of F.style==="double"?[-F.widthPt/3,F.widthPt/3]:[0]){const B=F.x1===F.x2?b:0,N=F.y1===F.y2?b:0;t.line(F.x1+B,F.y1+N,F.x2+B,F.y2+N)}}t.restoreGraphicsState(),f.pageBorders?.zOrder==="back"&&m&&m.unshift(...m.splice(x))}}static drawWatermarkOnPage(t,e,a,i){t.setFont("helvetica","normal");const r=be(e,a/this.PX_TO_PT,i/this.PX_TO_PT,(x,F)=>{t.setFontSize(F*this.PX_TO_PT);const b=t.getTextWidth(x);return typeof b=="number"?b/this.PX_TO_PT:0})*this.PX_TO_PT;t.setFontSize(r);const o=t.getTextWidth(e.text),l=this.hexToRgb(e.color);t.setTextColor(l.r,l.g,l.b);const n=typeof t.saveGraphicsState=="function"&&typeof t.setGState=="function"&&typeof t.GState=="function";n&&(t.saveGraphicsState(),t.setGState(new t.GState({opacity:e.opacity})));const h=e.diagonal?Math.atan2(i,a):0,s=Math.cos(h),g=Math.sin(h),P=a/2,c=i/2,d=o/2,f=-.35*r,T=P-(d*s+f*g),m=c-(-d*g+f*s);t.text(e.text,T,m,{...h!==0?{angle:h*180/Math.PI}:{}}),n&&t.restoreGraphicsState()}static installWatermarkUnderpaint(t,e){const a=()=>{const r=t.internal?.pageSize,o=typeof r?.getWidth=="function"?r.getWidth():r?.width,l=typeof r?.getHeight=="function"?r.getHeight():r?.height;!o||!l||this.drawWatermarkOnPage(t,e,o,l)},i=t.addPage.bind(t);t.addPage=(...r)=>{const o=i(...r);return a(),o},a()}static renderBodyLineNumbers(t,e,a,i){if(e.length===0)return;const r=h=>{let s,g=0;for(const[P,c]of a)P<=h&&P>g&&(s=c,g=P);return s??this.resolvePdfLayoutMetrics(i)},o=this.getPdfPageCount(t),l=o;let n=!1;for(let h=1;h<=o;h++){const s=r(h),g=s.lineNumbering;if(!g)continue;let P=g.start;if(g.restart==="continuous")for(const d of e)d.pageNumber<h&&P++;const c=s.marginLeftPt-(g.distancePx??12)*this.PX_TO_PT;t.setPage(h),t.setFont("helvetica","normal"),t.setFontSize(10*this.PX_TO_PT),t.setTextColor(115,115,115),n=!0;for(const d of e){if(d.pageNumber!==h)continue;const f=P++;f%g.countBy===0&&t.text(String(f),c,d.y+d.height/2,{align:"right",baseline:"middle"})}}n&&t.setPage(l)}static renderPageNumbers(t,e,a,i,r,o){const l=this.getPdfPageCount(t),n=12,h=n/2+6;t.setFont(this.mapFontFamily(a),"normal"),t.setFontSize(n),t.setTextColor(0,0,0);for(let s=0;s<l;s++){const g=i?.(s+1)??e;if(!g.showPageNumbers)continue;const P=s+1,c=g.pageNumberPosition.startsWith("top");if(o?.(P,c?"header":"footer"))continue;const d=g.pageNumberPosition.endsWith("right"),f=d?g.pageWidthPt-g.marginRightPt:g.marginLeftPt,T=c?Math.max(h,g.marginTopPt/2):g.pageHeightPt-Math.max(h,g.marginBottomPt/2);t.setPage(P),t.text(r?.(P)??ye({pageNumberStart:e.pageNumberStart,pageNumberFormat:e.pageNumberFormat??"decimal"},s),f,T,{align:d?"right":"left"})}}static getParagraphLineIndentPt(t,e,a){return _e(t,e,a)*this.PX_TO_PT}static createLayoutForWrapping(t,e,a=this.getDefaultPdfLayoutMetrics()){const i=t/this.PX_TO_PT;return{pageWidth:a.pageWidthPt/this.PX_TO_PT,pageHeight:a.pageHeightPt/this.PX_TO_PT,pageMargin:a.marginLeftPt/this.PX_TO_PT,pageMarginTop:a.marginTopPt/this.PX_TO_PT,pageMarginRight:a.marginRightPt/this.PX_TO_PT,pageMarginBottom:a.marginBottomPt/this.PX_TO_PT,pageMarginLeft:a.marginLeftPt/this.PX_TO_PT,pageSpacing:0,paragraphSpacing:0,availableWidth:i,textStartY:a.marginTopPt/this.PX_TO_PT,fontSize:16,fontFamily:this.DEFAULT_BODY_FONT,lineHeight:16*1.4,indentStepPx:e,pageless:!1,hyphenationEnabled:a.hyphenationEnabled}}static buildNumberedNoteEntries(t){const e=new Map,a=s=>{if(!s||typeof s!="object")return;if(Array.isArray(s)){s.forEach(a);return}const g=s;g.type!=="footnote"&&(g.marks?.footnoteRef&&!e.has(g.marks.footnoteRef)&&e.set(g.marks.footnoteRef,g.text??""),a(g.children))};a(t.children.filter(s=>s.type!=="footnote"));const i=[...t.notes??[],...t.children.filter(s=>s.type==="footnote")],r={footnote:0,endnote:0},o=new Map,l=new Map;for(const s of i)l.set(s.id,s.noteKind==="endnote"?"endnote":"footnote");for(const[s]of e){const g=l.get(s)??"footnote";r[g]+=1,o.set(s,$t(r[g],g))}const n=i.map(s=>{const g=l.get(s.id)??"footnote",P=o.get(s.id)||$t(r[g]+=1,g);return{footnoteId:s.id,number:P,kind:g,blocks:s.children}}),h=s=>{const g=[...o.keys()],P=g.indexOf(s.footnoteId);return P===-1?g.length:P};return n.sort((s,g)=>h(s)-h(g))}static async renderNoteEntry(t,e,a,i,r,o,l,n,h){n&&this.drawNoteNumeral(t,e.number,i.marginLeftPt,a,r);const s=tt.verticalPaddingPx*st.PX_TO_PT,g=tt.gutterPx*st.PX_TO_PT,P=a+s,c={...i,marginTopPt:i.marginTopPt+s,marginLeftPt:i.marginLeftPt+g,contentWidthPt:Math.max(1,i.contentWidthPt-g),blockSpacingPt:tt.blockSpacingPx*st.PX_TO_PT};if(h){const d=c.marginTopPt;Object.defineProperty(c,"marginTopPt",{get:()=>h.get(this.getPdfCurrentPage(t))??d})}return(await this.renderBodyBlocks(t,e.blocks,c,o,l,r,void 0,void 0,void 0,P)).finalY+s}static drawNoteNumeral(t,e,a,i,r){t.setFont(this.mapFontFamily(r),"normal"),t.setFontSize(Vt*this.PX_TO_PT),t.setTextColor(0,0,0),t.text(e,a+1.5,i+(6+Vt)*st.PX_TO_PT)}static mapFootnoteRefBlocks(t){const e=new Map,a=(i,r)=>{if(!i||typeof i!="object")return;if(Array.isArray(i)){i.forEach(l=>a(l,r));return}const o=i;o.marks?.footnoteRef&&!e.has(o.marks.footnoteRef)&&e.set(o.marks.footnoteRef,r),a(o.children,r)};for(const i of t)a(i,i.id??"");return e}static async renderBodyBlocks(t,e,a,i,r,o,l,n,h,s,g){const P=new Map,c=new Map([[1,0]]),d=[],f=[],T=Fe(e);let m=s??a.marginTopPt,x=a.contentWidthPt,F=a.indentStepPx,b=!0;const B=new Map([[1,this.physicalPageMetrics(a)]]),N=()=>t.getCurrentPageInfo?.()?.pageNumber??t.getNumberOfPages();let v=0;const M=I=>{if(v=I,!g)return;const u=a.columnFlow;!u||a.columnCount<=1||(u.index=0,u.topPt=m,u.pageOffset=0,u.balance=g.balanceBySection.get(I),a.marginLeftPt=a.pageMarginLeftPt)};M(0);for(let I=0;I<e.length;I++){this.syncPdfColumnOffset(a);const u=e[I],p=this.getPdfFlowBottom(t,a);if(u.type==="page-break"){!b&&a.blockSpacingPt>0&&(m+=a.blockSpacingPt),u.id&&P.set(u.id,N()),t.addPage([a.pageWidthPt,a.pageHeightPt],a.orientation),a.columnFlow&&(a.columnFlow.index=0,a.columnFlow.topPt=a.marginTopPt,a.columnFlow.pageOffset+=1,a.marginLeftPt=a.pageMarginLeftPt),m=a.marginTopPt,b=!0;continue}if(u.type==="docx-raw"){const k=St.heightPx*.75,R=a.pageWidthPt-a.marginLeftPt-a.marginRightPt,G=Se(u,R/.75)*.75;!b&&a.blockSpacingPt>0&&(m+=a.blockSpacingPt),m+k>p&&(m=this.advancePdfFlowRegion(t,a).y),u.id&&P.set(u.id,N());const H=a.marginLeftPt;t.setDrawColor(107,114,128),t.setFillColor(243,244,246),t.setLineWidth(.75),t.roundedRect(H,m,G,k,St.cornerRadiusPx*.75,St.cornerRadiusPx*.75,"FD"),t.setFont("courier","normal"),t.setFontSize(St.fontPx*.75),t.setTextColor(107,114,128),t.text(Le(u),H+St.paddingXPx*.75,m+k/2,{baseline:"middle"}),t.setTextColor(0,0,0),m+=k,b=!1;continue}if(u.type==="section-break"){u.id&&P.set(u.id,N());const k=l?.get(u.id),R=k?n?.(k)??k:void 0;if(R){const H=we(u.breakType==="continuous",{width:a.pageWidthPt,height:a.pageHeightPt},{width:R.pageWidthPt,height:R.pageHeightPt});a=R,x=R.contentWidthPt,F=R.indentStepPx,H?(m=Oe(m,a.blockSpacingPt,0,a.marginTopPt),m>this.getPdfWritableBottomPt(t,a)&&(t.addPage([a.pageWidthPt,a.pageHeightPt],a.orientation),m=a.marginTopPt)):(t.addPage([R.pageWidthPt,R.pageHeightPt],R.orientation),m=a.marginTopPt),B.set(N(),this.physicalPageMetrics(R))}else t.addPage(),m=a.marginTopPt;const G=h?.get(u.id);G!==void 0&&c.set(N(),G),M(v+1),b=!0;continue}if(u.type==="toc"){const k=a.blockSpacingPt;!b&&k>0&&(m+=k),b=!1,u.id&&P.set(u.id,N());const R=Ce({children:e.map(_=>_.type==="paragraph"?this.paragraphForPdfOutput(_):_)},ke(u)),G=(u.fontSize??16)*this.PX_TO_PT,H=G*1.4,j=Zt.paddingYPx*this.PX_TO_PT;t.setFont(this.mapFontFamily(u.fontFamily??o),"normal"),t.setFontSize(G);const y=this.hexToRgb(u.color??"#000000");t.setTextColor(y.r,y.g,y.b),m+=j,R.length===0&&(m+H>p&&(m=this.advancePdfFlowRegion(t,a).y),m+=H);for(const _ of R)m+H>p&&(m=this.advancePdfFlowRegion(t,a).y),f.push({pdfPage:N(),headingBlockId:_.blockId,block:u,entry:_,baseline:m+G,left:a.marginLeftPt,width:a.contentWidthPt,fontName:this.mapFontFamily(u.fontFamily??o),fontSizePt:G}),m+=H;m+=j;continue}const S=I>0?e[I-1]:void 0,w=st.pdfSpaceBeforePt(u,a,S)+st.pdfSpaceAfterPt(S,u);if(!b&&w>0?m+=w:b&&I===0&&a.keepFirstBlockDeclaredSpaceBefore&&(m+=(st.declaredSpacingPx(u,"spaceBefore")??0)*st.PX_TO_PT),b=!1,u.id&&u.type!=="paragraph"&&P.set(u.id,N()),u.type==="container"){const k=await this.renderContainerBlock(t,u,m,x,o,i,r,a);m=k.nextY;for(const[R,G]of k.blockStartPages)P.set(R,G);d.push(...k.lineMarks);continue}if(u.type==="placeholder"){m=this.advancePlaceholderBlock(t,u,m,a);continue}if(u.type==="image"){const k=await this.renderImageBlock(t,u,m,x,a);k&&(m=k.nextY);continue}if(u.type==="math"){const k=u;m=(await this.renderMathBlock(t,k,m,x,p,a)).nextY;continue}if(u.type==="list"){m=await this.renderListBlock(t,u,m,x,o,a,T.get(u.id),d);continue}if(u.type==="table"){m=await this.renderTableBlock(t,u,m,x,o,i,r,a);continue}if(u.type==="code"){m=await this.renderCodeBlock(t,u,m,x,p,a.marginLeftPt,i,r,a,d);continue}if(u.type!=="paragraph")continue;const C=u,{required:D,firstLineAdvance:V}=this.getRequiredParagraphStartHeight(e,I,x,F,a);D>0&&m+D>p&&a.marginTopPt+D<=p&&m!==a.marginTopPt&&(m=this.advancePdfFlowRegion(t,a).y),m+V>p&&m!==a.marginTopPt&&(m=this.advancePdfFlowRegion(t,a).y),C.id&&P.set(C.id,N()),m=await this.renderParagraph(t,C,m,x,o,p,F,a,d)}if(f.length>0){const I=N(),u=this.createPdfPageNumbering(B.get(1)??a,B,c).labelForPage;for(const p of f){t.setPage(p.pdfPage),t.setFont(p.fontName,"normal"),t.setFontSize(p.fontSizePt);const S=this.hexToRgb(p.block.color??"#000000");t.setTextColor(S.r,S.g,S.b);const w=P.get(p.headingBlockId),C=w!==void 0?u(w):"",D=Me(p.block,p.entry,p.left,p.width,C,V=>t.getTextWidth(V),this.PX_TO_PT);D.text&&t.text(D.text,D.textX,p.baseline,{align:D.align,...D.rtl?{isInputVisual:!1,isOutputVisual:!0,isInputRtl:!0,isOutputRtl:!1}:{}}),C&&D.leaderEnd-D.leaderStart>Zt.minimumLeaderWidthPx*this.PX_TO_PT&&(t.setDrawColor(150),typeof t.setLineDashPattern=="function"&&t.setLineDashPattern([.8,2.2],0),t.line(D.leaderStart,p.baseline,D.leaderEnd,p.baseline),typeof t.setLineDashPattern=="function"&&t.setLineDashPattern([],0),t.setDrawColor(0,0,0)),C&&t.text(C,D.numberX,p.baseline)}t.setPage(I)}return{blockStartPages:P,pageMetrics:B,pageSections:c,lineMarks:d,finalY:m}}static async renderContainerBlock(t,e,a,i,r,o,l,n){const h=Math.max(0,e.padding??Et.paddingPx)*this.PX_TO_PT,s=this.getPdfFlowBottom(t,n);a+h>s&&a!==n.marginTopPt&&(a=this.advancePdfFlowRegion(t,n).y);const g=()=>t.getCurrentPageInfo?.()?.pageNumber??t.getNumberOfPages(),P=g(),c=n.columnFlow?.index??0,d=n.columnFlow?.topPt??n.marginTopPt,f={...n,keepFirstBlockDeclaredSpaceBefore:void 0,marginTopPt:n.marginTopPt+h,marginRightPt:n.marginRightPt+h,marginBottomPt:n.marginBottomPt+h,marginLeftPt:n.marginLeftPt+h,contentWidthPt:Math.max(1,i-h*2),pageMarginLeftPt:n.pageMarginLeftPt+h},T=await this.renderBodyBlocks(t,e.children,f,o,l,r,void 0,void 0,void 0,a+h);let m=T.finalY+h;this.syncPdfColumnOffset(n),m>s&&T.finalY!==f.marginTopPt&&(m=this.advancePdfFlowRegion(t,n).y+h);const x=g(),F=n.columnFlow?.index??0,b=x,B=this.hexToRgb(e.borderColor??Et.borderColor);t.setDrawColor(B.r,B.g,B.b),t.setLineWidth(Et.borderWidthPx*this.PX_TO_PT);let N=P,v=c;for(;N<x||N===x&&v<=F;){t.setPage(N);const M=N===P&&v===c,I=N===x&&v===F,u=M?a:N===P?d:n.marginTopPt,p=I?m:s;p>u&&t.rect(n.pageMarginLeftPt+v*n.columnStridePt,u,i,p-u,"S"),v+=1,v>=n.columnCount&&(v=0,N+=1)}return t.setPage(b),{nextY:m,blockStartPages:T.blockStartPages,lineMarks:T.lineMarks}}static advancePlaceholderBlock(t,e,a,i){const r=Math.max(0,e.height||100)*this.PX_TO_PT,o=this.getPdfFlowBottom(t,i);return a+r>o&&a!==i.marginTopPt&&(a=this.advancePdfFlowRegion(t,i).y),a+r}static async toBlob(t,e,a){class i extends this{}return i.bundledGenreFamilies=new Map,i.scriptFallbackFamilies=new Map,i.shapingFonts=new Map,i.embeddedFamilyNames=new Map,i.inlineCodeFontFamily="courier",i.renderDocument(t,e,a)}static async renderDocument(t,e,a){t=this.splitDocumentFallbackRuns(t,await this.loadFallbackCoverage(t));const i=a||{...It,background:Lt.codeBackground,text:Lt.codeText};await this.ensureAllLatexRendered(t);const r=this.resolvePdfLayoutMetrics(t),o=t.children.filter(S=>S.type==="section-break"),l=new Map,n=new Map,h=t.pageLayout?.pageNumberRestart===!0?{...r,pageNumberStartExplicit:!0}:r;o.forEach((S,w)=>{const C=o[w+1];l.set(S.id,C?.layout?this.resolvePdfMetricsFromSettings(C.layout,t.pageLayout,!0):C?r:h),n.set(S.id,w+1)});const s=o[0]?.layout?this.resolvePdfMetricsFromSettings(o[0].layout,t.pageLayout,!1):r,g=await import("./jspdf.es.min-DlTF8uTw.js").then(S=>S.j),P=g.jsPDF??g.default,c=new P({orientation:s.orientation,unit:"pt",format:[s.pageWidthPt,s.pageHeightPt]}),d=this.DEFAULT_BODY_FONT,{hasSourceCodePro:f}=await this.registerDocumentFonts(c,t,d);e&&c.setProperties({title:e});const T=Ne(t.watermark);T&&this.installWatermarkUnderpaint(c,T);const m=[...t.children.filter(S=>S.type==="footnote"),...t.notes??[]],x=t.children.filter(S=>S.type!=="footnote"&&S.type!=="header-footer"),F={balanceBySection:this.computeColumnBalanceTargets(t,x)},b=m.length>0?this.buildNumberedNoteEntries(t):[],B=b.filter(S=>S.kind==="footnote"),N=b.filter(S=>S.kind==="endnote");let v=new Map([[1,s]]),M=new Map([[1,0]]),I=s.marginTopPt,u=[],p=new Map;if(B.length===0){const S=await this.renderBodyBlocks(c,x,s,i,f,d,l,void 0,n,void 0,F);v=S.pageMetrics,M=S.pageSections,u=S.lineMarks,I=S.finalY}else{const S=B,w=tt.separatorSpacePx*this.PX_TO_PT,C=this.mapFootnoteRefBlocks(x),D=new P({orientation:s.orientation,unit:"pt",format:[s.pageWidthPt,s.pageHeightPt]});await this.registerDocumentFonts(D,t,d);const V=await this.renderBodyBlocks(D,x,s,i,f,d,l,void 0,void 0,void 0,F),k=L=>{let A=s,z=0;for(const[U,Y]of V.pageMetrics)U<=L&&U>z&&(A=Y,z=U);return A},R=new Map,G=D.getNumberOfPages();for(const L of S){const A=C.get(L.footnoteId),z=(A?V.blockStartPages.get(A):void 0)??G,U=R.get(z)??[];U.push(L),R.set(z,U)}const H=new P({orientation:r.orientation,unit:"pt",format:[r.pageWidthPt,1e4]});await this.registerDocumentFonts(H,t,d);const j=new Map;for(const[L,A]of R){const z=k(L);for(const U of A){const Y={...z,pageHeightPt:1e4,marginTopPt:0,marginBottomPt:0},Z=await this.renderNoteEntry(H,U,0,Y,d,i,f,!1);j.set(U.footnoteId,Math.max(0,Z))}}const y=new Map;for(const[L,A]of R){const z=k(L),U=w+A.reduce((Q,rt)=>Q+(j.get(rt.footnoteId)??0),0),Y=z.pageHeightPt-z.marginTopPt-z.marginBottomPt,Z=V.lineMarks.filter(Q=>Q.pageNumber===L).sort((Q,rt)=>Q.y-rt.y).slice(0,tt.minimumBodyLinesBeforeFootnotes),q=this.getParagraphLineHeight({type:"paragraph",id:"__pdf_measure__",children:[]}),ot=(Z.length>0?Math.max(0,Math.max(...Z.map(Q=>Q.y+Q.height))-z.marginTopPt):q*tt.minimumBodyLinesBeforeFootnotes)+tt.bodyKeepSlackPx*this.PX_TO_PT;y.set(L,Math.min(U,Math.max(0,Y-ot)))}p=y;const _=L=>({...L,reservedInsetForPage:y}),X=_(s),O=await this.renderBodyBlocks(c,x,X,i,f,d,l,_,n,void 0,F);v=O.pageMetrics,M=O.pageSections,u=O.lineMarks,I=O.finalY;const K=new Map;for(const L of O.lineMarks)K.set(L.pageNumber,Math.max(K.get(L.pageNumber)??0,L.y+L.height+tt.separatorSpacePx*this.PX_TO_PT+tt.verticalPaddingPx*this.PX_TO_PT));const W=c.getNumberOfPages();for(const[L,A]of[...R.entries()].sort((z,U)=>z[0]-U[0])){const z=Math.min(L,W);c.setPage(z);const U=k(L),Y=y.get(L)??0,Z=U.pageHeightPt-U.marginBottomPt-Y+w;c.setDrawColor(120),c.setLineWidth(.75),c.line(U.marginLeftPt,Z-7,U.marginLeftPt+Math.max(tt.separatorWidthMinPx*this.PX_TO_PT,U.contentWidthPt*tt.separatorWidthFraction),Z-7);let q=Z;for(let ot=0;ot<A.length;ot++){ot>0&&(q+=tt.blockSpacingPx*this.PX_TO_PT);const Q=this.getPdfCurrentPage(c),rt=c.addPage.bind(c),lt=[];c.addPage=(...ct)=>{const et=this.getPdfCurrentPage(c)+1;return et<=W?c.setPage(et):rt(...ct),lt.push(this.getPdfCurrentPage(c)),c};try{q=await this.renderNoteEntry(c,A[ot],q,U,d,i,f,!0,K)}finally{c.addPage=rt}for(const ct of lt){c.setPage(ct),c.setDrawColor(120),c.setLineWidth(.75);const et=(K.get(ct)??U.marginTopPt)-tt.verticalPaddingPx*this.PX_TO_PT*2;c.line(U.marginLeftPt,et,U.marginLeftPt+U.contentWidthPt,et)}c.setPage(lt[lt.length-1]??Q)}}c.setPage(this.getPdfPageCount(c))}if(N.length>0){const S=new P({orientation:r.orientation,unit:"pt",format:[r.pageWidthPt,1e4]});await this.registerDocumentFonts(S,t,d);let w=tt.separatorToContentPx*this.PX_TO_PT;for(let H=0;H<N.length;H++){H>0&&(w+=tt.blockSpacingPx*this.PX_TO_PT);const j={...r,pageHeightPt:1e4,marginTopPt:0,marginBottomPt:0};w+=await this.renderNoteEntry(S,N[H],0,j,d,i,f,!1)}const C=this.getPdfPageCount(c);let D=s,V=0;for(const[H,j]of v)H<=C&&H>=V&&(D=j,V=H);const k=I+tt.inlineEndnoteGapPx*this.PX_TO_PT,R=k+w<=D.pageHeightPt-D.marginBottomPt-(p.get(C)??0);let G;R?(c.setPage(C),G=k):(c.addPage(),G=D.marginTopPt+tt.newPageSeparatorOffsetPx*this.PX_TO_PT),c.setDrawColor(120),c.setLineWidth(.75),c.line(D.marginLeftPt,G,D.marginLeftPt+Math.max(tt.separatorWidthMinPx*this.PX_TO_PT,D.contentWidthPt*tt.separatorWidthFraction),G),G+=tt.separatorToContentPx*this.PX_TO_PT;for(let H=0;H<N.length;H++)H>0&&(G+=tt.blockSpacingPx*this.PX_TO_PT),G=await this.renderNoteEntry(c,N[H],G,D,d,i,f,!0)}return await this.renderHeaderFooterChrome(c,t,r,d,v,M),this.renderBodyLineNumbers(c,u,v,t),c.output("blob")}static measureLineAdvancePt(t,e,a,i){let r=0,o=0;for(const h of t)h.latexImage?o=Math.max(o,h.latexImage.contentHeight*this.PX_TO_PT):r=Math.max(r,h.marks?.fontSize?h.marks.fontSize*this.PX_TO_PT:e);r===0&&(r=e);const l=i??(a?this.LINE_HEIGHT_MULTIPLIERS.heading:this.LINE_HEIGHT_MULTIPLIERS.paragraph),n=r*l;return o>n*1.25?o:n}static parseParagraphDecoration(t){const e=t.shading&&t.shading!=="transparent"?t.shading:void 0;if(!e&&!t.borders)return null;let a;if(t.borders)try{a=JSON.parse(t.borders)}catch{a=void 0}return!e&&!a?null:{...e?{shading:e}:{},...a?{edges:a}:{}}}static drawParagraphDecorationSlice(t,e,a,i,r,o,l,n){if(e.shading){const f=this.hexToRgb(e.shading);t.setFillColor(f.r,f.g,f.b),t.rect(a,i,r,o+(n?0:.5),"F")}const h=e.edges;if(!h)return;const s=(f,T,m,x,F)=>{const b=h[f];if(!b||b.style==="none")return;const B=Math.max(.4,(b.width??1)*this.PX_TO_PT),N=m===F,v=this.hexToRgb(b.color??"#000000");if(t.setDrawColor(v.r,v.g,v.b),t.setLineWidth(B),N&&oa(b.style)){const u=na(T,x,this.PX_TO_PT);for(const p of u.lines)t.line(p.from,m,p.to,m);t.setFillColor(v.r,v.g,v.b);for(const p of u.ornaments)if(b.style==="stars")for(const S of ra(p.cx,m,p.radius))t.line(S.x1,S.y1,S.x2,S.y2);else{const S=sa(p.cx,m,p.radius);t.lines([[S[1].x-S[0].x,S[1].y-S[0].y],[S[2].x-S[1].x,S[2].y-S[1].y],[S[3].x-S[2].x,S[3].y-S[2].y]],S[0].x,S[0].y,[1,1],"F",!0)}return}const M=typeof t.setLineDashPattern=="function";M&&(b.style==="dashed"?t.setLineDashPattern([4.5,2.25],0):b.style==="dotted"?t.setLineDashPattern([1.5,1.5],0):t.setLineDashPattern([],0));const I=u=>{t.line(T+(N?0:u),m+(N?u:0),x+(N?0:u),F+(N?u:0))};b.style==="double"?(I(-B),I(B)):I(0),M&&t.setLineDashPattern([],0)},g=n?0:.5,P=f=>Math.max(0,h[f]?.space??0)*this.PX_TO_PT,c=a-P("left"),d=a+r+P("right");if(s("left",c,i,c,i+o+g),s("right",d,i,d,i+o+g),l){const f=i-P("top");s("top",a,f,a+r,f)}if(n){const f=i+o+P("bottom");s("bottom",a,f,a+r,f)}}static measureParagraphLineAdvances(t,e,a,i){const r=this.createCanvasTextContext();if(!r)return[this.getParagraphLineHeight(t)];const o=this.createLayoutForWrapping(e,a,i),l=Jt(this.paragraphForPdfOutput(t),r,o);if(l.length===0)return[this.getEmptyParagraphLineHeight(t)];const n=this.getParagraphFontSize(t),h=this.getLineSpacingMultiplier(t);return l.map(s=>this.measureLineAdvancePt(s.segments.map(g=>({marks:g.marks})),n,!!t.heading,h))}static paragraphForPdfOutput(t){const e=t.children.filter(a=>a.type!=="text"||!a.marks?.hidden||!!a.marks.footnoteRef);return e.length===t.children.length?t:{...t,children:e}}static getParagraphDirection(t){let e="";for(const a of t.children)e+=a.text??"";return Re(t.direction,e)}static getEffectiveParagraphAlignment(t,e){return t.align||(e==="rtl"?"right":"left")}static getRequiredParagraphStartHeight(t,e,a,i,r){const o=t[e];if(!o||o.type!=="paragraph")return{required:0,firstLineAdvance:0};const l=vt(o),n=this.measureParagraphLineAdvances(o,a,i,r),h=this.paragraphForPdfOutput(o).children.every(c=>c.type==="text"&&c.text==="")||n.length===0?this.getEmptyParagraphLineHeight(o):n[0],s=c=>c.reduce((d,f)=>d+Math.max(0,f),0);let g=0;if(l.keepLines?g=s(n):l.widowControl&&n.length>=2&&(g=n[0]+n[1]),!l.keepNext)return{required:g,firstLineAdvance:h};let P=0;for(let c=0;c<qt;c++){const d=t[e+c+1];if(!d||d.type!=="paragraph")break;const f=this.measureParagraphLineAdvances(d,a,i,r);if(f.length===0)break;const T=t[e+c];P+=st.pdfSpaceBeforePt(d,r,T)+st.pdfSpaceAfterPt(T,d);const m=vt(d);if(m.keepNext&&c<qt-1){P+=s(f);continue}P+=f[0],m.widowControl&&f.length>=2&&(P+=f[1]);break}return{required:Math.max(g,s(n)+P),firstLineAdvance:h}}static async renderParagraph(t,e,a,i,r,o,l=this.resolveIndentStepPx(),n=this.getDefaultPdfLayoutMetrics(),h){let s=a;const g=this.paragraphForPdfOutput(e),P=this.getParagraphFontSize(e),c=this.getParagraphLineHeight(e),d=this.getLineSpacingMultiplier(e);let f=Number.isFinite(o)&&o>0?o:this.getPdfFlowBottom(t,n),T=n.marginLeftPt;const m=()=>{const M=this.advancePdfFlowRegion(t,n);s=M.y,T=M.x,f=this.getPdfFlowBottom(t,n)},x=(M=c)=>{if(s+M>f){if(s===n.marginTopPt)return;m()}},F=()=>t.getCurrentPageInfo?.()?.pageNumber??t.getNumberOfPages(),b=this.getParagraphDirection(g),B=this.getEffectiveParagraphAlignment(e,b),N=this.parseParagraphDecoration(e);if(g.children.length===0||g.children.length===1&&g.children[0].type==="text"&&g.children[0].text===""){const M=this.getEmptyParagraphLineHeight(e);return N&&(x(M),this.drawParagraphDecorationSlice(t,N,T,s,i,M,!0,!0)),s+M}const v=this.createCanvasTextContext();if(v){const M=this.createLayoutForWrapping(i,l,n),I=Jt(g,v,M),u=await this.prepareLatexImages(g,P),p=I.map(w=>w.segments.map(C=>C.marks?.latex?{text:C.text,marks:C.marks,latexImage:u.get(C.text)}:{text:C.text,marks:C.marks,font:C.marks?.fontFamily})),S=vt(e);for(let w=0;w<I.length;w++){const C=I[w],D=p[w];if(D.length>0){const V=this.getParagraphLineIndentPt(e,w,l),k=Math.max(1,i-V),R=this.measureLineAdvancePt(D,P,!!e.heading,d),G=p[w+1];if(S.widowControl&&I.length>=3&&w===I.length-2&&G&&s+R<=f){const j=this.measureLineAdvancePt(G,P,!!e.heading,d);s+R+j>f&&s!==n.marginTopPt&&m()}x(R);const H=b==="rtl"?T:T+V;N&&this.drawParagraphDecorationSlice(t,N,T,s,i,R,w===0,w===I.length-1),h?.push({pageNumber:F(),y:s,height:R}),s=this.renderLine(t,D,s,H,k,B,P,r,!!e.heading,d,w===I.length-1,{direction:b,...C.tabLayout?{tabLayoutPx:C.tabLayout.segments,...C.tabLayout.rtl?{tabRtl:!0,tabWidthPx:C.tabLayout.width}:{}}:{},...C.hyphenTrailing?{hyphenTrailing:!0}:{}})}}return s}return this.renderParagraphWithJsPDFWrapping(t,g,a,i,r,o,l,n)}static async prepareLatexImages(t,e){const a=new Map;for(const i of t.children)if(i.type==="text"&&i.marks?.latex){const r=await this.renderLatexToImage(i.text,!1,e);r&&a.set(i.text,r)}return a}static async renderParagraphWithJsPDFWrapping(t,e,a,i,r,o,l=this.resolveIndentStepPx(),n=this.getDefaultPdfLayoutMetrics()){let h=a;const s=this.getParagraphFontSize(e),g=this.getParagraphLineHeight(e),P=this.getLineSpacingMultiplier(e);let c=Number.isFinite(o)&&o>0?o:this.getPdfFlowBottom(t,n),d=n.marginLeftPt;const f=()=>{if(h+g>c){if(h===n.marginTopPt)return;const M=this.advancePdfFlowRegion(t,n);h=M.y,d=M.x,c=this.getPdfFlowBottom(t,n)}},T=this.getParagraphDirection(e),m=this.getEffectiveParagraphAlignment(e,T),x=await this.processTextNodesWithLatex(e.children,s);if(x.length===0)return h+this.getEmptyParagraphLineHeight(e);let F=[],b=0,B=0;const N=()=>Math.max(1,i-this.getParagraphLineIndentPt(e,B,l)),v=(M=!1)=>{if(F.length===0)return;f();const I=this.getParagraphLineIndentPt(e,B,l);h=this.renderLine(t,F,h,T==="rtl"?d:d+I,Math.max(1,i-I),m,s,r,!!e.heading,P,M,{direction:T}),F=[],b=0,B+=1};if(x.length===1&&x[0].text==="")return a+this.getEmptyParagraphLineHeight(e);for(const M of x){if(M.latexImage){const u=M.latexImage.contentWidth*this.PX_TO_PT;b+u>N()&&F.length>0&&v(),F.push({text:M.text,marks:M.marks,font:M.font||M.marks?.fontFamily,latexImage:M.latexImage}),b+=u;continue}this.setRunFont(t,M,r),t.setFontSize(this.getRunEffectiveFontSizePt(M.marks,s));const I=M.text.split(`
2
+ `);for(let u=0;u<I.length;u++){const p=I[u];u>0&&F.length>0&&v();const S=p.split(/(\s+)/);for(const w of S){const C=this.measureRunDisplayWidthPt(t,w,M.marks);b+C>N()&&F.length>0&&v(),(w.trim()||F.length>0)&&(F.push({text:w,marks:M.marks,font:M.font||M.marks?.fontFamily}),b+=C)}}}return F.length>0&&v(!0),h}static getLineSpacingMultiplier(t){return Qt(t)}static async renderListBlock(t,e,a,i,r,o=this.getDefaultPdfLayoutMetrics(),l,n){if(!e.children.length)return a;let h=a;const s=this.getPdfFlowBottom(t,o),g=l??Ee(e),P={...g.counters};let c;if(e.variant==="ordered"&&e.numberingFormat)try{t.setFont(this.mapFontFamily(r),"normal"),t.setFontSize(this.FONT_SIZES.normal);let d=0;for(const T of Ie(e,g))d=Math.max(d,t.getTextWidth(T)/this.PX_TO_PT);const f=this.ORDERED_LIST_INDENT_PT/this.PX_TO_PT;c=Math.min(Math.max(f,Math.ceil(d)+10),240)*this.PX_TO_PT}catch{c=void 0}for(let d=0;d<e.children.length;d++){const f=e.children[d],T=this.getListIndentLevel(f);let m;e.variant==="ordered"?m={type:"ordered",label:this.computeOrderedMarkerLabel(P,T,g.start,ve(e.numberingFormat))}:e.variant==="todo"?m={type:"todo",checked:!!f.checked}:m={type:"bullet",indentLevel:T},h=await this.renderListItem(t,f,e,m,h,i,s,r,o,n,c)}return h}static async renderListItem(t,e,a,i,r,o,l,n,h=this.getDefaultPdfLayoutMetrics(),s,g){let P=r+Math.max(0,e.spaceBefore??0)*this.PX_TO_PT;const c=this.getListIndentLevel(e)*this.SUBLIST_INDENT_PT,d=n,f=this.FONT_SIZES.normal,T=this.mapFontFamily(d);t.setFont(T,"normal"),t.setFontSize(f);const m=g??this.getListIndentPt(a.variant);let x=h.marginLeftPt,F=x+c+m,b=l;const B=()=>{const _=this.advancePdfFlowRegion(t,h);P=_.y,x=_.x,F=x+c+m,b=this.getPdfFlowBottom(t,h)};let N=o-c-m;(!Number.isFinite(N)||N<=0)&&(N=Math.max(o*.3,o*.1));let v="";for(const _ of e.children)v+=_.text??"";const M=Be(v)??"ltr",I=M==="rtl",u=()=>I?x:F,p=()=>I?x+N:F,S=e.lineSpacing??a.lineSpacing??this.LINE_HEIGHT_MULTIPLIERS.paragraph,w=f*S,C=await this.processTextNodesWithLatex(e.children,f);let D=C.length>0?C:[{text:""}];a.variant==="todo"&&e.checked&&(D=D.map(_=>_.latexImage?_:{..._,marks:{..._.marks,strikethrough:!0,color:Lt.todoCheckedText}}));const V=new Set(Object.values(this.SCRIPT_FALLBACK_FONTS).map(_=>_.family)),k=[...C].reverse().find(_=>!_.latexImage&&!_.marks?.latex&&_.text.length>0&&!V.has(_.marks?.fontFamily??""))?.marks;let R=[],G=0,H=!1;const j=()=>{H||(P+w>b&&P!==h.marginTopPt&&B(),this.drawListMarker(t,i,p(),P,w,f,d,n,I,k),H=!0)},y=()=>{R.length!==0&&(P+w>b&&P!==h.marginTopPt&&B(),j(),s?.push({pageNumber:t.getCurrentPageInfo?.().pageNumber??t.getNumberOfPages(),y:P,height:this.measureLineAdvancePt(R,f,!1,S)}),P=this.renderLine(t,R,P,u(),N,I?"right":"left",f,d,!1,S,!0,{direction:M}),R=[],G=0)};for(const _ of D){if(_.latexImage){const O=_.latexImage.contentWidth*this.PX_TO_PT;G+O>N&&R.length>0&&y(),R.push({text:_.text,marks:_.marks,font:_.font,latexImage:_.latexImage}),G+=O;continue}this.setRunFont(t,_,d||n),t.setFontSize(this.getRunEffectiveFontSizePt(_.marks,f));const X=_.text.split(`
3
+ `);for(let O=0;O<X.length;O++){const K=X[O];O>0&&(R.length>0?y():(j(),P+=w));const W=K.split(/(\s+)/);for(const L of W){const A=this.measureRunDisplayWidthPt(t,L,_.marks);G+A>N&&R.length>0&&y(),(L.trim()||R.length>0)&&(R.push({text:L,marks:_.marks,font:_.font}),G+=A)}}}return R.length>0&&y(),H||(j(),P+=w),P+Math.max(0,e.spaceAfter??0)*this.PX_TO_PT}static drawListMarker(t,e,a,i,r,o,l,n,h,s){t.setDrawColor(0,0,0);const g=(d,f=0)=>h?2*a-d-f:d,P=a-this.BULLET_MARKER_WIDTH_PT,c=i+r/2;switch(e.type){case"bullet":{const d=g(P+this.BULLET_CENTER_OFFSET_PT),f=this.BULLET_RADIUS_PT;if(e.indentLevel<=0)t.circle(d,c,f,"F");else if(e.indentLevel===1)t.circle(d,c,f,"S");else{const T=this.BULLET_SQUARE_HALF_PT*2,m=g(P+this.BULLET_SQUARE_INSET_PT,T),x=c-this.BULLET_SQUARE_HALF_PT+this.BULLET_SQUARE_VERTICAL_ADJUST_PT;t.rect(m,x,T,T,"S")}break}case"todo":{const d=this.TODO_CHECKBOX_SIZE_PT,f=g(P-this.TODO_CHECKBOX_OFFSET_PT,d),T=c-d/2;t.setLineWidth(.8),typeof t.roundedRect=="function"?t.roundedRect(f,T,d,d,this.TODO_CHECKBOX_RADIUS_PT,this.TODO_CHECKBOX_RADIUS_PT,"S"):t.rect(f,T,d,d,"S"),e.checked&&(t.setLineWidth(1.2),t.line(f+d*.15,T+d*.55,f+d*.4,T+d*.75),t.line(f+d*.4,T+d*.75,f+d*.85,T+d*.25));break}case"ordered":{const d=e.label,f=s?{fontFamily:s.fontFamily,fontSize:s.fontSize,bold:s.bold,italic:s.italic,code:s.code,superscript:s.superscript,subscript:s.subscript}:void 0;this.setRunFont(t,{text:d,marks:f},l||n);const T=this.getRunEffectiveFontSizePt(f,o);t.setFontSize(T);const m=t.getTextWidth(d),x=h?a+this.ORDERED_LABEL_GAP_PT:a-this.ORDERED_LABEL_GAP_PT-m;t.text(d,x,i+T);break}}t.setLineWidth(.5),t.setTextColor(0,0,0)}static async renderTableBlock(t,e,a,i,r,o=It,l=!1,n=this.getDefaultPdfLayoutMetrics()){if(!e.children||e.children.length===0)return a;const h=this.getPdfFlowBottom(t,n);let s=a;const g=e.borderWidth??Bt.borderWidthPx,P=e.borderColor??Bt.borderColor,c=this.hexToRgb(P),d=Number.isFinite(e.cellPadding)?Math.max(0,Math.round(e.cellPadding)):Bt.cellPaddingPx,f=d*this.PX_TO_PT,T=De(e.borders),m=Xe(e),x=m.cols,F=Math.min(e.tableWidth?e.tableWidth*this.PX_TO_PT:i,i),b=e.align==="center"?(i-F)/2:e.align==="right"?i-F:0;let B=n.marginLeftPt+b;const N=Ae(e.columnWidths??[],x).map(y=>y/100*F),v=[0];for(let y=0;y<x;y++)v.push(v[y]+N[y]);const M=y=>v[Math.min(y.col+y.colSpan,x)]-v[y.col],I=new Map;for(const y of m.cells){const _=We(d,y.cell.padding),X={top:_.top*this.PX_TO_PT,right:_.right*this.PX_TO_PT,bottom:_.bottom*this.PX_TO_PT,left:_.left*this.PX_TO_PT},O=M(y)-X.left-X.right,K=this.extractCellBlocks(y.cell);let W=this.FONT_SIZES.normal*this.LINE_HEIGHT_MULTIPLIERS.paragraph;if(K.length>0){const A=await import("./jspdf.es.min-DlTF8uTw.js").then(Z=>Z.j),z=A.jsPDF??A.default,U=new z({orientation:"portrait",unit:"pt",format:[Math.max(72,O),this.UNBOUNDED_CELL_FLOW_BOTTOM_PT]});await this.registerCurrentPdfFonts(U,l);const Y={...n,keepFirstBlockDeclaredSpaceBefore:!0,pageWidthPt:Math.max(72,O),pageHeightPt:this.UNBOUNDED_CELL_FLOW_BOTTOM_PT,marginTopPt:0,marginRightPt:0,marginBottomPt:0,marginLeftPt:0,contentWidthPt:Math.max(1,O)};W=(await this.renderBodyBlocks(U,K,Y,o,l,r,void 0,void 0,void 0,0)).finalY}const L=X.top+W+X.bottom;I.set(y.cell.id,{blocks:K,width:O,flowHeight:W,contentHeight:L,pad:X})}const u=e.children.map((y,_)=>{let X=0;for(const O of y.children){const K=m.byId.get(O.id);K&&K.rowSpan>1||(X=Math.max(X,I.get(O.id)?.contentHeight??0))}return X}),p=m.cells.filter(y=>y.rowSpan>1).sort((y,_)=>y.rowSpan-_.rowSpan);for(const y of p){const _=I.get(y.cell.id);if(!_)continue;let X=0;for(let O=y.row;O<y.row+y.rowSpan;O++)X+=u[O];_.contentHeight>X&&(u[y.row+y.rowSpan-1]+=_.contentHeight-X)}const S=y=>{let _=0;for(let X=y.row;X<y.row+y.rowSpan;X++)_+=u[X];return _},w=[],C=()=>{if(w.length===0)return;const y=this.getPdfCurrentPage(t);for(const{page:_,draw:X}of w)t.setPage(_),X();w.length=0,t.setPage(y)},D=(y,_,X,O,K,W,L)=>{const A=y.backgroundColor?this.hexToRgb(y.backgroundColor):L?{r:249,g:250,b:251}:{r:255,g:255,b:255};(y.backgroundColor||L)&&(t.setFillColor(A.r,A.g,A.b),t.rect(X,K,O,W,"F"));const z=this.getPdfCurrentPage(t),U=ca(y.borders);if(T||U){const Y=ha({tableBorders:T,cellBorders:U,flags:{isTopRow:(_?.row??0)===0,isBottomRow:_?_.row+_.rowSpan===m.rows:!1,isLeftCol:(_?.col??0)===0,isRightCol:_?_.col+_.colSpan===m.cols:!1},fallback:{style:"single",width:g,color:P}}),Z=X+O,q=K+W;w.push({page:z,draw:()=>{this.drawPdfBorderEdge(t,Y.top,X,K,Z,K),this.drawPdfBorderEdge(t,Y.bottom,X,q,Z,q),this.drawPdfBorderEdge(t,Y.left,X,K,X,q),this.drawPdfBorderEdge(t,Y.right,Z,K,Z,q)}})}else g>0&&w.push({page:z,draw:()=>{t.setDrawColor(c.r,c.g,c.b),t.setLineWidth(g*this.PX_TO_PT),t.rect(X,K,O,W,"S")}})},V=async(y,_,X,O)=>{const K=!!e.hasHeader&&_===0,W=u[_],L=this.getPdfCurrentPage(t);for(const A of y.children){t.setPage(L);const z=m.byId.get(A.id),U=B+(z?v[z.col]:0),Y=z?M(z):F/x,Z=O||!z?W:S(z);D(A,z,U,Y,X,Z,K);const q=I.get(A.id),ot=q?.blocks??this.extractCellBlocks(A),Q=q?.pad.left??f,rt=q?.pad.right??f,lt=q?.pad.top??f,ct=q?.pad.bottom??f,et=q?.width??Y-Q-rt,nt=q?.flowHeight??this.FONT_SIZES.normal*this.LINE_HEIGHT_MULTIPLIERS.paragraph,ft=Math.max(0,Z-lt-ct-nt),ut=A.verticalAlign==="bottom"?ft:A.verticalAlign==="middle"?ft/2:0,Ot=X+lt+ut;if(ot.length>0){const Ct={...n,keepFirstBlockDeclaredSpaceBefore:!0,columnCount:1,columnFlow:void 0,marginTopPt:Ot,marginRightPt:Math.max(0,n.pageWidthPt-(U+Q+et)),marginBottomPt:n.pageHeightPt-this.UNBOUNDED_CELL_FLOW_BOTTOM_PT,marginLeftPt:U+Q,pageMarginLeftPt:U+Q,contentWidthPt:Math.max(1,et),fullContentWidthPt:Math.max(1,et),columnStridePt:Math.max(1,et)};await this.renderBodyBlocks(t,ot,Ct,o,l,r,void 0,void 0,void 0,Ot)}}t.setPage(L)},k=(y,_)=>y.idx!==_.idx?y.idx>_.idx?y:_:y.y>=_.y?y:_,R=async(y,_,X,O,K,W)=>{const L=I.get(_.id),A=L?.blocks??this.extractCellBlocks(_),z=L?.pad.left??f,U=L?.pad.bottom??f,Y=X?M(X):F/x,Z=L?.width??Y-z-(L?.pad.right??f),q=X?v[X.col]:0;let ot=O.idx;if(A.length===0){const nt=L?.flowHeight??this.FONT_SIZES.normal*this.LINE_HEIGHT_MULTIPLIERS.paragraph;return{idx:ot,y:Math.min(W,O.y+nt+U)}}const Q=(nt,ft)=>{const ut=nt.left+q+z;ft.marginTopPt=nt.top,ft.marginLeftPt=ut,ft.pageMarginLeftPt=ut,ft.marginRightPt=Math.max(0,n.pageWidthPt-(ut+Z))},rt={...n,keepFirstBlockDeclaredSpaceBefore:!0,columnCount:1,columnFlow:void 0,marginBottomPt:n.pageHeightPt-W,reservedInsetForPage:void 0,contentWidthPt:Math.max(1,Z),fullContentWidthPt:Math.max(1,Z),columnStridePt:Math.max(1,Z)},lt=K(ot);Q(lt,rt),y.setPage(lt.page);const ct=y.addPage;y.addPage=()=>{ot+=1;const nt=K(ot);return Q(nt,rt),y.setPage(nt.page),y};let et=O.y;try{et=(await this.renderBodyBlocks(y,A,rt,o,l,r,void 0,void 0,void 0,O.y)).finalY}finally{y.addPage=ct}return{idx:ot,y:Math.min(W,et+U)}},G=async(y,_,X)=>{const O=h,K=H&&y>0?u[0]:0,W=n.marginTopPt+K,L=await import("./jspdf.es.min-DlTF8uTw.js").then($=>$.j),A=L.jsPDF??L.default,z=new A({orientation:n.orientation,unit:"pt",format:[n.pageWidthPt,n.pageHeightPt]});await this.registerCurrentPdfFonts(z,l);const U=z.addPage.bind(z),Y=[{page:1,top:n.marginTopPt,left:B}],Z=$=>{for(;Y.length<=$;)U(),Y.push({page:Y.length+1,top:W,left:B});return Y[$]},q=($,at)=>{let{idx:pt,y:ht}=$,gt=at;for(;;){const mt=Math.max(0,O-ht);if(gt<=mt+.01)return{idx:pt,y:ht+gt};gt-=mt,pt+=1,ht=W}},ot=[],Q=[],rt=new Map,lt=[];let ct={idx:0,y:X};for(let $=y;$<_;$++){const at=ct;ot[$-y]=at;for(const gt of e.children[$].children){const mt=m.byId.get(gt.id),xt=I.get(gt.id)?.pad.top??f,kt=at.y+xt>O+.01?{idx:at.idx+1,y:W+xt}:{idx:at.idx,y:at.y+xt};rt.set(gt.id,kt);const Tt=await R(z,gt,mt,kt,Z,O),yt=Math.min(_-1,$+(mt?.rowSpan??1)-1),_t=lt[yt-y];lt[yt-y]=_t?k(_t,Tt):Tt}const pt=q(at,u[$]),ht=lt[$-y];ct=ht?k(pt,ht):pt,Q[$-y]=ct}let et=ct.idx;for(const $ of rt.values())et=Math.max(et,$.idx);et=Math.max(et,Y.length-1);const nt=[{page:this.getPdfCurrentPage(t),top:n.marginTopPt,left:B}],ft=t.addPage,ut=()=>{const $=this.advancePdfFlowRegion(t,n);return B=$.x+b,{page:this.getPdfCurrentPage(t),top:$.y+K,left:B}};for(let $=1;$<=et;$++){const at=ut();nt.push(at),K>0&&await V(e.children[0],0,at.top-K,!0)}const Ot=$=>{for(;nt.length<=$;){const at=t.addPage;t.addPage=ft;try{nt.push(ut())}finally{t.addPage=at}}return nt[$]};for(let $=y;$<_;$++){const at=!!e.hasHeader&&$===0;for(const pt of e.children[$].children){const ht=m.byId.get(pt.id),gt=Math.min(_-1,$+(ht?.rowSpan??1)-1),mt=ot[$-y],xt=Q[gt-y],kt=ht?M(ht):F/x;for(let Tt=mt.idx;Tt<=xt.idx;Tt++){const yt=nt[Tt],_t=Tt===mt.idx?mt.y:yt.top,Wt=Tt===xt.idx?xt.y:O;Wt-_t<=.01||(t.setPage(yt.page),D(pt,ht,yt.left+(ht?v[ht.col]:0),kt,_t,Wt-_t,at))}}}for(let $=y;$<_;$++)for(const at of e.children[$].children)await R(t,at,m.byId.get(at.id),rt.get(at.id),Ot,O);const Ct=Q[Q.length-1],At=nt[Math.min(Ct.idx,nt.length-1)];return t.setPage(At.page),B=At.left,Ct.y},H=e.hasHeader===!0&&e.children.length>1&&!m.cells.some(y=>y.row===0&&y.rowSpan>1),j=e.children.map(()=>[]);for(const y of m.cells)j[y.row]?.push(y);for(let y=0;y<e.children.length;){let _=y+1,X=0;for(let L=y;L<_;L++){X+=u[L];for(const A of j[L])_=Math.min(e.children.length,Math.max(_,A.row+A.rowSpan))}const O=H&&y>0?u[0]:0,K=h-n.marginTopPt-O,W=X>K;if((W?s>=h-.01:s+X>h)&&s!==n.marginTopPt){const L=this.advancePdfFlowRegion(t,n);s=L.y,B=L.x+b,H&&y>0&&(await V(e.children[0],0,s,!0),s+=u[0])}if(W)s=await G(y,_,s);else for(let L=y;L<_;L++)await V(e.children[L],L,s,!1),s+=u[L];y=_}return C(),s}static async renderCodeBlock(t,e,a,i,r,o=this.MARGIN_LEFT,l=It,n=!1,h=this.getDefaultPdfLayoutMetrics(),s){const g=o-h.marginLeftPt;let P=o;const c=e.language||"",d=He(c);if(d&&e.renderDiagram!==!1&&d)return this.renderDiagramCodeBlock(t,e,a,i,r,P,d,l,n,h);const f=n?"SourceCodePro":"courier",T=e.content||"",m=c?await Ge(T,c,l):null,x=dt.fontSizePx*this.PX_TO_PT,F=x*dt.lineHeightMultiplier,b=dt.paddingPx*this.PX_TO_PT,B=dt.borderRadiusPx*this.PX_TO_PT,N=this.hexToRgb(l.background),v=this.hexToRgb(l.default);t.setFont(f,"normal"),t.setFontSize(x);const M=Math.max(1,i-b*2),I=te(T,k=>t.getTextWidth(k),M),u=[];let p=0;for(const k of m??[])u.push({start:p,end:p+k.text.length,color:k.color}),p+=k.text.length;const S=k=>{if(u.length===0)return[{text:k.text,color:l.default}];const R=[];for(const G of u){const H=Math.max(k.startCharOffset,G.start),j=Math.min(k.endCharOffset,G.end);j<=H||R.push({text:T.slice(H,j),color:G.color})}return R.length>0?R:[{text:k.text,color:l.default}]};let w=a,C=0,D=r;const V=()=>{const k=this.advancePdfFlowRegion(t,h);w=k.y,P=k.x+g,D=this.getPdfFlowBottom(t,h)};for(;C<I.length;){const k=C===0,R=k?b:0,G=R+F+(I.length===C+1?b:0);w+G>D&&w!==h.marginTopPt&&V();let H=C,j=R;for(;H<I.length;){const _=H===I.length-1,X=j+F+(_?b:0);if(w+X>D&&H>C)break;j+=F,H+=1}const y=H===I.length;y&&(j+=b),t.setFillColor(N.r,N.g,N.b),k&&y?this.drawRoundedRect(t,P,w,i,j,B):t.rect(P,w,i,j,"F"),t.setFont(f,"normal"),t.setFontSize(x);for(let _=C;_<H;_++){const X=_===0,O=_===I.length-1,K=w+R+(_-C)*F;s?.push({pageNumber:t.getCurrentPageInfo?.().pageNumber??t.getNumberOfPages(),y:K-(X?b:0),height:F+(X?b:0)+(O?b:0)});let W=P+b;const L=w+R+(_-C)*F+x;for(const A of S(I[_])){const z=A.color?this.hexToRgb(A.color):v;t.setTextColor(z.r,z.g,z.b),A.text&&t.text(A.text,W,L),W+=t.getTextWidth(A.text)}}w+=j,C=H,y||V()}return w}static async renderDiagramCodeBlock(t,e,a,i,r,o,l,n,h,s){const g=o-s.marginLeftPt;let P=o;const c=dt.paddingPx*this.PX_TO_PT,d=dt.diagramSourceGapPx*this.PX_TO_PT,f=ee(),T=Math.max(120,Math.round((i-c*2)/this.PX_TO_PT)),m=await Ue({protocol:l,source:e.content||"",theme:f,maxWidth:T}),x=Math.max(1,m.width*this.PX_TO_PT),F=Math.max(dt.diagramMinHeightPx,m.height)*this.PX_TO_PT,b=F+c*2,B=e.showDiagramSource!==!1,N=h?"SourceCodePro":"courier",v=dt.fontSizePx*this.PX_TO_PT;t.setFont(N,"normal"),t.setFontSize(v);const M=te(e.content||"",R=>t.getTextWidth(R),Math.max(1,i-c*2)),I=c*2+M.length*v*dt.lineHeightMultiplier,u=(B?I+d:0)+b;let p=a;if(p+u>r&&p!==s.marginTopPt){const R=this.advancePdfFlowRegion(t,s);p=R.y,P=R.x+g}B&&(p=await this.renderCodeBlock(t,{...e,renderDiagram:!1},p,i,r,P,n,h,s),p+=d);const S=this.hexToRgb(f.codeBorder||"#e0e0e0"),w=dt.borderRadiusPx*this.PX_TO_PT;t.setDrawColor(S.r,S.g,S.b),t.setLineWidth(this.BLOCK_BORDER_WIDTH_PT),this.drawRoundedRect(t,P,p,i,b,w,"S");const C=Math.min(i-c*2,x),D=Math.min(b-c*2,F),V=P+(i-C)/2,k=p+(b-D)/2;if(m.svg){const R=await this.svgToPng(m.svg,Math.max(1,Math.round(m.width)),Math.max(1,Math.round(m.height)),2);if(R)return t.addImage(R,"PNG",V,k,C,D),p+b}return t.setTextColor(220,38,38),t.setFont("helvetica","normal"),t.setFontSize(10),t.text("Diagram unavailable",P+c,p+c+10),p+b}static renderCellParagraph(t,e,a,i,r,o,l=!1){const n=this.getParagraphFontSize(e),h=this.getParagraphDirection(e),s=this.getEffectiveParagraphAlignment(e,h),g=this.getLineSpacingMultiplier(e),P=this.processTextNodes(e.children);let c=i,d=[],f=0;const T=m=>{d.length!==0&&(l?c+=this.measureLineAdvancePt(d,n,!!e.heading,g):c=this.renderLine(t,d,c,a,r,s,n,o,!!e.heading,g,m,{direction:h}),d=[],f=0)};for(const m of P){this.setRunFont(t,m,o),t.setFontSize(this.getRunEffectiveFontSizePt(m.marks,n));const x=m.text.split(`
4
+ `);for(let F=0;F<x.length;F++){F>0&&T(!1);const b=x[F].split(/(\s+)/);for(const B of b){const N=this.measureRunDisplayWidthPt(t,B,m.marks);f+N>r&&d.length>0&&T(!1),(B.trim()||d.length>0)&&(d.push({text:B,marks:m.marks,font:m.marks?.fontFamily}),f+=N)}}}return T(!0),c===i&&(c+=this.getEmptyParagraphLineHeight(e)),c}static extractCellBlocks(t){return t.children}static drawRoundedRect(t,e,a,i,r,o,l="F"){const n=Math.min(o,i/2,r/2);t.roundedRect(e,a,i,r,n,n,l)}static getListIndentPt(t){switch(t){case"todo":return this.TODO_LIST_INDENT_PT;case"ordered":return this.ORDERED_LIST_INDENT_PT;case"unordered":default:return this.UNORDERED_LIST_INDENT_PT}}static getListIndentLevel(t){const e=t.indentLevel??0;if(!Number.isFinite(e))return 0;const a=Math.floor(e);return Math.max(0,Math.min(a,this.MAX_LIST_INDENT_LEVEL))}static computeOrderedMarkerLabel(t,e,a,i){return ze(t,a,e,i)}static getRunLetterSpacingPt(t){return(typeof t?.letterSpacing=="number"&&Number.isFinite(t.letterSpacing)?t.letterSpacing:0)*this.PX_TO_PT}static getRunEffectiveFontSizePt(t,e){const a=t?.fontSize?t.fontSize*this.PX_TO_PT:e;return t?.superscript||t?.subscript?Math.round(a/this.PX_TO_PT*.7)*this.PX_TO_PT:a}static setRunFont(t,e,a){if(e.marks?.code){t.setFont(this.inlineCodeFontFamily,"normal");return}const i=this.mapFontFamily(e.font||e.marks?.fontFamily||a),r=this.resolveFontStyle(e.marks),o=this.scriptFallbackFor(t,e.text,i);if(o){t.setFont(o,r==="bold"||r==="bolditalic"?"bold":"normal");return}t.setFont(i,r)}static measureRunDisplayWidthPt(t,e,a){const i=o=>{const l=t.getFont?.()?.fontName,n=l?this.shapingFonts.get(l):void 0;return n?n.layout(o).advanceWidth*t.getFontSize()/n.unitsPerEm:t.getTextWidth(o)},r=Ke(a);return r?Ut(e,{...r,letterSpacingPx:this.getRunLetterSpacingPt(a)},i):i(e)}static drawShapedText(t,e,a,i,r,o,l){const n=t.getFont?.()?.fontName,h=n?this.shapingFonts.get(n):void 0;if(!h)return null;const s=h.layout(e);Array.from(e).every(f=>(f.codePointAt(0)??0)<=65535)&&t.text(e,a,i,{renderingMode:"invisible"}),t.setFillColor(l.r,l.g,l.b);const g=r/h.unitsPerEm;let P=0,c=0,d=0;for(let f=0;f<s.glyphs.length;f++){const T=s.glyphs[f],m=s.positions[f],x=[];let F=0,b=0;const B=v=>a+d+(P+m.xOffset+v)*g,N=v=>i-(c+m.yOffset+v)*g;for(const v of T.path.commands)if(v.command==="moveTo")[F,b]=v.args,x.push({op:"m",c:[B(F),N(b)]});else if(v.command==="lineTo")[F,b]=v.args,x.push({op:"l",c:[B(F),N(b)]});else if(v.command==="bezierCurveTo"){const[M,I,u,p,S,w]=v.args;x.push({op:"c",c:[B(M),N(I),B(u),N(p),B(S),N(w)]}),F=S,b=w}else if(v.command==="quadraticCurveTo"){const[M,I,u,p]=v.args,S=F+(M-F)*2/3,w=b+(I-b)*2/3,C=u+(M-u)*2/3,D=p+(I-p)*2/3;x.push({op:"c",c:[B(S),N(w),B(C),N(D),B(u),N(p)]}),F=u,b=p}else v.command==="closePath"&&x.push({op:"h",c:[]});x.length>0&&(t.path(x),t.fill()),P+=m.xAdvance,c+=m.yAdvance,d+=o*Math.max(1,T.codePoints?.length??1)}return s.advanceWidth*r/h.unitsPerEm+o*[...e].length}static renderLine(t,e,a,i,r,o,l,n,h,s,g=!0,P){e=e.filter(u=>!u.marks?.hidden||!!u.marks.footnoteRef);let c=P?.tabLayoutPx;const d=u=>u.marks?.fontSize?u.marks.fontSize*this.PX_TO_PT:l,f=P?.direction??"ltr";if(!c&&e.length>0&&!e.some(u=>u.latexImage||u.marks?.latex)){const u=e,p={segments:u.map(w=>({text:w.text}))},S=ae(p,f);if(S){const w=(D,V)=>{let k=0,R=0;for(const G of u){const H=Math.max(D,R),j=Math.min(V,R+G.text.length);if(H<j){const y=G.text.slice(H-R,j-R);this.setRunFont(t,{...G,text:y},n),t.setFontSize(this.getRunEffectiveFontSizePt(G.marks,l)),k+=this.measureRunDisplayWidthPt(t,y,G.marks)}R+=G.text.length}return k},C=u.map(D=>D.text).join("");e=ie(p,S,w,o==="justify"&&!g).map(D=>({...u[D.segmentIndex],text:C.slice(D.start,D.end),rtl:D.rtl}))}}if(P?.tabRtl&&c&&c.length>0){const u=e,p=c,S=[],w=[];let C=0;for(;C<u.length;){const D=u[C];if(D.text===" "){S.push(D),w.push(p[C]??{startX:0,endX:0}),C++;continue}const V=C;let k=Number.NEGATIVE_INFINITY;for(;C<u.length&&u[C].text!==" ";){const O=p[C];O&&(k=Math.max(k,O.endX)),C++}const R=u.slice(V,C),G=R.map(O=>O.text).join("");if(!G)continue;Number.isFinite(k)||(k=0);const H={segments:R.map(O=>({text:O.text}))},j=ae(H,"rtl");if(!j){for(let O=V;O<C;O++)S.push(u[O]),w.push(p[O]??{startX:0,endX:0});continue}const y=ie(H,j,(O,K)=>{let W=0,L=0;for(const A of R){const z=Math.max(O,L),U=Math.min(K,L+A.text.length);if(z<U){const Y=A.text.slice(z-L,U-L);this.setRunFont(t,{...A,text:Y},n),t.setFontSize(this.getRunEffectiveFontSizePt(A.marks,l)),W+=this.measureRunDisplayWidthPt(t,Y,A.marks)}L+=A.text.length}return W}),_=y.reduce((O,K)=>O+K.width,0),X=k*this.PX_TO_PT-_;for(const O of y)S.push({...R[O.segmentIndex],text:G.slice(O.start,O.end),rtl:O.rtl}),w.push({startX:(X+O.x)/this.PX_TO_PT,endX:(X+O.x+O.width)/this.PX_TO_PT})}e=S,c=w}let T=0,m=0;for(const u of e)if(u.latexImage){const p=u.latexImage.contentHeight*this.PX_TO_PT;p>m&&(m=p)}else{const p=d(u);p>T&&(T=p)}T===0&&(T=l);const x=a+T;let F=0;if(c&&c.length>0)F=P?.tabRtl?(P.tabWidthPx??Math.max(...c.map(u=>u.endX)))*this.PX_TO_PT:c[c.length-1].endX*this.PX_TO_PT;else for(const u of e)u.latexImage?F+=u.latexImage.contentWidth*this.PX_TO_PT:(this.setRunFont(t,u,n),t.setFontSize(this.getRunEffectiveFontSizePt(u.marks,l)),F+=this.measureRunDisplayWidthPt(t,u.text,u.marks));let b=i;o==="center"?b=i+(r-F)/2:(o==="right"||o==="justify"&&f==="rtl"&&(g||c))&&(b=i+r-F),P?.tabRtl&&c&&(b=i);let B=0;if(o==="justify"&&!g&&!c){let u=0;for(const p of e)p.latexImage||p.marks?.latex||(u+=(p.text.match(/ /g)||[]).length);u>0&&(B=Math.max(0,(r-F)/u))}const N=b;for(let u=0;u<e.length;u++){const p=e[u],S=c?.[u];if(S&&(b=N+S.startX*this.PX_TO_PT,p.text===" ")){if(S.leader){const W=this.getRunEffectiveFontSizePt(p.marks,l),L=p.marks?.color?this.hexToRgb(p.marks.color):{r:0,g:0,b:0};this.renderTabLeaderPdf(t,N+S.startX*this.PX_TO_PT,N+S.endX*this.PX_TO_PT,x,S.leader,W,L)}b=N+S.endX*this.PX_TO_PT;continue}if(p.latexImage){const W=p.latexImage.width*this.PX_TO_PT,L=p.latexImage.height*this.PX_TO_PT,A=p.latexImage.contentWidth*this.PX_TO_PT,z=p.latexImage.contentHeight*this.PX_TO_PT,U=(W-A)/2,Y=b-U,Z=x-z*.7-U;try{t.addImage(p.latexImage.dataUrl,"PNG",Y,Z,W,L)}catch(q){console.error("Failed to add inline latex image to PDF:",q)}b+=A;continue}this.setRunFont(t,p,n);const w=d(p),C=this.getRunEffectiveFontSizePt(p.marks,l),D=C/this.PX_TO_PT;t.setFontSize(C);const V=!!p.marks?.link;let k={r:0,g:0,b:0};V?k={r:37,g:99,b:235}:p.marks?.color?k=this.hexToRgb(p.marks.color):p.marks?.code&&(k=this.hexToRgb(Lt.codeText)),t.setTextColor(k.r,k.g,k.b);const R=!!(p.marks?.smallCaps&&!p.marks?.allCaps),G=this.getRunLetterSpacingPt(p.marks),H=p.rtl?{isInputVisual:!1,isOutputVisual:!0,isInputRtl:!0,isOutputRtl:!1}:void 0,j=G!==0||H?{...G!==0?{charSpace:G}:{},...H}:void 0,y=this.measureRunDisplayWidthPt(t,p.text,p.marks),_=B>0?(p.text.match(/ /g)||[]).length:0,X=y+_*B;if(p.marks?.backgroundColor){const W=je(p.marks.backgroundColor)??p.marks.backgroundColor,L=this.hexToRgb(W);t.setFillColor(L.r,L.g,L.b),t.rect(b,x-w*.8,X,w*1.1,"F"),t.setTextColor(k.r,k.g,k.b)}else if(p.marks?.code){const W=this.hexToRgb(Lt.codeBackground);t.setFillColor(W.r,W.g,W.b),this.drawRoundedRect(t,b-2*this.PX_TO_PT,x-w*.93,X+4*this.PX_TO_PT,w+4*this.PX_TO_PT,3*this.PX_TO_PT),t.setTextColor(k.r,k.g,k.b)}let O=x;p.marks?.superscript?O=x-w*.4:p.marks?.subscript&&(O=x+w*.15),(p.marks?.underline||V)&&!p.marks?.code&&(V?t.setDrawColor(37,99,235):t.setDrawColor(0,0,0),t.setLineWidth(.5),t.line(b,O+2,b+X,O+2));const K=(W,L)=>{const A=p.marks?.allCaps?Xt(W,p.marks.lang):W,z=this.drawShapedText(t,A,L,O,C,G,k);if(z!==null)return z;if(R){let U=L;for(const Y of la(W,p.marks?.lang)){const Z=Y.lower?t.getTextWidth(Xt(Y.text,p.marks?.lang))*oe:t.getTextWidth(Y.text);Y.lower?(t.setFontSize(C*oe),t.text(Xt(Y.text,p.marks?.lang),U,O,j),t.setFontSize(C)):t.text(Y.text,U,O,j),U+=Z+G*Y.text.length}return U-L}return t.text(A,L,O,j),this.measureRunDisplayWidthPt(t,W,p.marks)};if(B>0){let W=b;for(const L of p.text.split(/( +)/))L&&(W+=K(L,W),L[0]===" "&&(W+=B*L.length))}else K(p.text,b);if(p.marks?.strikethrough||p.marks?.doubleStrikethrough){t.setDrawColor(k.r,k.g,k.b),t.setLineWidth(Math.max(1,Math.round(D*.04))*this.PX_TO_PT);const W=L=>{const A=L-C*.3;t.line(b,A,b+X,A)};p.marks?.doubleStrikethrough?(W(O+C*.09),W(O-C*.09)):W(O)}if(V&&p.marks?.link){const W=x-w*.8,L=w*1.1;t.link(b,W,X,L,{url:p.marks.link})}b+=X}if(P?.hyphenTrailing){const u=e[e.length-1];if(u&&!u.marks?.latex){this.setRunFont(t,u,n),t.setFontSize(this.getRunEffectiveFontSizePt(u.marks,l));const p=u.marks?.color?this.hexToRgb(u.marks.color):{r:0,g:0,b:0};t.setTextColor(p.r,p.g,p.b),t.text("-",b,x)}}const v=s??(h?this.LINE_HEIGHT_MULTIPLIERS.heading:this.LINE_HEIGHT_MULTIPLIERS.paragraph),M=T*v,I=m>M*1.25?m:M;return a+I}static renderTabLeaderPdf(t,e,a,i,r,o,l){const n=Math.max(1.5,o*.12),h=e+n,s=a-n;if(s-h<1)return;if(t.setFillColor(l.r,l.g,l.b),r==="underscore"){const P=i+Math.max(1,o*.08),c=Math.max(.75,o*.055);t.rect(h,P,s-h,c,"F");return}const g=Math.max(2.25,o*.33);if(r==="dot"){const P=Math.max(.45,o*.045),c=i-P;for(let d=Math.ceil(h/g)*g;d<=s;d+=g)t.circle(d,c,P,"F")}else{const P=Math.max(1.5,o*.18),c=i-o*.28,d=Math.max(.75,o*.055);for(let f=Math.ceil(h/g)*g;f+P<=s;f+=g)t.rect(f,c,P,d,"F")}}static processTextNodes(t){const e=[];for(const a of t)if(a.type==="text"){const i=a;if(i.marks?.hidden&&!i.marks.footnoteRef)continue;e.push({text:i.text,marks:i.marks,font:i.marks?.fontFamily})}return e}static async processTextNodesWithLatex(t,e){const a=[];for(let o=0;o<t.length;o++){const l=t[o];if(l.type==="text"){const n=l;if(n.marks?.hidden&&!n.marks.footnoteRef)continue;n.marks?.latex?a.push({index:o,node:n,latexPromise:this.renderLatexToImage(n.text,!1,e)}):a.push({index:o,node:n})}}const i=await Promise.all(a.map(o=>o.latexPromise||Promise.resolve(null))),r=[];for(let o=0;o<a.length;o++){const{node:l}=a[o],n=i[o];r.push({text:l.text,marks:l.marks,font:l.marks?.fontFamily,latexImage:n||void 0})}return r}static getParagraphFontSize(t){return Ye(t)*this.PX_TO_PT}static getParagraphLineHeight(t){return this.getParagraphFontSize(t)*Qt(t)}static getEmptyParagraphLineHeight(t){return this.measureLineAdvancePt(this.paragraphForPdfOutput(t).children.map(e=>({marks:e.type==="text"?e.marks:void 0})),this.getParagraphFontSize(t),!!t.heading,this.getLineSpacingMultiplier(t))}static async embedLocalFonts(t,e){if(this.embeddedFamilyNames.clear(),typeof window>"u")return;const a=new Set(["sans-serif","sans","serif","monospace","system-ui","system ui","ui-sans-serif","ui-serif","ui-monospace"]),i=Nt(e).map(o=>o.family).filter(o=>{const l=o.toLowerCase();return!a.has(l)&&this.FONT_MAP[l]!=="KaTeX_Main"});if(i.length===0)return;let r;for(const o of i){const l=o.toLowerCase();let n=this.localFontFiles.get(l);if(n===void 0){if(r===void 0&&(r=await $e().catch(()=>null)),!r)return;try{n=await this.buildLocalFontFiles(o,r)}catch{n=null}this.localFontFiles.set(l,n)}if(n)try{for(const h of n)t.addFileToVFS(h.vfsName,h.base64),t.addFont(h.vfsName,o,h.style);this.embeddedFamilyNames.set(l,o)}catch(h){console.warn(`Failed to embed font "${o}" in PDF:`,h),this.localFontFiles.set(l,null)}}}static async buildLocalFontFiles(t,e){const a=t.toLowerCase(),i=e.filter(c=>c.family?.trim().toLowerCase()===a&&c.blob);if(i.length===0)return null;const r=i.map(c=>({entry:c,...Ve(c.style),specificity:(c.style??"").length})),o=(c,d)=>r.filter(f=>f.bold===c&&f.italic===d).sort((f,T)=>f.specificity-T.specificity)[0]?.entry,l=o(!1,!1)??r[0].entry,n=[{style:"normal",entry:l},{style:"bold",entry:o(!0,!1)??l},{style:"italic",entry:o(!1,!0)??l},{style:"bolditalic",entry:o(!0,!0)??o(!0,!1)??l}],h=new Map;for(const{entry:c}of n){if(h.has(c))continue;const d=await(await c.blob()).arrayBuffer(),f=Ht(new Uint8Array(d));h.set(c,f==="ttf"?this.arrayBufferToBase64(d):null)}if(!h.get(l))return null;const s=a.replace(/[^a-z0-9]+/g,"-"),g=new Map;let P=0;return n.map(({style:c,entry:d})=>{const f=h.get(d)?d:l;let T=g.get(f);return T||(T=`${s}-${P++}.ttf`,g.set(f,T)),{vfsName:T,base64:h.get(f),style:c}})}static mapFontFamily(t){const e=this.mapFontFamilyToStandard(t);return this.bundledGenreFamilies.get(e)??(e==="SourceSerif4"?"times":e)}static mapFontFamilyToStandard(t){if(!t)return"helvetica";const e=new Set(["helvetica","times","courier"]),a=t.split(",").map(r=>r.trim().replace(/^['"]|['"]$/g,"")).filter(r=>r.length>0);a.length===0&&a.push(t);for(const r of a){const o=r.toLowerCase(),l=this.embeddedFamilyNames.get(o);if(l)return l;if(e.has(o))return o;const n=this.FONT_MAP[o];if(n)return n}const i=Ze(a[0]);return i==="serif"?"times":i==="monospace"?"courier":"helvetica"}static resolveFontStyle(t){const e=!!t?.bold,a=!!t?.italic;return e&&a?"bolditalic":e?"bold":a?"italic":"normal"}static drawPdfBorderEdge(t,e,a,i,r,o){if(e.style==="none"||e.width<=0)return;const l=this.hexToRgb(e.color);t.setDrawColor(l.r,l.g,l.b);const n=Je(e).map(h=>h*this.PX_TO_PT);if(n.length>0&&typeof t.setLineDashPattern=="function"&&t.setLineDashPattern(n,0),e.style==="double"){const h=Math.max(e.width/3,.5)*this.PX_TO_PT,s=e.width*2/3/2*this.PX_TO_PT;t.setLineWidth(h);const g=i===o,P=g?0:s,c=g?s:0;t.line(a-P,i-c,r-P,o-c),t.line(a+P,i+c,r+P,o+c)}else t.setLineWidth(e.width*this.PX_TO_PT),t.line(a,i,r,o);n.length>0&&typeof t.setLineDashPattern=="function"&&t.setLineDashPattern([],0)}static hexToRgb(t){return qe(t)??{r:0,g:0,b:0}}static async renderImageBlock(t,e,a,i,r=this.getDefaultPdfLayoutMetrics()){if(!e.src)return{nextY:a};const o=this.getPdfFlowBottom(t,r);let l=Math.max(e.width||1,1)*this.PX_TO_PT,n=Math.max(e.height||1,1)*this.PX_TO_PT;if(l>i){const c=i/l;l=i,n*=c}(n<=0||!Number.isFinite(n))&&(n=72);let h=r.marginLeftPt;if(a+n>o&&a!==r.marginTopPt){const c=this.advancePdfFlowRegion(t,r);a=c.y,h=c.x}const s=e.align||"left";let g=h;if(s==="center"?g=h+(i-l)/2:s==="right"&&(g=h+i-l),e.originalFormat)return t.setFillColor(243,244,246),t.setDrawColor(209,213,219),t.setLineWidth(.75),t.rect(g,a,l,n,"FD"),t.setFont(this.mapFontFamily(void 0),"normal"),t.setFontSize(14*this.PX_TO_PT),t.setTextColor(107,114,128),t.text(`${e.originalFormat.toUpperCase()} image`,g+l/2,a+n/2,{align:"center",baseline:"middle"}),{nextY:a+n};const P=await this.resolveImageData(e.src);if(!P)return{nextY:a+n};try{t.addImage(P.data,P.format,g,a,l,n)}catch(c){return console.error("Failed to add image to PDF",c),{nextY:a+n}}return{nextY:a+n}}static async resolveImageData(t){const e=t.match(/^data:image\/([a-zA-Z0-9+.-]+);base64,/);if(e){const o=this.normalizeImageFormat(e[1]);return{data:t,format:o}}const a=await this.fetchImageAsBlob(t);if(!a)return null;const{blob:i,format:r}=a;return{data:await this.blobToDataUrl(i,r),format:r}}static async fetchImageAsBlob(t){try{const e=await fetch(t);if(!e.ok)throw new Error(`Failed to fetch image: ${e.status}`);const a=await e.blob(),i=this.extractImageFormat(a.type);return{blob:a,format:i}}catch(e){return console.error("Failed to load image for PDF export",e),null}}static async blobToDataUrl(t,e){const a=await t.arrayBuffer(),i=this.arrayBufferToBase64(a);return`data:${this.formatToMime(e)};base64,${i}`}static arrayBufferToBase64(t){const e=globalThis?.Buffer;if(e)return e.from(t).toString("base64");let a="";const i=new Uint8Array(t),r=32768;for(let o=0;o<i.length;o+=r){const l=i.subarray(o,o+r);a+=String.fromCharCode.apply(null,Array.from(l))}return btoa(a)}static formatToMime(t){const e=t.toLowerCase();return e==="jpeg"||e==="jpg"?"image/jpeg":e==="png"?"image/png":e==="webp"?"image/webp":`image/${e}`}static extractImageFormat(t){if(!t)return"PNG";const e=t.match(/^image\/([a-zA-Z0-9+.-]+)/);return e?this.normalizeImageFormat(e[1]):"PNG"}static normalizeImageFormat(t){const e=t.toLowerCase();return e==="jpg"||e==="jpeg"?"JPEG":e==="png"?"PNG":e==="webp"?"WEBP":e.toUpperCase()}static async renderMathBlock(t,e,a,i,r,o=this.getDefaultPdfLayoutMetrics()){if(!e.content||e.content.trim()==="")return{nextY:a};const l=e.displayMode!=="inline",n=await this.renderLatexToImage(e.content,l);if(!n)return{nextY:a+20};let h=n.width*this.PX_TO_PT,s=n.height*this.PX_TO_PT;const g=i-this.MATH_BLOCK_PADDING*2;if(h>g){const x=g/h;h=g,s*=x}const P=Math.max(this.MATH_BLOCK_MIN_HEIGHT,s)+this.MATH_BLOCK_PADDING*2;let c=o.marginLeftPt;if(a+P>r&&a!==o.marginTopPt){const x=this.advancePdfFlowRegion(t,o);a=x.y,c=x.x}const d=this.hexToRgb(ee().codeBorder||"#e0e0e0");t.setDrawColor(d.r,d.g,d.b),t.setLineWidth(this.BLOCK_BORDER_WIDTH_PT),typeof t.roundedRect=="function"?t.roundedRect(c,a,i,P,this.MATH_BLOCK_BORDER_RADIUS,this.MATH_BLOCK_BORDER_RADIUS,"S"):t.rect(c,a,i,P,"S");const f=e.align||"center";let T=c+this.MATH_BLOCK_PADDING;f==="center"?T=c+(i-h)/2:f==="right"&&(T=c+i-h-this.MATH_BLOCK_PADDING);const m=a+(P-s)/2;try{t.addImage(n.dataUrl,"PNG",T,m,h,s)}catch(x){console.error("Failed to add math image to PDF:",x)}return{nextY:a+P}}static async getHtml2Canvas(){return this.html2canvasModule?this.html2canvasModule:this.html2canvasLoading?this.html2canvasLoading:(this.html2canvasLoading=import("./html2canvas.esm-CntiHiYW.js").then(t=>(this.html2canvasModule=t.default,t.default)),this.html2canvasLoading)}static async renderLatexToImage(t,e,a=12){const i=this.getLatexSvgFromCache(t,e);if(i){const r=await this.svgToPng(i.svg,i.width,i.height,3);if(r){const o=e?1:this.INLINE_MATH_SCALE;return{dataUrl:r,width:i.width*o,height:i.height*o,contentWidth:i.contentWidth*o,contentHeight:i.contentHeight*o}}}try{const r=await this.getHtml2Canvas(),o=this.preprocessLaTeX(t),l=(await Qe()).renderToString(o,{displayMode:e,throwOnError:!1,errorColor:"#ef4444",trust:!1,strict:!1});this.ensureKaTeXStyles();const n=a/this.PX_TO_PT,h=e?20:n*this.INLINE_MATH_SCALE,s=4,g=document.createElement("div");g.style.cssText=`
5
+ position: fixed;
6
+ top: -9999px;
7
+ left: -9999px;
8
+ font-size: ${h}px;
9
+ line-height: 1.2;
10
+ background: transparent;
11
+ padding: ${s}px;
12
+ z-index: -9999;
13
+ `,g.innerHTML=l,document.body.appendChild(g),document.fonts?.ready&&await document.fonts.ready;const P=4,c=await r(g,{backgroundColor:null,scale:P,logging:!1,useCORS:!0,allowTaint:!1});document.body.removeChild(g);const d=c.toDataURL("image/png"),f=c.width/P,T=c.height/P,m=f-s*2,x=T-s*2;return{dataUrl:d,width:f,height:T,contentWidth:m,contentHeight:x}}catch(r){return console.error("Failed to render LaTeX for PDF:",r),null}}static preprocessLaTeX(t){if(!t.includes(`
14
+ `)||["align","aligned","gather","gathered","split","cases","matrix","pmatrix","bmatrix","array"].some(a=>t.includes(`\\begin{${a}}`)||t.includes(`\\begin{${a}*}`)))return t;const e=t.split(`
15
+ `).map(a=>a.trim()).filter(a=>a.length>0);return e.length<=1?t:`\\begin{gathered}
16
+ ${e.join(` \\\\
17
+ `)}
18
+ \\end{gathered}`}static ensureKaTeXStyles(){if(this.katexStylesLoaded)return;if(document.querySelector('link[href*="katex"]')){this.katexStylesLoaded=!0;return}const t=document.createElement("link");t.rel="stylesheet",t.href=Ft("katex.min.css"),document.head.appendChild(t),this.katexStylesLoaded=!0}static async parseFile(t){const e=await import("./pdf-BLWDCiFF.js");e.GlobalWorkerOptions.workerSrc=Ft("pdfjs/worker.js");const a=await t.arrayBuffer();try{const i=await e.getDocument(a).promise;let r="";for(let h=1;h<=i.numPages;h++){const s=(await(await i.getPage(h)).getTextContent()).items.map(g=>g.str).join(" ");r+=s+`
19
+
20
+ `}const o=r.trim().split(`
21
+ `),l=[];let n=[];for(let h=0;h<o.length;h++){const s=o[h].trim();if(s===""){if(n.length>0){const g=n.join(" ").trim();g&&l.push(wt([{type:"text",text:g}])),n=[]}}else{const g=s.length<60,P=s===s.toUpperCase()&&/[A-Z]/.test(s),c=/[.!?]$/.test(s),d=h+1<o.length&&o[h+1].trim()==="";if(g&&(P||d&&!c)){if(n.length>0){const f=n.join(" ").trim();f&&l.push(wt([{type:"text",text:f}])),n=[]}l.push(wt([{type:"text",text:s}]))}else n.push(s)}}if(n.length>0){const h=n.join(" ").trim();h&&l.push(wt([{type:"text",text:h}]))}return l.length===0&&l.push(wt()),{type:"doc",children:l}}catch(i){throw console.error("Failed to parse PDF:",i),new Error(`Failed to parse PDF: ${i instanceof Error?i.message:"Unknown error"}`)}}};E.PAGE_WIDTH=612,E.PAGE_HEIGHT=792,E.MARGIN_LEFT=72,E.MARGIN_RIGHT=72,E.MARGIN_TOP=72,E.MARGIN_BOTTOM=72,E.PX_TO_PT=re,E.UNBOUNDED_CELL_FLOW_BOTTOM_PT=1e4,E.DEFAULT_BODY_FONT="Arial, sans-serif",E.LINE_HEIGHT_MULTIPLIERS=se,E.FONT_SIZES={h1:bt.h1*E.PX_TO_PT,h2:bt.h2*E.PX_TO_PT,h3:bt.h3*E.PX_TO_PT,h4:bt.h4*E.PX_TO_PT,h5:bt.h5*E.PX_TO_PT,h6:bt.h6*E.PX_TO_PT,normal:bt.paragraph*E.PX_TO_PT},E.FONT_MAP={arial:"helvetica",helvetica:"helvetica","helvetica neue":"helvetica","times new roman":"times",georgia:"times","source serif 4":"SourceSerif4",times:"times",courier:"courier","courier new":"courier",monospace:"courier",verdana:"helvetica",tahoma:"helvetica",inter:"helvetica","system-ui":"helvetica","system ui":"helvetica","ui-sans-serif":"helvetica","ui-serif":"times","ui-monospace":"courier","sans-serif":"helvetica",sans:"helvetica",serif:"times",katex_main:"KaTeX_Main",computermodern:"KaTeX_Main","computer modern":"KaTeX_Main"},E.TODO_LIST_INDENT_PT=Pt.variantIndentPx.todo*E.PX_TO_PT,E.ORDERED_LIST_INDENT_PT=Pt.variantIndentPx.ordered*E.PX_TO_PT,E.UNORDERED_LIST_INDENT_PT=Pt.variantIndentPx.unordered*E.PX_TO_PT,E.SUBLIST_INDENT_PT=Pt.sublistIndentPx*E.PX_TO_PT,E.BULLET_MARKER_WIDTH_PT=Pt.markerWidthPx*E.PX_TO_PT,E.BULLET_CENTER_OFFSET_PT=8*E.PX_TO_PT,E.BULLET_RADIUS_PT=2.5*E.PX_TO_PT,E.BULLET_SQUARE_INSET_PT=5*E.PX_TO_PT,E.BULLET_SQUARE_HALF_PT=5*E.PX_TO_PT,E.BULLET_SQUARE_VERTICAL_ADJUST_PT=1*E.PX_TO_PT,E.ORDERED_LABEL_GAP_PT=6*E.PX_TO_PT,E.TODO_CHECKBOX_SIZE_PT=Pt.todoCheckboxSizePx*E.PX_TO_PT,E.TODO_CHECKBOX_RADIUS_PT=Pt.todoCheckboxRadiusPx*E.PX_TO_PT,E.TODO_CHECKBOX_OFFSET_PT=Pt.todoCheckboxOffsetPx*E.PX_TO_PT,E.MAX_LIST_INDENT_LEVEL=Pt.maxIndentLevel,E.MATH_BLOCK_PADDING=16*E.PX_TO_PT,E.MATH_BLOCK_MIN_HEIGHT=40*E.PX_TO_PT,E.MATH_BLOCK_BORDER_RADIUS=4*E.PX_TO_PT,E.BLOCK_BORDER_WIDTH_PT=1*E.PX_TO_PT,E.INLINE_MATH_SCALE=.85,E.BUNDLED_GENRE_FONTS={SourceSerif4:{family:"SourceSerif4",files:{normal:"SourceSerif4-Regular.ttf",bold:"SourceSerif4-Bold.ttf",italic:"SourceSerif4-It.ttf",bolditalic:"SourceSerif4-BoldIt.ttf"}},helvetica:{family:"LiberationSans",files:{normal:"LiberationSans-Regular.ttf",bold:"LiberationSans-Bold.ttf",italic:"LiberationSans-Italic.ttf",bolditalic:"LiberationSans-BoldItalic.ttf"}},times:{family:"LiberationSerif",files:{normal:"LiberationSerif-Regular.ttf",bold:"LiberationSerif-Bold.ttf",italic:"LiberationSerif-Italic.ttf",bolditalic:"LiberationSerif-BoldItalic.ttf"}},courier:{family:"LiberationMono",files:{normal:"LiberationMono-Regular.ttf",bold:"LiberationMono-Bold.ttf",italic:"LiberationMono-Italic.ttf",bolditalic:"LiberationMono-BoldItalic.ttf"}}},E.bundledGenreFamilies=new Map,E.SCRIPT_FALLBACK_FONTS=Pa,E.scriptFallbackFamilies=new Map,E.scriptFontCoverageCache=new Map,E.fallbackCharsetCache=new Map,E.shapingFonts=new Map,E.inlineCodeFontFamily="courier",E.fontFileData=new Map,E.localFontFiles=new Map,E.embeddedFamilyNames=new Map,E.COLUMN_BALANCE_SLACK_PT=1.5,E.html2canvasModule=null,E.html2canvasLoading=null,E.katexStylesLoaded=!1;let ua=E;export{ua as PdfConverter};
@@ -1,2 +1,2 @@
1
- import{a1 as re,T as ne,c1 as x,c2 as ae,c3 as se,aX as C,c4 as M,c5 as ie}from"./index-DyOcu9mD.js";import*as v from"yjs";const E=e=>new Promise(e);Promise.all.bind(Promise);const ce=e=>new Error(e),T=e=>E((t,o)=>{e.onerror=r=>o(new Error(r.target.error)),e.onsuccess=r=>t(r.target.result)}),de=(e,t)=>E((o,r)=>{const n=indexedDB.open(e);n.onupgradeneeded=a=>t(a.target.result),n.onerror=a=>r(ce(a.target.error)),n.onsuccess=a=>{const s=a.target.result;s.onversionchange=()=>{s.close()},o(s)}}),le=e=>T(indexedDB.deleteDatabase(e)),me=(e,t)=>t.forEach(o=>e.createObjectStore.apply(e,o)),_=(e,t,o="readwrite")=>{const r=e.transaction(t,o);return t.map(n=>Pe(r,n))},U=(e,t)=>T(e.count(t)),ue=(e,t)=>T(e.get(t)),j=(e,t)=>T(e.delete(t)),he=(e,t,o)=>T(e.put(t,o)),F=(e,t)=>T(e.add(t)),pe=(e,t,o)=>T(e.getAll(t,o)),fe=(e,t,o)=>{let r=null;return ye(e,t,n=>(r=n,!1),o).then(()=>r)},ge=(e,t=null)=>fe(e,t,"prev"),we=(e,t)=>E((o,r)=>{e.onerror=r,e.onsuccess=async n=>{const a=n.target.result;if(a===null||await t(a)===!1)return o();a.continue()}}),ye=(e,t,o,r="next")=>we(e.openKeyCursor(t,r),n=>o(n.key)),Pe=(e,t)=>e.objectStore(t),Ie=(e,t)=>IDBKeyRange.upperBound(e,t),be=(e,t)=>IDBKeyRange.lowerBound(e,t),L=()=>new Map,Te=(e,t,o)=>{let r=e.get(t);return r===void 0&&e.set(t,r=o()),r},ve=()=>new Set,_e=Array.from;class Ee{constructor(){this._observers=L()}on(t,o){Te(this._observers,t,ve).add(o)}once(t,o){const r=(...n)=>{this.off(t,r),o(...n)};this.on(t,r)}off(t,o){const r=this._observers.get(t);r!==void 0&&(r.delete(o),r.size===0&&this._observers.delete(t))}emit(t,o){return _e((this._observers.get(t)||L()).values()).forEach(r=>r(...o))}destroy(){this._observers=L()}}const $="custom",O="updates",R=500,z=(e,t=()=>{},o=()=>{})=>{const[r]=_(e.db,[O]);return pe(r,be(e._dbref,!1)).then(n=>{e._destroyed||(t(r),v.transact(e.doc,()=>{n.forEach(a=>v.applyUpdate(e.doc,a))},e,!1),o(r))}).then(()=>ge(r).then(n=>{e._dbref=n+1})).then(()=>U(r).then(n=>{e._dbsize=n})).then(()=>r)},De=(e,t=!0)=>z(e).then(o=>{(t||e._dbsize>=R)&&F(o,v.encodeStateAsUpdate(e.doc)).then(()=>j(o,Ie(e._dbref,!0))).then(()=>U(o).then(r=>{e._dbsize=r}))});class ke extends Ee{constructor(t,o){super(),this.doc=o,this.name=t,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=de(t,r=>me(r,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=E(r=>this.on("synced",()=>r(this))),this._db.then(r=>{this.db=r,z(this,n=>F(n,v.encodeStateAsUpdate(o)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(r,n)=>{if(this.db&&n!==this){const[a]=_(this.db,[O]);F(a,r),++this._dbsize>=R&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{De(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},o.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),o.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(t=>{t.close()})}clearData(){return this.destroy().then(()=>{le(this.name)})}get(t){return this._db.then(o=>{const[r]=_(o,[$],"readonly");return ue(r,t)})}set(t,o){return this._db.then(r=>{const[n]=_(r,[$]);return he(n,o,t)})}del(t){return this._db.then(o=>{const[r]=_(o,[$]);return j(r,t)})}}const Se="revise-anonymous-identity",xe=1,D="identities",N="pdf-browser-id",Fe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Le(){return new Promise((e,t)=>{const o=indexedDB.open(Se,xe);o.onupgradeneeded=()=>{o.result.objectStoreNames.contains(D)||o.result.createObjectStore(D)},o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error)})}async function A(){if(typeof window>"u"||typeof indexedDB>"u"||typeof crypto>"u"||typeof crypto.randomUUID!="function")return null;let e=null;try{return e=await Le(),await new Promise((t,o)=>{const r=e.transaction(D,"readwrite"),n=r.objectStore(D),a=n.get(N);let s="";a.onsuccess=()=>{const c=typeof a.result=="string"?a.result.trim().toLowerCase():"";s=Fe.test(c)?c:crypto.randomUUID(),s!==c&&n.put(s,N)},a.onerror=()=>o(a.error),r.oncomplete=()=>t(s),r.onerror=()=>o(r.error),r.onabort=()=>o(r.error)})}catch(t){return console.warn("Unable to load anonymous PDF browser identity:",t),null}finally{e?.close()}}const J="https://sync.revise-sdk.invalid";function K(){return J}function $e(){return J.replace(/^https/,"wss")}const B="yjs_document_index",Y="anon_session_id",G="yjs_document_deleted_",Ae="local-document-deleted";function W(e){return typeof window<"u"&&localStorage.getItem(G+e)==="1"}function X(){if(typeof window>"u")return[];try{const e=localStorage.getItem(B);return e?JSON.parse(e).filter(t=>!W(t)):[]}catch(e){return console.warn("Failed to read document index:",e),[]}}function Be(e){if(!(typeof window>"u"))try{if(W(e))return;const t=X();t.includes(e)||(t.push(e),localStorage.setItem(B,JSON.stringify(t)))}catch(t){console.warn("Failed to update document index:",t)}}function Ce(e){if(!(typeof window>"u"))try{localStorage.setItem(G+e,"1"),window.dispatchEvent(new CustomEvent(Ae,{detail:{documentId:e}}));const t=X().filter(o=>o!==e);localStorage.setItem(B,JSON.stringify(t))}catch(t){console.warn("Failed to remove from document index:",t)}}function Me(){const e="abcdefghijklmnopqrstuvwxyz0123456789";let t="";for(let o=0;o<8;o++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function q(){if(typeof window>"u")return"server";let e=localStorage.getItem(Y);return e||(e=crypto.randomUUID().replace(/-/g,"").slice(0,12),localStorage.setItem(Y,e)),e}const Ue=30*60*1e3,je=3e3,Oe=15e3,k=new Map;async function Re(e){const t=Me(),o=q(),r=`anon:${o}:${t}`,n=new v.Doc,a={children:[{type:"paragraph",id:re(),children:[{type:"text",text:"",marks:{}}]}]};ne(n,a),n.transact(()=>{const l=n.getMap("metadata");l.set("id",t),l.set("documentId",t),l.set("title",x(e)),l.set("createdAt",Date.now()),l.set("updatedAt",Date.now()),l.set("lastAccessedAt",Date.now()),l.set("storageType","local")});const s=new ke(t,n);await s.whenSynced;const c=await A(),i=$e(),u=c?`${i}${i.includes("?")?"&":"?"}anonymousBrowserId=${encodeURIComponent(c)}`:i;let p=null;const d=new Promise(l=>{p=l}),f=new ae({url:se(u),name:r,document:n,token:()=>"",onSynced:()=>{p?.()}});return ze(t,n,s,f),Be(t),await Promise.race([d,new Promise(l=>setTimeout(l,Oe))]),{docId:t,anonSessionId:o,anonymousBrowserId:c}}function ze(e,t,o,r){let n=null;const a=new Promise(d=>{n=d});let s=!1;const c=()=>{if(s)return;s=!0;const d=k.get(e);d&&(clearTimeout(d.maxLifetimeTimer),k.delete(e));try{r.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying provider for ${e}:`,f)}try{o.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying persistence for ${e}:`,f)}try{t.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying ydoc for ${e}:`,f)}n?.()},i=t.getMap("import-progress"),u=()=>{const d=i.get("stage");(d==="complete"||d==="error")&&(i.unobserve(u),setTimeout(c,je))};i.observe(u);const p=setTimeout(()=>{console.warn(`[PdfImportKeeper] Import ${e} exceeded max lifetime; releasing`),c()},Ue);k.set(e,{docId:e,ydoc:t,persistence:o,provider:r,done:a,finish:c,maxLifetimeTimer:p})}async function Ne(e){const t=k.get(e);if(t){Ce(e);try{await t.persistence.clearData()}catch(o){console.warn(`[PdfImportKeeper] Error clearing data for ${e}:`,o)}t.finish()}}const Je=10;async function Ke(e){const t=e.batchSize??Je;for(let o=1;o<=e.totalPages;o+=t){const r=Math.min(e.totalPages,o+t-1),n=[];for(let a=o;a<=r;a+=1)n.push(await e.preparePage(a));await e.sendBatch(n,r===e.totalPages)}}const V="https://app-api.revise-sdk.invalid",Ye="https://agent.revise.io",Ge=150;class S extends Error{constructor(t){super(t.message),this.name="PdfLimitError",this.data=t}static ocrLimitExceeded(t,o,r,n,a="month",s=!1,c,i){const u=a==="day"?`You have ${t} free PDF pages left today. Create a free account for more.`:s?`You have ${t} free PDF pages left this month. Create an account for more.`:`You have ${t} PDF pages left this month. Upgrade for more.`;return new S({type:"OCR_LIMIT_EXCEEDED",remaining:t,requested:o,monthlyLimit:r,limitPeriod:a,anonymous:s,freeAccountLimit:c,maxPlanLimit:i,message:u,thumbnails:n})}}function We(){try{return typeof window<"u"?localStorage.getItem("auth_token"):null}catch{return null}}async function Xe(e){try{const t=e?await fetch(`${V}/subscription/pdf-limits`,{method:"GET",headers:{Authorization:`Bearer ${e}`}}):await A().then(r=>fetch(`${Ye}/api/v1/pdf/page-limit`,{method:"GET",headers:r?{"X-Anonymous-Browser-Id":r}:void 0}));if(!t.ok)return console.warn("Failed to fetch OCR limit, using fallback"),H(e);const o=await t.json();return{ocrMonthlyLimit:o.ocrMonthlyLimit||3e3,ocrPagesRemaining:o.ocrPagesRemaining??3e3,limitPeriod:o.limitPeriod==="daily"?"day":"month",anonymous:!e,freeAccountLimit:o.freeAccountLimit,maxPlanLimit:o.maxPlanLimit}}catch(t){return console.warn("Error fetching OCR limit:",t),H(e)}}function H(e){return e?{ocrMonthlyLimit:3e3,ocrPagesRemaining:3e3,limitPeriod:"month",anonymous:!1,freeAccountLimit:100,maxPlanLimit:3e3}:{ocrMonthlyLimit:10,ocrPagesRemaining:10,limitPeriod:"month",anonymous:!0,freeAccountLimit:100,maxPlanLimit:3e3}}async function qe(e,t,o){const r=await fetch(`${V}/uploads/images/presign`,{method:"POST",headers:{"Content-Type":"application/json",...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify({fileName:`page-${t}.png`,contentType:"image/png",fileSize:e.size,prefix:"pdf-temp"})});if(!r.ok){const c=await r.text();throw new Error(c||`Failed to get upload URL for page ${t}`)}const n=await r.json(),a=new Headers,s={...n.headers||{},"Content-Type":n.contentType||"image/png"};for(const[c,i]of Object.entries(s))i&&a.set(c,i);if(!(await fetch(n.uploadUrl,{method:n.method||"PUT",body:e,headers:a})).ok)throw new Error(`Failed to upload page ${t}`);return n.fileUrl}async function Ve(e){const{totalPages:t,title:o,token:r,timeoutMessage:n,targetDocumentId:a,afterBlockId:s}=e,c=x(o),i=!r&&!a?await Re(c):null,u=!r&&a?{docId:a,anonSessionId:q(),anonymousBrowserId:await A()}:null,p=i??u;try{const d=new AbortController,f=setTimeout(()=>d.abort(),10*60*1e3);let l;try{l=await fetch(`${K()}/api/pdf/import-streaming`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{},Accept:"text/event-stream"},body:JSON.stringify({totalPages:t,title:c,provider:ie,...r&&a?{targetDocumentId:a}:{},...a&&s?{afterBlockId:s}:{},...p?{anonSessionId:p.anonSessionId,anonDocId:p.docId,anonymousBrowserId:p.anonymousBrowserId||void 0}:{}}),signal:d.signal})}catch(P){throw P?.name==="AbortError"?new Error(n):new Error("Failed to start import. Please check your connection and try again.")}finally{clearTimeout(f)}if(!l.ok){const P=await l.text().catch(()=>"");let g={};try{g=JSON.parse(P)}catch{}throw new Error(g.error||P||`Import failed: ${l.status}`)}const h=await He(l);if(!h.importId||!h.uploadToken)throw new Error("Server did not create a page upload session.");return{documentId:h.documentId,title:h.title||c,importId:h.importId,uploadToken:h.uploadToken}}catch(d){throw i&&Ne(i.docId),d}}async function He(e){const t=e.body?.getReader();if(!t)throw new Error("Failed to read server response");const o=new TextDecoder;let r="",n="";for(;;){const{done:a,value:s}=await t.read();if(a)break;r+=o.decode(s,{stream:!0});const c=r.split(`
2
- `);r=c.pop()||"";for(const i of c)if(i.startsWith("event: "))n=i.slice(7).trim();else if(i.startsWith("data: ")){let u=null;try{u=JSON.parse(i.slice(6))}catch{}if(u){if(n==="document_created")return t.releaseLock(),u;if(n==="error")throw t.releaseLock(),new Error(u.error||"Import failed")}n=""}}throw new Error("Server did not create document. Please try again.")}async function Q(e){const t=await fetch(`${K()}/api/pdf/import-streaming/${encodeURIComponent(e.importId)}/batches`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({uploadToken:e.uploadToken,pages:e.pages,final:e.final,error:e.error})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.error||"Failed to upload PDF page batch")}}async function Z(e,t){let o;try{o=await e.getPage(t)}catch{throw new Error(`Failed to read page ${t}. The PDF may be damaged.`)}let r=Ge/72,n=o.getViewport({scale:r});r*=1568/Math.max(n.width,n.height),n=o.getViewport({scale:r});const a=document.createElement("canvas"),s=a.getContext("2d");if(!s)throw new Error("Failed to create canvas. Your browser may not support this feature.");a.width=n.width,a.height=n.height,s.fillStyle="white",s.fillRect(0,0,a.width,a.height);try{await o.render({canvasContext:s,viewport:n}).promise}catch{throw new Error(`Failed to render page ${t}. The page may contain unsupported content.`)}const c=40,i=4;let u=!1;for(let m=0;m<c&&!u;m++){const w=Math.floor(a.width*m/c),b=Math.min(i,a.width-w);if(b<=0)continue;const y=s.getImageData(w,0,b,a.height).data;for(let I=0;I<y.length&&!u;I+=4)(y[I]<250||y[I+1]<250||y[I+2]<250)&&(u=!0)}if(!u)throw new Error(`Page ${t} appears blank. The PDF may use an unsupported image format.`);const p=await new Promise((m,w)=>{a.toBlob(b=>{b?m(b):w(new Error(`Failed to process page ${t}. The page may be too complex or large.`))},"image/png")}),d=120,f=d/a.height,l=Math.round(a.width*f),h=document.createElement("canvas");h.width=l,h.height=d;const P=h.getContext("2d");P&&P.drawImage(a,0,0,l,d);const g=h.toDataURL("image/jpeg",.7);return{blob:p,width:n.width,height:n.height,thumbnail:g}}const Qe=5;async function ee(e,t,o){const r=y=>{o&&o(y)},n=We(),{ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:u,maxPlanLimit:p}=await Xe(n);r({stage:"loading",message:"Loading PDF..."});const d=await import("./pdf-BLWDCiFF.js");d.GlobalWorkerOptions.workerSrc=C("pdfjs/worker.js");const f=await e.arrayBuffer(),l=d.getDocument({data:f,wasmUrl:C("pdfjs/")});let h;try{h=await l.promise}catch(y){const I=y?.message?.toLowerCase()||"";throw I.includes("password")||I.includes("encrypted")?new Error("This PDF is password-protected. Please remove the password and try again."):I.includes("invalid")||I.includes("corrupt")?new Error("This PDF appears to be corrupted or invalid. Please try a different file."):new Error("Failed to read PDF file. Please try a different file.")}if(!h.numPages||h.numPages===0)throw new Error("This PDF has no pages.");const P=h.numPages,g=P>s,m=g?Math.min(Qe,P):0,w=[];for(let y=1;y<=m;y++){const{thumbnail:I}=await Z(h,y);w.push(I),r({stage:"rasterizing",currentPage:y,totalPages:m,message:`Preparing preview ${y} of ${m}...`,thumbnail:I})}const b=x(e.name?.replace(/\.pdf$/i,"")||"Imported PDF");return{thumbnails:w,totalPages:P,ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:u,maxPlanLimit:p,exceedsLimit:g,title:b,_pdf:h,_token:n,_file:e}}async function te(e,t,o,r){const n=m=>{t&&t(m)},{_pdf:a,_token:s,_file:c,totalPages:i,title:u,ocrMonthlyLimit:p,ocrPagesRemaining:d,limitPeriod:f,anonymous:l,freeAccountLimit:h,maxPlanLimit:P}=e;if(i>d)throw S.ocrLimitExceeded(d,i,p,e.thumbnails,f,l,h,P);n({stage:"converting",totalPages:i,message:"Creating document..."}),M.track("PDF Import Started",{"Total Pages":i,"File Name":c.name,Anonymous:!s});const g=await Ve({totalPages:i,title:u,token:s,timeoutMessage:"Import timed out after 10 minutes. Please try with a shorter PDF.",targetDocumentId:o,afterBlockId:r});return Ke({totalPages:i,preparePage:async m=>{const{blob:w,thumbnail:b}=await Z(a,m);return n({stage:"rasterizing",currentPage:m,totalPages:i,message:`Processing page ${m} of ${i}`,thumbnail:b}),{url:await qe(w,m,s),mediaType:"image/png",pageNumber:m}},sendBatch:(m,w)=>Q({importId:g.importId,uploadToken:g.uploadToken,pages:m,final:w})}).catch(async m=>{const w=m instanceof Error?m.message:"Failed to prepare PDF pages";console.error("[PDF Import] Background page upload failed:",m),n({stage:"error",totalPages:i,message:w});try{await Q({importId:g.importId,uploadToken:g.uploadToken,error:w})}catch(b){console.error("[PDF Import] Failed to report page upload error:",b)}}),n({stage:"complete",totalPages:i,message:"Document created! Content is streaming..."}),M.track("PDF Import Completed",{"Document ID":g.documentId,"Total Pages":i,Anonymous:!s}),{documentId:g.documentId,title:g.title,pagesProcessed:i,inputTokens:0,outputTokens:0,streaming:!0}}function oe(e){const t=e.getMap("import-progress");let o=()=>{};const r=new Promise((n,a)=>{const s=()=>{const i=t.get("stage");i!=="complete"&&i!=="error"||(o(),i==="complete"?n():a(new Error(String(t.get("error")||"PDF import failed."))))},c=setTimeout(()=>{o(),a(new Error("PDF import timed out before content was ready."))},9e5);o=()=>{clearTimeout(c),t.unobserve(s)},t.observe(s)});return r.catch(()=>{}),{done:r,cancel:()=>o()}}async function Ze(e,t,o,r,n){const a=await ee(e,void 0,r),s=oe(o);try{const c=await te(a,r,t,n);return await s.done,c}catch(c){throw s.cancel(),c}}export{S as PdfLimitError,te as confirmPdfImport,Ze as importPdfIntoExistingDocument,ee as previewPdfForImport,oe as watchImportCompletion};
1
+ import{a1 as re,T as ne,c6 as x,c7 as ae,c8 as se,aZ as C,c9 as M,ca as ie}from"./index-iZC8xN0t.js";import*as v from"yjs";const E=e=>new Promise(e);Promise.all.bind(Promise);const ce=e=>new Error(e),T=e=>E((t,o)=>{e.onerror=r=>o(new Error(r.target.error)),e.onsuccess=r=>t(r.target.result)}),de=(e,t)=>E((o,r)=>{const n=indexedDB.open(e);n.onupgradeneeded=a=>t(a.target.result),n.onerror=a=>r(ce(a.target.error)),n.onsuccess=a=>{const s=a.target.result;s.onversionchange=()=>{s.close()},o(s)}}),le=e=>T(indexedDB.deleteDatabase(e)),me=(e,t)=>t.forEach(o=>e.createObjectStore.apply(e,o)),_=(e,t,o="readwrite")=>{const r=e.transaction(t,o);return t.map(n=>Pe(r,n))},U=(e,t)=>T(e.count(t)),ue=(e,t)=>T(e.get(t)),j=(e,t)=>T(e.delete(t)),he=(e,t,o)=>T(e.put(t,o)),F=(e,t)=>T(e.add(t)),pe=(e,t,o)=>T(e.getAll(t,o)),fe=(e,t,o)=>{let r=null;return ye(e,t,n=>(r=n,!1),o).then(()=>r)},ge=(e,t=null)=>fe(e,t,"prev"),we=(e,t)=>E((o,r)=>{e.onerror=r,e.onsuccess=async n=>{const a=n.target.result;if(a===null||await t(a)===!1)return o();a.continue()}}),ye=(e,t,o,r="next")=>we(e.openKeyCursor(t,r),n=>o(n.key)),Pe=(e,t)=>e.objectStore(t),Ie=(e,t)=>IDBKeyRange.upperBound(e,t),be=(e,t)=>IDBKeyRange.lowerBound(e,t),L=()=>new Map,Te=(e,t,o)=>{let r=e.get(t);return r===void 0&&e.set(t,r=o()),r},ve=()=>new Set,_e=Array.from;class Ee{constructor(){this._observers=L()}on(t,o){Te(this._observers,t,ve).add(o)}once(t,o){const r=(...n)=>{this.off(t,r),o(...n)};this.on(t,r)}off(t,o){const r=this._observers.get(t);r!==void 0&&(r.delete(o),r.size===0&&this._observers.delete(t))}emit(t,o){return _e((this._observers.get(t)||L()).values()).forEach(r=>r(...o))}destroy(){this._observers=L()}}const $="custom",O="updates",R=500,z=(e,t=()=>{},o=()=>{})=>{const[r]=_(e.db,[O]);return pe(r,be(e._dbref,!1)).then(n=>{e._destroyed||(t(r),v.transact(e.doc,()=>{n.forEach(a=>v.applyUpdate(e.doc,a))},e,!1),o(r))}).then(()=>ge(r).then(n=>{e._dbref=n+1})).then(()=>U(r).then(n=>{e._dbsize=n})).then(()=>r)},De=(e,t=!0)=>z(e).then(o=>{(t||e._dbsize>=R)&&F(o,v.encodeStateAsUpdate(e.doc)).then(()=>j(o,Ie(e._dbref,!0))).then(()=>U(o).then(r=>{e._dbsize=r}))});class ke extends Ee{constructor(t,o){super(),this.doc=o,this.name=t,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=de(t,r=>me(r,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=E(r=>this.on("synced",()=>r(this))),this._db.then(r=>{this.db=r,z(this,n=>F(n,v.encodeStateAsUpdate(o)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(r,n)=>{if(this.db&&n!==this){const[a]=_(this.db,[O]);F(a,r),++this._dbsize>=R&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{De(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},o.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),o.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(t=>{t.close()})}clearData(){return this.destroy().then(()=>{le(this.name)})}get(t){return this._db.then(o=>{const[r]=_(o,[$],"readonly");return ue(r,t)})}set(t,o){return this._db.then(r=>{const[n]=_(r,[$]);return he(n,o,t)})}del(t){return this._db.then(o=>{const[r]=_(o,[$]);return j(r,t)})}}const Se="revise-anonymous-identity",xe=1,D="identities",N="pdf-browser-id",Fe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Le(){return new Promise((e,t)=>{const o=indexedDB.open(Se,xe);o.onupgradeneeded=()=>{o.result.objectStoreNames.contains(D)||o.result.createObjectStore(D)},o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error)})}async function A(){if(typeof window>"u"||typeof indexedDB>"u"||typeof crypto>"u"||typeof crypto.randomUUID!="function")return null;let e=null;try{return e=await Le(),await new Promise((t,o)=>{const r=e.transaction(D,"readwrite"),n=r.objectStore(D),a=n.get(N);let s="";a.onsuccess=()=>{const c=typeof a.result=="string"?a.result.trim().toLowerCase():"";s=Fe.test(c)?c:crypto.randomUUID(),s!==c&&n.put(s,N)},a.onerror=()=>o(a.error),r.oncomplete=()=>t(s),r.onerror=()=>o(r.error),r.onabort=()=>o(r.error)})}catch(t){return console.warn("Unable to load anonymous PDF browser identity:",t),null}finally{e?.close()}}const J="https://sync.revise-sdk.invalid";function K(){return J}function $e(){return J.replace(/^https/,"wss")}const B="yjs_document_index",Y="anon_session_id",G="yjs_document_deleted_",Ae="local-document-deleted";function W(e){return typeof window<"u"&&localStorage.getItem(G+e)==="1"}function q(){if(typeof window>"u")return[];try{const e=localStorage.getItem(B);return e?JSON.parse(e).filter(t=>!W(t)):[]}catch(e){return console.warn("Failed to read document index:",e),[]}}function Be(e){if(!(typeof window>"u"))try{if(W(e))return;const t=q();t.includes(e)||(t.push(e),localStorage.setItem(B,JSON.stringify(t)))}catch(t){console.warn("Failed to update document index:",t)}}function Ce(e){if(!(typeof window>"u"))try{localStorage.setItem(G+e,"1"),window.dispatchEvent(new CustomEvent(Ae,{detail:{documentId:e}}));const t=q().filter(o=>o!==e);localStorage.setItem(B,JSON.stringify(t))}catch(t){console.warn("Failed to remove from document index:",t)}}function Me(){const e="abcdefghijklmnopqrstuvwxyz0123456789";let t="";for(let o=0;o<8;o++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function V(){if(typeof window>"u")return"server";let e=localStorage.getItem(Y);return e||(e=crypto.randomUUID().replace(/-/g,"").slice(0,12),localStorage.setItem(Y,e)),e}const Ue=30*60*1e3,je=3e3,Oe=15e3,k=new Map;async function Re(e){const t=Me(),o=V(),r=`anon:${o}:${t}`,n=new v.Doc,a={children:[{type:"paragraph",id:re(),children:[{type:"text",text:"",marks:{}}]}]};ne(n,a),n.transact(()=>{const l=n.getMap("metadata");l.set("id",t),l.set("documentId",t),l.set("title",x(e)),l.set("createdAt",Date.now()),l.set("updatedAt",Date.now()),l.set("lastAccessedAt",Date.now()),l.set("storageType","local")});const s=new ke(t,n);await s.whenSynced;const c=await A(),i=$e(),u=c?`${i}${i.includes("?")?"&":"?"}anonymousBrowserId=${encodeURIComponent(c)}`:i;let p=null;const d=new Promise(l=>{p=l}),f=new ae({url:se(u),name:r,document:n,token:()=>"",onSynced:()=>{p?.()}});return ze(t,n,s,f),Be(t),await Promise.race([d,new Promise(l=>setTimeout(l,Oe))]),{docId:t,anonSessionId:o,anonymousBrowserId:c}}function ze(e,t,o,r){let n=null;const a=new Promise(d=>{n=d});let s=!1;const c=()=>{if(s)return;s=!0;const d=k.get(e);d&&(clearTimeout(d.maxLifetimeTimer),k.delete(e));try{r.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying provider for ${e}:`,f)}try{o.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying persistence for ${e}:`,f)}try{t.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying ydoc for ${e}:`,f)}n?.()},i=t.getMap("import-progress"),u=()=>{const d=i.get("stage");(d==="complete"||d==="error")&&(i.unobserve(u),setTimeout(c,je))};i.observe(u);const p=setTimeout(()=>{console.warn(`[PdfImportKeeper] Import ${e} exceeded max lifetime; releasing`),c()},Ue);k.set(e,{docId:e,ydoc:t,persistence:o,provider:r,done:a,finish:c,maxLifetimeTimer:p})}async function Ne(e){const t=k.get(e);if(t){Ce(e);try{await t.persistence.clearData()}catch(o){console.warn(`[PdfImportKeeper] Error clearing data for ${e}:`,o)}t.finish()}}const Je=10;async function Ke(e){const t=e.batchSize??Je;for(let o=1;o<=e.totalPages;o+=t){const r=Math.min(e.totalPages,o+t-1),n=[];for(let a=o;a<=r;a+=1)n.push(await e.preparePage(a));await e.sendBatch(n,r===e.totalPages)}}const X="https://app-api.revise-sdk.invalid",Ye="https://agent.revise.io",Ge=150;class S extends Error{constructor(t){super(t.message),this.name="PdfLimitError",this.data=t}static ocrLimitExceeded(t,o,r,n,a="month",s=!1,c,i){const u=a==="day"?`You have ${t} free PDF pages left today. Create a free account for more.`:s?`You have ${t} free PDF pages left this month. Create an account for more.`:`You have ${t} PDF pages left this month. Upgrade for more.`;return new S({type:"OCR_LIMIT_EXCEEDED",remaining:t,requested:o,monthlyLimit:r,limitPeriod:a,anonymous:s,freeAccountLimit:c,maxPlanLimit:i,message:u,thumbnails:n})}}function We(){try{return typeof window<"u"?localStorage.getItem("auth_token"):null}catch{return null}}async function qe(e){try{const t=e?await fetch(`${X}/subscription/pdf-limits`,{method:"GET",headers:{Authorization:`Bearer ${e}`}}):await A().then(r=>fetch(`${Ye}/api/v1/pdf/page-limit`,{method:"GET",headers:r?{"X-Anonymous-Browser-Id":r}:void 0}));if(!t.ok)return console.warn("Failed to fetch OCR limit, using fallback"),H(e);const o=await t.json();return{ocrMonthlyLimit:o.ocrMonthlyLimit||3e3,ocrPagesRemaining:o.ocrPagesRemaining??3e3,limitPeriod:o.limitPeriod==="daily"?"day":"month",anonymous:!e,freeAccountLimit:o.freeAccountLimit,maxPlanLimit:o.maxPlanLimit}}catch(t){return console.warn("Error fetching OCR limit:",t),H(e)}}function H(e){return e?{ocrMonthlyLimit:3e3,ocrPagesRemaining:3e3,limitPeriod:"month",anonymous:!1,freeAccountLimit:100,maxPlanLimit:3e3}:{ocrMonthlyLimit:10,ocrPagesRemaining:10,limitPeriod:"month",anonymous:!0,freeAccountLimit:100,maxPlanLimit:3e3}}async function Ve(e,t,o){const r=await fetch(`${X}/uploads/images/presign`,{method:"POST",headers:{"Content-Type":"application/json",...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify({fileName:`page-${t}.png`,contentType:"image/png",fileSize:e.size,prefix:"pdf-temp"})});if(!r.ok){const c=await r.text();throw new Error(c||`Failed to get upload URL for page ${t}`)}const n=await r.json(),a=new Headers,s={...n.headers||{},"Content-Type":n.contentType||"image/png"};for(const[c,i]of Object.entries(s))i&&a.set(c,i);if(!(await fetch(n.uploadUrl,{method:n.method||"PUT",body:e,headers:a})).ok)throw new Error(`Failed to upload page ${t}`);return n.fileUrl}async function Xe(e){const{totalPages:t,title:o,token:r,timeoutMessage:n,targetDocumentId:a,afterBlockId:s}=e,c=x(o),i=!r&&!a?await Re(c):null,u=!r&&a?{docId:a,anonSessionId:V(),anonymousBrowserId:await A()}:null,p=i??u;try{const d=new AbortController,f=setTimeout(()=>d.abort(),10*60*1e3);let l;try{l=await fetch(`${K()}/api/pdf/import-streaming`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{},Accept:"text/event-stream"},body:JSON.stringify({totalPages:t,title:c,provider:ie,...r&&a?{targetDocumentId:a}:{},...a&&s?{afterBlockId:s}:{},...p?{anonSessionId:p.anonSessionId,anonDocId:p.docId,anonymousBrowserId:p.anonymousBrowserId||void 0}:{}}),signal:d.signal})}catch(P){throw P?.name==="AbortError"?new Error(n):new Error("Failed to start import. Please check your connection and try again.")}finally{clearTimeout(f)}if(!l.ok){const P=await l.text().catch(()=>"");let g={};try{g=JSON.parse(P)}catch{}throw new Error(g.error||P||`Import failed: ${l.status}`)}const h=await He(l);if(!h.importId||!h.uploadToken)throw new Error("Server did not create a page upload session.");return{documentId:h.documentId,title:h.title||c,importId:h.importId,uploadToken:h.uploadToken}}catch(d){throw i&&Ne(i.docId),d}}async function He(e){const t=e.body?.getReader();if(!t)throw new Error("Failed to read server response");const o=new TextDecoder;let r="",n="";for(;;){const{done:a,value:s}=await t.read();if(a)break;r+=o.decode(s,{stream:!0});const c=r.split(`
2
+ `);r=c.pop()||"";for(const i of c)if(i.startsWith("event: "))n=i.slice(7).trim();else if(i.startsWith("data: ")){let u=null;try{u=JSON.parse(i.slice(6))}catch{}if(u){if(n==="document_created")return t.releaseLock(),u;if(n==="error")throw t.releaseLock(),new Error(u.error||"Import failed")}n=""}}throw new Error("Server did not create document. Please try again.")}async function Z(e){const t=await fetch(`${K()}/api/pdf/import-streaming/${encodeURIComponent(e.importId)}/batches`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({uploadToken:e.uploadToken,pages:e.pages,final:e.final,error:e.error})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.error||"Failed to upload PDF page batch")}}async function Q(e,t){let o;try{o=await e.getPage(t)}catch{throw new Error(`Failed to read page ${t}. The PDF may be damaged.`)}let r=Ge/72,n=o.getViewport({scale:r});r*=1568/Math.max(n.width,n.height),n=o.getViewport({scale:r});const a=document.createElement("canvas"),s=a.getContext("2d");if(!s)throw new Error("Failed to create canvas. Your browser may not support this feature.");a.width=n.width,a.height=n.height,s.fillStyle="white",s.fillRect(0,0,a.width,a.height);try{await o.render({canvasContext:s,viewport:n}).promise}catch{throw new Error(`Failed to render page ${t}. The page may contain unsupported content.`)}const c=40,i=4;let u=!1;for(let m=0;m<c&&!u;m++){const w=Math.floor(a.width*m/c),b=Math.min(i,a.width-w);if(b<=0)continue;const y=s.getImageData(w,0,b,a.height).data;for(let I=0;I<y.length&&!u;I+=4)(y[I]<250||y[I+1]<250||y[I+2]<250)&&(u=!0)}if(!u)throw new Error(`Page ${t} appears blank. The PDF may use an unsupported image format.`);const p=await new Promise((m,w)=>{a.toBlob(b=>{b?m(b):w(new Error(`Failed to process page ${t}. The page may be too complex or large.`))},"image/png")}),d=120,f=d/a.height,l=Math.round(a.width*f),h=document.createElement("canvas");h.width=l,h.height=d;const P=h.getContext("2d");P&&P.drawImage(a,0,0,l,d);const g=h.toDataURL("image/jpeg",.7);return{blob:p,width:n.width,height:n.height,thumbnail:g}}const Ze=5;async function ee(e,t,o){const r=y=>{o&&o(y)},n=We(),{ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:u,maxPlanLimit:p}=await qe(n);r({stage:"loading",message:"Loading PDF..."});const d=await import("./pdf-BLWDCiFF.js");d.GlobalWorkerOptions.workerSrc=C("pdfjs/worker.js");const f=await e.arrayBuffer(),l=d.getDocument({data:f,wasmUrl:C("pdfjs/")});let h;try{h=await l.promise}catch(y){const I=y?.message?.toLowerCase()||"";throw I.includes("password")||I.includes("encrypted")?new Error("This PDF is password-protected. Please remove the password and try again."):I.includes("invalid")||I.includes("corrupt")?new Error("This PDF appears to be corrupted or invalid. Please try a different file."):new Error("Failed to read PDF file. Please try a different file.")}if(!h.numPages||h.numPages===0)throw new Error("This PDF has no pages.");const P=h.numPages,g=P>s,m=g?Math.min(Ze,P):0,w=[];for(let y=1;y<=m;y++){const{thumbnail:I}=await Q(h,y);w.push(I),r({stage:"rasterizing",currentPage:y,totalPages:m,message:`Preparing preview ${y} of ${m}...`,thumbnail:I})}const b=x(e.name?.replace(/\.pdf$/i,"")||"Imported PDF");return{thumbnails:w,totalPages:P,ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:u,maxPlanLimit:p,exceedsLimit:g,title:b,_pdf:h,_token:n,_file:e}}async function te(e,t,o,r){const n=m=>{t&&t(m)},{_pdf:a,_token:s,_file:c,totalPages:i,title:u,ocrMonthlyLimit:p,ocrPagesRemaining:d,limitPeriod:f,anonymous:l,freeAccountLimit:h,maxPlanLimit:P}=e;if(i>d)throw S.ocrLimitExceeded(d,i,p,e.thumbnails,f,l,h,P);n({stage:"converting",totalPages:i,message:"Creating document..."}),M.track("PDF Import Started",{"Total Pages":i,"File Name":c.name,Anonymous:!s});const g=await Xe({totalPages:i,title:u,token:s,timeoutMessage:"Import timed out after 10 minutes. Please try with a shorter PDF.",targetDocumentId:o,afterBlockId:r});return Ke({totalPages:i,preparePage:async m=>{const{blob:w,thumbnail:b}=await Q(a,m);return n({stage:"rasterizing",currentPage:m,totalPages:i,message:`Processing page ${m} of ${i}`,thumbnail:b}),{url:await Ve(w,m,s),mediaType:"image/png",pageNumber:m}},sendBatch:(m,w)=>Z({importId:g.importId,uploadToken:g.uploadToken,pages:m,final:w})}).catch(async m=>{const w=m instanceof Error?m.message:"Failed to prepare PDF pages";console.error("[PDF Import] Background page upload failed:",m),n({stage:"error",totalPages:i,message:w});try{await Z({importId:g.importId,uploadToken:g.uploadToken,error:w})}catch(b){console.error("[PDF Import] Failed to report page upload error:",b)}}),n({stage:"complete",totalPages:i,message:"Document created! Content is streaming..."}),M.track("PDF Import Completed",{"Document ID":g.documentId,"Total Pages":i,Anonymous:!s}),{documentId:g.documentId,title:g.title,pagesProcessed:i,inputTokens:0,outputTokens:0,streaming:!0}}function oe(e){const t=e.getMap("import-progress");let o=()=>{};const r=new Promise((n,a)=>{const s=()=>{const i=t.get("stage");i!=="complete"&&i!=="error"||(o(),i==="complete"?n():a(new Error(String(t.get("error")||"PDF import failed."))))},c=setTimeout(()=>{o(),a(new Error("PDF import timed out before content was ready."))},9e5);o=()=>{clearTimeout(c),t.unobserve(s)},t.observe(s)});return r.catch(()=>{}),{done:r,cancel:()=>o()}}async function Qe(e,t,o,r,n){const a=await ee(e,void 0,r),s=oe(o);try{const c=await te(a,r,t,n);return await s.done,c}catch(c){throw s.cancel(),c}}export{S as PdfLimitError,te as confirmPdfImport,Qe as importPdfIntoExistingDocument,ee as previewPdfForImport,oe as watchImportCompletion};
@@ -1,2 +1,2 @@
1
- import{a1 as re,T as ne,c1 as x,c2 as ae,c3 as se,aX as C,c4 as M,c5 as ie}from"./index-CjeGoI2g.js";import*as v from"yjs";const E=e=>new Promise(e);Promise.all.bind(Promise);const ce=e=>new Error(e),T=e=>E((t,o)=>{e.onerror=r=>o(new Error(r.target.error)),e.onsuccess=r=>t(r.target.result)}),de=(e,t)=>E((o,r)=>{const n=indexedDB.open(e);n.onupgradeneeded=a=>t(a.target.result),n.onerror=a=>r(ce(a.target.error)),n.onsuccess=a=>{const s=a.target.result;s.onversionchange=()=>{s.close()},o(s)}}),le=e=>T(indexedDB.deleteDatabase(e)),me=(e,t)=>t.forEach(o=>e.createObjectStore.apply(e,o)),_=(e,t,o="readwrite")=>{const r=e.transaction(t,o);return t.map(n=>Pe(r,n))},U=(e,t)=>T(e.count(t)),ue=(e,t)=>T(e.get(t)),j=(e,t)=>T(e.delete(t)),he=(e,t,o)=>T(e.put(t,o)),F=(e,t)=>T(e.add(t)),pe=(e,t,o)=>T(e.getAll(t,o)),fe=(e,t,o)=>{let r=null;return ye(e,t,n=>(r=n,!1),o).then(()=>r)},ge=(e,t=null)=>fe(e,t,"prev"),we=(e,t)=>E((o,r)=>{e.onerror=r,e.onsuccess=async n=>{const a=n.target.result;if(a===null||await t(a)===!1)return o();a.continue()}}),ye=(e,t,o,r="next")=>we(e.openKeyCursor(t,r),n=>o(n.key)),Pe=(e,t)=>e.objectStore(t),Ie=(e,t)=>IDBKeyRange.upperBound(e,t),be=(e,t)=>IDBKeyRange.lowerBound(e,t),L=()=>new Map,Te=(e,t,o)=>{let r=e.get(t);return r===void 0&&e.set(t,r=o()),r},ve=()=>new Set,_e=Array.from;class Ee{constructor(){this._observers=L()}on(t,o){Te(this._observers,t,ve).add(o)}once(t,o){const r=(...n)=>{this.off(t,r),o(...n)};this.on(t,r)}off(t,o){const r=this._observers.get(t);r!==void 0&&(r.delete(o),r.size===0&&this._observers.delete(t))}emit(t,o){return _e((this._observers.get(t)||L()).values()).forEach(r=>r(...o))}destroy(){this._observers=L()}}const $="custom",O="updates",R=500,z=(e,t=()=>{},o=()=>{})=>{const[r]=_(e.db,[O]);return pe(r,be(e._dbref,!1)).then(n=>{e._destroyed||(t(r),v.transact(e.doc,()=>{n.forEach(a=>v.applyUpdate(e.doc,a))},e,!1),o(r))}).then(()=>ge(r).then(n=>{e._dbref=n+1})).then(()=>U(r).then(n=>{e._dbsize=n})).then(()=>r)},De=(e,t=!0)=>z(e).then(o=>{(t||e._dbsize>=R)&&F(o,v.encodeStateAsUpdate(e.doc)).then(()=>j(o,Ie(e._dbref,!0))).then(()=>U(o).then(r=>{e._dbsize=r}))});class ke extends Ee{constructor(t,o){super(),this.doc=o,this.name=t,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=de(t,r=>me(r,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=E(r=>this.on("synced",()=>r(this))),this._db.then(r=>{this.db=r,z(this,n=>F(n,v.encodeStateAsUpdate(o)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(r,n)=>{if(this.db&&n!==this){const[a]=_(this.db,[O]);F(a,r),++this._dbsize>=R&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{De(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},o.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),o.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(t=>{t.close()})}clearData(){return this.destroy().then(()=>{le(this.name)})}get(t){return this._db.then(o=>{const[r]=_(o,[$],"readonly");return ue(r,t)})}set(t,o){return this._db.then(r=>{const[n]=_(r,[$]);return he(n,o,t)})}del(t){return this._db.then(o=>{const[r]=_(o,[$]);return j(r,t)})}}const Se="revise-anonymous-identity",xe=1,D="identities",N="pdf-browser-id",Fe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Le(){return new Promise((e,t)=>{const o=indexedDB.open(Se,xe);o.onupgradeneeded=()=>{o.result.objectStoreNames.contains(D)||o.result.createObjectStore(D)},o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error)})}async function A(){if(typeof window>"u"||typeof indexedDB>"u"||typeof crypto>"u"||typeof crypto.randomUUID!="function")return null;let e=null;try{return e=await Le(),await new Promise((t,o)=>{const r=e.transaction(D,"readwrite"),n=r.objectStore(D),a=n.get(N);let s="";a.onsuccess=()=>{const c=typeof a.result=="string"?a.result.trim().toLowerCase():"";s=Fe.test(c)?c:crypto.randomUUID(),s!==c&&n.put(s,N)},a.onerror=()=>o(a.error),r.oncomplete=()=>t(s),r.onerror=()=>o(r.error),r.onabort=()=>o(r.error)})}catch(t){return console.warn("Unable to load anonymous PDF browser identity:",t),null}finally{e?.close()}}const J="https://sync.revise-sdk.invalid";function K(){return J}function $e(){return J.replace(/^https/,"wss")}const B="yjs_document_index",Y="anon_session_id",G="yjs_document_deleted_",Ae="local-document-deleted";function W(e){return typeof window<"u"&&localStorage.getItem(G+e)==="1"}function X(){if(typeof window>"u")return[];try{const e=localStorage.getItem(B);return e?JSON.parse(e).filter(t=>!W(t)):[]}catch(e){return console.warn("Failed to read document index:",e),[]}}function Be(e){if(!(typeof window>"u"))try{if(W(e))return;const t=X();t.includes(e)||(t.push(e),localStorage.setItem(B,JSON.stringify(t)))}catch(t){console.warn("Failed to update document index:",t)}}function Ce(e){if(!(typeof window>"u"))try{localStorage.setItem(G+e,"1"),window.dispatchEvent(new CustomEvent(Ae,{detail:{documentId:e}}));const t=X().filter(o=>o!==e);localStorage.setItem(B,JSON.stringify(t))}catch(t){console.warn("Failed to remove from document index:",t)}}function Me(){const e="abcdefghijklmnopqrstuvwxyz0123456789";let t="";for(let o=0;o<8;o++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function q(){if(typeof window>"u")return"server";let e=localStorage.getItem(Y);return e||(e=crypto.randomUUID().replace(/-/g,"").slice(0,12),localStorage.setItem(Y,e)),e}const Ue=30*60*1e3,je=3e3,Oe=15e3,k=new Map;async function Re(e){const t=Me(),o=q(),r=`anon:${o}:${t}`,n=new v.Doc,a={children:[{type:"paragraph",id:re(),children:[{type:"text",text:"",marks:{}}]}]};ne(n,a),n.transact(()=>{const l=n.getMap("metadata");l.set("id",t),l.set("documentId",t),l.set("title",x(e)),l.set("createdAt",Date.now()),l.set("updatedAt",Date.now()),l.set("lastAccessedAt",Date.now()),l.set("storageType","local")});const s=new ke(t,n);await s.whenSynced;const c=await A(),i=$e(),u=c?`${i}${i.includes("?")?"&":"?"}anonymousBrowserId=${encodeURIComponent(c)}`:i;let p=null;const d=new Promise(l=>{p=l}),f=new ae({url:se(u),name:r,document:n,token:()=>"",onSynced:()=>{p?.()}});return ze(t,n,s,f),Be(t),await Promise.race([d,new Promise(l=>setTimeout(l,Oe))]),{docId:t,anonSessionId:o,anonymousBrowserId:c}}function ze(e,t,o,r){let n=null;const a=new Promise(d=>{n=d});let s=!1;const c=()=>{if(s)return;s=!0;const d=k.get(e);d&&(clearTimeout(d.maxLifetimeTimer),k.delete(e));try{r.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying provider for ${e}:`,f)}try{o.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying persistence for ${e}:`,f)}try{t.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying ydoc for ${e}:`,f)}n?.()},i=t.getMap("import-progress"),u=()=>{const d=i.get("stage");(d==="complete"||d==="error")&&(i.unobserve(u),setTimeout(c,je))};i.observe(u);const p=setTimeout(()=>{console.warn(`[PdfImportKeeper] Import ${e} exceeded max lifetime; releasing`),c()},Ue);k.set(e,{docId:e,ydoc:t,persistence:o,provider:r,done:a,finish:c,maxLifetimeTimer:p})}async function Ne(e){const t=k.get(e);if(t){Ce(e);try{await t.persistence.clearData()}catch(o){console.warn(`[PdfImportKeeper] Error clearing data for ${e}:`,o)}t.finish()}}const Je=10;async function Ke(e){const t=e.batchSize??Je;for(let o=1;o<=e.totalPages;o+=t){const r=Math.min(e.totalPages,o+t-1),n=[];for(let a=o;a<=r;a+=1)n.push(await e.preparePage(a));await e.sendBatch(n,r===e.totalPages)}}const V="https://app-api.revise-sdk.invalid",Ye="https://agent.revise.io",Ge=150;class S extends Error{constructor(t){super(t.message),this.name="PdfLimitError",this.data=t}static ocrLimitExceeded(t,o,r,n,a="month",s=!1,c,i){const u=a==="day"?`You have ${t} free PDF pages left today. Create a free account for more.`:s?`You have ${t} free PDF pages left this month. Create an account for more.`:`You have ${t} PDF pages left this month. Upgrade for more.`;return new S({type:"OCR_LIMIT_EXCEEDED",remaining:t,requested:o,monthlyLimit:r,limitPeriod:a,anonymous:s,freeAccountLimit:c,maxPlanLimit:i,message:u,thumbnails:n})}}function We(){try{return typeof window<"u"?localStorage.getItem("auth_token"):null}catch{return null}}async function Xe(e){try{const t=e?await fetch(`${V}/subscription/pdf-limits`,{method:"GET",headers:{Authorization:`Bearer ${e}`}}):await A().then(r=>fetch(`${Ye}/api/v1/pdf/page-limit`,{method:"GET",headers:r?{"X-Anonymous-Browser-Id":r}:void 0}));if(!t.ok)return console.warn("Failed to fetch OCR limit, using fallback"),H(e);const o=await t.json();return{ocrMonthlyLimit:o.ocrMonthlyLimit||3e3,ocrPagesRemaining:o.ocrPagesRemaining??3e3,limitPeriod:o.limitPeriod==="daily"?"day":"month",anonymous:!e,freeAccountLimit:o.freeAccountLimit,maxPlanLimit:o.maxPlanLimit}}catch(t){return console.warn("Error fetching OCR limit:",t),H(e)}}function H(e){return e?{ocrMonthlyLimit:3e3,ocrPagesRemaining:3e3,limitPeriod:"month",anonymous:!1,freeAccountLimit:100,maxPlanLimit:3e3}:{ocrMonthlyLimit:10,ocrPagesRemaining:10,limitPeriod:"month",anonymous:!0,freeAccountLimit:100,maxPlanLimit:3e3}}async function qe(e,t,o){const r=await fetch(`${V}/uploads/images/presign`,{method:"POST",headers:{"Content-Type":"application/json",...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify({fileName:`page-${t}.png`,contentType:"image/png",fileSize:e.size,prefix:"pdf-temp"})});if(!r.ok){const c=await r.text();throw new Error(c||`Failed to get upload URL for page ${t}`)}const n=await r.json(),a=new Headers,s={...n.headers||{},"Content-Type":n.contentType||"image/png"};for(const[c,i]of Object.entries(s))i&&a.set(c,i);if(!(await fetch(n.uploadUrl,{method:n.method||"PUT",body:e,headers:a})).ok)throw new Error(`Failed to upload page ${t}`);return n.fileUrl}async function Ve(e){const{totalPages:t,title:o,token:r,timeoutMessage:n,targetDocumentId:a,afterBlockId:s}=e,c=x(o),i=!r&&!a?await Re(c):null,u=!r&&a?{docId:a,anonSessionId:q(),anonymousBrowserId:await A()}:null,p=i??u;try{const d=new AbortController,f=setTimeout(()=>d.abort(),10*60*1e3);let l;try{l=await fetch(`${K()}/api/pdf/import-streaming`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{},Accept:"text/event-stream"},body:JSON.stringify({totalPages:t,title:c,provider:ie,...r&&a?{targetDocumentId:a}:{},...a&&s?{afterBlockId:s}:{},...p?{anonSessionId:p.anonSessionId,anonDocId:p.docId,anonymousBrowserId:p.anonymousBrowserId||void 0}:{}}),signal:d.signal})}catch(P){throw P?.name==="AbortError"?new Error(n):new Error("Failed to start import. Please check your connection and try again.")}finally{clearTimeout(f)}if(!l.ok){const P=await l.text().catch(()=>"");let g={};try{g=JSON.parse(P)}catch{}throw new Error(g.error||P||`Import failed: ${l.status}`)}const h=await He(l);if(!h.importId||!h.uploadToken)throw new Error("Server did not create a page upload session.");return{documentId:h.documentId,title:h.title||c,importId:h.importId,uploadToken:h.uploadToken}}catch(d){throw i&&Ne(i.docId),d}}async function He(e){const t=e.body?.getReader();if(!t)throw new Error("Failed to read server response");const o=new TextDecoder;let r="",n="";for(;;){const{done:a,value:s}=await t.read();if(a)break;r+=o.decode(s,{stream:!0});const c=r.split(`
2
- `);r=c.pop()||"";for(const i of c)if(i.startsWith("event: "))n=i.slice(7).trim();else if(i.startsWith("data: ")){let u=null;try{u=JSON.parse(i.slice(6))}catch{}if(u){if(n==="document_created")return t.releaseLock(),u;if(n==="error")throw t.releaseLock(),new Error(u.error||"Import failed")}n=""}}throw new Error("Server did not create document. Please try again.")}async function Q(e){const t=await fetch(`${K()}/api/pdf/import-streaming/${encodeURIComponent(e.importId)}/batches`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({uploadToken:e.uploadToken,pages:e.pages,final:e.final,error:e.error})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.error||"Failed to upload PDF page batch")}}async function Z(e,t){let o;try{o=await e.getPage(t)}catch{throw new Error(`Failed to read page ${t}. The PDF may be damaged.`)}let r=Ge/72,n=o.getViewport({scale:r});r*=1568/Math.max(n.width,n.height),n=o.getViewport({scale:r});const a=document.createElement("canvas"),s=a.getContext("2d");if(!s)throw new Error("Failed to create canvas. Your browser may not support this feature.");a.width=n.width,a.height=n.height,s.fillStyle="white",s.fillRect(0,0,a.width,a.height);try{await o.render({canvasContext:s,viewport:n}).promise}catch{throw new Error(`Failed to render page ${t}. The page may contain unsupported content.`)}const c=40,i=4;let u=!1;for(let m=0;m<c&&!u;m++){const w=Math.floor(a.width*m/c),b=Math.min(i,a.width-w);if(b<=0)continue;const y=s.getImageData(w,0,b,a.height).data;for(let I=0;I<y.length&&!u;I+=4)(y[I]<250||y[I+1]<250||y[I+2]<250)&&(u=!0)}if(!u)throw new Error(`Page ${t} appears blank. The PDF may use an unsupported image format.`);const p=await new Promise((m,w)=>{a.toBlob(b=>{b?m(b):w(new Error(`Failed to process page ${t}. The page may be too complex or large.`))},"image/png")}),d=120,f=d/a.height,l=Math.round(a.width*f),h=document.createElement("canvas");h.width=l,h.height=d;const P=h.getContext("2d");P&&P.drawImage(a,0,0,l,d);const g=h.toDataURL("image/jpeg",.7);return{blob:p,width:n.width,height:n.height,thumbnail:g}}const Qe=5;async function ee(e,t,o){const r=y=>{o&&o(y)},n=We(),{ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:u,maxPlanLimit:p}=await Xe(n);r({stage:"loading",message:"Loading PDF..."});const d=await import("./pdf-BLWDCiFF.js");d.GlobalWorkerOptions.workerSrc=C("pdfjs/worker.js");const f=await e.arrayBuffer(),l=d.getDocument({data:f,wasmUrl:C("pdfjs/")});let h;try{h=await l.promise}catch(y){const I=y?.message?.toLowerCase()||"";throw I.includes("password")||I.includes("encrypted")?new Error("This PDF is password-protected. Please remove the password and try again."):I.includes("invalid")||I.includes("corrupt")?new Error("This PDF appears to be corrupted or invalid. Please try a different file."):new Error("Failed to read PDF file. Please try a different file.")}if(!h.numPages||h.numPages===0)throw new Error("This PDF has no pages.");const P=h.numPages,g=P>s,m=g?Math.min(Qe,P):0,w=[];for(let y=1;y<=m;y++){const{thumbnail:I}=await Z(h,y);w.push(I),r({stage:"rasterizing",currentPage:y,totalPages:m,message:`Preparing preview ${y} of ${m}...`,thumbnail:I})}const b=x(e.name?.replace(/\.pdf$/i,"")||"Imported PDF");return{thumbnails:w,totalPages:P,ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:u,maxPlanLimit:p,exceedsLimit:g,title:b,_pdf:h,_token:n,_file:e}}async function te(e,t,o,r){const n=m=>{t&&t(m)},{_pdf:a,_token:s,_file:c,totalPages:i,title:u,ocrMonthlyLimit:p,ocrPagesRemaining:d,limitPeriod:f,anonymous:l,freeAccountLimit:h,maxPlanLimit:P}=e;if(i>d)throw S.ocrLimitExceeded(d,i,p,e.thumbnails,f,l,h,P);n({stage:"converting",totalPages:i,message:"Creating document..."}),M.track("PDF Import Started",{"Total Pages":i,"File Name":c.name,Anonymous:!s});const g=await Ve({totalPages:i,title:u,token:s,timeoutMessage:"Import timed out after 10 minutes. Please try with a shorter PDF.",targetDocumentId:o,afterBlockId:r});return Ke({totalPages:i,preparePage:async m=>{const{blob:w,thumbnail:b}=await Z(a,m);return n({stage:"rasterizing",currentPage:m,totalPages:i,message:`Processing page ${m} of ${i}`,thumbnail:b}),{url:await qe(w,m,s),mediaType:"image/png",pageNumber:m}},sendBatch:(m,w)=>Q({importId:g.importId,uploadToken:g.uploadToken,pages:m,final:w})}).catch(async m=>{const w=m instanceof Error?m.message:"Failed to prepare PDF pages";console.error("[PDF Import] Background page upload failed:",m),n({stage:"error",totalPages:i,message:w});try{await Q({importId:g.importId,uploadToken:g.uploadToken,error:w})}catch(b){console.error("[PDF Import] Failed to report page upload error:",b)}}),n({stage:"complete",totalPages:i,message:"Document created! Content is streaming..."}),M.track("PDF Import Completed",{"Document ID":g.documentId,"Total Pages":i,Anonymous:!s}),{documentId:g.documentId,title:g.title,pagesProcessed:i,inputTokens:0,outputTokens:0,streaming:!0}}function oe(e){const t=e.getMap("import-progress");let o=()=>{};const r=new Promise((n,a)=>{const s=()=>{const i=t.get("stage");i!=="complete"&&i!=="error"||(o(),i==="complete"?n():a(new Error(String(t.get("error")||"PDF import failed."))))},c=setTimeout(()=>{o(),a(new Error("PDF import timed out before content was ready."))},9e5);o=()=>{clearTimeout(c),t.unobserve(s)},t.observe(s)});return r.catch(()=>{}),{done:r,cancel:()=>o()}}async function Ze(e,t,o,r,n){const a=await ee(e,void 0,r),s=oe(o);try{const c=await te(a,r,t,n);return await s.done,c}catch(c){throw s.cancel(),c}}export{S as PdfLimitError,te as confirmPdfImport,Ze as importPdfIntoExistingDocument,ee as previewPdfForImport,oe as watchImportCompletion};
1
+ import{a1 as re,T as ne,c6 as x,c7 as ae,c8 as se,aZ as C,c9 as M,ca as ie}from"./index-C-4H81OE.js";import*as v from"yjs";const E=e=>new Promise(e);Promise.all.bind(Promise);const ce=e=>new Error(e),T=e=>E((t,o)=>{e.onerror=r=>o(new Error(r.target.error)),e.onsuccess=r=>t(r.target.result)}),de=(e,t)=>E((o,r)=>{const n=indexedDB.open(e);n.onupgradeneeded=a=>t(a.target.result),n.onerror=a=>r(ce(a.target.error)),n.onsuccess=a=>{const s=a.target.result;s.onversionchange=()=>{s.close()},o(s)}}),le=e=>T(indexedDB.deleteDatabase(e)),me=(e,t)=>t.forEach(o=>e.createObjectStore.apply(e,o)),_=(e,t,o="readwrite")=>{const r=e.transaction(t,o);return t.map(n=>Pe(r,n))},U=(e,t)=>T(e.count(t)),ue=(e,t)=>T(e.get(t)),j=(e,t)=>T(e.delete(t)),he=(e,t,o)=>T(e.put(t,o)),F=(e,t)=>T(e.add(t)),pe=(e,t,o)=>T(e.getAll(t,o)),fe=(e,t,o)=>{let r=null;return ye(e,t,n=>(r=n,!1),o).then(()=>r)},ge=(e,t=null)=>fe(e,t,"prev"),we=(e,t)=>E((o,r)=>{e.onerror=r,e.onsuccess=async n=>{const a=n.target.result;if(a===null||await t(a)===!1)return o();a.continue()}}),ye=(e,t,o,r="next")=>we(e.openKeyCursor(t,r),n=>o(n.key)),Pe=(e,t)=>e.objectStore(t),Ie=(e,t)=>IDBKeyRange.upperBound(e,t),be=(e,t)=>IDBKeyRange.lowerBound(e,t),L=()=>new Map,Te=(e,t,o)=>{let r=e.get(t);return r===void 0&&e.set(t,r=o()),r},ve=()=>new Set,_e=Array.from;class Ee{constructor(){this._observers=L()}on(t,o){Te(this._observers,t,ve).add(o)}once(t,o){const r=(...n)=>{this.off(t,r),o(...n)};this.on(t,r)}off(t,o){const r=this._observers.get(t);r!==void 0&&(r.delete(o),r.size===0&&this._observers.delete(t))}emit(t,o){return _e((this._observers.get(t)||L()).values()).forEach(r=>r(...o))}destroy(){this._observers=L()}}const $="custom",O="updates",R=500,z=(e,t=()=>{},o=()=>{})=>{const[r]=_(e.db,[O]);return pe(r,be(e._dbref,!1)).then(n=>{e._destroyed||(t(r),v.transact(e.doc,()=>{n.forEach(a=>v.applyUpdate(e.doc,a))},e,!1),o(r))}).then(()=>ge(r).then(n=>{e._dbref=n+1})).then(()=>U(r).then(n=>{e._dbsize=n})).then(()=>r)},De=(e,t=!0)=>z(e).then(o=>{(t||e._dbsize>=R)&&F(o,v.encodeStateAsUpdate(e.doc)).then(()=>j(o,Ie(e._dbref,!0))).then(()=>U(o).then(r=>{e._dbsize=r}))});class ke extends Ee{constructor(t,o){super(),this.doc=o,this.name=t,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=de(t,r=>me(r,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=E(r=>this.on("synced",()=>r(this))),this._db.then(r=>{this.db=r,z(this,n=>F(n,v.encodeStateAsUpdate(o)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(r,n)=>{if(this.db&&n!==this){const[a]=_(this.db,[O]);F(a,r),++this._dbsize>=R&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{De(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},o.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),o.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(t=>{t.close()})}clearData(){return this.destroy().then(()=>{le(this.name)})}get(t){return this._db.then(o=>{const[r]=_(o,[$],"readonly");return ue(r,t)})}set(t,o){return this._db.then(r=>{const[n]=_(r,[$]);return he(n,o,t)})}del(t){return this._db.then(o=>{const[r]=_(o,[$]);return j(r,t)})}}const Se="revise-anonymous-identity",xe=1,D="identities",N="pdf-browser-id",Fe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Le(){return new Promise((e,t)=>{const o=indexedDB.open(Se,xe);o.onupgradeneeded=()=>{o.result.objectStoreNames.contains(D)||o.result.createObjectStore(D)},o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error)})}async function A(){if(typeof window>"u"||typeof indexedDB>"u"||typeof crypto>"u"||typeof crypto.randomUUID!="function")return null;let e=null;try{return e=await Le(),await new Promise((t,o)=>{const r=e.transaction(D,"readwrite"),n=r.objectStore(D),a=n.get(N);let s="";a.onsuccess=()=>{const c=typeof a.result=="string"?a.result.trim().toLowerCase():"";s=Fe.test(c)?c:crypto.randomUUID(),s!==c&&n.put(s,N)},a.onerror=()=>o(a.error),r.oncomplete=()=>t(s),r.onerror=()=>o(r.error),r.onabort=()=>o(r.error)})}catch(t){return console.warn("Unable to load anonymous PDF browser identity:",t),null}finally{e?.close()}}const J="https://sync.revise-sdk.invalid";function K(){return J}function $e(){return J.replace(/^https/,"wss")}const B="yjs_document_index",Y="anon_session_id",G="yjs_document_deleted_",Ae="local-document-deleted";function W(e){return typeof window<"u"&&localStorage.getItem(G+e)==="1"}function q(){if(typeof window>"u")return[];try{const e=localStorage.getItem(B);return e?JSON.parse(e).filter(t=>!W(t)):[]}catch(e){return console.warn("Failed to read document index:",e),[]}}function Be(e){if(!(typeof window>"u"))try{if(W(e))return;const t=q();t.includes(e)||(t.push(e),localStorage.setItem(B,JSON.stringify(t)))}catch(t){console.warn("Failed to update document index:",t)}}function Ce(e){if(!(typeof window>"u"))try{localStorage.setItem(G+e,"1"),window.dispatchEvent(new CustomEvent(Ae,{detail:{documentId:e}}));const t=q().filter(o=>o!==e);localStorage.setItem(B,JSON.stringify(t))}catch(t){console.warn("Failed to remove from document index:",t)}}function Me(){const e="abcdefghijklmnopqrstuvwxyz0123456789";let t="";for(let o=0;o<8;o++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function V(){if(typeof window>"u")return"server";let e=localStorage.getItem(Y);return e||(e=crypto.randomUUID().replace(/-/g,"").slice(0,12),localStorage.setItem(Y,e)),e}const Ue=30*60*1e3,je=3e3,Oe=15e3,k=new Map;async function Re(e){const t=Me(),o=V(),r=`anon:${o}:${t}`,n=new v.Doc,a={children:[{type:"paragraph",id:re(),children:[{type:"text",text:"",marks:{}}]}]};ne(n,a),n.transact(()=>{const l=n.getMap("metadata");l.set("id",t),l.set("documentId",t),l.set("title",x(e)),l.set("createdAt",Date.now()),l.set("updatedAt",Date.now()),l.set("lastAccessedAt",Date.now()),l.set("storageType","local")});const s=new ke(t,n);await s.whenSynced;const c=await A(),i=$e(),u=c?`${i}${i.includes("?")?"&":"?"}anonymousBrowserId=${encodeURIComponent(c)}`:i;let p=null;const d=new Promise(l=>{p=l}),f=new ae({url:se(u),name:r,document:n,token:()=>"",onSynced:()=>{p?.()}});return ze(t,n,s,f),Be(t),await Promise.race([d,new Promise(l=>setTimeout(l,Oe))]),{docId:t,anonSessionId:o,anonymousBrowserId:c}}function ze(e,t,o,r){let n=null;const a=new Promise(d=>{n=d});let s=!1;const c=()=>{if(s)return;s=!0;const d=k.get(e);d&&(clearTimeout(d.maxLifetimeTimer),k.delete(e));try{r.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying provider for ${e}:`,f)}try{o.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying persistence for ${e}:`,f)}try{t.destroy()}catch(f){console.warn(`[PdfImportKeeper] Error destroying ydoc for ${e}:`,f)}n?.()},i=t.getMap("import-progress"),u=()=>{const d=i.get("stage");(d==="complete"||d==="error")&&(i.unobserve(u),setTimeout(c,je))};i.observe(u);const p=setTimeout(()=>{console.warn(`[PdfImportKeeper] Import ${e} exceeded max lifetime; releasing`),c()},Ue);k.set(e,{docId:e,ydoc:t,persistence:o,provider:r,done:a,finish:c,maxLifetimeTimer:p})}async function Ne(e){const t=k.get(e);if(t){Ce(e);try{await t.persistence.clearData()}catch(o){console.warn(`[PdfImportKeeper] Error clearing data for ${e}:`,o)}t.finish()}}const Je=10;async function Ke(e){const t=e.batchSize??Je;for(let o=1;o<=e.totalPages;o+=t){const r=Math.min(e.totalPages,o+t-1),n=[];for(let a=o;a<=r;a+=1)n.push(await e.preparePage(a));await e.sendBatch(n,r===e.totalPages)}}const X="https://app-api.revise-sdk.invalid",Ye="https://agent.revise.io",Ge=150;class S extends Error{constructor(t){super(t.message),this.name="PdfLimitError",this.data=t}static ocrLimitExceeded(t,o,r,n,a="month",s=!1,c,i){const u=a==="day"?`You have ${t} free PDF pages left today. Create a free account for more.`:s?`You have ${t} free PDF pages left this month. Create an account for more.`:`You have ${t} PDF pages left this month. Upgrade for more.`;return new S({type:"OCR_LIMIT_EXCEEDED",remaining:t,requested:o,monthlyLimit:r,limitPeriod:a,anonymous:s,freeAccountLimit:c,maxPlanLimit:i,message:u,thumbnails:n})}}function We(){try{return typeof window<"u"?localStorage.getItem("auth_token"):null}catch{return null}}async function qe(e){try{const t=e?await fetch(`${X}/subscription/pdf-limits`,{method:"GET",headers:{Authorization:`Bearer ${e}`}}):await A().then(r=>fetch(`${Ye}/api/v1/pdf/page-limit`,{method:"GET",headers:r?{"X-Anonymous-Browser-Id":r}:void 0}));if(!t.ok)return console.warn("Failed to fetch OCR limit, using fallback"),H(e);const o=await t.json();return{ocrMonthlyLimit:o.ocrMonthlyLimit||3e3,ocrPagesRemaining:o.ocrPagesRemaining??3e3,limitPeriod:o.limitPeriod==="daily"?"day":"month",anonymous:!e,freeAccountLimit:o.freeAccountLimit,maxPlanLimit:o.maxPlanLimit}}catch(t){return console.warn("Error fetching OCR limit:",t),H(e)}}function H(e){return e?{ocrMonthlyLimit:3e3,ocrPagesRemaining:3e3,limitPeriod:"month",anonymous:!1,freeAccountLimit:100,maxPlanLimit:3e3}:{ocrMonthlyLimit:10,ocrPagesRemaining:10,limitPeriod:"month",anonymous:!0,freeAccountLimit:100,maxPlanLimit:3e3}}async function Ve(e,t,o){const r=await fetch(`${X}/uploads/images/presign`,{method:"POST",headers:{"Content-Type":"application/json",...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify({fileName:`page-${t}.png`,contentType:"image/png",fileSize:e.size,prefix:"pdf-temp"})});if(!r.ok){const c=await r.text();throw new Error(c||`Failed to get upload URL for page ${t}`)}const n=await r.json(),a=new Headers,s={...n.headers||{},"Content-Type":n.contentType||"image/png"};for(const[c,i]of Object.entries(s))i&&a.set(c,i);if(!(await fetch(n.uploadUrl,{method:n.method||"PUT",body:e,headers:a})).ok)throw new Error(`Failed to upload page ${t}`);return n.fileUrl}async function Xe(e){const{totalPages:t,title:o,token:r,timeoutMessage:n,targetDocumentId:a,afterBlockId:s}=e,c=x(o),i=!r&&!a?await Re(c):null,u=!r&&a?{docId:a,anonSessionId:V(),anonymousBrowserId:await A()}:null,p=i??u;try{const d=new AbortController,f=setTimeout(()=>d.abort(),10*60*1e3);let l;try{l=await fetch(`${K()}/api/pdf/import-streaming`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{},Accept:"text/event-stream"},body:JSON.stringify({totalPages:t,title:c,provider:ie,...r&&a?{targetDocumentId:a}:{},...a&&s?{afterBlockId:s}:{},...p?{anonSessionId:p.anonSessionId,anonDocId:p.docId,anonymousBrowserId:p.anonymousBrowserId||void 0}:{}}),signal:d.signal})}catch(P){throw P?.name==="AbortError"?new Error(n):new Error("Failed to start import. Please check your connection and try again.")}finally{clearTimeout(f)}if(!l.ok){const P=await l.text().catch(()=>"");let g={};try{g=JSON.parse(P)}catch{}throw new Error(g.error||P||`Import failed: ${l.status}`)}const h=await He(l);if(!h.importId||!h.uploadToken)throw new Error("Server did not create a page upload session.");return{documentId:h.documentId,title:h.title||c,importId:h.importId,uploadToken:h.uploadToken}}catch(d){throw i&&Ne(i.docId),d}}async function He(e){const t=e.body?.getReader();if(!t)throw new Error("Failed to read server response");const o=new TextDecoder;let r="",n="";for(;;){const{done:a,value:s}=await t.read();if(a)break;r+=o.decode(s,{stream:!0});const c=r.split(`
2
+ `);r=c.pop()||"";for(const i of c)if(i.startsWith("event: "))n=i.slice(7).trim();else if(i.startsWith("data: ")){let u=null;try{u=JSON.parse(i.slice(6))}catch{}if(u){if(n==="document_created")return t.releaseLock(),u;if(n==="error")throw t.releaseLock(),new Error(u.error||"Import failed")}n=""}}throw new Error("Server did not create document. Please try again.")}async function Z(e){const t=await fetch(`${K()}/api/pdf/import-streaming/${encodeURIComponent(e.importId)}/batches`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({uploadToken:e.uploadToken,pages:e.pages,final:e.final,error:e.error})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.error||"Failed to upload PDF page batch")}}async function Q(e,t){let o;try{o=await e.getPage(t)}catch{throw new Error(`Failed to read page ${t}. The PDF may be damaged.`)}let r=Ge/72,n=o.getViewport({scale:r});r*=1568/Math.max(n.width,n.height),n=o.getViewport({scale:r});const a=document.createElement("canvas"),s=a.getContext("2d");if(!s)throw new Error("Failed to create canvas. Your browser may not support this feature.");a.width=n.width,a.height=n.height,s.fillStyle="white",s.fillRect(0,0,a.width,a.height);try{await o.render({canvasContext:s,viewport:n}).promise}catch{throw new Error(`Failed to render page ${t}. The page may contain unsupported content.`)}const c=40,i=4;let u=!1;for(let m=0;m<c&&!u;m++){const w=Math.floor(a.width*m/c),b=Math.min(i,a.width-w);if(b<=0)continue;const y=s.getImageData(w,0,b,a.height).data;for(let I=0;I<y.length&&!u;I+=4)(y[I]<250||y[I+1]<250||y[I+2]<250)&&(u=!0)}if(!u)throw new Error(`Page ${t} appears blank. The PDF may use an unsupported image format.`);const p=await new Promise((m,w)=>{a.toBlob(b=>{b?m(b):w(new Error(`Failed to process page ${t}. The page may be too complex or large.`))},"image/png")}),d=120,f=d/a.height,l=Math.round(a.width*f),h=document.createElement("canvas");h.width=l,h.height=d;const P=h.getContext("2d");P&&P.drawImage(a,0,0,l,d);const g=h.toDataURL("image/jpeg",.7);return{blob:p,width:n.width,height:n.height,thumbnail:g}}const Ze=5;async function ee(e,t,o){const r=y=>{o&&o(y)},n=We(),{ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:u,maxPlanLimit:p}=await qe(n);r({stage:"loading",message:"Loading PDF..."});const d=await import("./pdf-BLWDCiFF.js");d.GlobalWorkerOptions.workerSrc=C("pdfjs/worker.js");const f=await e.arrayBuffer(),l=d.getDocument({data:f,wasmUrl:C("pdfjs/")});let h;try{h=await l.promise}catch(y){const I=y?.message?.toLowerCase()||"";throw I.includes("password")||I.includes("encrypted")?new Error("This PDF is password-protected. Please remove the password and try again."):I.includes("invalid")||I.includes("corrupt")?new Error("This PDF appears to be corrupted or invalid. Please try a different file."):new Error("Failed to read PDF file. Please try a different file.")}if(!h.numPages||h.numPages===0)throw new Error("This PDF has no pages.");const P=h.numPages,g=P>s,m=g?Math.min(Ze,P):0,w=[];for(let y=1;y<=m;y++){const{thumbnail:I}=await Q(h,y);w.push(I),r({stage:"rasterizing",currentPage:y,totalPages:m,message:`Preparing preview ${y} of ${m}...`,thumbnail:I})}const b=x(e.name?.replace(/\.pdf$/i,"")||"Imported PDF");return{thumbnails:w,totalPages:P,ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:u,maxPlanLimit:p,exceedsLimit:g,title:b,_pdf:h,_token:n,_file:e}}async function te(e,t,o,r){const n=m=>{t&&t(m)},{_pdf:a,_token:s,_file:c,totalPages:i,title:u,ocrMonthlyLimit:p,ocrPagesRemaining:d,limitPeriod:f,anonymous:l,freeAccountLimit:h,maxPlanLimit:P}=e;if(i>d)throw S.ocrLimitExceeded(d,i,p,e.thumbnails,f,l,h,P);n({stage:"converting",totalPages:i,message:"Creating document..."}),M.track("PDF Import Started",{"Total Pages":i,"File Name":c.name,Anonymous:!s});const g=await Xe({totalPages:i,title:u,token:s,timeoutMessage:"Import timed out after 10 minutes. Please try with a shorter PDF.",targetDocumentId:o,afterBlockId:r});return Ke({totalPages:i,preparePage:async m=>{const{blob:w,thumbnail:b}=await Q(a,m);return n({stage:"rasterizing",currentPage:m,totalPages:i,message:`Processing page ${m} of ${i}`,thumbnail:b}),{url:await Ve(w,m,s),mediaType:"image/png",pageNumber:m}},sendBatch:(m,w)=>Z({importId:g.importId,uploadToken:g.uploadToken,pages:m,final:w})}).catch(async m=>{const w=m instanceof Error?m.message:"Failed to prepare PDF pages";console.error("[PDF Import] Background page upload failed:",m),n({stage:"error",totalPages:i,message:w});try{await Z({importId:g.importId,uploadToken:g.uploadToken,error:w})}catch(b){console.error("[PDF Import] Failed to report page upload error:",b)}}),n({stage:"complete",totalPages:i,message:"Document created! Content is streaming..."}),M.track("PDF Import Completed",{"Document ID":g.documentId,"Total Pages":i,Anonymous:!s}),{documentId:g.documentId,title:g.title,pagesProcessed:i,inputTokens:0,outputTokens:0,streaming:!0}}function oe(e){const t=e.getMap("import-progress");let o=()=>{};const r=new Promise((n,a)=>{const s=()=>{const i=t.get("stage");i!=="complete"&&i!=="error"||(o(),i==="complete"?n():a(new Error(String(t.get("error")||"PDF import failed."))))},c=setTimeout(()=>{o(),a(new Error("PDF import timed out before content was ready."))},9e5);o=()=>{clearTimeout(c),t.unobserve(s)},t.observe(s)});return r.catch(()=>{}),{done:r,cancel:()=>o()}}async function Qe(e,t,o,r,n){const a=await ee(e,void 0,r),s=oe(o);try{const c=await te(a,r,t,n);return await s.done,c}catch(c){throw s.cancel(),c}}export{S as PdfLimitError,te as confirmPdfImport,Qe as importPdfIntoExistingDocument,ee as previewPdfForImport,oe as watchImportCompletion};
@@ -1,4 +1,4 @@
1
- import{V as q,W as L,X as _,Y as C,Z as D,_ as H,$ as M,a0 as O}from"./index-CjeGoI2g.js";const E=new Set(["fonttbl","colortbl","stylesheet","info","pict","object","header","footer","headerl","headerr","headerf","footerl","footerr","footerf","footnote","annotation","xmlnstbl","themedata","colorschememapping","latentstyles","datastore","listtable","listoverridetable","revtbl","generator","filetbl"]),T={emdash:"—",endash:"–",lquote:"‘",rquote:"’",ldblquote:"“",rdblquote:"”",bullet:"•",tab:" ",line:`
1
+ import{V as q,W as L,X as _,Y as C,Z as D,_ as H,$ as M,a0 as O}from"./index-C-4H81OE.js";const E=new Set(["fonttbl","colortbl","stylesheet","info","pict","object","header","footer","headerl","headerr","headerf","footerl","footerr","footerf","footnote","annotation","xmlnstbl","themedata","colorschememapping","latentstyles","datastore","listtable","listoverridetable","revtbl","generator","filetbl"]),T={emdash:"—",endash:"–",lquote:"‘",rquote:"’",ldblquote:"“",rdblquote:"”",bullet:"•",tab:" ",line:`
2
2
  `,"~":" ",_:"-","-":""};function v(h){const t=/\\ansicpg(\d+)/i.exec(h)?.[1]??"1252";return{65001:"utf-8",932:"shift_jis",936:"gb18030",949:"euc-kr",950:"big5"}[t]??`windows-${t}`}function S(h,t){try{return new TextDecoder(t).decode(h)}catch{return new TextDecoder("windows-1252").decode(h)}}const $=class{static async parseFile(t){const e=await t.arrayBuffer(),r=new Uint8Array(e),n=new TextDecoder("windows-1252").decode(r.subarray(0,512)),d=S(r,v(n));return this.fromRtf(d)}static fromRtf(t){const e=v(t),r=[];let n=[],d="",p={},o,b={},k=null;const g=[];let s={marks:{},skip:!1,unicodeSkip:1};const y=()=>{d&&(n.push({type:"text",text:d,marks:{...p}}),d="")},R=(c,l)=>{s.skip||!!s.marks[c]===l||(y(),l?s.marks[c]=!0:delete s.marks[c],p={...s.marks})},N=()=>{y();const c=n.filter(x=>x.text.length>0),l=q(c.length>0?c:[{type:"text",text:"",marks:{}}]);o&&(l.align=o),Object.keys(b).length>0&&(l.borders=JSON.stringify(b)),r.push(l),n=[]},w=c=>{s.skip||!c||(d+=c)};let i=0;const j=t.length;for(;i<j;){const c=t[i];if(c==="{"){y(),g.push(s),s={marks:{...s.marks},align:s.align,skip:s.skip,unicodeSkip:s.unicodeSkip},p={...s.marks},i++;continue}if(c==="}"){y(),s=g.pop()??{marks:{},skip:!1,unicodeSkip:1},p={...s.marks},i++;continue}if(c==="\\"){const l=t[i+1];if(l==="\\"||l==="{"||l==="}"){w(l),i+=2;continue}if(l==="'"){const u=[];for(;t.startsWith("\\'",i);){const f=parseInt(t.slice(i+2,i+4),16);if(Number.isNaN(f))break;u.push(f),i+=4}if(u.length===0){i+=2;continue}w(S(new Uint8Array(u),e));continue}if(l==="~"||l==="-"||l==="_"){w(T[l]??""),i+=2;continue}if(l===`
3
3
  `||l==="\r"){s.skip||N(),i+=2;continue}const x=/^\\([a-zA-Z]+)(-?\d+)? ?/.exec(t.slice(i));if(x){const u=x[1],f=x[2]!==void 0?parseInt(x[2],10):null;if(i+=x[0].length,E.has(u)){s.skip=!0;continue}switch(u){case"par":s.skip||N();break;case"pard":o=void 0,b={},k=null;break;case"brdrt":case"brdrb":case"brdrl":case"brdrr":{if(s.skip)break;const a={brdrt:"top",brdrb:"bottom",brdrl:"left",brdrr:"right"}[u];k=a,b[a]={style:"single",width:1,color:"#000000"};break}case"brdrs":case"brdrth":case"brdrdb":case"brdrdash":case"brdrdashsm":case"brdrdot":case"brdrnone":{if(s.skip||!k)break;const a=b[k];if(!a)break;u==="brdrnone"?(delete b[k],k=null):u==="brdrdb"?a.style="double":u==="brdrdash"||u==="brdrdashsm"?a.style="dashed":u==="brdrdot"?a.style="dotted":u==="brdrth"?(a.style="single",a.width=Math.max(a.width,2)):a.style="single";break}case"brdrw":{if(s.skip||!k||f===null)break;const a=b[k];if(!a)break;a.width=Math.min(8,Math.max(1,Math.round(f/15)));break}case"qc":o="center";break;case"qr":o="right";break;case"ql":case"qj":o=void 0;break;case"plain":y(),s.marks={},p={};break;case"b":R("bold",f!==0);break;case"i":R("italic",f!==0);break;case"ul":R("underline",f!==0);break;case"ulnone":R("underline",!1);break;case"strike":R("strikethrough",f!==0);break;case"uc":s.unicodeSkip=f??1;break;case"u":{if(f!==null&&!s.skip){const I=f<0?f+65536:f;w(String.fromCharCode(I))}let a=s.unicodeSkip;for(;a>0&&i<j;)t.startsWith("\\'",i)?i+=4:i+=1,a--;break}default:if(u in T){const a=T[u];a===`
4
4
  `?s.skip||N():w(a===" "?" ":a)}break}continue}if(l==="*"){s.skip=!0,i+=2;continue}i++;continue}if(c===`
@@ -1,4 +1,4 @@
1
- import{V as q,W as L,X as _,Y as C,Z as D,_ as H,$ as M,a0 as O}from"./index-DyOcu9mD.js";const E=new Set(["fonttbl","colortbl","stylesheet","info","pict","object","header","footer","headerl","headerr","headerf","footerl","footerr","footerf","footnote","annotation","xmlnstbl","themedata","colorschememapping","latentstyles","datastore","listtable","listoverridetable","revtbl","generator","filetbl"]),T={emdash:"—",endash:"–",lquote:"‘",rquote:"’",ldblquote:"“",rdblquote:"”",bullet:"•",tab:" ",line:`
1
+ import{V as q,W as L,X as _,Y as C,Z as D,_ as H,$ as M,a0 as O}from"./index-iZC8xN0t.js";const E=new Set(["fonttbl","colortbl","stylesheet","info","pict","object","header","footer","headerl","headerr","headerf","footerl","footerr","footerf","footnote","annotation","xmlnstbl","themedata","colorschememapping","latentstyles","datastore","listtable","listoverridetable","revtbl","generator","filetbl"]),T={emdash:"—",endash:"–",lquote:"‘",rquote:"’",ldblquote:"“",rdblquote:"”",bullet:"•",tab:" ",line:`
2
2
  `,"~":" ",_:"-","-":""};function v(h){const t=/\\ansicpg(\d+)/i.exec(h)?.[1]??"1252";return{65001:"utf-8",932:"shift_jis",936:"gb18030",949:"euc-kr",950:"big5"}[t]??`windows-${t}`}function S(h,t){try{return new TextDecoder(t).decode(h)}catch{return new TextDecoder("windows-1252").decode(h)}}const $=class{static async parseFile(t){const e=await t.arrayBuffer(),r=new Uint8Array(e),n=new TextDecoder("windows-1252").decode(r.subarray(0,512)),d=S(r,v(n));return this.fromRtf(d)}static fromRtf(t){const e=v(t),r=[];let n=[],d="",p={},o,b={},k=null;const g=[];let s={marks:{},skip:!1,unicodeSkip:1};const y=()=>{d&&(n.push({type:"text",text:d,marks:{...p}}),d="")},R=(c,l)=>{s.skip||!!s.marks[c]===l||(y(),l?s.marks[c]=!0:delete s.marks[c],p={...s.marks})},N=()=>{y();const c=n.filter(x=>x.text.length>0),l=q(c.length>0?c:[{type:"text",text:"",marks:{}}]);o&&(l.align=o),Object.keys(b).length>0&&(l.borders=JSON.stringify(b)),r.push(l),n=[]},w=c=>{s.skip||!c||(d+=c)};let i=0;const j=t.length;for(;i<j;){const c=t[i];if(c==="{"){y(),g.push(s),s={marks:{...s.marks},align:s.align,skip:s.skip,unicodeSkip:s.unicodeSkip},p={...s.marks},i++;continue}if(c==="}"){y(),s=g.pop()??{marks:{},skip:!1,unicodeSkip:1},p={...s.marks},i++;continue}if(c==="\\"){const l=t[i+1];if(l==="\\"||l==="{"||l==="}"){w(l),i+=2;continue}if(l==="'"){const u=[];for(;t.startsWith("\\'",i);){const f=parseInt(t.slice(i+2,i+4),16);if(Number.isNaN(f))break;u.push(f),i+=4}if(u.length===0){i+=2;continue}w(S(new Uint8Array(u),e));continue}if(l==="~"||l==="-"||l==="_"){w(T[l]??""),i+=2;continue}if(l===`
3
3
  `||l==="\r"){s.skip||N(),i+=2;continue}const x=/^\\([a-zA-Z]+)(-?\d+)? ?/.exec(t.slice(i));if(x){const u=x[1],f=x[2]!==void 0?parseInt(x[2],10):null;if(i+=x[0].length,E.has(u)){s.skip=!0;continue}switch(u){case"par":s.skip||N();break;case"pard":o=void 0,b={},k=null;break;case"brdrt":case"brdrb":case"brdrl":case"brdrr":{if(s.skip)break;const a={brdrt:"top",brdrb:"bottom",brdrl:"left",brdrr:"right"}[u];k=a,b[a]={style:"single",width:1,color:"#000000"};break}case"brdrs":case"brdrth":case"brdrdb":case"brdrdash":case"brdrdashsm":case"brdrdot":case"brdrnone":{if(s.skip||!k)break;const a=b[k];if(!a)break;u==="brdrnone"?(delete b[k],k=null):u==="brdrdb"?a.style="double":u==="brdrdash"||u==="brdrdashsm"?a.style="dashed":u==="brdrdot"?a.style="dotted":u==="brdrth"?(a.style="single",a.width=Math.max(a.width,2)):a.style="single";break}case"brdrw":{if(s.skip||!k||f===null)break;const a=b[k];if(!a)break;a.width=Math.min(8,Math.max(1,Math.round(f/15)));break}case"qc":o="center";break;case"qr":o="right";break;case"ql":case"qj":o=void 0;break;case"plain":y(),s.marks={},p={};break;case"b":R("bold",f!==0);break;case"i":R("italic",f!==0);break;case"ul":R("underline",f!==0);break;case"ulnone":R("underline",!1);break;case"strike":R("strikethrough",f!==0);break;case"uc":s.unicodeSkip=f??1;break;case"u":{if(f!==null&&!s.skip){const I=f<0?f+65536:f;w(String.fromCharCode(I))}let a=s.unicodeSkip;for(;a>0&&i<j;)t.startsWith("\\'",i)?i+=4:i+=1,a--;break}default:if(u in T){const a=T[u];a===`
4
4
  `?s.skip||N():w(a===" "?" ":a)}break}continue}if(l==="*"){s.skip=!0,i+=2;continue}i++;continue}if(c===`
@@ -0,0 +1,45 @@
1
+ import{C as q,aP as L,f as _,aQ as C}from"./backend-BIhAX-Gi.js";import{f as D}from"./footnoteFlatten-Bekh8ZfM.js";import{a as H,e as M}from"./ListNumbering-Qlu6AuRZ.js";import{b as O}from"./TableGrid-DbroRucl.js";
2
+ const P=new Set(["fonttbl","colortbl","stylesheet","info","pict","object","header","footer","headerl","headerr","headerf","footerl","footerr","footerf","footnote","annotation","xmlnstbl","themedata","\
3
+ colorschememapping","latentstyles","datastore","listtable","listoverridetable","revtbl","generator","filetbl"]),T={emdash:"—",endash:"–",lquote:"‘",rquote:"’",ldblquote:"“",rdblquote:"”",bullet:"\
4
+ •",tab:" ",line:`
5
+ `,"~":" ",_:"-","-":""};function v(p){const t=/\\ansicpg(\d+)/i.exec(p)?.[1]??"1252";return{65001:"utf-8",932:"shift_jis",936:"gb18030",949:"euc-kr",950:"big5"}[t]??`windows-${t}`}function S(p,t){try{
6
+ return new TextDecoder(t).decode(p)}catch{return new TextDecoder("windows-1252").decode(p)}}const $=class{static async parseFile(t){const e=await t.arrayBuffer(),r=new Uint8Array(e),n=new TextDecoder(
7
+ "windows-1252").decode(r.subarray(0,512)),d=S(r,v(n));return this.fromRtf(d)}static fromRtf(t){const e=v(t),r=[];let n=[],d="",h={},o,b={},k=null;const m=[];let s={marks:{},skip:!1,unicodeSkip:1};const y=()=>{
8
+ d&&(n.push({type:"text",text:d,marks:{...h}}),d="")},R=(c,l)=>{s.skip||!!s.marks[c]===l||(y(),l?s.marks[c]=!0:delete s.marks[c],h={...s.marks})},N=()=>{y();const c=n.filter(x=>x.text.length>0),l=q(c.length>
9
+ 0?c:[{type:"text",text:"",marks:{}}]);o&&(l.align=o),Object.keys(b).length>0&&(l.borders=JSON.stringify(b)),r.push(l),n=[]},w=c=>{s.skip||!c||(d+=c)};let i=0;const j=t.length;for(;i<j;){const c=t[i];if(c===
10
+ "{"){y(),m.push(s),s={marks:{...s.marks},align:s.align,skip:s.skip,unicodeSkip:s.unicodeSkip},h={...s.marks},i++;continue}if(c==="}"){y(),s=m.pop()??{marks:{},skip:!1,unicodeSkip:1},h={...s.marks},i++;
11
+ continue}if(c==="\\"){const l=t[i+1];if(l==="\\"||l==="{"||l==="}"){w(l),i+=2;continue}if(l==="'"){const u=[];for(;t.startsWith("\\'",i);){const f=parseInt(t.slice(i+2,i+4),16);if(Number.isNaN(f))break;
12
+ u.push(f),i+=4}if(u.length===0){i+=2;continue}w(S(new Uint8Array(u),e));continue}if(l==="~"||l==="-"||l==="_"){w(T[l]??""),i+=2;continue}if(l===`
13
+ `||l==="\r"){s.skip||N(),i+=2;continue}const x=/^\\([a-zA-Z]+)(-?\d+)? ?/.exec(t.slice(i));if(x){const u=x[1],f=x[2]!==void 0?parseInt(x[2],10):null;if(i+=x[0].length,P.has(u)){s.skip=!0;continue}switch(u){case"\
14
+ par":s.skip||N();break;case"pard":o=void 0,b={},k=null;break;case"brdrt":case"brdrb":case"brdrl":case"brdrr":{if(s.skip)break;const a={brdrt:"top",brdrb:"bottom",brdrl:"left",brdrr:"right"}[u];k=a,b[a]=
15
+ {style:"single",width:1,color:"#000000"};break}case"brdrs":case"brdrth":case"brdrdb":case"brdrdash":case"brdrdashsm":case"brdrdot":case"brdrnone":{if(s.skip||!k)break;const a=b[k];if(!a)break;u==="brd\
16
+ rnone"?(delete b[k],k=null):u==="brdrdb"?a.style="double":u==="brdrdash"||u==="brdrdashsm"?a.style="dashed":u==="brdrdot"?a.style="dotted":u==="brdrth"?(a.style="single",a.width=Math.max(a.width,2)):a.
17
+ style="single";break}case"brdrw":{if(s.skip||!k||f===null)break;const a=b[k];if(!a)break;a.width=Math.min(8,Math.max(1,Math.round(f/15)));break}case"qc":o="center";break;case"qr":o="right";break;case"\
18
+ ql":case"qj":o=void 0;break;case"plain":y(),s.marks={},h={};break;case"b":R("bold",f!==0);break;case"i":R("italic",f!==0);break;case"ul":R("underline",f!==0);break;case"ulnone":R("underline",!1);break;case"\
19
+ strike":R("strikethrough",f!==0);break;case"uc":s.unicodeSkip=f??1;break;case"u":{if(f!==null&&!s.skip){const I=f<0?f+65536:f;w(String.fromCharCode(I))}let a=s.unicodeSkip;for(;a>0&&i<j;)t.startsWith(
20
+ "\\'",i)?i+=4:i+=1,a--;break}default:if(u in T){const a=T[u];a===`
21
+ `?s.skip||N():w(a===" "?" ":a)}break}continue}if(l==="*"){s.skip=!0,i+=2;continue}i++;continue}if(c===`
22
+ `||c==="\r"){i++;continue}w(c),i++}for(y(),n.some(c=>c.text.trim().length>0)&&N();r.length>0&&A(r[0]);)r.shift();for(;r.length>0&&A(r[r.length-1]);)r.pop();return r.length===0&&r.push(q()),{type:"doc",
23
+ children:r}}static toRtf(t){t=D(t),this.exportListNumbering=H(t);const e=[];for(const r of t.children){const n=this.blockToRtf(r,t);n!==null&&e.push(n)}return this.exportListNumbering=null,`{\\rtf1\\ans\
24
+ i\\ansicpg1252\\deff0\\uc1{\\fonttbl{\\f0\\froman Times New Roman;}{\\f1\\fmodern Courier New;}}
25
+ \\f0\\fs24
26
+ `+e.join(`
27
+ `)+`
28
+ }`}static blockToRtf(t,e){switch(t.type){case"paragraph":return C(t)?"\\pard\\brdrb\\brdrs\\brdrw15 \\par":this.paragraphToRtf(t);case"list":return this.listToRtf(t);case"table":return this.tableToRtf(
29
+ t);case"code":return"\\pard{\\f1\\fs20 "+g(t.content).replace(/\n/g,"\\line ")+"}\\par";case"math":return"\\pard "+g(t.content)+"\\par";case"toc":{const r=L(e,_(t));return r.length===0?null:r.map(n=>`\
30
+ \\pard${t.direction==="rtl"?"\\rtlpar":"\\ltrpar"}${t.align==="justify"?"\\qj":t.align==="center"?"\\qc":(t.align??(t.direction==="rtl"?"right":"left"))==="right"?"\\qr":"\\ql"}\\${t.direction==="rtl"?
31
+ "ri":"li"}${(n.level-1)*360} `+g(n.text)+"\\par").join(`
32
+ `)}case"image":return"\\pard{\\i [Image"+(t.alt?`: ${g(t.alt)}`:"")+"]}\\par";case"page-break":return"\\page";case"container":return t.children.map(r=>this.blockToRtf(r,e)).filter(r=>r!==null).join(`
33
+ `);default:return null}}static paragraphToRtf(t){let e="\\pard";t.align==="center"?e+="\\qc":t.align==="right"?e+="\\qr":t.align==="justify"&&(e+="\\qj");let r=this.inlineNodesToRtf(t.children);return t.
34
+ heading&&(r=`{\\b\\fs${this.HEADING_HALF_POINTS[t.heading-1]} ${r}}`),`${e} ${r}\\par`}static listToRtf(t){const e=this.exportListNumbering?.get(t.id);let r=e?M(e):t.startNumber??1;const n=[];for(const d of t.
35
+ children){if(d.type!=="list-item")continue;const h=((d.indentLevel??0)+1)*360;let o;t.variant==="ordered"?(o=`${r}. `,r++):t.variant==="todo"?o=d.checked?"[x] ":"[ ] ":o="\\bullet ",n.push(`\\pard\\li${h}\
36
+ ${o}`+this.inlineNodesToRtf(d.children)+"\\par")}return n.join(`
37
+ `)}static tableToRtf(t){if(!t.children||t.children.length===0)return"";const e=O(t),r=9360,n=[];for(let d=0;d<e.rows;d++){const h=["\\trowd\\trgaph108"];for(let o=0;o<e.cols;o++)h.push(`\\cellx${Math.
38
+ round(r*(o+1)/e.cols)}`);for(let o=0;o<e.cols;o++){const b=e.occupancy[d][o];let k="";b&&b.row===d&&b.col===o&&(k=b.cell.children.map(m=>m.type==="paragraph"?this.inlineNodesToRtf(m.children):m.type===
39
+ "code"?g(m.content):"").filter(m=>m.length>0).join("\\line ")),h.push(`\\pard\\intbl ${k}\\cell`)}h.push("\\row"),n.push(h.join(""))}return n.join(`
40
+ `)+`
41
+ \\pard`}static inlineNodesToRtf(t){return t.map(e=>this.textNodeToRtf(e)).join("")}static textNodeToRtf(t){if(t.marks?.footnoteRef)return`{\\super ${g(t.text)}}`;const e=g(t.text).replace(/\n/g,"\\line\
42
+ ");if(!t.marks)return e;const r=[];t.marks.bold&&r.push("\\b"),t.marks.italic&&r.push("\\i"),t.marks.underline&&r.push("\\ul"),t.marks.strikethrough&&r.push("\\strike"),t.marks.superscript&&r.push("\\\
43
+ super"),t.marks.subscript&&r.push("\\sub"),t.marks.code&&r.push("\\f1");const n=r.length>0?`{${r.join("")} ${e}}`:e;return t.marks.link?`{\\field{\\*\\fldinst HYPERLINK "${g(t.marks.link)}"}{\\fldrslt ${n}\
44
+ }}`:n}};$.exportListNumbering=null,$.HEADING_HALF_POINTS=[32,28,26,24,22,22];let E=$;function g(p){let t="";for(let e=0;e<p.length;e++){const r=p[e];if(r==="\\"||r==="{"||r==="}"){t+="\\"+r;continue}const n=p.
45
+ charCodeAt(e);if(n<128){t+=r;continue}t+=`\\u${n>32767?n-65536:n}?`}return t}function A(p){return p.borders?!1:p.children.every(t=>t.type==="text"&&t.text.trim()==="")}export{E as RtfConverter,g as escapeRtfText};
@@ -0,0 +1,30 @@
1
+ import{k as N}from"./backend-BIhAX-Gi.js";const g="#C0C0C0",p=.3,$=.5,z=.7;function y(t){if(typeof t!="string"||t.trim()==="")return null;let o;try{const i=JSON.parse(t);if(typeof i=="string")o={text:i};else if(i&&
2
+ typeof i=="object"&&typeof i.text=="string")o=i;else return null}catch{o={text:t}}const e=o.text.trim();if(!e)return null;const n=typeof o.opacity=="number"&&o.opacity>=0&&o.opacity<=1?o.opacity:p,r=typeof o.
3
+ fontSizePx=="number"&&o.fontSizePx>0?o.fontSizePx:void 0;return{text:e,color:typeof o.color=="string"&&o.color.trim()!==""?o.color:g,opacity:n,diagonal:o.diagonal!==!1,...r!==void 0?{fontSizePx:r}:{}}}
4
+ function x(t){const o={text:t.text};return typeof t.color=="string"&&t.color.trim()!==""&&t.color.toUpperCase()!==g&&(o.color=t.color),typeof t.opacity=="number"&&t.opacity>=0&&t.opacity<=1&&t.opacity!==
5
+ p&&(o.opacity=t.opacity),t.diagonal===!1&&(o.diagonal=!1),typeof t.fontSizePx=="number"&&t.fontSizePx>0&&(o.fontSizePx=t.fontSizePx),JSON.stringify(o)}function P(t){if(t==null)return null;const o=y(t);
6
+ return o?x(o):null}function C(t,o,e,n){if(t.fontSizePx)return t.fontSizePx;const r=Math.hypot(o,e)*z,i=100;let s=0;try{s=n(t.text,i)}catch{s=0}(!Number.isFinite(s)||s<=0)&&(s=t.text.length*i*.6);const c=i*
7
+ r/s;return Math.max(12,Math.min(400,c))}function k(t,o){return Math.max(1,t-o.left-o.right)}const F=new Set(["single","dashed","dotted","double","none"]),L=24,m=200;function O(t){if(typeof t!="object"||
8
+ t===null)return;const o=t,e=typeof o.style=="string"&&F.has(o.style)?o.style:"single",n=Number(o.width),r=Number.isFinite(n)?Math.min(Math.max(0,n),L):1,i=typeof o.color=="string"&&o.color.trim().length>
9
+ 0?o.color.trim():"#cccccc";return{style:e,width:r,color:i}}const a=new Map,h=new Map;function w(t,o){let e;try{e=JSON.parse(t)}catch{return null}if(typeof e!="object"||e===null)return null;const n=e,r={},
10
+ i=o?["top","bottom","left","right","insideH","insideV"]:["top","bottom","left","right"];let s=!1;for(const c of i){const l=O(n[c]);l&&(r[c]=l,s=!0)}return s?r:null}function T(t){if(!t)return;let o=a.get(
11
+ t);return o===void 0&&(o=w(t,!0),a.size>500&&a.clear(),a.set(t,o)),o??void 0}function J(t){if(!t)return;const o=`cell:${t}`;let e=a.get(o);return e===void 0&&(e=w(t,!1),a.size>500&&a.clear(),a.set(o,e)),
12
+ e??void 0}function v(t){if(!t)return;let o=h.get(t);return o===void 0&&(o=(()=>{let e;try{e=JSON.parse(t)}catch{return null}if(typeof e!="object"||e===null)return null;const n=e,r=u=>{const f=Number(n[u]);
13
+ return Number.isFinite(f)?Math.min(Math.max(0,f),m):void 0},i=r("top"),s=r("right"),c=r("bottom"),l=r("left");return i===void 0&&s===void 0&&c===void 0&&l===void 0?null:{top:i??0,right:s??0,bottom:c??
14
+ 0,left:l??0}})(),h.size>500&&h.clear(),h.set(t,o)),o??void 0}function M(t){const o={};for(const e of["top","bottom","left","right","insideH","insideV"]){const n=t[e];n&&(o[e]={style:n.style,width:n.width,
15
+ color:n.color})}return Object.keys(o).length>0?JSON.stringify(o):void 0}function j(t){const o=e=>Number.isFinite(e)?Math.min(Math.max(0,e),m):0;if(!(t.top===void 0&&t.right===void 0&&t.bottom===void 0&&
16
+ t.left===void 0))return JSON.stringify({top:o(t.top),right:o(t.right),bottom:o(t.bottom),left:o(t.left)})}function H(t,o){const e=v(o);if(e)return e;const n=Number.isFinite(t)?Math.max(0,Math.round(t)):
17
+ 8;return{top:n,right:n,bottom:n,left:n}}function V(t){const{tableBorders:o,cellBorders:e,flags:n,fallback:r}=t,i=(s,c,l)=>(s?o?.[c]:o?.[l])??r;return{top:e?.top??i(n.isTopRow,"top","insideH"),bottom:e?.
18
+ bottom??i(n.isBottomRow,"bottom","insideH"),left:e?.left??i(n.isLeftCol,"left","insideV"),right:e?.right??i(n.isRightCol,"right","insideV")}}function S(t){const o=Math.max(1,t.width);return t.style===
19
+ "dashed"?[o*3,o*2]:t.style==="dotted"?[o,o*1.5]:[]}function B(t,o,e,n,r,i){if(o.style==="none"||o.width<=0)return;t.save(),t.strokeStyle=o.color;const s=S(o);if(s.length>0&&t.setLineDash(s),o.style===
20
+ "double"){const c=Math.max(o.width/3,.5),l=o.width-c;t.lineWidth=c;const u=n===i,f=u?0:l/2,d=u?l/2:0;t.beginPath(),t.moveTo(e-f,n-d),t.lineTo(r-f,i-d),t.moveTo(e+f,n+d),t.lineTo(r+f,i+d),t.stroke()}else
21
+ t.lineWidth=o.width,t.beginPath(),t.moveTo(e,n),t.lineTo(r,i),t.stroke();t.restore()}const R={single:"solid",dashed:"dashed",dotted:"dotted",double:"double",none:"none"};function W(t){return t.style===
22
+ "none"||t.width<=0?"none":`${t.width}px ${R[t.style]} ${t.color}`}function b(t){if(!t)return;const o=t.trim();if(!o)return;if(/(?:^|\s)(none|hidden)(?=\s|$)/i.test(o)||/^0(?:\.0+)?(?:px|pt)?$/i.test(o))
23
+ return{style:"none",width:0,color:"#000000"};const e=o.match(/\b(solid|dashed|dotted|double)\b/i);if(!e)return;const n=e[1].toLowerCase()==="solid"?"single":e[1].toLowerCase(),r=o.match(/\b([\d.]+)\s*(px|pt)\b/i);
24
+ let i=1;if(r){const l=Number(r[1]);if(Number.isFinite(l)){const u=r[2].toLowerCase()==="pt"?l*4/3:l;i=Math.min(Math.max(0,u),24)}}const s=o.replace(e[0]," ").replace(r?.[0]??""," ").trim(),c=s?N(s):"#\
25
+ cccccc";if(c)return{style:n,width:i,color:c}}function D(t){return t.top===t.right&&t.top===t.bottom&&t.top===t.left?`${t.top}px`:`${t.top}px ${t.right}px ${t.bottom}px ${t.left}px`}function E(t){if(!t)
26
+ return;const o=t.trim().split(/\s+/);if(o.length===0||o.length>4)return;const e=[];for(const c of o){const l=c.match(/^([\d.]+)(px)?$/i);if(!l)return;const u=Number(l[1]);if(!Number.isFinite(u))return;
27
+ e.push(Math.min(Math.max(0,u),m))}const[n,r=n,i=n,s=r]=e;return{top:n,right:r,bottom:i,left:s}}function q(t){return t.style==="single"&&t.width===1&&(t.color.toLowerCase()==="#ccc"||t.color.toLowerCase()===
28
+ "#cccccc")}function A(t){if(!t)return;const o=i=>{const s=t.match(new RegExp(`(?:^|;)\\s*${i}\\s*:\\s*([^;]+)`,"i"));return s?s[1].trim():void 0},e=b(o("border")),n={};let r=!1;for(const i of["top","r\
29
+ ight","bottom","left"]){const s=b(o(`border-${i}`))??e;s&&(n[i]=s,q(s)||(r=!0))}if(r)return n}function G(t){return t?M(t):void 0}export{$ as W,T as a,J as b,W as c,v as d,D as e,G as f,A as g,E as h,j as i,
30
+ x as j,y as k,p as l,C as m,P as n,S as o,b as p,V as q,H as r,M as s,k as t,B as u};
@@ -0,0 +1,12 @@
1
+ const M=r=>Math.max(1,Math.floor(r.colSpan??1)),S=r=>Math.max(1,Math.floor(r.rowSpan??1));function x(r){return r.children.reduce((h,t)=>h+M(t),0)}function y(r){const h=r.children.length;let t=r.columnWidths?.
2
+ length??0;for(const c of r.children)t=Math.max(t,x(c));t=Math.max(t,1);const i=Array.from({length:h},()=>new Array(t).fill(void 0)),n=[],f=new Map;for(let c=0;c<h;c++){const p=r.children[c];let e=0;for(let l=0;l<
3
+ p.children.length;l++){const w=p.children[l];for(;e<t&&i[c][e]!==void 0;)e++;if(e>=t)break;const u=Math.min(M(w),t-e),m=Math.min(S(w),h-c),o={cell:w,row:c,col:e,rowSpan:m,colSpan:u,physicalIndex:l};n.
4
+ push(o),f.set(w.id,o);for(let a=c;a<c+m;a++)for(let s=e;s<e+u;s++)i[a][s]===void 0&&(i[a][s]=o);e+=u}}return{rows:h,cols:t,cells:n,byId:f,occupancy:i}}function b(r,h){let{top:t,left:i,bottom:n,right:f}=h;
5
+ t=Math.max(0,Math.min(t,r.rows-1)),n=Math.max(t,Math.min(n,r.rows-1)),i=Math.max(0,Math.min(i,r.cols-1)),f=Math.max(i,Math.min(f,r.cols-1));let c=!0;for(;c;){c=!1;for(let p=t;p<=n;p++)for(let e=i;e<=f;e++){
6
+ const l=r.occupancy[p][e];l&&(l.row<t&&(t=l.row,c=!0),l.col<i&&(i=l.col,c=!0),l.row+l.rowSpan-1>n&&(n=l.row+l.rowSpan-1,c=!0),l.col+l.colSpan-1>f&&(f=l.col+l.colSpan-1,c=!0))}}return{top:t,left:i,bottom:n,
7
+ right:f}}function g(r,h){let t=r.filter(n=>Number.isFinite(n)&&n>0);if(t.length>h&&(t=t.slice(0,h)),t.length<h){const n=t.reduce((p,e)=>p+e,0),f=h-t.length,c=n>0?n/Math.max(t.length,1):100/h;t=t.concat(
8
+ Array(f).fill(c))}const i=t.reduce((n,f)=>n+f,0);return i<=0?Array(h).fill(100/h):Math.abs(i-100)<.01?t:t.map(n=>n/i*100)}function A(r,h,t,i){const n=g(t,r.cols).map(o=>h*o/100),f=[];let c=0;for(const o of n)
9
+ f.push(c),c+=o;const p=o=>{let a=0;for(let s=o.col;s<o.col+o.colSpan;s++)a+=n[s]??0;return a},e=new Map;for(const o of r.cells)e.set(o.cell.id,i(o.cell,p(o)));const l=[];for(let o=0;o<r.rows;o++){let a=0;
10
+ for(const s of r.cells)s.row===o&&s.rowSpan===1&&(a=Math.max(a,e.get(s.cell.id)??0));l.push(a)}const w=r.cells.filter(o=>o.rowSpan>1).sort((o,a)=>o.rowSpan-a.rowSpan);for(const o of w){let a=0;for(let d=o.
11
+ row;d<o.row+o.rowSpan;d++)a+=l[d]??0;const s=(e.get(o.cell.id)??0)-a;s>0&&(l[o.row+o.rowSpan-1]+=s)}const u=[];let m=0;for(const o of l)u.push(m),m+=o;return{colLefts:f,colWidths:n,rowTops:u,rowHeights:l,
12
+ totalHeight:m,cellWidth:p,measuredCellHeight:o=>e.get(o.cell.id)??0,cellHeight:o=>{let a=0;for(let s=o.row;s<o.row+o.rowSpan;s++)a+=l[s]??0;return a}}}export{y as b,A as c,b as e,g as n};