revise 3.1.7 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/CHANGELOG.md +1677 -184
  2. package/FONT-LICENSE-HAN-EXT-B.txt +91 -0
  3. package/FONT-LICENSE-KATEX.txt +95 -0
  4. package/FONT-LICENSE-LIBERATION.txt +102 -0
  5. package/FONT-LICENSE-NOTO-MULTILINGUAL.txt +93 -0
  6. package/FONT-LICENSE-NOTO-SANS-SC.txt +93 -0
  7. package/FONT-LICENSE-NOTO.txt +94 -0
  8. package/FONT-LICENSE-SOURCE-CODE-PRO.txt +94 -0
  9. package/FONT-LICENSE-SOURCE-SERIF-4.txt +93 -0
  10. package/LICENSE +41 -21
  11. package/README.md +29 -121
  12. package/THIRD-PARTY-NOTICES.md +2751 -0
  13. package/assets/historyMaterializeWorker-ZFUHJDWr.js +619 -0
  14. package/chunks/AgentPageRenderer-CHHktDQ1.js +1 -0
  15. package/chunks/AgentPageRenderer-CN-N65JC.js +1 -0
  16. package/chunks/AttachmentDocumentImporter-DnHC9t7I.js +1 -0
  17. package/chunks/AttachmentDocumentImporter-Dqg7IPtK.js +1 -0
  18. package/chunks/ColorParserFull-BKH72fK8.js +446 -0
  19. package/chunks/DocumentScrubber-Ch_bOtHW.js +1 -0
  20. package/chunks/DocumentScrubber-DRzACkWJ.js +1 -0
  21. package/chunks/DocxConverter-BGPkGmyg.js +13 -0
  22. package/chunks/DocxConverter-DeurS5EF.js +13 -0
  23. package/chunks/DocxGraft-D71OgoMh.js +1 -0
  24. package/chunks/DocxGraft-QLkGEcwQ.js +1 -0
  25. package/chunks/FileImporter-BIT0ZBDY.js +1 -0
  26. package/chunks/FileImporter-Cgwoawuk.js +1 -0
  27. package/chunks/OdtConverter-2pm0SH5c.js +6 -0
  28. package/chunks/OdtConverter-CSUQTfVp.js +6 -0
  29. package/chunks/OfficeImportShared-C_mYnG5V.js +1 -0
  30. package/chunks/OfficeImportShared-O-d47J7O.js +1 -0
  31. package/chunks/PdfConverter-BYg_pr5J.js +21 -0
  32. package/chunks/PdfConverter-Z2HlY84F.js +21 -0
  33. package/chunks/PdfImportService-C2gwK1Sq.js +2 -0
  34. package/chunks/PdfImportService-CxtUtxM6.js +2 -0
  35. package/chunks/RtfConverter-BrtojpDV.js +15 -0
  36. package/chunks/RtfConverter-DlztsAoK.js +15 -0
  37. package/chunks/XmlConverter-3XWISlqr.js +2 -0
  38. package/chunks/XmlConverter-B1Kcohr0.js +2 -0
  39. package/chunks/__vite-browser-external-l0sNRNKZ.js +0 -0
  40. package/chunks/_revise-sdk-lazy-harfbuzz-X8gnYTZL.js +1 -0
  41. package/chunks/ar-vDYSGTpE.js +13 -0
  42. package/chunks/browser-module-BVdVmrPb.js +3 -0
  43. package/chunks/browser-module-CWlRHeO2.js +3 -0
  44. package/chunks/bundle.min-DRpfgV69.js +782 -0
  45. package/chunks/de-CWX4cvtt.js +13 -0
  46. package/chunks/es-DoAhvF6_.js +13 -0
  47. package/chunks/fil-DdAeD8Br.js +13 -0
  48. package/chunks/fr-CazsUjNQ.js +13 -0
  49. package/chunks/html2canvas.esm-CntiHiYW.js +997 -0
  50. package/chunks/index-BWdRWxoH.js +1807 -0
  51. package/chunks/index-D9_PwgOX.js +402 -0
  52. package/chunks/index-DcIXw_KB.js +402 -0
  53. package/chunks/ja-alh_QHTB.js +13 -0
  54. package/chunks/jspdf.es.min-BuJNZ-oY.js +1882 -0
  55. package/chunks/katex-DWj8TvwO.js +1462 -0
  56. package/chunks/pdf-BLWDCiFF.js +1828 -0
  57. package/chunks/persistInlineDocumentImages-DQj2iaqg.js +1 -0
  58. package/chunks/pseudoLocale-Bld5ZUFr.js +1 -0
  59. package/chunks/pseudoLocale-CLm3_c4X.js +1 -0
  60. package/chunks/tree-sitter-D6zWWUMP.js +4 -0
  61. package/chunks/wasmInline.generated-CBYFkdSM.js +1 -0
  62. package/chunks/web-tree-sitter-BXGZGnNj.js +2 -0
  63. package/chunks/zh-20eXwzFZ.js +13 -0
  64. package/cli-shim.js +34 -0
  65. package/full.js +1 -0
  66. package/index.d.ts +995 -13
  67. package/index.js +1 -31
  68. package/legacy/server.d.ts +19 -19
  69. package/legacy/server.js +39 -23
  70. package/package.json +55 -45
  71. package/serverToolContract.d.ts +420 -0
  72. package/serverToolInputs.generated.d.ts +269 -0
  73. package/style.css +1 -0
  74. package/version.d.ts +4 -0
  75. package/version.js +2 -0
  76. package/agent.d.ts +0 -139
  77. package/chunks/chunk-SMTOJL2X.js +0 -2436
  78. package/chunks/chunk-U5X47PZ6.js +0 -135
  79. package/chunks/chunk-U6YKQBKL.js +0 -15
  80. package/chunks/package-5SHL5FOJ.js +0 -14
  81. package/chunks/render-QD5VWKSV.js +0 -109
  82. package/cli-output.schema.json +0 -2159
  83. package/cli.js +0 -4152
  84. package/document.d.ts +0 -439
  85. package/docx.d.ts +0 -73
  86. package/errors.d.ts +0 -14
  87. package/legacy/editor.d.ts +0 -19
  88. package/legacy/editor.js +0 -16
  89. package/legacy/style.css +0 -2
  90. package/package.d.ts +0 -23
  91. package/render.d.ts +0 -27
@@ -0,0 +1,21 @@
1
+ import{ba as Ft,bb as oe,bc as re,aB as se,an as bt,bd as Pt,Y as le,be as ce,bf as Ht,bg as Nt,bh as Gt,bi as zt,av as Ut,bj as Kt,bk as Rt,bl as jt,aI as Yt,bm as he,bn as ge,bo as de,bp as fe,T as me,bq as Pe,br as ue,bs as pe,bt as Te,bu as xe,bv as be,bw as _e,bx as ye,by as Fe,J as $t,bz as tt,bA as Vt,bB as Se,bC as Le,bD as St,bE as we,bF as Oe,bG as Ce,ak as Me,bH as Zt,bI as ke,bJ as vt,bK as Lt,aR as It,_ as Ne,$ as Re,bL as Jt,bM as ve,bN as Bt,bO as Qt,bP as qt,bQ as Ie,bR as Be,bS as Ee,az as De,bT as Et,b7 as Xe,L as Ae,bU as We,bV as He,aV as Ge,bW as ze,bX as dt,bY as te,Q as ee,bZ as Ue,b_ as Ke,b$ as je,c0 as ae,c1 as ie,c2 as Ye,c3 as $e,c4 as Ve,c5 as Ze,c6 as Je,c7 as Qe,c8 as qe,aH as ta,F as wt,c9 as ea,ar as aa,as as ia,ca as Dt,cb as na,cc as oa,cd as ra,ce as sa,cf as la,cg as Xt,ch as ca,ci as ne,b8 as ha,cj as ga}from"./index-D9_PwgOX.js";const kt=new Map;oe(()=>kt.clear());function da(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 fa(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 ma(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 da(e)?fa(e):null}catch{return null}}async function Pa(it){let t=kt.get(it);return t||(t=ma(it),kt.set(it,t),t.then(e=>{e===null&&kt.delete(it)})),t}const J=it=>({normal:it,bold:it}),ua={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}},v=class st{static async ensureAllLatexRendered(t){const e=[],a=new Set,i=(n,l)=>{const o=`${l}:${n}`;!a.has(o)&&n.trim()&&(a.add(o),e.push({content:n,displayMode:l}))},r=n=>{if(!n||typeof n!="object")return;if(Array.isArray(n)){n.forEach(r);return}const l=n;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(n=>le(n.content,n.displayMode)))}static getLatexSvgFromCache(t,e){return ce(t,e)}static async svgToPng(t,e,a,i=3){return new Promise(r=>{const n=new Image,l="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(t);n.onload=()=>{try{const o=document.createElement("canvas");o.width=e*i,o.height=a*i;const h=o.getContext("2d");if(!h){r(null);return}h.scale(i,i),h.drawImage(n,0,0,e,a),r(o.toDataURL("image/png"))}catch(o){console.error("Failed to convert SVG to PNG:",o),r(null)}},n.onerror=()=>{r(null)},n.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 Pa(t);let n=r??null;try{if(r===void 0){const l=await fetch(Ft(`fonts/${t}`));if(l.ok){const o=await l.arrayBuffer();Ht(new Uint8Array(o))==="ttf"&&(n=this.arrayBufferToBase64(o))}}}catch{}return n||(n=await this.readFontFromDisk(t)),!n&&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,n),n}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=n=>{const l=this.mapFontFamilyToStandard(n);this.BUNDLED_GENRE_FONTS[l]&&i.add(l)};r(a);for(const n of Nt(e))r(n.value);for(const n of i){const l=this.BUNDLED_GENRE_FONTS[n],o=await Promise.all(Object.entries(l.files).map(async([h,s])=>({style:h,file:s,base64:await this.loadFontFile(s)})));if(!o.some(h=>!h.base64)){for(const{style:h,file:s,base64:g}of o)t.addFileToVFS(s,g),t.addFont(s,l.family,h);this.bundledGenreFamilies.set(n,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 n=r;if(typeof n.text=="string"&&n.text)for(const l of a)!e.has(l)&&this.SCRIPT_FALLBACK_FONTS[l].charRegex.test(n.text)&&e.add(l);i(n.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(f=>e(f,P));if(c)return c}return g[0]},r=/[\p{Letter}\p{Number}]/u,n=this.SCRIPT_FALLBACK_FONTS.japanese.charRegex,l=this.SCRIPT_FALLBACK_FONTS.korean.charRegex,o=s=>{const g=s.text??"";if(!g)return[{...s}];const P=[];let c="",f=null;for(const d of g.split(/(\s+)/)){const T=n.test(d)?"japanese":l.test(d)?"korean":null;for(const m of d){let x=i(m);if(x==="han"&&T&&(x=T),!x&&r.test(m)&&(x="base"),!x){f?f.text+=m:c+=m;continue}!f||f.key!==x?(f&&P.push(f),f={key:x,text:c+m},c=""):f.text+=m}}return f?(f.text+=c,P.push(f)):P.push({key:"base",text:c}),P.map(d=>{if(d.key==="base")return{...s,text:d.text};const T=this.SCRIPT_FALLBACK_FONTS[d.key];return{...s,text:d.text,marks:{...s.marks,fontFamily:T.family}}})},h=s=>Array.isArray(s)?s.flatMap(g=>g&&typeof g=="object"&&g.type==="text"?o(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 o=l;if(typeof o.text=="string")for(const h of o.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(o.children)};r(t.children),r(t.chrome),r(t.notes);const n=new Map;for(const l of a){const o=this.SCRIPT_FALLBACK_FONTS[l].files.normal;let h=this.fallbackCharsetCache.get(o);if(h===void 0){h=null;const s=await this.loadFontFile(o,!1);if(s)try{const g=(await import("./browser-module-CWlRHeO2.js")).create(Gt(s));h=new Set(g.characterSet??[])}catch{h=null}this.fallbackCharsetCache.set(o,h)}h&&n.set(l,h)}return(l,o)=>{const h=n.get(l);return h?h.has(o):!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 n=r?a.files.bold:a.files.normal;if(t.addFont(a.files.normal,a.family,"normal"),t.addFont(n,a.family,"bold"),t.addFont(a.files.normal,a.family,"italic"),t.addFont(n,a.family,"bolditalic"),a.shape&&!this.shapingFonts.has(a.family))try{const[l,o]=await Promise.all([import("./browser-module-CWlRHeO2.js"),import("./_revise-sdk-lazy-harfbuzz-X8gnYTZL.js")]),h=o,s=h.loadHarfBuzz?await h.loadHarfBuzz():o,g=Gt(i),P=l.create(g),c=new s.Blob(g),f=new s.Face(c),d=new s.Font(f);this.shapingFonts.set(a.family,{unitsPerEm:f.upem,notdefPathCommands:P.getGlyph(0).path.commands,layout:T=>{const m=new s.Buffer;m.addText(T),m.guessSegmentProperties(),s.shape(d,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,E)=>b+E.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 n;try{n=t.getFont(e,"normal")}catch{n=void 0}r=!!n?.metadata?.cmap?.unicode?.codeMap?.[a],this.scriptFontCoverageCache.set(i,r)}return r}static fontCoversMatchedChars(t,e,a,i){let r=!1;for(const n of a)if(i.test(n)&&(r=!0,!this.fontCoversCodePoint(t,e,n.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,n]of Object.entries(this.SCRIPT_FALLBACK_FONTS)){const l=this.scriptFallbackFamilies.get(r);if(l&&n.charRegex.test(e)&&!this.fontCoversCodePoint(t,a,n.probeCodePoint)&&!this.fontCoversMatchedChars(t,a,e,n.charRegex)){if(this.fontCoversMatchedChars(t,l,e,n.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 n=await Promise.all(Object.entries(r.files).map(async([l,o])=>({style:l,file:o,base64:await this.loadFontFile(o)})));for(const{style:l,file:o,base64:h}of n)h&&(t.addFileToVFS(o,h),t.addFont(o,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:zt(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=Ut(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,pleadingGrid:t.pleadingGrid}}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:n,pageHeight:l}=Yt(i),o=n*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,f=Math.max(1,o-c-g),d=Math.max(1,i.columnCount),T=Rt(i.columnGapTwips),m=he(f,d,T);return{orientation:i.orientation,pageWidthPt:o,pageHeightPt:h,marginTopPt:s,marginRightPt:g,marginBottomPt:P,marginLeftPt:c,contentWidthPt:m,fullContentWidthPt:f,pageMarginLeftPt:c,columnCount:d,columnGapPt:T,columnStridePt:Kt(m,T),...d>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,pleadingGrid:i.pleadingGrid}}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=Ut(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 n=this.computeEngineLayout(t);if(!n?.pageGeometries||n.pageGeometries.length===0)return a;const l=new Map(n.pageGeometries.map(g=>[g.pageIndex+1,g.pageTop])),o=(g,P)=>{if(!g||typeof g!="object")return;if(Array.isArray(g)){g.forEach(f=>o(f,P));return}const c=g;typeof c.id=="string"&&c.id&&P.add(c.id),o(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)),o(g,P)}for(const g of r){const P=h.get(g);if(!P||P.size===0)continue;const c=n.fragments.filter(x=>!x.isChrome&&typeof x.pageNumber=="number"&&P.has(x.blockId));if(c.length===0)continue;let f=Number.POSITIVE_INFINITY,d=0;for(const x of c)f=Math.min(f,x.pageNumber),d=Math.max(d,x.pageNumber);const T=l.get(d);if(T===void 0)continue;let m=0;for(const x of c)x.pageNumber===d&&(m=Math.max(m,x.bounds.y+x.bounds.height-T));m<=0||a.set(g,{pageOffset:d-f,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((o,h)=>o-h),r=o=>{let h=t;for(const s of i){if(s>o)break;h=e.get(s)}return h},n=[],l=o=>{const h=Math.max(1,Math.floor(o));for(let s=n.length+1;s<=h;s++){const g=r(s);n.push(s===1||a?.has(s)&&g.pageNumberStartExplicit?g.pageNumberStart:n[s-2]+1)}return n[h-1]};return{metricsForPage:r,numberForPage:l,labelForPage:o=>Te(l(o),r(o).pageNumberFormat)}}static async renderHeaderFooterChrome(t,e,a,i,r,n){const l=this.getPdfPageCount(t),o=f=>{if(!r)return a;let d=a,T=0;for(const[m,x]of r)m<=f&&m>T&&(d=x,T=m);return d},h=f=>{if(!n)return 0;let d=0,T=0;for(const[m,x]of n)m<=f&&m>T&&(d=x,T=m);return d},s=f=>{if(!n)return 1;let d=1;for(const[T]of n)T<=f&&T>d&&(d=T);return d},g=this.createPdfPageNumbering(a,r,n).labelForPage,P=(f,d)=>{if(e.chrome&&e.chrome.length>0)return ea(e.chrome,f,d,h(d));const T=f==="header"?e.headers:e.footers;if(!T)return;const m=d===s(d)&&T.first?"first":d%2===0&&T.even?"even":"default",x=T[m];if(x)return aa(f,m,ia(x),i)},c=async(f,d,T)=>{const m=o(T),x=f.children.slice(0,3).map((k,I)=>{const u=Dt[I];return{...k,...u&&!k.align?{align:u}:{},children:k.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 k=x.length;x.push({type:"paragraph",id:`${f.id}-pdf-column-${k}`,children:[{type:"text",text:""}],...Dt[k]?{align:Dt[k]}:{}})}const F=this.createLayoutForWrapping(m.contentWidthPt,m.indentStepPx,m),b=this.createCanvasTextContext(),E=b?na(f,b,F,e,x).map(k=>k*this.PX_TO_PT):[m.contentWidthPt/3,m.contentWidthPt/3,m.contentWidthPt/3],R=d?Math.max(10*this.PX_TO_PT,m.marginTopPt/2):m.pageHeightPt-Math.max(10*this.PX_TO_PT,m.marginBottomPt/2);let B=m.marginLeftPt;for(let k=0;k<3;k++){const I=x[k],u=E[k],p=this.measureParagraphLineAdvances(I,u,m.indentStepPx,m).reduce((C,D)=>C+D,0),S=R-p/2,w={...m,marginTopPt:S,marginLeftPt:B,marginRightPt:Math.max(0,m.pageWidthPt-B-u),contentWidthPt:Math.max(1,u)};await this.renderParagraph(t,I,S,u,i,1e9,m.indentStepPx,w),B+=u}};for(let f=0;f<l;f++){const d=f+1;t.setPage(d);const T=P("header",d),m=P("footer",d);T&&await c(T,!0,d),m&&await c(m,!1,d),await this.drawChromeImages(t,e,o(d),d,h(d))}this.renderPageNumbers(t,a,i,o,g,(f,d)=>!!P(d,f));for(let f=1;f<=l;f++){const d=o(f),T=xe(d.pageBorders,d.pageWidthPt,d.pageHeightPt,{top:d.marginTopPt,right:d.marginRightPt,bottom:d.marginBottomPt,left:d.pageMarginLeftPt},f===s(f));if(!T.length)continue;t.setPage(f);const m=t.internal?.pages?.[f],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 E=F.x1===F.x2?b:0,R=F.y1===F.y2?b:0;t.line(F.x1+E,F.y1+R,F.x2+E,F.y2+R)}}t.restoreGraphicsState(),d.pageBorders?.zOrder==="back"&&m&&m.unshift(...m.splice(x))}}static async drawChromeImages(t,e,a,i,r){if(!e.chromeImages?.length)return;const n=be({chrome:e.chrome??[],records:e.chromeImages,pageNumber:i,isFirstPage:i===1,sectionIndex:r,pageWidth:a.pageWidthPt,pageHeight:a.pageHeightPt,marginTop:a.marginTopPt,marginBottom:a.marginBottomPt,marginLeft:a.pageMarginLeftPt,marginRight:Math.max(0,a.pageWidthPt-a.pageMarginLeftPt-a.fullContentWidthPt),unit:this.PX_TO_PT});for(const l of n){const o=await this.resolveImageDataCached(t,l.src);if(o)try{t.addImage(o.data,o.format,l.x,l.y,l.width,l.height)}catch(h){console.error("Failed to add header/footer image to PDF",h)}}}static drawWatermarkOnPage(t,e,a,i){t.setFont("helvetica","normal");const r=_e(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 n=t.getTextWidth(e.text),l=this.hexToRgb(e.color);t.setTextColor(l.r,l.g,l.b);const o=typeof t.saveGraphicsState=="function"&&typeof t.setGState=="function"&&typeof t.GState=="function";o&&(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,f=n/2,d=-.35*r,T=P-(f*s+d*g),m=c-(-f*g+d*s);t.text(e.text,T,m,{...h!==0?{angle:h*180/Math.PI}:{}}),o&&t.restoreGraphicsState()}static installWatermarkUnderpaint(t,e){const a=()=>{const r=t.internal?.pageSize,n=typeof r?.getWidth=="function"?r.getWidth():r?.width,l=typeof r?.getHeight=="function"?r.getHeight():r?.height;!n||!l||this.drawWatermarkOnPage(t,e,n,l)},i=t.addPage.bind(t);t.addPage=(...r)=>{const n=i(...r);return a(),n},a()}static renderBodyLineNumbers(t,e,a,i,r){const n=s=>{let g,P=0;for(const[c,f]of a)c<=s&&c>P&&(g=f,P=c);return g??this.resolvePdfLayoutMetrics(i)},l=this.getPdfPageCount(t),o=l;let h=!1;for(let s=1;s<=l;s++){const g=n(s),P=g.pleadingGrid;P&&(t.setPage(s),h=!0,this.renderPleadingGrid(t,P,g,r?.get(s)??P.fontFamily));const c=g.lineNumbering;if(!c||e.length===0)continue;let f=c.start;if(c.restart==="continuous")for(const T of e)T.pageNumber<s&&f++;t.setPage(s),h=!0,t.setFont(this.mapFontFamily(r?.get(s)),"normal"),t.setFontSize(10*this.PX_TO_PT),t.setTextColor(115,115,115);const d=g.marginLeftPt-(c.distancePx??12)*this.PX_TO_PT;for(const T of e){if(T.pageNumber!==s)continue;const m=f++;if(m%c.countBy!==0)continue;const x=T.baselineOffset??Math.min(T.height,12);t.text(String(m),d,T.y+x,{align:"right",baseline:"alphabetic"})}}h&&t.setPage(o)}static renderPleadingGrid(t,e,a,i){t.setFont(this.mapFontFamily(i??"Times New Roman"),"normal");const r=(e.fontSizePx??16)*this.PX_TO_PT;t.setFontSize(r),t.setTextColor(0,0,0);const n=e.firstBaselinePx!==void 0?e.firstBaselinePx*this.PX_TO_PT:a.marginTopPt+r,l=(a.pageMarginLeftPt??a.marginLeftPt)-(e.distancePx??14)*this.PX_TO_PT;for(let o=0;o<e.rows;o++)t.text(String(o+1),l,n+o*e.pitchPx*this.PX_TO_PT,{align:"right",baseline:"alphabetic"})}static lineBaselineOffsetPt(t,e){let a=0;for(const i of t){if(i.latexImage||i.marks?.latex)continue;const r=i.marks?.fontSize?i.marks.fontSize*this.PX_TO_PT:e;r>a&&(a=r)}return a||e}static renderPageNumbers(t,e,a,i,r,n){const l=this.getPdfPageCount(t),o=12,h=o/2+6;t.setFont(this.mapFontFamily(a),"normal"),t.setFontSize(o),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(n?.(P,c?"header":"footer"))continue;const f=g.pageNumberPosition.endsWith("right"),d=f?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),d,T,{align:f?"right":"left"})}}static getParagraphLineIndentPt(t,e,a){return Fe(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},n=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,n.set(s,$t(r[g],g))}const o=i.map(s=>{const g=l.get(s.id)??"footnote",P=n.get(s.id)||$t(r[g]+=1,g);return{footnoteId:s.id,number:P,kind:g,blocks:s.children}}),h=s=>{const g=[...n.keys()],P=g.indexOf(s.footnoteId);return P===-1?g.length:P};return o.sort((s,g)=>h(s)-h(g))}static async renderNoteEntry(t,e,a,i,r,n,l,o,h){o&&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 f=c.marginTopPt;Object.defineProperty(c,"marginTopPt",{get:()=>h.get(this.getPdfCurrentPage(t))??f})}return(await this.renderBodyBlocks(t,e.blocks,c,n,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 n=i;n.marks?.footnoteRef&&!e.has(n.marks.footnoteRef)&&e.set(n.marks.footnoteRef,r),a(n.children,r)};for(const i of t)a(i,i.id??"");return e}static async renderBodyBlocks(t,e,a,i,r,n,l,o,h,s,g){const P=new Map,c=new Map([[1,0]]),f=[],d=[],T=Se(e);let m=s??a.marginTopPt,x=a.contentWidthPt,F=a.indentStepPx,b=!0;const E=new Map([[1,this.physicalPageMetrics(a)]]),R=()=>t.getCurrentPageInfo?.()?.pageNumber??t.getNumberOfPages();let B=0;const k=I=>{if(B=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)};k(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,R()),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 M=St.heightPx*.75,N=a.pageWidthPt-a.marginLeftPt-a.marginRightPt,G=Le(u,N/.75)*.75;!b&&a.blockSpacingPt>0&&(m+=a.blockSpacingPt),m+M>p&&(m=this.advancePdfFlowRegion(t,a).y),u.id&&P.set(u.id,R());const H=a.marginLeftPt;t.setDrawColor(107,114,128),t.setFillColor(243,244,246),t.setLineWidth(.75),t.roundedRect(H,m,G,M,St.cornerRadiusPx*.75,St.cornerRadiusPx*.75,"FD"),t.setFont("courier","normal"),t.setFontSize(St.fontPx*.75),t.setTextColor(107,114,128),t.text(we(u),H+St.paddingXPx*.75,m+M/2,{baseline:"middle"}),t.setTextColor(0,0,0),m+=M,b=!1;continue}if(u.type==="section-break"){u.id&&P.set(u.id,R());const M=l?.get(u.id),N=M?o?.(M)??M:void 0;if(N){const H=Oe(u.breakType==="continuous",{width:a.pageWidthPt,height:a.pageHeightPt},{width:N.pageWidthPt,height:N.pageHeightPt});a=N,x=N.contentWidthPt,F=N.indentStepPx,H?(m=Ce(m,a.blockSpacingPt,0,a.marginTopPt),m>this.getPdfWritableBottomPt(t,a)&&(t.addPage([a.pageWidthPt,a.pageHeightPt],a.orientation),m=a.marginTopPt)):(t.addPage([N.pageWidthPt,N.pageHeightPt],N.orientation),m=a.marginTopPt),E.set(R(),this.physicalPageMetrics(N))}else t.addPage(),m=a.marginTopPt;const G=h?.get(u.id);G!==void 0&&c.set(R(),G),k(B+1),b=!0;continue}if(u.type==="toc"){const M=a.blockSpacingPt;!b&&M>0&&(m+=M),b=!1,u.id&&P.set(u.id,R());const N=Me({children:e.map(y=>y.type==="paragraph"?this.paragraphForPdfOutput(y):y)},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??n),"normal"),t.setFontSize(G);const _=this.hexToRgb(u.color??"#000000");t.setTextColor(_.r,_.g,_.b),m+=j,N.length===0&&(m+H>p&&(m=this.advancePdfFlowRegion(t,a).y),m+=H);for(const y of N)m+H>p&&(m=this.advancePdfFlowRegion(t,a).y),d.push({pdfPage:R(),headingBlockId:y.blockId,block:u,entry:y,baseline:m+G,left:a.marginLeftPt,width:a.contentWidthPt,fontName:this.mapFontFamily(u.fontFamily??n),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,R()),u.type==="container"){const M=await this.renderContainerBlock(t,u,m,x,n,i,r,a);m=M.nextY;for(const[N,G]of M.blockStartPages)P.set(N,G);f.push(...M.lineMarks);continue}if(u.type==="placeholder"){m=this.advancePlaceholderBlock(t,u,m,a);continue}if(u.type==="image"){const M=await this.renderImageBlock(t,u,m,x,a);M&&(m=M.nextY);continue}if(u.type==="math"){const M=u;m=(await this.renderMathBlock(t,M,m,x,p,a)).nextY;continue}if(u.type==="list"){m=await this.renderListBlock(t,u,m,x,n,a,T.get(u.id),f);continue}if(u.type==="table"){m=await this.renderTableBlock(t,u,m,x,n,i,r,a);continue}if(u.type==="code"){m=await this.renderCodeBlock(t,u,m,x,p,a.marginLeftPt,i,r,a,f);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,R()),m=await this.renderParagraph(t,C,m,x,n,p,F,a,f)}if(d.length>0){const I=R(),u=this.createPdfPageNumbering(E.get(1)??a,E,c).labelForPage;for(const p of d){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=ke(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:E,pageSections:c,lineMarks:f,finalY:m}}static async renderContainerBlock(t,e,a,i,r,n,l,o){const h=Math.max(0,e.padding??vt.paddingPx)*this.PX_TO_PT,s=this.getPdfFlowBottom(t,o);a+h>s&&a!==o.marginTopPt&&(a=this.advancePdfFlowRegion(t,o).y);const g=()=>t.getCurrentPageInfo?.()?.pageNumber??t.getNumberOfPages(),P=g(),c=o.columnFlow?.index??0,f=o.columnFlow?.topPt??o.marginTopPt,d={...o,keepFirstBlockDeclaredSpaceBefore:void 0,marginTopPt:o.marginTopPt+h,marginRightPt:o.marginRightPt+h,marginBottomPt:o.marginBottomPt+h,marginLeftPt:o.marginLeftPt+h,contentWidthPt:Math.max(1,i-h*2),pageMarginLeftPt:o.pageMarginLeftPt+h},T=await this.renderBodyBlocks(t,e.children,d,n,l,r,void 0,void 0,void 0,a+h);let m=T.finalY+h;this.syncPdfColumnOffset(o),m>s&&T.finalY!==d.marginTopPt&&(m=this.advancePdfFlowRegion(t,o).y+h);const x=g(),F=o.columnFlow?.index??0,b=x,E=this.hexToRgb(e.borderColor??vt.borderColor);t.setDrawColor(E.r,E.g,E.b),t.setLineWidth(vt.borderWidthPx*this.PX_TO_PT);let R=P,B=c;for(;R<x||R===x&&B<=F;){t.setPage(R);const k=R===P&&B===c,I=R===x&&B===F,u=k?a:R===P?f:o.marginTopPt,p=I?m:s;p>u&&t.rect(o.pageMarginLeftPt+B*o.columnStridePt,u,i,p-u,"S"),B+=1,B>=o.columnCount&&(B=0,R+=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,n=this.getPdfFlowBottom(t,i);return a+r>n&&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),n=t.children.filter(S=>S.type==="section-break"),l=new Map,o=new Map,h=t.pageLayout?.pageNumberRestart===!0?{...r,pageNumberStartExplicit:!0}:r;n.forEach((S,w)=>{const C=n[w+1];l.set(S.id,C?.layout?this.resolvePdfMetricsFromSettings(C.layout,t.pageLayout,!0):C?r:h),o.set(S.id,w+1)});const s=n[0]?.layout?this.resolvePdfMetricsFromSettings(n[0].layout,t.pageLayout,!1):r,g=await import("./jspdf.es.min-BuJNZ-oY.js"),P=g.jsPDF??g.default,c=new P({orientation:s.orientation,unit:"pt",format:[s.pageWidthPt,s.pageHeightPt]}),f=this.DEFAULT_BODY_FONT,{hasSourceCodePro:d}=await this.registerDocumentFonts(c,t,f);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):[],E=b.filter(S=>S.kind==="footnote"),R=b.filter(S=>S.kind==="endnote");let B=new Map([[1,s]]),k=new Map([[1,0]]),I=s.marginTopPt,u=[],p=new Map;if(E.length===0){const S=await this.renderBodyBlocks(c,x,s,i,d,f,l,void 0,o,void 0,F);B=S.pageMetrics,k=S.pageSections,u=S.lineMarks,I=S.finalY}else{const S=E,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,f);const V=await this.renderBodyBlocks(D,x,s,i,d,f,l,void 0,void 0,void 0,F),M=L=>{let A=s,U=0;for(const[z,Y]of V.pageMetrics)z<=L&&z>U&&(A=Y,U=z);return A},N=new Map,G=D.getNumberOfPages();for(const L of S){const A=C.get(L.footnoteId),U=(A?V.blockStartPages.get(A):void 0)??G,z=N.get(U)??[];z.push(L),N.set(U,z)}const H=new P({orientation:r.orientation,unit:"pt",format:[r.pageWidthPt,1e4]});await this.registerDocumentFonts(H,t,f);const j=new Map;for(const[L,A]of N){const U=M(L);for(const z of A){const Y={...U,pageHeightPt:1e4,marginTopPt:0,marginBottomPt:0},Z=await this.renderNoteEntry(H,z,0,Y,f,i,d,!1);j.set(z.footnoteId,Math.max(0,Z))}}const _=new Map;for(const[L,A]of N){const U=M(L),z=w+A.reduce((q,rt)=>q+(j.get(rt.footnoteId)??0),0),Y=U.pageHeightPt-U.marginTopPt-U.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:[]}),nt=(Z.length>0?Math.max(0,Math.max(...Z.map(q=>q.y+q.height))-U.marginTopPt):Q*tt.minimumBodyLinesBeforeFootnotes)+tt.bodyKeepSlackPx*this.PX_TO_PT;_.set(L,Math.min(z,Math.max(0,Y-nt)))}p=_;const y=L=>({...L,reservedInsetForPage:_}),X=y(s),O=await this.renderBodyBlocks(c,x,X,i,d,f,l,y,o,void 0,F);B=O.pageMetrics,k=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[...N.entries()].sort((U,z)=>U[0]-z[0])){const U=Math.min(L,W);c.setPage(U);const z=M(L),Y=_.get(L)??0,Z=z.pageHeightPt-z.marginBottomPt-Y+w;c.setDrawColor(120),c.setLineWidth(.75),c.line(z.marginLeftPt,Z-7,z.marginLeftPt+Math.max(tt.separatorWidthMinPx*this.PX_TO_PT,z.contentWidthPt*tt.separatorWidthFraction),Z-7);let Q=Z;for(let nt=0;nt<A.length;nt++){nt>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[nt],Q,z,f,i,d,!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)??z.marginTopPt)-tt.verticalPaddingPx*this.PX_TO_PT*2;c.line(z.marginLeftPt,et,z.marginLeftPt+z.contentWidthPt,et)}c.setPage(lt[lt.length-1]??q)}}c.setPage(this.getPdfPageCount(c))}if(R.length>0){const S=new P({orientation:r.orientation,unit:"pt",format:[r.pageWidthPt,1e4]});await this.registerDocumentFonts(S,t,f);let w=tt.separatorToContentPx*this.PX_TO_PT;for(let H=0;H<R.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,R[H],0,j,f,i,d,!1)}const C=this.getPdfPageCount(c);let D=s,V=0;for(const[H,j]of B)H<=C&&H>=V&&(D=j,V=H);const M=I+tt.inlineEndnoteGapPx*this.PX_TO_PT,N=M+w<=D.pageHeightPt-D.marginBottomPt-(p.get(C)??0);let G;N?(c.setPage(C),G=M):(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<R.length;H++)H>0&&(G+=tt.blockSpacingPx*this.PX_TO_PT),G=await this.renderNoteEntry(c,R[H],G,D,f,i,d,!0)}return await this.renderHeaderFooterChrome(c,t,r,f,B,k),this.renderBodyLineNumbers(c,u,B,t,[...B.values()].some(S=>S.lineNumbering||S.pleadingGrid)?Re(this.computeEngineLayout(t),this.DEFAULT_BODY_FONT):void 0),c.output("blob")}static measureLineAdvancePt(t,e,a,i){let r=0,n=0;for(const h of t)h.latexImage?n=Math.max(n,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),o=r*l;return n>o*1.25?n:o}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,n,l,o){if(e.shading){const d=this.hexToRgb(e.shading);t.setFillColor(d.r,d.g,d.b),t.rect(a,i,r,n+(o?0:.5),"F")}const h=e.edges;if(!h)return;const s=(d,T,m,x,F)=>{const b=h[d];if(!b||b.style==="none")return;const E=Math.max(.4,(b.width??1)*this.PX_TO_PT),R=m===F,B=this.hexToRgb(b.color??"#000000");if(t.setDrawColor(B.r,B.g,B.b),t.setLineWidth(E),R&&oa(b.style)){const u=ra(T,x,this.PX_TO_PT);for(const p of u.lines)t.line(p.from,m,p.to,m);t.setFillColor(B.r,B.g,B.b);for(const p of u.ornaments)if(b.style==="stars")for(const S of sa(p.cx,m,p.radius))t.line(S.x1,S.y1,S.x2,S.y2);else{const S=la(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 k=typeof t.setLineDashPattern=="function";k&&(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+(R?0:u),m+(R?u:0),x+(R?0:u),F+(R?u:0))};b.style==="double"?(I(-E),I(E)):I(0),k&&t.setLineDashPattern([],0)},g=o?0:.5,P=d=>Math.max(0,h[d]?.space??0)*this.PX_TO_PT,c=a-P("left"),f=a+r+P("right");if(s("left",c,i,c,i+n+g),s("right",f,i,f,i+n+g),l){const d=i-P("top");s("top",a,d,a+r,d)}if(o){const d=i+n+P("bottom");s("bottom",a,d,a+r,d)}}static measureParagraphLineAdvances(t,e,a,i){const r=this.createCanvasTextContext();if(!r)return[this.getParagraphLineHeight(t)];const n=this.createLayoutForWrapping(e,a,i),l=Jt(this.paragraphForPdfOutput(t),r,n);if(l.length===0)return[this.getEmptyParagraphLineHeight(t)];const o=this.getParagraphFontSize(t),h=this.getLineSpacingMultiplier(t);return l.map(s=>this.measureLineAdvancePt(s.segments.map(g=>({marks:g.marks})),o,!!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 ve(t.direction,e)}static getEffectiveParagraphAlignment(t,e){return t.align||(e==="rtl"?"right":"left")}static getRequiredParagraphStartHeight(t,e,a,i,r){const n=t[e];if(!n||n.type!=="paragraph")return{required:0,firstLineAdvance:0};const l=Bt(n),o=this.measureParagraphLineAdvances(n,a,i,r),h=this.paragraphForPdfOutput(n).children.every(c=>c.type==="text"&&c.text==="")||o.length===0?this.getEmptyParagraphLineHeight(n):o[0],s=c=>c.reduce((f,d)=>f+Math.max(0,d),0);let g=0;if(l.keepLines?g=s(o):l.widowControl&&o.length>=2&&(g=o[0]+o[1]),!l.keepNext)return{required:g,firstLineAdvance:h};let P=0;for(let c=0;c<Qt;c++){const f=t[e+c+1];if(!f||f.type!=="paragraph")break;const d=this.measureParagraphLineAdvances(f,a,i,r);if(d.length===0)break;const T=t[e+c];P+=st.pdfSpaceBeforePt(f,r,T)+st.pdfSpaceAfterPt(T,f);const m=Bt(f);if(m.keepNext&&c<Qt-1){P+=s(d);continue}P+=d[0],m.widowControl&&d.length>=2&&(P+=d[1]);break}return{required:Math.max(g,s(o)+P),firstLineAdvance:h}}static async renderParagraph(t,e,a,i,r,n,l=this.resolveIndentStepPx(),o=this.getDefaultPdfLayoutMetrics(),h){let s=a;const g=this.paragraphForPdfOutput(e),P=this.getParagraphFontSize(e),c=this.getParagraphLineHeight(e),f=this.getLineSpacingMultiplier(e);let d=Number.isFinite(n)&&n>0?n:this.getPdfFlowBottom(t,o),T=o.marginLeftPt;const m=()=>{const k=this.advancePdfFlowRegion(t,o);s=k.y,T=k.x,d=this.getPdfFlowBottom(t,o)},x=(k=c)=>{if(s+k>d){if(s===o.marginTopPt)return;m()}},F=()=>t.getCurrentPageInfo?.()?.pageNumber??t.getNumberOfPages(),b=this.getParagraphDirection(g),E=this.getEffectiveParagraphAlignment(e,b),R=this.parseParagraphDecoration(e);if(g.children.length===0||g.children.length===1&&g.children[0].type==="text"&&g.children[0].text===""){const k=this.getEmptyParagraphLineHeight(e);return R&&(x(k),this.drawParagraphDecorationSlice(t,R,T,s,i,k,!0,!0)),s+k}const B=this.createCanvasTextContext();if(B){const k=this.createLayoutForWrapping(i,l,o),I=Jt(g,B,k),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=Bt(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),M=Math.max(1,i-V),N=this.measureLineAdvancePt(D,P,!!e.heading,f),G=p[w+1];if(S.widowControl&&I.length>=3&&w===I.length-2&&G&&s+N<=d){const j=this.measureLineAdvancePt(G,P,!!e.heading,f);s+N+j>d&&s!==o.marginTopPt&&m()}x(N);const H=b==="rtl"?T:T+V;R&&this.drawParagraphDecorationSlice(t,R,T,s,i,N,w===0,w===I.length-1),h?.push({pageNumber:F(),y:s,height:N,baselineOffset:this.lineBaselineOffsetPt(D,P)}),s=this.renderLine(t,D,s,H,M,E,P,r,!!e.heading,f,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,n,l,o)}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,n,l=this.resolveIndentStepPx(),o=this.getDefaultPdfLayoutMetrics()){let h=a;const s=this.getParagraphFontSize(e),g=this.getParagraphLineHeight(e),P=this.getLineSpacingMultiplier(e);let c=Number.isFinite(n)&&n>0?n:this.getPdfFlowBottom(t,o),f=o.marginLeftPt;const d=()=>{if(h+g>c){if(h===o.marginTopPt)return;const k=this.advancePdfFlowRegion(t,o);h=k.y,f=k.x,c=this.getPdfFlowBottom(t,o)}},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,E=0;const R=()=>Math.max(1,i-this.getParagraphLineIndentPt(e,E,l)),B=(k=!1)=>{if(F.length===0)return;d();const I=this.getParagraphLineIndentPt(e,E,l);h=this.renderLine(t,F,h,T==="rtl"?f:f+I,Math.max(1,i-I),m,s,r,!!e.heading,P,k,{direction:T}),F=[],b=0,E+=1};if(x.length===1&&x[0].text==="")return a+this.getEmptyParagraphLineHeight(e);for(const k of x){if(k.latexImage){const u=k.latexImage.contentWidth*this.PX_TO_PT;b+u>R()&&F.length>0&&B(),F.push({text:k.text,marks:k.marks,font:k.font||k.marks?.fontFamily,latexImage:k.latexImage}),b+=u;continue}this.setRunFont(t,k,r),t.setFontSize(this.getRunEffectiveFontSizePt(k.marks,s));const I=k.text.split(`
2
+ `);for(let u=0;u<I.length;u++){const p=I[u];u>0&&F.length>0&&B();const S=p.split(/(\s+)/);for(const w of S){const C=this.measureRunDisplayWidthPt(t,w,k.marks);b+C>R()&&F.length>0&&B(),(w.trim()||F.length>0)&&(F.push({text:w,marks:k.marks,font:k.font||k.marks?.fontFamily}),b+=C)}}}return F.length>0&&B(!0),h}static getLineSpacingMultiplier(t){return qt(t)}static async renderListBlock(t,e,a,i,r,n=this.getDefaultPdfLayoutMetrics(),l,o){if(!e.children.length)return a;let h=a;const s=this.getPdfFlowBottom(t,n),g=l??Ie(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 f=0;for(const T of Be(e,g))f=Math.max(f,t.getTextWidth(T)/this.PX_TO_PT);const d=this.ORDERED_LIST_INDENT_PT/this.PX_TO_PT;c=Math.min(Math.max(d,Math.ceil(f)+10),240)*this.PX_TO_PT}catch{c=void 0}for(let f=0;f<e.children.length;f++){const d=e.children[f],T=this.getListIndentLevel(d);let m;e.variant==="ordered"?m={type:"ordered",label:this.computeOrderedMarkerLabel(P,T,g.start,Ee(e.numberingFormat))}:e.variant==="todo"?m={type:"todo",checked:!!d.checked}:m={type:"bullet",indentLevel:T},h=await this.renderListItem(t,d,e,m,h,i,s,r,n,o,c)}return h}static async renderListItem(t,e,a,i,r,n,l,o,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,f=o,d=this.FONT_SIZES.normal,T=this.mapFontFamily(f);t.setFont(T,"normal"),t.setFontSize(d);const m=g??this.getListIndentPt(a.variant);let x=h.marginLeftPt,F=x+c+m,b=l;const E=()=>{const y=this.advancePdfFlowRegion(t,h);P=y.y,x=y.x,F=x+c+m,b=this.getPdfFlowBottom(t,h)};let R=n-c-m;(!Number.isFinite(R)||R<=0)&&(R=Math.max(n*.3,n*.1));let B="";for(const y of e.children)B+=y.text??"";const k=De(B)??"ltr",I=k==="rtl",u=()=>I?x:F,p=()=>I?x+R:F,S=e.lineSpacing??a.lineSpacing??this.LINE_HEIGHT_MULTIPLIERS.paragraph,w=d*S,C=await this.processTextNodesWithLatex(e.children,d);let D=C.length>0?C:[{text:""}];a.variant==="todo"&&e.checked&&(D=D.map(y=>y.latexImage?y:{...y,marks:{...y.marks,strikethrough:!0,color:Lt.todoCheckedText}}));const V=new Set(Object.values(this.SCRIPT_FALLBACK_FONTS).map(y=>y.family)),M=[...C].reverse().find(y=>!y.latexImage&&!y.marks?.latex&&y.text.length>0&&!V.has(y.marks?.fontFamily??""))?.marks;let N=[],G=0,H=!1;const j=()=>{H||(P+w>b&&P!==h.marginTopPt&&E(),this.drawListMarker(t,i,p(),P,w,d,f,o,I,M),H=!0)},_=()=>{N.length!==0&&(P+w>b&&P!==h.marginTopPt&&E(),j(),s?.push({pageNumber:t.getCurrentPageInfo?.().pageNumber??t.getNumberOfPages(),y:P,height:this.measureLineAdvancePt(N,d,!1,S),baselineOffset:this.lineBaselineOffsetPt(N,d)}),P=this.renderLine(t,N,P,u(),R,I?"right":"left",d,f,!1,S,!0,{direction:k}),N=[],G=0)};for(const y of D){if(y.latexImage){const O=y.latexImage.contentWidth*this.PX_TO_PT;G+O>R&&N.length>0&&_(),N.push({text:y.text,marks:y.marks,font:y.font,latexImage:y.latexImage}),G+=O;continue}this.setRunFont(t,y,f||o),t.setFontSize(this.getRunEffectiveFontSizePt(y.marks,d));const X=y.text.split(`
3
+ `);for(let O=0;O<X.length;O++){const K=X[O];O>0&&(N.length>0?_():(j(),P+=w));const W=K.split(/(\s+)/);for(const L of W){const A=this.measureRunDisplayWidthPt(t,L,y.marks);G+A>R&&N.length>0&&_(),(L.trim()||N.length>0)&&(N.push({text:L,marks:y.marks,font:y.font}),G+=A)}}}return N.length>0&&_(),H||(j(),P+=w),P+Math.max(0,e.spaceAfter??0)*this.PX_TO_PT}static drawListMarker(t,e,a,i,r,n,l,o,h,s){t.setDrawColor(0,0,0);const g=(f,d=0)=>h?2*a-f-d:f,P=a-this.BULLET_MARKER_WIDTH_PT,c=i+r/2;switch(e.type){case"bullet":{const f=g(P+this.BULLET_CENTER_OFFSET_PT),d=this.BULLET_RADIUS_PT;if(e.indentLevel<=0)t.circle(f,c,d,"F");else if(e.indentLevel===1)t.circle(f,c,d,"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 f=this.TODO_CHECKBOX_SIZE_PT,d=g(P-this.TODO_CHECKBOX_OFFSET_PT,f),T=c-f/2;t.setLineWidth(.8),typeof t.roundedRect=="function"?t.roundedRect(d,T,f,f,this.TODO_CHECKBOX_RADIUS_PT,this.TODO_CHECKBOX_RADIUS_PT,"S"):t.rect(d,T,f,f,"S"),e.checked&&(t.setLineWidth(1.2),t.line(d+f*.15,T+f*.55,d+f*.4,T+f*.75),t.line(d+f*.4,T+f*.75,d+f*.85,T+f*.25));break}case"ordered":{const f=e.label,d=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:f,marks:d},l||o);const T=this.getRunEffectiveFontSizePt(d,n);t.setFontSize(T);const m=t.getTextWidth(f),x=h?a+this.ORDERED_LABEL_GAP_PT:a-this.ORDERED_LABEL_GAP_PT-m;t.text(f,x,i+T);break}}t.setLineWidth(.5),t.setTextColor(0,0,0)}static async renderTableBlock(t,e,a,i,r,n=It,l=!1,o=this.getDefaultPdfLayoutMetrics()){if(!e.children||e.children.length===0)return a;const h=this.getPdfFlowBottom(t,o);let s=a;const g=e.borderWidth??Et.borderWidthPx,P=e.borderColor??Et.borderColor,c=this.hexToRgb(P),f=Number.isFinite(e.cellPadding)?Math.max(0,Math.round(e.cellPadding)):Et.cellPaddingPx,d=f*this.PX_TO_PT,T=Xe(e.borders),m=Ae(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 E=o.marginLeftPt+b;const R=We(e.columnWidths??[],x).map(_=>_/100*F),B=[0];for(let _=0;_<x;_++)B.push(B[_]+R[_]);const k=_=>B[Math.min(_.col+_.colSpan,x)]-B[_.col],I=new Map;for(const _ of m.cells){const y=He(f,_.cell.padding),X={top:y.top*this.PX_TO_PT,right:y.right*this.PX_TO_PT,bottom:y.bottom*this.PX_TO_PT,left:y.left*this.PX_TO_PT},O=k(_)-X.left-X.right,K=this.extractCellBlocks(_.cell);let W=this.FONT_SIZES.normal*this.LINE_HEIGHT_MULTIPLIERS.paragraph;if(K.length>0){const A=await import("./jspdf.es.min-BuJNZ-oY.js"),U=A.jsPDF??A.default,z=new U({orientation:"portrait",unit:"pt",format:[Math.max(72,O),this.UNBOUNDED_CELL_FLOW_BOTTOM_PT]});await this.registerCurrentPdfFonts(z,l);const Y={...o,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(z,K,Y,n,l,r,void 0,void 0,void 0,0)).finalY}const L=X.top+W+X.bottom;I.set(_.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 _.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(_=>_.rowSpan>1).sort((_,y)=>_.rowSpan-y.rowSpan);for(const _ of p){const y=I.get(_.cell.id);if(!y)continue;let X=0;for(let O=_.row;O<_.row+_.rowSpan;O++)X+=u[O];y.contentHeight>X&&(u[_.row+_.rowSpan-1]+=y.contentHeight-X)}const S=_=>{let y=0;for(let X=_.row;X<_.row+_.rowSpan;X++)y+=u[X];return y},w=[],C=()=>{if(w.length===0)return;const _=this.getPdfCurrentPage(t);for(const{page:y,draw:X}of w)t.setPage(y),X();w.length=0,t.setPage(_)},D=(_,y,X,O,K,W,L)=>{const A=_.backgroundColor?this.hexToRgb(_.backgroundColor):L?{r:249,g:250,b:251}:{r:255,g:255,b:255};(_.backgroundColor||L)&&(t.setFillColor(A.r,A.g,A.b),t.rect(X,K,O,W,"F"));const U=this.getPdfCurrentPage(t),z=ha(_.borders);if(T||z){const Y=ga({tableBorders:T,cellBorders:z,flags:{isTopRow:(y?.row??0)===0,isBottomRow:y?y.row+y.rowSpan===m.rows:!1,isLeftCol:(y?.col??0)===0,isRightCol:y?y.col+y.colSpan===m.cols:!1},fallback:{style:"single",width:g,color:P}}),Z=X+O,Q=K+W;w.push({page:U,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:U,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&&y===0,W=u[y],L=this.getPdfCurrentPage(t);for(const A of _.children){t.setPage(L);const U=m.byId.get(A.id),z=E+(U?B[U.col]:0),Y=U?k(U):F/x,Z=O||!U?W:S(U);D(A,U,z,Y,X,Z,K);const Q=I.get(A.id),nt=Q?.blocks??this.extractCellBlocks(A),q=Q?.pad.left??d,rt=Q?.pad.right??d,lt=Q?.pad.top??d,ct=Q?.pad.bottom??d,et=Q?.width??Y-q-rt,ot=Q?.flowHeight??this.FONT_SIZES.normal*this.LINE_HEIGHT_MULTIPLIERS.paragraph,ft=Math.max(0,Z-lt-ct-ot),ut=A.verticalAlign==="bottom"?ft:A.verticalAlign==="middle"?ft/2:0,Ot=X+lt+ut;if(nt.length>0){const Ct={...o,keepFirstBlockDeclaredSpaceBefore:!0,columnCount:1,columnFlow:void 0,marginTopPt:Ot,marginRightPt:Math.max(0,o.pageWidthPt-(z+q+et)),marginBottomPt:o.pageHeightPt-this.UNBOUNDED_CELL_FLOW_BOTTOM_PT,marginLeftPt:z+q,pageMarginLeftPt:z+q,contentWidthPt:Math.max(1,et),fullContentWidthPt:Math.max(1,et),columnStridePt:Math.max(1,et)};await this.renderBodyBlocks(t,nt,Ct,n,l,r,void 0,void 0,void 0,Ot)}}t.setPage(L)},M=(_,y)=>_.idx!==y.idx?_.idx>y.idx?_:y:_.y>=y.y?_:y,N=async(_,y,X,O,K,W)=>{const L=I.get(y.id),A=L?.blocks??this.extractCellBlocks(y),U=L?.pad.left??d,z=L?.pad.bottom??d,Y=X?k(X):F/x,Z=L?.width??Y-U-(L?.pad.right??d),Q=X?B[X.col]:0;let nt=O.idx;if(A.length===0){const ot=L?.flowHeight??this.FONT_SIZES.normal*this.LINE_HEIGHT_MULTIPLIERS.paragraph;return{idx:nt,y:Math.min(W,O.y+ot+z)}}const q=(ot,ft)=>{const ut=ot.left+Q+U;ft.marginTopPt=ot.top,ft.marginLeftPt=ut,ft.pageMarginLeftPt=ut,ft.marginRightPt=Math.max(0,o.pageWidthPt-(ut+Z))},rt={...o,keepFirstBlockDeclaredSpaceBefore:!0,columnCount:1,columnFlow:void 0,marginBottomPt:o.pageHeightPt-W,reservedInsetForPage:void 0,contentWidthPt:Math.max(1,Z),fullContentWidthPt:Math.max(1,Z),columnStridePt:Math.max(1,Z)},lt=K(nt);q(lt,rt),_.setPage(lt.page);const ct=_.addPage;_.addPage=()=>{nt+=1;const ot=K(nt);return q(ot,rt),_.setPage(ot.page),_};let et=O.y;try{et=(await this.renderBodyBlocks(_,A,rt,n,l,r,void 0,void 0,void 0,O.y)).finalY}finally{_.addPage=ct}return{idx:nt,y:Math.min(W,et+z)}},G=async(_,y,X)=>{const O=h,K=H&&_>0?u[0]:0,W=o.marginTopPt+K,L=await import("./jspdf.es.min-BuJNZ-oY.js"),A=L.jsPDF??L.default,U=new A({orientation:o.orientation,unit:"pt",format:[o.pageWidthPt,o.pageHeightPt]});await this.registerCurrentPdfFonts(U,l);const z=U.addPage.bind(U),Y=[{page:1,top:o.marginTopPt,left:E}],Z=$=>{for(;Y.length<=$;)z(),Y.push({page:Y.length+1,top:W,left:E});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}},nt=[],q=[],rt=new Map,lt=[];let ct={idx:0,y:X};for(let $=_;$<y;$++){const at=ct;nt[$-_]=at;for(const gt of e.children[$].children){const mt=m.byId.get(gt.id),xt=I.get(gt.id)?.pad.top??d,Mt=at.y+xt>O+.01?{idx:at.idx+1,y:W+xt}:{idx:at.idx,y:at.y+xt};rt.set(gt.id,Mt);const Tt=await N(U,gt,mt,Mt,Z,O),_t=Math.min(y-1,$+(mt?.rowSpan??1)-1),yt=lt[_t-_];lt[_t-_]=yt?M(yt,Tt):Tt}const pt=Q(at,u[$]),ht=lt[$-_];ct=ht?M(pt,ht):pt,q[$-_]=ct}let et=ct.idx;for(const $ of rt.values())et=Math.max(et,$.idx);et=Math.max(et,Y.length-1);const ot=[{page:this.getPdfCurrentPage(t),top:o.marginTopPt,left:E}],ft=t.addPage,ut=()=>{const $=this.advancePdfFlowRegion(t,o);return E=$.x+b,{page:this.getPdfCurrentPage(t),top:$.y+K,left:E}};for(let $=1;$<=et;$++){const at=ut();ot.push(at),K>0&&await V(e.children[0],0,at.top-K,!0)}const Ot=$=>{for(;ot.length<=$;){const at=t.addPage;t.addPage=ft;try{ot.push(ut())}finally{t.addPage=at}}return ot[$]};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(y-1,$+(ht?.rowSpan??1)-1),mt=nt[$-_],xt=q[gt-_],Mt=ht?k(ht):F/x;for(let Tt=mt.idx;Tt<=xt.idx;Tt++){const _t=ot[Tt],yt=Tt===mt.idx?mt.y:_t.top,Wt=Tt===xt.idx?xt.y:O;Wt-yt<=.01||(t.setPage(_t.page),D(pt,ht,_t.left+(ht?B[ht.col]:0),Mt,yt,Wt-yt,at))}}}for(let $=_;$<y;$++)for(const at of e.children[$].children)await N(t,at,m.byId.get(at.id),rt.get(at.id),Ot,O);const Ct=q[q.length-1],At=ot[Math.min(Ct.idx,ot.length-1)];return t.setPage(At.page),E=At.left,Ct.y},H=e.hasHeader===!0&&e.children.length>1&&!m.cells.some(_=>_.row===0&&_.rowSpan>1),j=e.children.map(()=>[]);for(const _ of m.cells)j[_.row]?.push(_);for(let _=0;_<e.children.length;){let y=_+1,X=0;for(let L=_;L<y;L++){X+=u[L];for(const A of j[L])y=Math.min(e.children.length,Math.max(y,A.row+A.rowSpan))}const O=H&&_>0?u[0]:0,K=h-o.marginTopPt-O,W=X>K;if((W?s>=h-.01:s+X>h)&&s!==o.marginTopPt){const L=this.advancePdfFlowRegion(t,o);s=L.y,E=L.x+b,H&&_>0&&(await V(e.children[0],0,s,!0),s+=u[0])}if(W)s=await G(_,y,s);else for(let L=_;L<y;L++)await V(e.children[L],L,s,!1),s+=u[L];_=y}return C(),s}static async renderCodeBlock(t,e,a,i,r,n=this.MARGIN_LEFT,l=It,o=!1,h=this.getDefaultPdfLayoutMetrics(),s){const g=n-h.marginLeftPt;let P=n;const c=e.language||"",f=Ge(c);if(f&&e.renderDiagram!==!1&&f)return this.renderDiagramCodeBlock(t,e,a,i,r,P,f,l,o,h);const d=o?"SourceCodePro":"courier",T=e.content||"",m=c?await ze(T,c,l):null,x=dt.fontSizePx*this.PX_TO_PT,F=x*dt.lineHeightMultiplier,b=dt.paddingPx*this.PX_TO_PT,E=dt.borderRadiusPx*this.PX_TO_PT,R=this.hexToRgb(l.background),B=this.hexToRgb(l.default);t.setFont(d,"normal"),t.setFontSize(x);const k=Math.max(1,i-b*2),I=te(T,M=>t.getTextWidth(M),k),u=[];let p=0;for(const M of m??[])u.push({start:p,end:p+M.text.length,color:M.color}),p+=M.text.length;const S=M=>{if(u.length===0)return[{text:M.text,color:l.default}];const N=[];for(const G of u){const H=Math.max(M.startCharOffset,G.start),j=Math.min(M.endCharOffset,G.end);j<=H||N.push({text:T.slice(H,j),color:G.color})}return N.length>0?N:[{text:M.text,color:l.default}]};let w=a,C=0,D=r;const V=()=>{const M=this.advancePdfFlowRegion(t,h);w=M.y,P=M.x+g,D=this.getPdfFlowBottom(t,h)};for(;C<I.length;){const M=C===0,N=M?b:0,G=N+F+(I.length===C+1?b:0);w+G>D&&w!==h.marginTopPt&&V();let H=C,j=N;for(;H<I.length;){const y=H===I.length-1,X=j+F+(y?b:0);if(w+X>D&&H>C)break;j+=F,H+=1}const _=H===I.length;_&&(j+=b),t.setFillColor(R.r,R.g,R.b),M&&_?this.drawRoundedRect(t,P,w,i,j,E):t.rect(P,w,i,j,"F"),t.setFont(d,"normal"),t.setFontSize(x);for(let y=C;y<H;y++){const X=y===0,O=y===I.length-1,K=w+N+(y-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+N+(y-C)*F+x;for(const A of S(I[y])){const U=A.color?this.hexToRgb(A.color):B;t.setTextColor(U.r,U.g,U.b),A.text&&t.text(A.text,W,L),W+=t.getTextWidth(A.text)}}w+=j,C=H,_||V()}return w}static async renderDiagramCodeBlock(t,e,a,i,r,n,l,o,h,s){const g=n-s.marginLeftPt;let P=n;const c=dt.paddingPx*this.PX_TO_PT,f=dt.diagramSourceGapPx*this.PX_TO_PT,d=ee(),T=Math.max(120,Math.round((i-c*2)/this.PX_TO_PT)),m=await Ue({protocol:l,source:e.content||"",theme:d,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,E=e.showDiagramSource!==!1,R=h?"SourceCodePro":"courier",B=dt.fontSizePx*this.PX_TO_PT;t.setFont(R,"normal"),t.setFontSize(B);const k=te(e.content||"",N=>t.getTextWidth(N),Math.max(1,i-c*2)),I=c*2+k.length*B*dt.lineHeightMultiplier,u=(E?I+f:0)+b;let p=a;if(p+u>r&&p!==s.marginTopPt){const N=this.advancePdfFlowRegion(t,s);p=N.y,P=N.x+g}E&&(p=await this.renderCodeBlock(t,{...e,renderDiagram:!1},p,i,r,P,o,h,s),p+=f);const S=this.hexToRgb(d.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,M=p+(b-D)/2;if(m.svg){const N=await this.svgToPng(m.svg,Math.max(1,Math.round(m.width)),Math.max(1,Math.round(m.height)),2);if(N)return t.addImage(N,"PNG",V,M,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,n,l=!1){const o=this.getParagraphFontSize(e),h=this.getParagraphDirection(e),s=this.getEffectiveParagraphAlignment(e,h),g=this.getLineSpacingMultiplier(e),P=this.processTextNodes(e.children);let c=i,f=[],d=0;const T=m=>{f.length!==0&&(l?c+=this.measureLineAdvancePt(f,o,!!e.heading,g):c=this.renderLine(t,f,c,a,r,s,o,n,!!e.heading,g,m,{direction:h}),f=[],d=0)};for(const m of P){this.setRunFont(t,m,n),t.setFontSize(this.getRunEffectiveFontSizePt(m.marks,o));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 E of b){const R=this.measureRunDisplayWidthPt(t,E,m.marks);d+R>r&&f.length>0&&T(!1),(E.trim()||f.length>0)&&(f.push({text:E,marks:m.marks,font:m.marks?.fontFamily}),d+=R)}}}return T(!0),c===i&&(c+=this.getEmptyParagraphLineHeight(e)),c}static extractCellBlocks(t){return t.children}static drawRoundedRect(t,e,a,i,r,n,l="F"){const o=Math.min(n,i/2,r/2);t.roundedRect(e,a,i,r,o,o,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 Ke(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),n=this.scriptFallbackFor(t,e.text,i);if(n){t.setFont(n,r==="bold"||r==="bolditalic"?"bold":"normal");return}t.setFont(i,r)}static measureRunDisplayWidthPt(t,e,a){const i=n=>{const l=t.getFont?.()?.fontName,o=l?this.shapingFonts.get(l):void 0;return o?o.layout(n).advanceWidth*t.getFontSize()/o.unitsPerEm:t.getTextWidth(n)},r=je(a);return r?zt(e,{...r,letterSpacingPx:this.getRunLetterSpacingPt(a)},i):i(e)}static drawShapedText(t,e,a,i,r,n,l){const o=t.getFont?.()?.fontName,h=o?this.shapingFonts.get(o):void 0;if(!h)return null;const s=h.layout(e);Array.from(e).every(d=>(d.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,f=0;for(let d=0;d<s.glyphs.length;d++){const T=s.glyphs[d],m=s.positions[d],x=[];let F=0,b=0;const E=B=>a+f+(P+m.xOffset+B)*g,R=B=>i-(c+m.yOffset+B)*g;for(const B of T.path.commands)if(B.command==="moveTo")[F,b]=B.args,x.push({op:"m",c:[E(F),R(b)]});else if(B.command==="lineTo")[F,b]=B.args,x.push({op:"l",c:[E(F),R(b)]});else if(B.command==="bezierCurveTo"){const[k,I,u,p,S,w]=B.args;x.push({op:"c",c:[E(k),R(I),E(u),R(p),E(S),R(w)]}),F=S,b=w}else if(B.command==="quadraticCurveTo"){const[k,I,u,p]=B.args,S=F+(k-F)*2/3,w=b+(I-b)*2/3,C=u+(k-u)*2/3,D=p+(I-p)*2/3;x.push({op:"c",c:[E(S),R(w),E(C),R(D),E(u),R(p)]}),F=u,b=p}else B.command==="closePath"&&x.push({op:"h",c:[]});x.length>0&&(t.path(x),t.fill()),P+=m.xAdvance,c+=m.yAdvance,f+=n*Math.max(1,T.codePoints?.length??1)}return s.advanceWidth*r/h.unitsPerEm+n*[...e].length}static renderLine(t,e,a,i,r,n,l,o,h,s,g=!0,P){e=e.filter(u=>!u.marks?.hidden||!!u.marks.footnoteRef);let c=P?.tabLayoutPx;const f=u=>u.marks?.fontSize?u.marks.fontSize*this.PX_TO_PT:l,d=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,d);if(S){const w=(D,V)=>{let M=0,N=0;for(const G of u){const H=Math.max(D,N),j=Math.min(V,N+G.text.length);if(H<j){const _=G.text.slice(H-N,j-N);this.setRunFont(t,{...G,text:_},o),t.setFontSize(this.getRunEffectiveFontSizePt(G.marks,l)),M+=this.measureRunDisplayWidthPt(t,_,G.marks)}N+=G.text.length}return M},C=u.map(D=>D.text).join("");e=ie(p,S,w,n==="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 M=Number.NEGATIVE_INFINITY;for(;C<u.length&&u[C].text!==" ";){const O=p[C];O&&(M=Math.max(M,O.endX)),C++}const N=u.slice(V,C),G=N.map(O=>O.text).join("");if(!G)continue;Number.isFinite(M)||(M=0);const H={segments:N.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 _=ie(H,j,(O,K)=>{let W=0,L=0;for(const A of N){const U=Math.max(O,L),z=Math.min(K,L+A.text.length);if(U<z){const Y=A.text.slice(U-L,z-L);this.setRunFont(t,{...A,text:Y},o),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=M*this.PX_TO_PT-y;for(const O of _)S.push({...N[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=f(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,o),t.setFontSize(this.getRunEffectiveFontSizePt(u.marks,l)),F+=this.measureRunDisplayWidthPt(t,u.text,u.marks));let b=i;n==="center"?b=i+(r-F)/2:(n==="right"||n==="justify"&&d==="rtl"&&(g||c))&&(b=i+r-F),P?.tabRtl&&c&&(b=i);let E=0;if(n==="justify"&&!g&&!c){let u=0;for(const p of e)p.latexImage||p.marks?.latex||(u+=(p.text.match(/ /g)||[]).length);u>0&&(E=Math.max(0,(r-F)/u))}const R=b;for(let u=0;u<e.length;u++){const p=e[u],S=c?.[u];if(S&&(b=R+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,R+S.startX*this.PX_TO_PT,R+S.endX*this.PX_TO_PT,x,S.leader,W,L)}b=R+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,U=p.latexImage.contentHeight*this.PX_TO_PT,z=(W-A)/2,Y=b-z,Z=x-U*.7-z;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,o);const w=f(p),C=this.getRunEffectiveFontSizePt(p.marks,l),D=C/this.PX_TO_PT;t.setFontSize(C);const V=!!p.marks?.link;let M={r:0,g:0,b:0};V?M={r:37,g:99,b:235}:p.marks?.color?M=this.hexToRgb(p.marks.color):p.marks?.code&&(M=this.hexToRgb(Lt.codeText)),t.setTextColor(M.r,M.g,M.b);const N=!!(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,_=this.measureRunDisplayWidthPt(t,p.text,p.marks),y=E>0?(p.text.match(/ /g)||[]).length:0,X=_+y*E;if(p.marks?.backgroundColor){const W=Ye(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(M.r,M.g,M.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(M.r,M.g,M.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,U=this.drawShapedText(t,A,L,O,C,G,M);if(U!==null)return U;if(N){let z=L;for(const Y of ca(W,p.marks?.lang)){const Z=Y.lower?t.getTextWidth(Xt(Y.text,p.marks?.lang))*ne:t.getTextWidth(Y.text);Y.lower?(t.setFontSize(C*ne),t.text(Xt(Y.text,p.marks?.lang),z,O,j),t.setFontSize(C)):t.text(Y.text,z,O,j),z+=Z+G*Y.text.length}return z-L}return t.text(A,L,O,j),this.measureRunDisplayWidthPt(t,W,p.marks)};if(E>0){let W=b;for(const L of p.text.split(/( +)/))L&&(W+=K(L,W),L[0]===" "&&(W+=E*L.length))}else K(p.text,b);if(p.marks?.strikethrough||p.marks?.doubleStrikethrough){t.setDrawColor(M.r,M.g,M.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,o),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 B=s??(h?this.LINE_HEIGHT_MULTIPLIERS.heading:this.LINE_HEIGHT_MULTIPLIERS.paragraph),k=T*B,I=m>k*1.25?m:k;return a+I}static renderTabLeaderPdf(t,e,a,i,r,n,l){const o=Math.max(1.5,n*.12),h=e+o,s=a-o;if(s-h<1)return;if(t.setFillColor(l.r,l.g,l.b),r==="underscore"){const P=i+Math.max(1,n*.08),c=Math.max(.75,n*.055);t.rect(h,P,s-h,c,"F");return}const g=Math.max(2.25,n*.33);if(r==="dot"){const P=Math.max(.45,n*.045),c=i-P;for(let f=Math.ceil(h/g)*g;f<=s;f+=g)t.circle(f,c,P,"F")}else{const P=Math.max(1.5,n*.18),c=i-n*.28,f=Math.max(.75,n*.055);for(let d=Math.ceil(h/g)*g;d+P<=s;d+=g)t.rect(d,c,P,f,"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 n=0;n<t.length;n++){const l=t[n];if(l.type==="text"){const o=l;if(o.marks?.hidden&&!o.marks.footnoteRef)continue;o.marks?.latex?a.push({index:n,node:o,latexPromise:this.renderLatexToImage(o.text,!1,e)}):a.push({index:n,node:o})}}const i=await Promise.all(a.map(n=>n.latexPromise||Promise.resolve(null))),r=[];for(let n=0;n<a.length;n++){const{node:l}=a[n],o=i[n];r.push({text:l.text,marks:l.marks,font:l.marks?.fontFamily,latexImage:o||void 0})}return r}static getParagraphFontSize(t){return $e(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(n=>n.family).filter(n=>{const l=n.toLowerCase();return!a.has(l)&&this.FONT_MAP[l]!=="KaTeX_Main"});if(i.length===0)return;let r;for(const n of i){const l=n.toLowerCase();let o=this.localFontFiles.get(l);if(o===void 0){if(r===void 0&&(r=await Ve().catch(()=>null)),!r)return;try{o=await this.buildLocalFontFiles(n,r)}catch{o=null}this.localFontFiles.set(l,o)}if(o)try{for(const h of o)t.addFileToVFS(h.vfsName,h.base64),t.addFont(h.vfsName,n,h.style);this.embeddedFamilyNames.set(l,n)}catch(h){console.warn(`Failed to embed font "${n}" 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,...Ze(c.style),specificity:(c.style??"").length})),n=(c,f)=>r.filter(d=>d.bold===c&&d.italic===f).sort((d,T)=>d.specificity-T.specificity)[0]?.entry,l=n(!1,!1)??r[0].entry,o=[{style:"normal",entry:l},{style:"bold",entry:n(!0,!1)??l},{style:"italic",entry:n(!1,!0)??l},{style:"bolditalic",entry:n(!0,!0)??n(!0,!1)??l}],h=new Map;for(const{entry:c}of o){if(h.has(c))continue;const f=await(await c.blob()).arrayBuffer(),d=Ht(new Uint8Array(f));h.set(c,d==="ttf"?this.arrayBufferToBase64(f):null)}if(!h.get(l))return null;const s=a.replace(/[^a-z0-9]+/g,"-"),g=new Map;let P=0;return o.map(({style:c,entry:f})=>{const d=h.get(f)?f:l;let T=g.get(d);return T||(T=`${s}-${P++}.ttf`,g.set(d,T)),{vfsName:T,base64:h.get(d),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 n=r.toLowerCase(),l=this.embeddedFamilyNames.get(n);if(l)return l;if(e.has(n))return n;const o=this.FONT_MAP[n];if(o)return o}const i=Je(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,n){if(e.style==="none"||e.width<=0)return;const l=this.hexToRgb(e.color);t.setDrawColor(l.r,l.g,l.b);const o=Qe(e).map(h=>h*this.PX_TO_PT);if(o.length>0&&typeof t.setLineDashPattern=="function"&&t.setLineDashPattern(o,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===n,P=g?0:s,c=g?s:0;t.line(a-P,i-c,r-P,n-c),t.line(a+P,i+c,r+P,n+c)}else t.setLineWidth(e.width*this.PX_TO_PT),t.line(a,i,r,n);o.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 n=this.getPdfFlowBottom(t,r);let l=Math.max(e.width||1,1)*this.PX_TO_PT,o=Math.max(e.height||1,1)*this.PX_TO_PT;if(l>i){const c=i/l;l=i,o*=c}(o<=0||!Number.isFinite(o))&&(o=72);let h=r.marginLeftPt;if(a+o>n&&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,o,"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+o/2,{align:"center",baseline:"middle"}),{nextY:a+o};const P=await this.resolveImageDataCached(t,e.src);if(!P)return{nextY:a+o};try{t.addImage(P.data,P.format,g,a,l,o)}catch(c){return console.error("Failed to add image to PDF",c),{nextY:a+o}}return{nextY:a+o}}static resolveImageDataCached(t,e){let a=this.imageDataCache.get(t);a||(a=new Map,this.imageDataCache.set(t,a));let i=a.get(e);return i||(i=this.resolveImageData(e),a.set(e,i)),i}static async resolveImageData(t){if(/^data:image\/svg\+xml[;,]/i.test(t))return this.rasterizeSvgImage(t);const e=t.match(/^data:image\/([a-zA-Z0-9+.-]+);base64,/);if(e){const l=this.normalizeImageFormat(e[1]);return{data:t,format:l}}const a=await this.fetchImageAsBlob(t);if(!a)return null;const{blob:i,format:r}=a,n=await this.blobToDataUrl(i,r);return r==="SVG+XML"?this.rasterizeSvgImage(n):{data:n,format:r}}static async rasterizeSvgImage(t){const e=this.decodeSvgDataUrl(t);if(!e)return null;const a=this.svgIntrinsicSize(e),i=2;if(typeof process<"u"&&process.versions?.node&&(typeof navigator>"u"||/jsdom|node/i.test(navigator.userAgent??"")))try{const n=await import(["can","vas"].join("")),l=await n.loadImage(Buffer.from(e,"utf8")),o=n.createCanvas(Math.max(1,Math.round(a.width*i)),Math.max(1,Math.round(a.height*i)));return o.getContext("2d").drawImage(l,0,0,o.width,o.height),{data:o.toDataURL("image/png"),format:"PNG"}}catch(n){return console.error("Failed to rasterize SVG image for PDF export",n),null}const r=await Promise.race([this.svgToPng(e,a.width,a.height,i),new Promise(n=>setTimeout(()=>n(null),5e3))]);return r?{data:r,format:"PNG"}:null}static decodeSvgDataUrl(t){const e=t.indexOf(",");if(e<0)return null;const a=t.slice(0,e),i=t.slice(e+1);try{if(/;base64$/i.test(a)){const r=globalThis?.Buffer;if(r)return r.from(i,"base64").toString();const n=atob(i),l=Uint8Array.from(n,o=>o.charCodeAt(0));return new TextDecoder().decode(l)}return decodeURIComponent(i)}catch{return null}}static svgIntrinsicSize(t){const e=/<svg\b[^>]*>/i.exec(t)?.[0]??"",a=o=>{const h=new RegExp(`\\s${o}="([\\d.]+)(px)?"`,"i").exec(e),s=h?Number(h[1]):NaN;return Number.isFinite(s)&&s>0?s:void 0},i=/\sviewBox="([^"]+)"/i.exec(e)?.[1]?.trim().split(/[\s,]+/).map(Number),r=i&&i.length===4&&i[2]>0?i[2]:void 0,n=i&&i.length===4&&i[3]>0?i[3]:void 0,l=o=>Math.min(4e3,Math.max(1,o));return{width:l(a("width")??r??300),height:l(a("height")??n??150)}}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 n=0;n<i.length;n+=r){const l=i.subarray(n,n+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,n=this.getDefaultPdfLayoutMetrics()){if(!e.content||e.content.trim()==="")return{nextY:a};const l=e.displayMode!=="inline",o=await this.renderLatexToImage(e.content,l);if(!o)return{nextY:a+20};let h=o.width*this.PX_TO_PT,s=o.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=n.marginLeftPt;if(a+P>r&&a!==n.marginTopPt){const x=this.advancePdfFlowRegion(t,n);a=x.y,c=x.x}const f=this.hexToRgb(ee().codeBorder||"#e0e0e0");t.setDrawColor(f.r,f.g,f.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 d=e.align||"center";let T=c+this.MATH_BLOCK_PADDING;d==="center"?T=c+(i-h)/2:d==="right"&&(T=c+i-h-this.MATH_BLOCK_PADDING);const m=a+(P-s)/2;try{t.addImage(o.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 n=e?1:this.INLINE_MATH_SCALE;return{dataUrl:r,width:i.width*n,height:i.height*n,contentWidth:i.contentWidth*n,contentHeight:i.contentHeight*n}}}try{const r=await this.getHtml2Canvas(),n=this.preprocessLaTeX(t),l=(await ta()).renderToString(n,{displayMode:e,throwOnError:!1,errorColor:"#ef4444",trust:!1,strict:!1});this.ensureKaTeXStyles();const o=a/this.PX_TO_PT,h=e?20:o*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 f=c.toDataURL("image/png"),d=c.width/P,T=c.height/P,m=d-s*2,x=T-s*2;return{dataUrl:f,width:d,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 n=r.trim().split(`
21
+ `),l=[];let o=[];for(let h=0;h<n.length;h++){const s=n[h].trim();if(s===""){if(o.length>0){const g=o.join(" ").trim();g&&l.push(wt([{type:"text",text:g}])),o=[]}}else{const g=s.length<60,P=s===s.toUpperCase()&&/[A-Z]/.test(s),c=/[.!?]$/.test(s),f=h+1<n.length&&n[h+1].trim()==="";if(g&&(P||f&&!c)){if(o.length>0){const d=o.join(" ").trim();d&&l.push(wt([{type:"text",text:d}])),o=[]}l.push(wt([{type:"text",text:s}]))}else o.push(s)}}if(o.length>0){const h=o.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"}`)}}};v.PAGE_WIDTH=612,v.PAGE_HEIGHT=792,v.MARGIN_LEFT=72,v.MARGIN_RIGHT=72,v.MARGIN_TOP=72,v.MARGIN_BOTTOM=72,v.PX_TO_PT=re,v.UNBOUNDED_CELL_FLOW_BOTTOM_PT=1e4,v.DEFAULT_BODY_FONT="Arial, sans-serif",v.LINE_HEIGHT_MULTIPLIERS=se,v.FONT_SIZES={h1:bt.h1*v.PX_TO_PT,h2:bt.h2*v.PX_TO_PT,h3:bt.h3*v.PX_TO_PT,h4:bt.h4*v.PX_TO_PT,h5:bt.h5*v.PX_TO_PT,h6:bt.h6*v.PX_TO_PT,normal:bt.paragraph*v.PX_TO_PT},v.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"},v.TODO_LIST_INDENT_PT=Pt.variantIndentPx.todo*v.PX_TO_PT,v.ORDERED_LIST_INDENT_PT=Pt.variantIndentPx.ordered*v.PX_TO_PT,v.UNORDERED_LIST_INDENT_PT=Pt.variantIndentPx.unordered*v.PX_TO_PT,v.SUBLIST_INDENT_PT=Pt.sublistIndentPx*v.PX_TO_PT,v.BULLET_MARKER_WIDTH_PT=Pt.markerWidthPx*v.PX_TO_PT,v.BULLET_CENTER_OFFSET_PT=8*v.PX_TO_PT,v.BULLET_RADIUS_PT=2.5*v.PX_TO_PT,v.BULLET_SQUARE_INSET_PT=5*v.PX_TO_PT,v.BULLET_SQUARE_HALF_PT=5*v.PX_TO_PT,v.BULLET_SQUARE_VERTICAL_ADJUST_PT=1*v.PX_TO_PT,v.ORDERED_LABEL_GAP_PT=6*v.PX_TO_PT,v.TODO_CHECKBOX_SIZE_PT=Pt.todoCheckboxSizePx*v.PX_TO_PT,v.TODO_CHECKBOX_RADIUS_PT=Pt.todoCheckboxRadiusPx*v.PX_TO_PT,v.TODO_CHECKBOX_OFFSET_PT=Pt.todoCheckboxOffsetPx*v.PX_TO_PT,v.MAX_LIST_INDENT_LEVEL=Pt.maxIndentLevel,v.MATH_BLOCK_PADDING=16*v.PX_TO_PT,v.MATH_BLOCK_MIN_HEIGHT=40*v.PX_TO_PT,v.MATH_BLOCK_BORDER_RADIUS=4*v.PX_TO_PT,v.BLOCK_BORDER_WIDTH_PT=1*v.PX_TO_PT,v.INLINE_MATH_SCALE=.85,v.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"}}},v.bundledGenreFamilies=new Map,v.SCRIPT_FALLBACK_FONTS=ua,v.scriptFallbackFamilies=new Map,v.scriptFontCoverageCache=new Map,v.fallbackCharsetCache=new Map,v.shapingFonts=new Map,v.inlineCodeFontFamily="courier",v.fontFileData=new Map,v.localFontFiles=new Map,v.embeddedFamilyNames=new Map,v.COLUMN_BALANCE_SLACK_PT=1.5,v.imageDataCache=new WeakMap,v.html2canvasModule=null,v.html2canvasLoading=null,v.katexStylesLoaded=!1;let pa=v;export{pa as PdfConverter};
@@ -0,0 +1,2 @@
1
+ import{H as re,a8 as ne,cm as x,cn as ae,co as se,ba as C,cp as ie,cq as M,cr as ce}from"./index-D9_PwgOX.js";import*as v from"yjs";const E=e=>new Promise(e);Promise.all.bind(Promise);const de=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)}),le=(e,t)=>E((o,r)=>{const n=indexedDB.open(e);n.onupgradeneeded=a=>t(a.target.result),n.onerror=a=>r(de(a.target.error)),n.onsuccess=a=>{const s=a.target.result;s.onversionchange=()=>{s.close()},o(s)}}),ue=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=>Ie(r,n))},U=(e,t)=>T(e.count(t)),he=(e,t)=>T(e.get(t)),j=(e,t)=>T(e.delete(t)),pe=(e,t,o)=>T(e.put(t,o)),F=(e,t)=>T(e.add(t)),fe=(e,t,o)=>T(e.getAll(t,o)),ge=(e,t,o)=>{let r=null;return Pe(e,t,n=>(r=n,!1),o).then(()=>r)},we=(e,t=null)=>ge(e,t,"prev"),ye=(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()}}),Pe=(e,t,o,r="next")=>ye(e.openKeyCursor(t,r),n=>o(n.key)),Ie=(e,t)=>e.objectStore(t),be=(e,t)=>IDBKeyRange.upperBound(e,t),Te=(e,t)=>IDBKeyRange.lowerBound(e,t),L=()=>new Map,ve=(e,t,o)=>{let r=e.get(t);return r===void 0&&e.set(t,r=o()),r},_e=()=>new Set,Ee=Array.from;class De{constructor(){this._observers=L()}on(t,o){ve(this._observers,t,_e).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 Ee((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 fe(r,Te(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(()=>we(r).then(n=>{e._dbref=n+1})).then(()=>U(r).then(n=>{e._dbsize=n})).then(()=>r)},ke=(e,t=!0)=>z(e).then(o=>{(t||e._dbsize>=R)&&F(o,v.encodeStateAsUpdate(e.doc)).then(()=>j(o,be(e._dbref,!0))).then(()=>U(o).then(r=>{e._dbsize=r}))});class Se extends De{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=le(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(()=>{ke(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(()=>{ue(this.name)})}get(t){return this._db.then(o=>{const[r]=_(o,[$],"readonly");return he(r,t)})}set(t,o){return this._db.then(r=>{const[n]=_(r,[$]);return pe(n,o,t)})}del(t){return this._db.then(o=>{const[r]=_(o,[$]);return j(r,t)})}}const xe="revise-anonymous-identity",Fe=1,D="identities",N="pdf-browser-id",Le=/^[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 $e(){return new Promise((e,t)=>{const o=indexedDB.open(xe,Fe);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 $e(),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=Le.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 Ae(){return J.replace(/^https/,"wss")}const B="yjs_document_index",Y="anon_session_id",q="yjs_document_deleted_",Be="local-document-deleted";function G(e){return typeof window<"u"&&localStorage.getItem(q+e)==="1"}function W(){if(typeof window>"u")return[];try{const e=localStorage.getItem(B);return e?JSON.parse(e).filter(t=>!G(t)):[]}catch(e){return console.warn("Failed to read document index:",e),[]}}function Ce(e){if(!(typeof window>"u"))try{if(G(e))return;const t=W();t.includes(e)||(t.push(e),localStorage.setItem(B,JSON.stringify(t)))}catch(t){console.warn("Failed to update document index:",t)}}function Me(e){if(!(typeof window>"u"))try{localStorage.setItem(q+e,"1"),window.dispatchEvent(new CustomEvent(Be,{detail:{documentId:e}}));const t=W().filter(o=>o!==e);localStorage.setItem(B,JSON.stringify(t))}catch(t){console.warn("Failed to remove from document index:",t)}}function Ue(){const e="abcdefghijklmnopqrstuvwxyz0123456789";let t="";for(let o=0;o<8;o++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function H(){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 je=30*60*1e3,Oe=3e3,Re=15e3,k=new Map;async function ze(e){const t=Ue(),o=H(),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 Se(t,n);await s.whenSynced;const c=await A(),i=Ae(),m=c?`${i}${i.includes("?")?"&":"?"}anonymousBrowserId=${encodeURIComponent(c)}`:i;let p=null;const d=new Promise(l=>{p=l}),f=new ae({url:se(m),name:r,document:n,token:()=>"",onSynced:()=>{p?.()}});return Ne(t,n,s,f),Ce(t),await Promise.race([d,new Promise(l=>setTimeout(l,Re))]),{docId:t,anonSessionId:o,anonymousBrowserId:c}}function Ne(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"),m=()=>{const d=i.get("stage");(d==="complete"||d==="error")&&(i.unobserve(m),setTimeout(c,Oe))};i.observe(m);const p=setTimeout(()=>{console.warn(`[PdfImportKeeper] Import ${e} exceeded max lifetime; releasing`),c()},je);k.set(e,{docId:e,ydoc:t,persistence:o,provider:r,done:a,finish:c,maxLifetimeTimer:p})}async function Je(e){const t=k.get(e);if(t){Me(e);try{await t.persistence.clearData()}catch(o){console.warn(`[PdfImportKeeper] Error clearing data for ${e}:`,o)}t.finish()}}const Ke=10;async function Ye(e){const t=e.batchSize??Ke;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",qe="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 m=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:m,thumbnails:n})}}function We(){try{return typeof window<"u"?localStorage.getItem("auth_token"):null}catch{return null}}async function He(e){try{const t=e?await fetch(`${V}/subscription/pdf-limits`,{method:"GET",headers:{Authorization:`Bearer ${e}`}}):await A().then(r=>fetch(`${qe}/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"),X(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),X(e)}}function X(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(`${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 Xe(e){const{totalPages:t,title:o,token:r,timeoutMessage:n,targetDocumentId:a,afterBlockId:s}=e,c=x(o),i=!r&&!a?await ze(c):null,m=!r&&a?{docId:a,anonSessionId:H(),anonymousBrowserId:await A()}:null,p=i??m;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:ce,...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 Qe(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&&Je(i.docId),d}}async function Qe(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 m=null;try{m=JSON.parse(i.slice(6))}catch{}if(m){if(n==="document_created")return t.releaseLock(),m;if(n==="error")throw t.releaseLock(),new Error(m.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 m=!1;for(let u=0;u<c&&!m;u++){const w=Math.floor(a.width*u/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&&!m;I+=4)(y[I]<250||y[I+1]<250||y[I+2]<250)&&(m=!0)}if(!m)throw new Error(`Page ${t} appears blank. The PDF may use an unsupported image format.`);const p=await new Promise((u,w)=>{a.toBlob(b=>{b?u(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:m,maxPlanLimit:p}=await He(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,u=g?Math.min(Ze,P):0,w=[];for(let y=1;y<=u;y++){const{thumbnail:I}=await Z(h,y);w.push(I),r({stage:"rasterizing",currentPage:y,totalPages:u,message:`Preparing preview ${y} of ${u}...`,thumbnail:I})}const b=x(ie(e.name??"")||"Imported PDF");return{thumbnails:w,totalPages:P,ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:m,maxPlanLimit:p,exceedsLimit:g,title:b,_pdf:h,_token:n,_file:e}}async function te(e,t,o,r){const n=u=>{t&&t(u)},{_pdf:a,_token:s,_file:c,totalPages:i,title:m,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:m,token:s,timeoutMessage:"Import timed out after 10 minutes. Please try with a shorter PDF.",targetDocumentId:o,afterBlockId:r});return Ye({totalPages:i,preparePage:async u=>{const{blob:w,thumbnail:b}=await Z(a,u);return n({stage:"rasterizing",currentPage:u,totalPages:i,message:`Processing page ${u} of ${i}`,thumbnail:b}),{url:await Ve(w,u,s),mediaType:"image/png",pageNumber:u}},sendBatch:(u,w)=>Q({importId:g.importId,uploadToken:g.uploadToken,pages:u,final:w})}).catch(async u=>{const w=u instanceof Error?u.message:"Failed to prepare PDF pages";console.error("[PDF Import] Background page upload failed:",u),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 et(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,et as importPdfIntoExistingDocument,ee as previewPdfForImport,oe as watchImportCompletion};
@@ -0,0 +1,2 @@
1
+ import{H as re,a8 as ne,cm as x,cn as ae,co as se,ba as C,cp as ie,cq as M,cr as ce}from"./index-DcIXw_KB.js";import*as v from"yjs";const E=e=>new Promise(e);Promise.all.bind(Promise);const de=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)}),le=(e,t)=>E((o,r)=>{const n=indexedDB.open(e);n.onupgradeneeded=a=>t(a.target.result),n.onerror=a=>r(de(a.target.error)),n.onsuccess=a=>{const s=a.target.result;s.onversionchange=()=>{s.close()},o(s)}}),ue=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=>Ie(r,n))},U=(e,t)=>T(e.count(t)),he=(e,t)=>T(e.get(t)),j=(e,t)=>T(e.delete(t)),pe=(e,t,o)=>T(e.put(t,o)),F=(e,t)=>T(e.add(t)),fe=(e,t,o)=>T(e.getAll(t,o)),ge=(e,t,o)=>{let r=null;return Pe(e,t,n=>(r=n,!1),o).then(()=>r)},we=(e,t=null)=>ge(e,t,"prev"),ye=(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()}}),Pe=(e,t,o,r="next")=>ye(e.openKeyCursor(t,r),n=>o(n.key)),Ie=(e,t)=>e.objectStore(t),be=(e,t)=>IDBKeyRange.upperBound(e,t),Te=(e,t)=>IDBKeyRange.lowerBound(e,t),L=()=>new Map,ve=(e,t,o)=>{let r=e.get(t);return r===void 0&&e.set(t,r=o()),r},_e=()=>new Set,Ee=Array.from;class De{constructor(){this._observers=L()}on(t,o){ve(this._observers,t,_e).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 Ee((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 fe(r,Te(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(()=>we(r).then(n=>{e._dbref=n+1})).then(()=>U(r).then(n=>{e._dbsize=n})).then(()=>r)},ke=(e,t=!0)=>z(e).then(o=>{(t||e._dbsize>=R)&&F(o,v.encodeStateAsUpdate(e.doc)).then(()=>j(o,be(e._dbref,!0))).then(()=>U(o).then(r=>{e._dbsize=r}))});class Se extends De{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=le(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(()=>{ke(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(()=>{ue(this.name)})}get(t){return this._db.then(o=>{const[r]=_(o,[$],"readonly");return he(r,t)})}set(t,o){return this._db.then(r=>{const[n]=_(r,[$]);return pe(n,o,t)})}del(t){return this._db.then(o=>{const[r]=_(o,[$]);return j(r,t)})}}const xe="revise-anonymous-identity",Fe=1,D="identities",N="pdf-browser-id",Le=/^[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 $e(){return new Promise((e,t)=>{const o=indexedDB.open(xe,Fe);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 $e(),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=Le.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 Ae(){return J.replace(/^https/,"wss")}const B="yjs_document_index",Y="anon_session_id",q="yjs_document_deleted_",Be="local-document-deleted";function G(e){return typeof window<"u"&&localStorage.getItem(q+e)==="1"}function W(){if(typeof window>"u")return[];try{const e=localStorage.getItem(B);return e?JSON.parse(e).filter(t=>!G(t)):[]}catch(e){return console.warn("Failed to read document index:",e),[]}}function Ce(e){if(!(typeof window>"u"))try{if(G(e))return;const t=W();t.includes(e)||(t.push(e),localStorage.setItem(B,JSON.stringify(t)))}catch(t){console.warn("Failed to update document index:",t)}}function Me(e){if(!(typeof window>"u"))try{localStorage.setItem(q+e,"1"),window.dispatchEvent(new CustomEvent(Be,{detail:{documentId:e}}));const t=W().filter(o=>o!==e);localStorage.setItem(B,JSON.stringify(t))}catch(t){console.warn("Failed to remove from document index:",t)}}function Ue(){const e="abcdefghijklmnopqrstuvwxyz0123456789";let t="";for(let o=0;o<8;o++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function H(){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 je=30*60*1e3,Oe=3e3,Re=15e3,k=new Map;async function ze(e){const t=Ue(),o=H(),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 Se(t,n);await s.whenSynced;const c=await A(),i=Ae(),m=c?`${i}${i.includes("?")?"&":"?"}anonymousBrowserId=${encodeURIComponent(c)}`:i;let p=null;const d=new Promise(l=>{p=l}),f=new ae({url:se(m),name:r,document:n,token:()=>"",onSynced:()=>{p?.()}});return Ne(t,n,s,f),Ce(t),await Promise.race([d,new Promise(l=>setTimeout(l,Re))]),{docId:t,anonSessionId:o,anonymousBrowserId:c}}function Ne(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"),m=()=>{const d=i.get("stage");(d==="complete"||d==="error")&&(i.unobserve(m),setTimeout(c,Oe))};i.observe(m);const p=setTimeout(()=>{console.warn(`[PdfImportKeeper] Import ${e} exceeded max lifetime; releasing`),c()},je);k.set(e,{docId:e,ydoc:t,persistence:o,provider:r,done:a,finish:c,maxLifetimeTimer:p})}async function Je(e){const t=k.get(e);if(t){Me(e);try{await t.persistence.clearData()}catch(o){console.warn(`[PdfImportKeeper] Error clearing data for ${e}:`,o)}t.finish()}}const Ke=10;async function Ye(e){const t=e.batchSize??Ke;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",qe="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 m=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:m,thumbnails:n})}}function We(){try{return typeof window<"u"?localStorage.getItem("auth_token"):null}catch{return null}}async function He(e){try{const t=e?await fetch(`${V}/subscription/pdf-limits`,{method:"GET",headers:{Authorization:`Bearer ${e}`}}):await A().then(r=>fetch(`${qe}/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"),X(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),X(e)}}function X(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(`${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 Xe(e){const{totalPages:t,title:o,token:r,timeoutMessage:n,targetDocumentId:a,afterBlockId:s}=e,c=x(o),i=!r&&!a?await ze(c):null,m=!r&&a?{docId:a,anonSessionId:H(),anonymousBrowserId:await A()}:null,p=i??m;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:ce,...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 Qe(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&&Je(i.docId),d}}async function Qe(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 m=null;try{m=JSON.parse(i.slice(6))}catch{}if(m){if(n==="document_created")return t.releaseLock(),m;if(n==="error")throw t.releaseLock(),new Error(m.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 m=!1;for(let u=0;u<c&&!m;u++){const w=Math.floor(a.width*u/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&&!m;I+=4)(y[I]<250||y[I+1]<250||y[I+2]<250)&&(m=!0)}if(!m)throw new Error(`Page ${t} appears blank. The PDF may use an unsupported image format.`);const p=await new Promise((u,w)=>{a.toBlob(b=>{b?u(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:m,maxPlanLimit:p}=await He(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,u=g?Math.min(Ze,P):0,w=[];for(let y=1;y<=u;y++){const{thumbnail:I}=await Z(h,y);w.push(I),r({stage:"rasterizing",currentPage:y,totalPages:u,message:`Preparing preview ${y} of ${u}...`,thumbnail:I})}const b=x(ie(e.name??"")||"Imported PDF");return{thumbnails:w,totalPages:P,ocrMonthlyLimit:a,ocrPagesRemaining:s,limitPeriod:c,anonymous:i,freeAccountLimit:m,maxPlanLimit:p,exceedsLimit:g,title:b,_pdf:h,_token:n,_file:e}}async function te(e,t,o,r){const n=u=>{t&&t(u)},{_pdf:a,_token:s,_file:c,totalPages:i,title:m,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:m,token:s,timeoutMessage:"Import timed out after 10 minutes. Please try with a shorter PDF.",targetDocumentId:o,afterBlockId:r});return Ye({totalPages:i,preparePage:async u=>{const{blob:w,thumbnail:b}=await Z(a,u);return n({stage:"rasterizing",currentPage:u,totalPages:i,message:`Processing page ${u} of ${i}`,thumbnail:b}),{url:await Ve(w,u,s),mediaType:"image/png",pageNumber:u}},sendBatch:(u,w)=>Q({importId:g.importId,uploadToken:g.uploadToken,pages:u,final:w})}).catch(async u=>{const w=u instanceof Error?u.message:"Failed to prepare PDF pages";console.error("[PDF Import] Background page upload failed:",u),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 et(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,et as importPdfIntoExistingDocument,ee as previewPdfForImport,oe as watchImportCompletion};
@@ -0,0 +1,15 @@
1
+ import{F as P,H as w,ah as D,ai as K,aj as U,ak as G,al as z,am as _,L as Y}from"./index-D9_PwgOX.js";import{N as X,k as Z,h as $,g as J,r as T,t as k,i as Q,m as tt,d as et,s as st,b as rt,l as nt,f as it,j as at,a as ot,p as lt}from"./OfficeImportShared-C_mYnG5V.js";const ct={65001:"utf-8",932:"shift_jis",936:"gb18030",949:"euc-kr",950:"big5",874:"windows-874",1e4:"macintosh",437:"windows-1252",850:"windows-1252"};function ht(a){const t=/\\ansicpg(\d+)/i.exec(a)?.[1];return t?C(t):/\\mac\b/.test(a)?"macintosh":"windows-1252"}function C(a){const t=String(a);return ct[t]??`windows-${t}`}const dt={77:1e4,128:932,129:949,134:936,136:950,161:1253,162:1254,163:1258,177:1255,178:1256,186:1257,204:1251,222:874,238:1250},W=new Map;function ut(a,t){let e=W.get(t);if(!e){try{D(new Uint8Array,t),e=t}catch{e="windows-1252"}W.set(t,e)}return D(a instanceof Uint8Array?a:new Uint8Array(a),e)}class L{constructor(t){this.kind=t,this.items=[],this.runs=[],this.runText="",this.runMarks={},this.paraId=w(),this.suppressEmptyPar=!1}}const pt=new Map([["emdash","—"],["endash","–"],["lquote","‘"],["rquote","’"],["ldblquote","“"],["rdblquote","”"],["bullet","•"],["emspace"," "],["enspace"," "],["qmspace"," "],["zwj","‍"],["zwnj","‌"],["ltrmark","‎"],["rtlmark","‏"]]),ft=new Set(["info","xmlnstbl","themedata","colorschememapping","latentstyles","datastore","generator","filetbl","rsidtbl","nonshppict","objdata","objclass","objname","shpinst","shptxt","userprops","docvar","pgdsctbl","mmathPr","bkmkstart","bkmkend","xe","tc","txe","template","private","passwordhash","wgrffmtfilter","defchp","defpap","listpicture","pnseclvl","protusertbl","fchars","lchars","aftnsep","aftnsepc","aftncn","ftnsep","ftnsepc","ftncn","blipuid","picprop","atnicn","atntime","do","falt","panose","fname","oldcprops","oldpprops","oldtprops","oldsprops","annotation-ignore"]),gt=new Set(["expandedcolortbl","listtable","listoverridetable","shppict","fldinst","annotation","atnauthor","atnid","atnref","atndate","atrfstart","atrfend","pn","revtbl","footnote"]),mt=new Set(["pict","footnote","annotation","fldinst","fldrslt","header","headerl","headerr","headerf","footer","footerl","footerr","footerf"]),bt=new Set(["ul","uld","uldash","uldashd","uldashdd","uldb","ulhwave","ulldash","ulth","ulthd","ulthdash","ulthdashd","ulthdashdd","ulthldash","ululdbwave","ulw","ulwave"]),E=new Map([["header","default"],["headerr","default"],["headerl","even"],["headerf","first"],["footer","default"],["footerr","default"],["footerl","even"],["footerf","first"]]);function F(a,t={}){return new kt(a,t).read()}class kt{constructor(t,e){this.rtf=t,this.options=e,this.defaultFont=0,this.fonts=new Map,this.colors=[],this.colorParts={r:0,g:0,b:0},this.colorHasValue=!1,this.expandedIndex=0,this.expandedParts=[],this.styles=new Map,this.currentStyle=null,this.lists=new Map,this.currentList=null,this.listOverrides=new Map,this.currentOverride=null,this.revAuthors=[],this.currentFontEntry=null,this.rowDefs=[],this.pendingCellDef={},this.rowIsHeader=!1,this.body=new L("body"),this.notes=new X("rtffn"),this.headers={},this.footers={},this.comments=[],this.openCommentRanges=[],this.commentMeta={},this.annotationCounter=0,this.commentRangeIds=new Map,this.commentIds=new Set,this.page={margins:{}},this.sectionSeen=!1,this.stack=[],this.marksVersion=0,this.cachedMarksVersion=-1,this.cachedMarks={},this.pendingBytes=[],this.pendingBytesEncoding="",this.chainsSeen=new Set,this.ansiEncoding=ht(t.slice(0,4096)),this.cocoa=/\\cocoartf/.test(t.slice(0,512)),this.state={dest:"body",chars:{},para:{borders:{}},unicodeSkip:1,storyRef:{story:this.body}}}read(){this.tokenize(),this.flushBytes();const t=this.body;this.flushRun(t),t.runs.some(i=>i.text.trim().length>0)&&this.flushParagraph(t);const e=this.buildBlocks(t.items,"body");V(e),e.length===0&&e.push(P());const s={type:"doc",children:e};this.notes.notes.length>0&&(s.notes=this.notes.notes),Object.keys(this.headers).length>0&&(s.headers=this.headers),Object.keys(this.footers).length>0&&(s.footers=this.footers);const r=Z(this.comments,[s.children,s.notes??[]]);r.length>0&&(s.comments=r);const n=this.pageLayout();return n&&(s.pageLayout=n),s}tokenize(){const t=this.rtf,e=t.length,s=/\\([a-zA-Z]{1,32})(-?\d{1,10})? ?/y;let r=0;for(;r<e;){const n=t.charCodeAt(r);if(n===123){this.flushBytes(),this.pushGroup(),r++;continue}if(n===125){this.flushBytes(),this.popGroup(),r++;continue}if(n===10||n===13){r++;continue}if(n!==92){let l=r+1;for(;l<e;){const f=t.charCodeAt(l);if(f===92||f===123||f===125||f===10||f===13)break;l++}this.literal(t.slice(r,l)),r=l;continue}const i=t[r+1];if(i===void 0)break;if(i==="\\"||i==="{"||i==="}"){this.flushBytes(),this.text(i),r+=2;continue}if(i==="'"){const l=parseInt(t.slice(r+2,r+4),16);r+=4,Number.isNaN(l)||this.byte(l);continue}if(this.flushBytes(),i==="*"){this.state.starred=!0,r+=2;continue}if(i==="~"){this.text(" "),r+=2;continue}if(i==="_"){this.text("‑"),r+=2;continue}if(i==="-"){r+=2;continue}if(i===`
2
+ `||i==="\r"){this.controlWord("par",null),r+=2;continue}s.lastIndex=r;const o=s.exec(t);if(!o){r+=2;continue}r+=o[0].length;const c=o[1],d=o[2]!==void 0?parseInt(o[2],10):null;if(c==="bin"&&d!==null&&d>0){this.binary(t.slice(r,r+d)),r+=d;continue}if(c==="u"&&d!==null){this.text(String.fromCharCode(d<0?d+65536:d));let l=this.state.unicodeSkip;for(;l>0&&r<e;){const f=t[r];if(f==="\\")if(t[r+1]==="'")r+=4;else{s.lastIndex=r;const m=s.exec(t);r+=m?m[0].length:2}else{if(f==="{"||f==="}")break;if(f===`
3
+ `||f==="\r"){r+=1;continue}else r+=1}l--}continue}this.controlWord(c,d)}}pushGroup(){const t=this.state;this.stack.push(t),this.state={dest:t.dest,chars:{...t.chars},para:{...t.para,borders:{...t.para.borders}},unicodeSkip:t.unicodeSkip,storyRef:t.storyRef,field:t.field,link:t.link,fieldKind:t.fieldKind,capture:void 0,metaKind:t.dest==="meta"?t.metaKind:void 0},(t.dest==="listtext"||t.dest==="fldinst"||t.dest==="meta")&&(this.state.capture=t.capture),this.marksVersion++}popGroup(){const t=this.state,e=this.stack.pop();e&&(this.endGroup(t,e),this.state=e,this.marksVersion++)}endGroup(t,e){switch(t.dest){case"pict":t.pict&&t.pict!==e.pict&&this.finishPicture(t.pict,t);break;case"fonttbl":t.capture&&t.capture!==e.capture&&this.finishFontName(t.capture.text);break;case"stylesheet":t.capture&&t.capture!==e.capture&&this.finishStyle(t.capture.text);break;case"listtext":e.dest!=="listtext"&&t.capture&&(t.storyRef.story.listText=t.capture.text);break;case"fldinst":e.dest!=="fldinst"&&t.capture&&t.field&&(t.field.instr=t.capture.text);break;case"meta":e.dest!=="meta"&&t.capture&&t.metaKind&&this.finishMeta(t.metaKind,t.capture.text.trim());break;case"revtbl":if(t.capture&&t.capture!==e.capture)for(const s of t.capture.text.split(";").slice(0,-1))this.revAuthors.push(s.trim());break}t.opensStory&&this.finishStory(t,e)}literal(t){const e=this.state;if(this.flushBytes(),e.dest==="pict"){e.pict?.hex.push(t);return}if(this.options.binary){let s=0;for(let r=0;r<t.length;r++)t.charCodeAt(r)>=128&&(r>s&&(this.flushBytes(),this.text(t.slice(s,r))),this.byte(t.charCodeAt(r)&255),s=r+1);s<t.length&&(this.flushBytes(),this.text(t.slice(s)));return}this.text(t)}byte(t){const e=this.currentEncoding();this.pendingBytes.length>0&&e!==this.pendingBytesEncoding&&this.flushBytes(),this.pendingBytesEncoding=e,this.pendingBytes.push(t)}flushBytes(){if(this.pendingBytes.length===0)return;const t=this.pendingBytes;this.pendingBytes=[],this.text(ut(t,this.pendingBytesEncoding))}currentEncoding(){const t=this.state.chars;return this.fonts.get(t.font??t.lochFont??this.defaultFont)?.encoding??this.ansiEncoding}binary(t){const e=this.state.pict;if(this.state.dest!=="pict"||!e)return;const s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r)&255;(e.binary??(e.binary=[])).push(s)}text(t){if(!t)return;const e=this.state;switch(e.dest){case"body":{const s=e.storyRef.story,r=this.effectiveMarks();J(r,s.runMarks)||(this.flushRun(s),s.runMarks=r),s.runText+=t,s.suppressEmptyPar=!1;return}case"fonttbl":case"stylesheet":case"listtext":case"fldinst":case"meta":e.capture&&(e.capture.text+=t),e.dest==="fonttbl"&&t.includes(";")&&this.fontTableSemicolons(t);return;case"colortbl":for(const s of t)s===";"&&(this.colors.push(this.colorHasValue?$(this.colorParts.r,this.colorParts.g,this.colorParts.b):void 0),this.colorParts={r:0,g:0,b:0},this.colorHasValue=!1);return;case"expandedcolortbl":for(const s of t){if(s!==";")continue;const r=this.expandedParts,n=i=>i/1e5*255;if(r.length>=3)this.colors[this.expandedIndex]=$(n(r[0]),n(r[1]),n(r[2]));else if(r.length===1){const i=n(r[0]);this.colors[this.expandedIndex]=$(i,i,i)}this.expandedParts=[],this.expandedIndex++}return;case"revtbl":e.capture?e.capture.text+=t:e.capture={text:t};return;default:return}}fontTableSemicolons(t){const e=this.state.capture;if(!e)return;const s=e.text.split(";");for(let r=0;r<s.length-1;r++)this.finishFontName(s[r]);e.text=s[s.length-1]}effectiveMarks(){if(this.cachedMarksVersion===this.marksVersion)return this.cachedMarks;const t=this.state,e=t.chars,s={};e.bold&&(s.bold=!0),e.italic&&(s.italic=!0),e.underline&&(s.underline=!0),e.strike&&(s.strikethrough=!0),e.dstrike&&(s.doubleStrikethrough=!0),e.superscript?s.superscript=!0:e.subscript&&(s.subscript=!0),e.caps&&(s.allCaps=!0),e.scaps&&(s.smallCaps=!0),e.hidden&&(s.hidden=!0);const r=this.fonts.get(e.font??e.lochFont??this.defaultFont)?.name;r&&(s.fontFamily=r),e.halfPoints&&e.halfPoints>0&&(s.fontSize=T(e.halfPoints/2*(96/72)));const n=e.color?this.colors[e.color]:void 0;n&&n!=="#000000"&&(s.color=n);const i=(e.highlight?this.colors[e.highlight]:void 0)??(e.background?this.colors[e.background]:void 0);return i&&i!=="#ffffff"&&(s.backgroundColor=i),e.expandTwips&&(s.letterSpacing=T(k(e.expandTwips))),t.link&&(s.link=t.link),t.fieldKind&&(s.field=t.fieldKind),this.openCommentRanges.length>0&&t.storyRef.story.kind!=="annotation"&&(s.comment=this.openCommentRanges.join(",")),e.deleted?Object.assign(s,this.revisionMarks("deletion",e.revAuthorDel??e.revAuthor,e.revTimeDel??e.revTime)):e.revised&&Object.assign(s,this.revisionMarks("insertion",e.revAuthor,e.revTime)),this.cachedMarks=s,this.cachedMarksVersion=this.marksVersion,s}revisionMarks(t,e,s){const r=e!==void 0?this.revAuthors[e]:void 0,n=s!==void 0?H(s):void 0;return Q(t,`rtfrev-${t==="insertion"?"ins":"del"}-${e??0}-${s??0}`,r&&r!=="Unknown"?r:void 0,n)}flushRun(t){t.runText&&(t.runs.push({type:"text",text:t.runText,marks:{...t.runMarks}}),t.runText="")}flushParagraph(t,e=!1){this.flushRun(t);const s=t.runs.filter(r=>r.text.length>0);if(t.runs=[],s.length===0&&t.suppressEmptyPar&&!e){t.suppressEmptyPar=!1,t.listText=void 0,t.paraId=w();return}t.items.push({kind:"para",id:t.paraId,runs:tt(s),para:{...this.state.para,borders:{...this.state.para.borders}},...t.listText!==void 0?{listText:t.listText}:{},...e?{forcedInTable:!0}:{}}),t.listText=void 0,t.suppressEmptyPar=!1,t.paraId=w()}controlWord(t,e){const s=this.state,r=s.starred;if(s.starred=!1,s.dest!=="skip"&&!this.startDestination(t)){if(r&&!gt.has(t)){s.dest="skip";return}if(ft.has(t)){s.dest="skip";return}switch(s.dest){case"fonttbl":this.fontTableWord(t,e);return;case"colortbl":this.colorTableWord(t,e);return;case"expandedcolortbl":t==="c"&&e!==null?this.expandedParts.push(e):(t==="cssrgb"||t==="csgray"||t==="csgenericrgb")&&(this.expandedParts=[]);return;case"stylesheet":this.styleSheetWord(t,e);return;case"listtable":this.listTableWord(t,e);return;case"listoverridetable":this.listOverrideWord(t,e);return;case"pict":this.pictWord(t,e);return;case"pn":this.pnWord(t,e);return;case"listtext":case"fldinst":case"meta":t==="tab"&&this.text(" ");return;case"revtbl":return}if(this.characterWord(t,e)){this.marksVersion++;return}this.paragraphWord(t,e)||this.structureWord(t,e)}}startDestination(t){const e=this.state;if(e.dest!=="body"&&mt.has(t))return e.dest="skip",!0;switch(t){case"fonttbl":return e.dest="fonttbl",e.capture={text:""},!0;case"colortbl":return e.dest="colortbl",this.colors=[],!0;case"expandedcolortbl":return e.dest="expandedcolortbl",this.expandedIndex=0,this.expandedParts=[],!0;case"stylesheet":return e.dest="stylesheet",!0;case"listtable":return e.dest="listtable",!0;case"listoverridetable":return e.dest="listoverridetable",!0;case"revtbl":return e.dest="revtbl",!0;case"pict":return e.dest="pict",e.pict={hex:[]},!0;case"shppict":case"shprslt":case"result":case"shp":case"object":case"field":return t==="field"&&(e.field={instr:""}),!0;case"fldinst":return e.dest="fldinst",e.capture={text:""},!0;case"fldrslt":{const s=e.field?.instr??"",r=/^\s*HYPERLINK\s+(?:\\[a-z]\s+)*"([^"]+)"/i.exec(s);return r&&!/^\s*HYPERLINK\s+\\l\b/i.test(s)&&(e.link=et(r[1])),/^\s*PAGE\b/i.test(s)&&(e.fieldKind="page"),/^\s*NUMPAGES\b/i.test(s)&&(e.fieldKind="numPages"),this.marksVersion++,!0}case"listtext":case"pntext":return e.dest="listtext",e.capture={text:""},!0;case"pn":return e.dest="pn",e.para.pn={kind:"number",level:0},!0;case"footnote":return this.openStory("footnote");case"annotation":return this.openStory("annotation");case"atnauthor":case"atnid":case"atnref":case"atndate":case"atrfstart":case"atrfend":return e.dest="meta",e.metaKind=t,e.capture={text:""},!0;default:return E.has(t)?(e.dest="body",e.opensStory=!0,e.storyRef={story:new L("header")},e.para={borders:{}},e.headerWord=t,!0):!1}}openStory(t){const e=this.state;return e.dest="body",e.opensStory=!0,e.storyRef={story:new L(t)},e.para={borders:{}},e.link=void 0,t==="annotation"&&(this.annotationRef=void 0,this.annotationDate=void 0),this.marksVersion++,!0}finishStory(t,e){const s=t.storyRef.story;if(this.flushRun(s),s.runs.some(i=>i.text.length>0)){const i=this.state;this.state=t,this.flushParagraph(s),this.state=i}const r=this.buildBlocks(s.items,s.kind);V(r);const n=e.storyRef.story;if(s.kind==="footnote"||s.kind==="endnote"){if(e.dest!=="body")return;this.flushRun(n),this.state=e,this.marksVersion++;const i=this.effectiveMarks(),o=this.notes.add(s.kind,r,i);n.runs.push(o),n.runMarks={},this.marksVersion++;return}if(s.kind==="header"){const i=t.headerWord??"header",o=E.get(i)??"default",c=r.filter(d=>d.type==="paragraph");if(c.some(d=>d.children.some(l=>l.text.trim()!==""||l.marks?.field))){const d=i.startsWith("footer")?this.footers:this.headers;d[o]=c}return}if(s.kind==="annotation"){const i=r.map(l=>l.type==="paragraph"?l.children.map(f=>f.text).join("").trim():"").filter(l=>l.length>0).join(`
4
+
5
+ `);this.annotationCounter++;const o=this.annotationRef;let c=`rtfcmt-${o??`point-${this.annotationCounter}`}`,d=o!==void 0&&this.commentRangeIds.has(o);if(this.commentIds.has(c)){d=!1;let l=this.annotationCounter;for(;this.commentIds.has(`${c}-${l}`);)l++;c=`${c}-${l}`}this.commentIds.add(c),this.comments.push({id:c,author:this.commentMeta.author||this.commentMeta.initials||"Unknown",...this.commentMeta.initials?{initials:this.commentMeta.initials}:{},createdAt:new Date(this.annotationDate!==void 0?H(this.annotationDate)??0:0).toISOString(),bodyMd:i,...d?{}:{anchorBlockId:n.paraId}}),this.commentMeta={}}}finishMeta(t,e){switch(t){case"atnauthor":this.commentMeta.author=e;break;case"atnid":this.commentMeta.initials=e;break;case"atnref":this.annotationRef=e;break;case"atndate":{const s=parseInt(e,10);Number.isFinite(s)&&(this.annotationDate=s);break}case"atrfstart":e&&(this.commentRangeIds.set(e,`rtfcmt-${e}`),this.openCommentRanges=[...this.openCommentRanges,`rtfcmt-${e}`],this.marksVersion++);break;case"atrfend":e&&(this.openCommentRanges=this.openCommentRanges.filter(s=>s!==`rtfcmt-${e}`),this.marksVersion++);break}}fontTableWord(t,e){if(t==="f"&&e!==null){const r=this.state.capture;r&&r.text.trim()&&this.currentFontEntry!==null&&this.finishFontName(r.text),this.currentFontEntry=e,this.fonts.has(e)||this.fonts.set(e,{name:""}),this.state.capture={text:""};return}const s=this.currentFontEntry!==null?this.fonts.get(this.currentFontEntry):void 0;if(s)if(t==="fcharset"&&e!==null){const r=dt[e];r&&(s.encoding=C(r)),e===2&&(s.encoding="windows-1252")}else t==="cpg"&&e!==null&&e>0&&(s.encoding=C(e))}finishFontName(t){if(this.currentFontEntry===null)return;const e=this.fonts.get(this.currentFontEntry),s=t.replace(/;$/,"").trim();e&&s&&!e.name&&(e.name=this.cocoa?St(s):s)}colorTableWord(t,e){if(e!==null){if(t==="red")this.colorParts.r=e;else if(t==="green")this.colorParts.g=e;else if(t==="blue")this.colorParts.b=e;else return;this.colorHasValue=!0}}styleSheetWord(t,e){const s=this.state;t==="s"&&e!==null?(this.currentStyle={index:e},s.capture={text:""}):t==="outlinelevel"&&e!==null&&this.currentStyle&&(this.currentStyle.outlineLevel=e)}finishStyle(t){if(!this.currentStyle)return;const e=t.replace(/;[\s\S]*$/,"").trim();this.styles.set(this.currentStyle.index,{name:e,outlineLevel:this.currentStyle.outlineLevel}),this.currentStyle=null}listTableWord(t,e){switch(t){case"list":this.currentList={def:{levels:[]}};break;case"listlevel":this.currentList?.def.levels.push({nfc:0,startAt:1});break;case"levelnfc":case"levelnfcn":{const s=this.currentList?.def.levels.at(-1);s&&e!==null&&(s.nfc=e);break}case"levelstartat":{const s=this.currentList?.def.levels.at(-1);s&&e!==null&&(s.startAt=e);break}case"listid":this.currentList&&e!==null&&(this.currentList.id=e,this.lists.set(e,this.currentList.def));break}}listOverrideWord(t,e){t==="listoverride"?this.currentOverride={}:t==="listid"&&this.currentOverride&&e!==null?this.currentOverride.listId=e:t==="ls"&&this.currentOverride&&e!==null&&(this.currentOverride.ls=e);const s=this.currentOverride;s?.listId!==void 0&&s.ls!==void 0&&this.listOverrides.set(s.ls,s.listId)}pnWord(t,e){const s=this.state.para.pn;if(!s)return;t==="pnlvlblt"?s.kind="bullet":/^pn(dec|ucltr|lcltr|ucrm|lcrm|ord|ordt|cardt)$/.test(t)?s.kind="number":t==="pnlvl"&&e!==null&&(s.level=Math.max(0,e-1));const r=this.stack[this.stack.length-1];r&&(r.para.pn={...s})}pictWord(t,e){const s=this.state.pict;if(s)switch(t){case"pngblip":s.format="png";break;case"jpegblip":s.format="jpeg";break;case"emfblip":s.format="emf";break;case"wmetafile":s.format="wmf";break;case"macpict":case"dibitmap":case"wbitmap":case"pmmetafile":s.format??(s.format="unsupported");break;case"picw":e!==null&&(s.picw=e);break;case"pich":e!==null&&(s.pich=e);break;case"picwgoal":e!==null&&(s.goalW=e);break;case"pichgoal":e!==null&&(s.goalH=e);break;case"picscalex":e!==null&&(s.scaleX=e);break;case"picscaley":e!==null&&(s.scaleY=e);break}}finishPicture(t,e){let s;if(t.binary&&t.binary.length>0){const b=t.binary.reduce((u,p)=>u+p.length,0);s=new Uint8Array(b);let h=0;for(const u of t.binary)s.set(u,h),h+=u.length}else s=vt(t.hex.join(""));if(s.length===0)return;const r=t.format&&t.format!=="unsupported"?t.format:void 0,n=st(s)??r;if(!n)return;const i=n==="emf"||n==="wmf",o=(t.scaleX??100)/100,c=(t.scaleY??100)/100,d=(b,h)=>b?k(b):h?i?h/2540*96:h:void 0,l=d(t.goalW,t.picw),f=d(t.goalH,t.pich),m=e.storyRef.story,M=e.para;if(this.flushRun(m),m.runs.some(b=>b.text.length>0)){const b=this.state;this.state=e,this.flushParagraph(m),this.state=b}else m.runs=[];const A=M.align==="justify"?void 0:M.align;m.items.push({kind:"image",image:rt(s,n,{width:l!==void 0?l*o:void 0,height:f!==void 0?f*c:void 0},{align:A}),inTable:!!M.inTable}),m.suppressEmptyPar=!0}characterWord(t,e){const s=this.state.chars,r=e!==0;if(bt.has(t))return s.underline=r,!0;switch(t){case"plain":{const{revised:n,deleted:i,revAuthor:o,revTime:c,revAuthorDel:d,revTimeDel:l}=s;return this.state.chars={revised:n,deleted:i,revAuthor:o,revTime:c,revAuthorDel:d,revTimeDel:l},!0}case"b":return s.bold=r,!0;case"i":return s.italic=r,!0;case"ulnone":return s.underline=!1,!0;case"strike":return s.strike=r,!0;case"striked":return s.dstrike=r,!0;case"super":return s.superscript=r,s.subscript=!1,!0;case"sub":return s.subscript=r,s.superscript=!1,!0;case"nosupersub":return s.superscript=!1,s.subscript=!1,!0;case"caps":return s.caps=r,!0;case"scaps":return s.scaps=r,!0;case"v":return s.hidden=r,!0;case"f":return e!==null&&(s.font=e),!0;case"loch":case"hich":case"dbch":return s.script=t,!0;case"rtlch":case"ltrch":return s.script=void 0,!0;case"af":return e!==null&&(s.script==="loch"||s.script==="hich")&&(s.lochFont=e),!0;case"fs":return e!==null&&(s.halfPoints=e),!0;case"fsmilli":return e!==null&&(s.halfPoints=e/1e3*2),!0;case"cf":return s.color=e??0,!0;case"highlight":return s.highlight=e??0,!0;case"cb":case"chcbpat":return s.background=e??0,!0;case"expndtw":return s.expandTwips=e??0,!0;case"expnd":return s.expandTwips===void 0&&e!==null&&(s.expandTwips=e*5),!0;case"revised":return s.revised=r,!0;case"deleted":return s.deleted=r,!0;case"revauth":return e!==null&&(s.revAuthor=e),!0;case"revdttm":return e!==null&&(s.revTime=e),!0;case"revauthdel":return e!==null&&(s.revAuthorDel=e),!0;case"revdttmdel":return e!==null&&(s.revTimeDel=e),!0;default:return!1}}paragraphWord(t,e){const s=this.state.para;switch(t){case"pard":return this.state.para={borders:{}},!0;case"qc":return s.align="center",!0;case"qr":return s.align="right",!0;case"qj":case"qd":return s.align="justify",!0;case"ql":return s.align=void 0,!0;case"li":case"lin":return e!==null&&(s.leftTwips=e),!0;case"fi":return e!==null&&(s.firstTwips=e),!0;case"sb":return e!==null&&(s.spaceBeforeTwips=e),!0;case"sa":return e!==null&&(s.spaceAfterTwips=e),!0;case"sl":return s.lineTwips=e??0,!0;case"slmult":return s.lineMultiple=e===1,!0;case"keepn":return s.keepNext=e!==0,!0;case"keep":return s.keepLines=e!==0,!0;case"rtlpar":return s.rtl=!0,!0;case"ltrpar":return s.rtl=!1,!0;case"s":return e!==null&&(s.style=e),!0;case"outlinelevel":return e!==null&&(s.outlineLevel=e),!0;case"intbl":return s.inTable=e!==0,!0;case"itap":return e!==null&&(s.inTable=e>0),!0;case"ls":return e!==null&&(s.ls=e),!0;case"ilvl":return e!==null&&(s.ilvl=e),!0;case"cbpat":return e!==null&&(s.shading=e),!0;case"pagebb":return s.pageBreakBefore=e!==0,!0;case"brdrt":case"brdrb":case"brdrl":case"brdrr":case"box":{const r=t==="box"?["top","bottom","left","right"]:[{brdrt:"top",brdrb:"bottom",brdrl:"left",brdrr:"right"}[t]];for(const n of r)s.borders[n]={style:"single",width:1,color:"#000000"};return s.borderTarget=t==="box"?"box":r[0],!0}case"brdrs":case"brdrth":case"brdrsh":case"brdrdb":case"brdrdash":case"brdrdashsm":case"brdrdot":case"brdrnone":case"brdrw":case"brdrcf":{const r=s.borderTarget;if(!r||r==="ignore")return!0;const n=r==="box"?["top","bottom","left","right"]:[r];for(const i of n){const o=s.borders[i];o&&(t==="brdrnone"?delete s.borders[i]:t==="brdrdb"?o.style="double":t==="brdrdash"||t==="brdrdashsm"?o.style="dashed":t==="brdrdot"?o.style="dotted":t==="brdrth"?(o.style="single",o.width=Math.max(o.width,2)):t==="brdrw"&&e!==null?o.width=Math.min(8,Math.max(1,Math.round(e/15))):t==="brdrcf"&&e!==null?o.color=this.colors[e]??o.color:(t==="brdrs"||t==="brdrsh")&&(o.style="single"))}return!0}default:return/^(tr|cl|pg)brdr[tblrhv]$|^brdrbtw$|^brdrbar$/.test(t)?(s.borderTarget="ignore",!(t.startsWith("cl")||t.startsWith("tr"))):!1}}structureWord(t,e){const s=this.state.storyRef.story,r=this.state.dest==="body";switch(t){case"par":r&&this.flushParagraph(s);return;case"sect":r&&(s.runs.length>0||s.runText)&&this.flushParagraph(s),this.sectionSeen=!0;return;case"line":this.text(`
6
+ `);return;case"tab":this.text(" ");return;case"page":if(!r||s.kind!=="body")return;this.flushRun(s),s.runs.some(n=>n.text.length>0)&&this.flushParagraph(s),s.runs=[],s.items.push({kind:"pagebreak",inTable:!!this.state.para.inTable}),s.suppressEmptyPar=!0;return;case"cell":case"nestcell":if(!r)return;this.flushParagraph(s,!0),t==="cell"&&s.items.push({kind:"cell"});return;case"row":if(!r)return;this.flushRun(s),s.runs.some(n=>n.text.length>0)&&(this.flushParagraph(s,!0),s.items.push({kind:"cell"})),s.runs=[],s.items.push({kind:"row",defs:this.rowDefs.slice(),header:this.rowIsHeader});return;case"trowd":this.rowDefs=[],this.pendingCellDef={},this.rowIsHeader=!1;return;case"trhdr":this.rowIsHeader=!0;return;case"clmgf":this.pendingCellDef.hmergeFirst=!0;return;case"clmrg":this.pendingCellDef.hmergeCont=!0;return;case"clvmgf":this.pendingCellDef.vmergeFirst=!0;return;case"clvmrg":this.pendingCellDef.vmergeCont=!0;return;case"clcbpat":e!==null&&(this.pendingCellDef.background=e);return;case"clvertalt":this.pendingCellDef.valign="top";return;case"clvertalc":this.pendingCellDef.valign="middle";return;case"clvertalb":this.pendingCellDef.valign="bottom";return;case"cellx":e!==null&&(this.rowDefs.push({right:e,...this.pendingCellDef}),this.pendingCellDef={});return;case"chftn":case"chatn":case"chpgn":t==="chpgn"&&r&&s.kind==="header"&&(this.state.fieldKind="page",this.marksVersion++,this.text("1"),this.state.fieldKind=void 0,this.marksVersion++);return;case"ftnalt":s.kind==="footnote"&&(s.kind="endnote");return;case"uc":this.state.unicodeSkip=e??1;return;case"deff":e!==null&&(this.defaultFont=e);return;case"paperw":case"pgwsxn":e!==null&&(!this.sectionSeen||this.page.widthTwips===void 0)&&(this.page.widthTwips=e);return;case"paperh":case"pghsxn":e!==null&&(!this.sectionSeen||this.page.heightTwips===void 0)&&(this.page.heightTwips=e);return;case"landscape":case"lndscpsxn":this.page.landscape=!0;return;case"margl":case"margr":case"margt":case"margb":case"marglsxn":case"margrsxn":case"margtsxn":case"margbsxn":{if(e===null)return;const n=t.slice(4,5);if(t.endsWith("sxn")&&this.sectionSeen)return;this.page.margins[n]=e;return}default:{const n=pt.get(t);n!==void 0&&this.text(n)}}}buildBlocks(t,e){const s=[],r=i=>i.kind==="cell"||i.kind==="row"||i.kind==="para"&&(!!i.para.inTable||!!i.forcedInTable)||(i.kind==="image"||i.kind==="pagebreak")&&i.inTable;let n=0;for(;n<t.length;){const i=t[n];if(e!=="header"&&r(i)){const o=n;for(;n<t.length&&r(t[n]);)n++;const c=this.buildTable(t.slice(o,n),e);c&&s.push(...c);continue}if(i.kind==="para"){const o=this.listInfo(i);if(o&&e!=="header"){const c=[{item:i,info:o}];for(n++;n<t.length;){const d=t[n];if(d.kind!=="para"||r(d))break;const l=this.listInfo(d);if(!l||l.key!==o.key)break;c.push({item:d,info:l}),n++}s.push(this.buildList(c));continue}i.para.pageBreakBefore&&e==="body"&&s.length>0&&s.push({type:"page-break",id:w()}),s.push(this.buildParagraph(i,e)),n++;continue}i.kind==="image"?s.push(i.image):i.kind==="pagebreak"&&s.push({type:"page-break",id:w()}),n++}return s}buildParagraph(t,e){const s=t.runs.length>0?t.runs:[{type:"text",text:"",marks:{}}],r=P(s);r.id=t.id;const n=t.para;if(n.align&&(r.align=n.align),n.rtl&&(r.direction="rtl"),e!=="header"){const i=this.headingLevel(n);if(i&&(r.heading=i),n.leftTwips!==void 0){const c=nt(k(n.leftTwips));c&&(r.leftIndent=c)}if(n.firstTwips!==void 0){const c=it(k(n.firstTwips));c&&(r.firstLineIndent=c)}n.spaceBeforeTwips!==void 0&&(r.spaceBefore=T(k(Math.max(0,n.spaceBeforeTwips)))),n.spaceAfterTwips!==void 0&&(r.spaceAfter=T(k(Math.max(0,n.spaceAfterTwips)))),n.lineMultiple&&n.lineTwips&&n.lineTwips>0&&(r.lineSpacing=T(n.lineTwips/240)),n.keepNext&&(r.keepNext=!0),n.keepLines&&(r.keepLines=!0);const o=n.shading?this.colors[n.shading]:void 0;o&&o!=="#ffffff"&&(r.shading=o),Object.keys(n.borders).length>0&&(r.borders=JSON.stringify(n.borders))}return r}headingLevel(t){let e;if(t.outlineLevel!==void 0&&t.outlineLevel<9&&(e=t.outlineLevel+1),e===void 0&&t.style!==void 0){const s=this.styles.get(t.style),r=s?.name&&/^heading\s*(\d)$/i.exec(s.name);r?e=parseInt(r[1],10):s?.outlineLevel!==void 0&&s.outlineLevel<9&&(e=s.outlineLevel+1)}if(!(!e||e<1))return Math.min(e,6)}listInfo(t){const e=t.para;if(!this.headingLevel(e)){if(e.ls!==void 0&&e.ls>0){const s=this.listOverrides.get(e.ls),r=s!==void 0?this.lists.get(s):void 0,n=Math.max(0,Math.min(8,e.ilvl??0));if(r){const i=r.levels[n]??r.levels[0];if(i&&i.nfc===255&&t.listText===void 0)return;const o=i?i.nfc!==23&&i.nfc!==255:!1;return{key:`ls${e.ls}`,ordered:o,level:n,startAt:r.levels[0]?.startAt??1,chain:`rtf-ls-${e.ls}`}}return{key:`ls${e.ls}`,ordered:t.listText!==void 0&&O(t.listText),level:n,startAt:1,chain:`rtf-ls-${e.ls}`}}if(e.pn)return{key:`pn-${e.pn.kind}`,ordered:e.pn.kind==="number",level:e.pn.level,startAt:1};if(t.listText!==void 0&&t.listText.trim()!==""){const s=O(t.listText);return{key:`lt-${s}`,ordered:s,level:0,startAt:1}}}}buildList(t){const e=t[0].info,s=t.map(({item:i,info:o})=>{const c=i.runs.length>0?i.runs:[{type:"text",text:"",marks:{}}];return{type:"list-item",id:i.id,children:c,...o.level>0?{indentLevel:o.level}:{},...i.para.rtl?{direction:"rtl"}:{}}}),r={type:"list",id:w(),variant:e.ordered?"ordered":"unordered",children:s};e.ordered&&e.chain?(r.numberingChainId=e.chain,this.chainsSeen.has(e.chain)||(this.chainsSeen.add(e.chain),e.startAt!==1&&(r.startNumber=e.startAt))):e.ordered&&e.startAt!==1&&(r.startNumber=e.startAt);const n=t[0].item.para;return n.spaceAfterTwips!==void 0&&(r.spaceAfter=T(k(Math.max(0,n.spaceAfterTwips)))),n.spaceBeforeTwips!==void 0&&(r.spaceBefore=T(k(Math.max(0,n.spaceBeforeTwips)))),n.lineMultiple&&n.lineTwips&&n.lineTwips>0&&(r.lineSpacing=T(n.lineTwips/240)),r}buildTable(t,e){const s=[];let r=[],n=[],i=[];for(const h of t)h.kind==="cell"?(r.push({items:n}),n=[]):h.kind==="row"?(n.length>0&&(r.push({items:n}),n=[]),s.push({cells:r,defs:h.defs.length>0?h.defs:i,header:h.header}),h.defs.length>0&&(i=h.defs),r=[]):n.push(h);if(n.length>0&&r.push({items:n}),r.length>0&&s.push({cells:r,defs:i,header:!1}),s.length===0)return null;const o=new Set([0]),c=s.map(h=>{const u=[];let p=0,g=0;const I=h.defs.length>0?h.defs[h.defs.length-1].right/Math.max(1,h.defs.length):1440;return h.cells.forEach((R,S)=>{const x=h.defs[S],v=x?x.right:g+Math.max(1,Math.round(I));if(x?.hmergeCont&&u.length>0){const N=u[u.length-1];N.right=v,N.items.push(...R.items.filter(q=>!wt(q)))}else u.push({left:p,right:Math.max(v,p+1),def:x,items:R.items});p=v,g=v}),u}),d=0;for(const h of c)for(const u of h)o.add(Math.max(d,u.left)),o.add(u.right);const l=xt(yt([...o].sort((h,u)=>h-u),30),at(c.length)),f=h=>{let u=0,p=l.length-1;for(;u<p;){const g=u+p>>1;l[g]<h?u=g+1:p=g}return u>0&&Math.abs(l[u-1]-h)<=Math.abs(l[u]-h)?u-1:u},m=[],M=new Map;c.forEach(h=>{const u=[];for(const p of h){const g=f(p.left),I=Math.max(g+1,f(p.right));if(p.def?.vmergeCont){const v=M.get(g);if(v){v.rowSpan=(v.rowSpan??1)+1;continue}}const R=this.buildBlocks(p.items.map(v=>Tt(v)),e);Mt(R);const S={type:"table-cell",id:w(),children:R.length>0?R:[P()]};I-g>1&&(S.colSpan=I-g);const x=p.def?.background?this.colors[p.def.background]:void 0;x&&x!=="#ffffff"&&(S.backgroundColor=x),p.def?.valign&&p.def.valign!=="top"&&(S.verticalAlign=p.def.valign),p.def?.vmergeFirst?M.set(g,S):M.delete(g),u.push(S)}m.push({type:"table-row",id:w(),children:u})});const A=[];for(let h=1;h<l.length;h++)A.push(l[h]-l[h-1]);const b=ot(m,{columnWidths:A,hasHeader:s[0]?.header});return b?[b]:null}pageLayout(){const t=this.page,e=s=>t.margins[s]!==void 0?k(t.margins[s]):void 0;return lt({widthPx:t.widthTwips?k(t.widthTwips):void 0,heightPx:t.heightTwips?k(t.heightTwips):void 0,landscape:t.landscape,marginTopPx:e("t"),marginRightPx:e("r"),marginBottomPx:e("b"),marginLeftPx:e("l")})}}function O(a){const t=a.replace(/[\t\s]+/g,"");return/^(\d+|[a-zA-Z]|[ivxlcdm]+|[IVXLCDM]+)[.)]?$/.test(t)&&t.length>0}function vt(a){const t=a.replace(/[^0-9a-fA-F]/g,""),e=new Uint8Array(t.length>>1);for(let s=0;s<e.length;s++)e[s]=parseInt(t.slice(s*2,s*2+2),16);return e}function yt(a,t){const e=[];for(const s of a)(e.length===0||s-e[e.length-1]>t)&&e.push(s);return e}function xt(a,t){if(a.length-1<=t)return a;const e=a.length-1,s=[];for(let r=0;r<=t;r++)s.push(a[Math.round(r*e/t)]);return s}function wt(a){return a.kind==="para"&&a.runs.every(t=>t.text.trim()==="")}function Tt(a){return a.kind==="para"?{...a,forcedInTable:!1,para:{...a.para,inTable:!1}}:a.kind==="image"||a.kind==="pagebreak"?{...a,inTable:!1}:a}function B(a){return a.type==="paragraph"&&!a.borders&&a.children.every(t=>t.text.trim()===""&&!t.marks?.footnoteRef)}function V(a){for(;a.length>0&&B(a[0]);)a.shift();for(;a.length>0&&B(a[a.length-1]);)a.pop()}function Mt(a){for(;a.length>1&&B(a[a.length-1]);)a.pop()}function H(a){const t=a>>>0;if(t===0)return;const e=t&63,s=t>>>6&31,r=t>>>11&31,n=t>>>16&15,i=(t>>>20&511)+1900;if(!(n<1||n>12||r<1))return Date.UTC(i,n-1,r,s,e)}function St(a){if(a.startsWith("."))return"";if(/\s/.test(a))return a;let t=a.replace(/-(Regular|Roman|Book|Bold|Italic|Oblique|BoldItalic|BoldOblique|Light|LightItalic|Medium|MediumItalic|Semibold|SemiBold|SemiboldItalic|Heavy|Black|Condensed|Thin|UltraLight)$/,"");return t=t.replace(/(PSMT|PS|MT)$/,""),t=t.replace(/([a-z])([A-Z])/g,"$1 $2"),t}const j=class{static async parseFile(t){const e=new Uint8Array(await t.arrayBuffer());let s="";const r=32768;for(let n=0;n<e.length;n+=r)s+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+r)));return F(s,{binary:!0})}static fromRtf(t){return F(t)}static toRtf(t){t=K(t),this.exportListNumbering=U(t);const e=[];for(const s of t.children){const r=this.blockToRtf(s,t);r!==null&&e.push(r)}return this.exportListNumbering=null,`{\\rtf1\\ansi\\ansicpg1252\\deff0\\uc1{\\fonttbl{\\f0\\froman Times New Roman;}{\\f1\\fmodern Courier New;}}
7
+ \\f0\\fs24
8
+ `+e.join(`
9
+ `)+`
10
+ }`}static blockToRtf(t,e){switch(t.type){case"paragraph":return z(t)?"\\pard\\brdrb\\brdrs\\brdrw15 \\par":this.paragraphToRtf(t);case"list":return this.listToRtf(t);case"table":return this.tableToRtf(t);case"code":return"\\pard{\\f1\\fs20 "+y(t.content).replace(/\n/g,"\\line ")+"}\\par";case"math":return"\\pard "+y(t.content)+"\\par";case"toc":{const s=G(e,t);return s.length===0?null:s.map(r=>`\\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"?"ri":"li"}${(r.level-1)*360} `+y(r.text)+"\\par").join(`
11
+ `)}case"image":return"\\pard{\\i [Image"+(t.alt?`: ${y(t.alt)}`:"")+"]}\\par";case"page-break":return"\\page";case"container":return t.children.map(s=>this.blockToRtf(s,e)).filter(s=>s!==null).join(`
12
+ `);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 s=this.inlineNodesToRtf(t.children);return t.heading&&(s=`{\\b\\fs${this.HEADING_HALF_POINTS[t.heading-1]} ${s}}`),`${e} ${s}\\par`}static listToRtf(t){const e=this.exportListNumbering?.get(t.id);let s=e?_(e):t.startNumber??1;const r=[];for(const n of t.children){if(n.type!=="list-item")continue;const i=((n.indentLevel??0)+1)*360;let o;t.variant==="ordered"?(o=`${s}. `,s++):t.variant==="todo"?o=n.checked?"[x] ":"[ ] ":o="\\bullet ",r.push(`\\pard\\li${i} ${o}`+this.inlineNodesToRtf(n.children)+"\\par")}return r.join(`
13
+ `)}static tableToRtf(t){if(!t.children||t.children.length===0)return"";const e=Y(t),s=9360,r=[];for(let n=0;n<e.rows;n++){const i=["\\trowd\\trgaph108"];for(let o=0;o<e.cols;o++)i.push(`\\cellx${Math.round(s*(o+1)/e.cols)}`);for(let o=0;o<e.cols;o++){const c=e.occupancy[n][o];let d="";c&&c.row===n&&c.col===o&&(d=c.cell.children.map(l=>l.type==="paragraph"?this.inlineNodesToRtf(l.children):l.type==="code"?y(l.content):"").filter(l=>l.length>0).join("\\line ")),i.push(`\\pard\\intbl ${d}\\cell`)}i.push("\\row"),r.push(i.join(""))}return r.join(`
14
+ `)+`
15
+ \\pard`}static inlineNodesToRtf(t){return t.map(e=>this.textNodeToRtf(e)).join("")}static textNodeToRtf(t){if(t.marks?.footnoteRef)return`{\\super ${y(t.text)}}`;const e=y(t.text).replace(/\n/g,"\\line ");if(!t.marks)return e;const s=[];t.marks.bold&&s.push("\\b"),t.marks.italic&&s.push("\\i"),t.marks.underline&&s.push("\\ul"),t.marks.strikethrough&&s.push("\\strike"),t.marks.superscript&&s.push("\\super"),t.marks.subscript&&s.push("\\sub"),t.marks.code&&s.push("\\f1");const r=s.length>0?`{${s.join("")} ${e}}`:e;return t.marks.link?`{\\field{\\*\\fldinst HYPERLINK "${y(t.marks.link)}"}{\\fldrslt ${r}}}`:r}};j.exportListNumbering=null,j.HEADING_HALF_POINTS=[32,28,26,24,22,22];let Rt=j;function y(a){let t="";for(let e=0;e<a.length;e++){const s=a[e];if(s==="\\"||s==="{"||s==="}"){t+="\\"+s;continue}const r=a.charCodeAt(e);if(r<128){t+=s;continue}t+=`\\u${r>32767?r-65536:r}?`}return t}export{Rt as RtfConverter,y as escapeRtfText};
@@ -0,0 +1,15 @@
1
+ import{F as P,H as w,ah as D,ai as K,aj as U,ak as G,al as z,am as _,L as Y}from"./index-DcIXw_KB.js";import{N as X,k as Z,h as $,g as J,r as T,t as k,i as Q,m as tt,d as et,s as st,b as rt,l as nt,f as it,j as at,a as ot,p as lt}from"./OfficeImportShared-O-d47J7O.js";const ct={65001:"utf-8",932:"shift_jis",936:"gb18030",949:"euc-kr",950:"big5",874:"windows-874",1e4:"macintosh",437:"windows-1252",850:"windows-1252"};function ht(a){const t=/\\ansicpg(\d+)/i.exec(a)?.[1];return t?C(t):/\\mac\b/.test(a)?"macintosh":"windows-1252"}function C(a){const t=String(a);return ct[t]??`windows-${t}`}const dt={77:1e4,128:932,129:949,134:936,136:950,161:1253,162:1254,163:1258,177:1255,178:1256,186:1257,204:1251,222:874,238:1250},W=new Map;function ut(a,t){let e=W.get(t);if(!e){try{D(new Uint8Array,t),e=t}catch{e="windows-1252"}W.set(t,e)}return D(a instanceof Uint8Array?a:new Uint8Array(a),e)}class L{constructor(t){this.kind=t,this.items=[],this.runs=[],this.runText="",this.runMarks={},this.paraId=w(),this.suppressEmptyPar=!1}}const pt=new Map([["emdash","—"],["endash","–"],["lquote","‘"],["rquote","’"],["ldblquote","“"],["rdblquote","”"],["bullet","•"],["emspace"," "],["enspace"," "],["qmspace"," "],["zwj","‍"],["zwnj","‌"],["ltrmark","‎"],["rtlmark","‏"]]),ft=new Set(["info","xmlnstbl","themedata","colorschememapping","latentstyles","datastore","generator","filetbl","rsidtbl","nonshppict","objdata","objclass","objname","shpinst","shptxt","userprops","docvar","pgdsctbl","mmathPr","bkmkstart","bkmkend","xe","tc","txe","template","private","passwordhash","wgrffmtfilter","defchp","defpap","listpicture","pnseclvl","protusertbl","fchars","lchars","aftnsep","aftnsepc","aftncn","ftnsep","ftnsepc","ftncn","blipuid","picprop","atnicn","atntime","do","falt","panose","fname","oldcprops","oldpprops","oldtprops","oldsprops","annotation-ignore"]),gt=new Set(["expandedcolortbl","listtable","listoverridetable","shppict","fldinst","annotation","atnauthor","atnid","atnref","atndate","atrfstart","atrfend","pn","revtbl","footnote"]),mt=new Set(["pict","footnote","annotation","fldinst","fldrslt","header","headerl","headerr","headerf","footer","footerl","footerr","footerf"]),bt=new Set(["ul","uld","uldash","uldashd","uldashdd","uldb","ulhwave","ulldash","ulth","ulthd","ulthdash","ulthdashd","ulthdashdd","ulthldash","ululdbwave","ulw","ulwave"]),E=new Map([["header","default"],["headerr","default"],["headerl","even"],["headerf","first"],["footer","default"],["footerr","default"],["footerl","even"],["footerf","first"]]);function F(a,t={}){return new kt(a,t).read()}class kt{constructor(t,e){this.rtf=t,this.options=e,this.defaultFont=0,this.fonts=new Map,this.colors=[],this.colorParts={r:0,g:0,b:0},this.colorHasValue=!1,this.expandedIndex=0,this.expandedParts=[],this.styles=new Map,this.currentStyle=null,this.lists=new Map,this.currentList=null,this.listOverrides=new Map,this.currentOverride=null,this.revAuthors=[],this.currentFontEntry=null,this.rowDefs=[],this.pendingCellDef={},this.rowIsHeader=!1,this.body=new L("body"),this.notes=new X("rtffn"),this.headers={},this.footers={},this.comments=[],this.openCommentRanges=[],this.commentMeta={},this.annotationCounter=0,this.commentRangeIds=new Map,this.commentIds=new Set,this.page={margins:{}},this.sectionSeen=!1,this.stack=[],this.marksVersion=0,this.cachedMarksVersion=-1,this.cachedMarks={},this.pendingBytes=[],this.pendingBytesEncoding="",this.chainsSeen=new Set,this.ansiEncoding=ht(t.slice(0,4096)),this.cocoa=/\\cocoartf/.test(t.slice(0,512)),this.state={dest:"body",chars:{},para:{borders:{}},unicodeSkip:1,storyRef:{story:this.body}}}read(){this.tokenize(),this.flushBytes();const t=this.body;this.flushRun(t),t.runs.some(i=>i.text.trim().length>0)&&this.flushParagraph(t);const e=this.buildBlocks(t.items,"body");V(e),e.length===0&&e.push(P());const s={type:"doc",children:e};this.notes.notes.length>0&&(s.notes=this.notes.notes),Object.keys(this.headers).length>0&&(s.headers=this.headers),Object.keys(this.footers).length>0&&(s.footers=this.footers);const r=Z(this.comments,[s.children,s.notes??[]]);r.length>0&&(s.comments=r);const n=this.pageLayout();return n&&(s.pageLayout=n),s}tokenize(){const t=this.rtf,e=t.length,s=/\\([a-zA-Z]{1,32})(-?\d{1,10})? ?/y;let r=0;for(;r<e;){const n=t.charCodeAt(r);if(n===123){this.flushBytes(),this.pushGroup(),r++;continue}if(n===125){this.flushBytes(),this.popGroup(),r++;continue}if(n===10||n===13){r++;continue}if(n!==92){let l=r+1;for(;l<e;){const f=t.charCodeAt(l);if(f===92||f===123||f===125||f===10||f===13)break;l++}this.literal(t.slice(r,l)),r=l;continue}const i=t[r+1];if(i===void 0)break;if(i==="\\"||i==="{"||i==="}"){this.flushBytes(),this.text(i),r+=2;continue}if(i==="'"){const l=parseInt(t.slice(r+2,r+4),16);r+=4,Number.isNaN(l)||this.byte(l);continue}if(this.flushBytes(),i==="*"){this.state.starred=!0,r+=2;continue}if(i==="~"){this.text(" "),r+=2;continue}if(i==="_"){this.text("‑"),r+=2;continue}if(i==="-"){r+=2;continue}if(i===`
2
+ `||i==="\r"){this.controlWord("par",null),r+=2;continue}s.lastIndex=r;const o=s.exec(t);if(!o){r+=2;continue}r+=o[0].length;const c=o[1],d=o[2]!==void 0?parseInt(o[2],10):null;if(c==="bin"&&d!==null&&d>0){this.binary(t.slice(r,r+d)),r+=d;continue}if(c==="u"&&d!==null){this.text(String.fromCharCode(d<0?d+65536:d));let l=this.state.unicodeSkip;for(;l>0&&r<e;){const f=t[r];if(f==="\\")if(t[r+1]==="'")r+=4;else{s.lastIndex=r;const m=s.exec(t);r+=m?m[0].length:2}else{if(f==="{"||f==="}")break;if(f===`
3
+ `||f==="\r"){r+=1;continue}else r+=1}l--}continue}this.controlWord(c,d)}}pushGroup(){const t=this.state;this.stack.push(t),this.state={dest:t.dest,chars:{...t.chars},para:{...t.para,borders:{...t.para.borders}},unicodeSkip:t.unicodeSkip,storyRef:t.storyRef,field:t.field,link:t.link,fieldKind:t.fieldKind,capture:void 0,metaKind:t.dest==="meta"?t.metaKind:void 0},(t.dest==="listtext"||t.dest==="fldinst"||t.dest==="meta")&&(this.state.capture=t.capture),this.marksVersion++}popGroup(){const t=this.state,e=this.stack.pop();e&&(this.endGroup(t,e),this.state=e,this.marksVersion++)}endGroup(t,e){switch(t.dest){case"pict":t.pict&&t.pict!==e.pict&&this.finishPicture(t.pict,t);break;case"fonttbl":t.capture&&t.capture!==e.capture&&this.finishFontName(t.capture.text);break;case"stylesheet":t.capture&&t.capture!==e.capture&&this.finishStyle(t.capture.text);break;case"listtext":e.dest!=="listtext"&&t.capture&&(t.storyRef.story.listText=t.capture.text);break;case"fldinst":e.dest!=="fldinst"&&t.capture&&t.field&&(t.field.instr=t.capture.text);break;case"meta":e.dest!=="meta"&&t.capture&&t.metaKind&&this.finishMeta(t.metaKind,t.capture.text.trim());break;case"revtbl":if(t.capture&&t.capture!==e.capture)for(const s of t.capture.text.split(";").slice(0,-1))this.revAuthors.push(s.trim());break}t.opensStory&&this.finishStory(t,e)}literal(t){const e=this.state;if(this.flushBytes(),e.dest==="pict"){e.pict?.hex.push(t);return}if(this.options.binary){let s=0;for(let r=0;r<t.length;r++)t.charCodeAt(r)>=128&&(r>s&&(this.flushBytes(),this.text(t.slice(s,r))),this.byte(t.charCodeAt(r)&255),s=r+1);s<t.length&&(this.flushBytes(),this.text(t.slice(s)));return}this.text(t)}byte(t){const e=this.currentEncoding();this.pendingBytes.length>0&&e!==this.pendingBytesEncoding&&this.flushBytes(),this.pendingBytesEncoding=e,this.pendingBytes.push(t)}flushBytes(){if(this.pendingBytes.length===0)return;const t=this.pendingBytes;this.pendingBytes=[],this.text(ut(t,this.pendingBytesEncoding))}currentEncoding(){const t=this.state.chars;return this.fonts.get(t.font??t.lochFont??this.defaultFont)?.encoding??this.ansiEncoding}binary(t){const e=this.state.pict;if(this.state.dest!=="pict"||!e)return;const s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r)&255;(e.binary??(e.binary=[])).push(s)}text(t){if(!t)return;const e=this.state;switch(e.dest){case"body":{const s=e.storyRef.story,r=this.effectiveMarks();J(r,s.runMarks)||(this.flushRun(s),s.runMarks=r),s.runText+=t,s.suppressEmptyPar=!1;return}case"fonttbl":case"stylesheet":case"listtext":case"fldinst":case"meta":e.capture&&(e.capture.text+=t),e.dest==="fonttbl"&&t.includes(";")&&this.fontTableSemicolons(t);return;case"colortbl":for(const s of t)s===";"&&(this.colors.push(this.colorHasValue?$(this.colorParts.r,this.colorParts.g,this.colorParts.b):void 0),this.colorParts={r:0,g:0,b:0},this.colorHasValue=!1);return;case"expandedcolortbl":for(const s of t){if(s!==";")continue;const r=this.expandedParts,n=i=>i/1e5*255;if(r.length>=3)this.colors[this.expandedIndex]=$(n(r[0]),n(r[1]),n(r[2]));else if(r.length===1){const i=n(r[0]);this.colors[this.expandedIndex]=$(i,i,i)}this.expandedParts=[],this.expandedIndex++}return;case"revtbl":e.capture?e.capture.text+=t:e.capture={text:t};return;default:return}}fontTableSemicolons(t){const e=this.state.capture;if(!e)return;const s=e.text.split(";");for(let r=0;r<s.length-1;r++)this.finishFontName(s[r]);e.text=s[s.length-1]}effectiveMarks(){if(this.cachedMarksVersion===this.marksVersion)return this.cachedMarks;const t=this.state,e=t.chars,s={};e.bold&&(s.bold=!0),e.italic&&(s.italic=!0),e.underline&&(s.underline=!0),e.strike&&(s.strikethrough=!0),e.dstrike&&(s.doubleStrikethrough=!0),e.superscript?s.superscript=!0:e.subscript&&(s.subscript=!0),e.caps&&(s.allCaps=!0),e.scaps&&(s.smallCaps=!0),e.hidden&&(s.hidden=!0);const r=this.fonts.get(e.font??e.lochFont??this.defaultFont)?.name;r&&(s.fontFamily=r),e.halfPoints&&e.halfPoints>0&&(s.fontSize=T(e.halfPoints/2*(96/72)));const n=e.color?this.colors[e.color]:void 0;n&&n!=="#000000"&&(s.color=n);const i=(e.highlight?this.colors[e.highlight]:void 0)??(e.background?this.colors[e.background]:void 0);return i&&i!=="#ffffff"&&(s.backgroundColor=i),e.expandTwips&&(s.letterSpacing=T(k(e.expandTwips))),t.link&&(s.link=t.link),t.fieldKind&&(s.field=t.fieldKind),this.openCommentRanges.length>0&&t.storyRef.story.kind!=="annotation"&&(s.comment=this.openCommentRanges.join(",")),e.deleted?Object.assign(s,this.revisionMarks("deletion",e.revAuthorDel??e.revAuthor,e.revTimeDel??e.revTime)):e.revised&&Object.assign(s,this.revisionMarks("insertion",e.revAuthor,e.revTime)),this.cachedMarks=s,this.cachedMarksVersion=this.marksVersion,s}revisionMarks(t,e,s){const r=e!==void 0?this.revAuthors[e]:void 0,n=s!==void 0?H(s):void 0;return Q(t,`rtfrev-${t==="insertion"?"ins":"del"}-${e??0}-${s??0}`,r&&r!=="Unknown"?r:void 0,n)}flushRun(t){t.runText&&(t.runs.push({type:"text",text:t.runText,marks:{...t.runMarks}}),t.runText="")}flushParagraph(t,e=!1){this.flushRun(t);const s=t.runs.filter(r=>r.text.length>0);if(t.runs=[],s.length===0&&t.suppressEmptyPar&&!e){t.suppressEmptyPar=!1,t.listText=void 0,t.paraId=w();return}t.items.push({kind:"para",id:t.paraId,runs:tt(s),para:{...this.state.para,borders:{...this.state.para.borders}},...t.listText!==void 0?{listText:t.listText}:{},...e?{forcedInTable:!0}:{}}),t.listText=void 0,t.suppressEmptyPar=!1,t.paraId=w()}controlWord(t,e){const s=this.state,r=s.starred;if(s.starred=!1,s.dest!=="skip"&&!this.startDestination(t)){if(r&&!gt.has(t)){s.dest="skip";return}if(ft.has(t)){s.dest="skip";return}switch(s.dest){case"fonttbl":this.fontTableWord(t,e);return;case"colortbl":this.colorTableWord(t,e);return;case"expandedcolortbl":t==="c"&&e!==null?this.expandedParts.push(e):(t==="cssrgb"||t==="csgray"||t==="csgenericrgb")&&(this.expandedParts=[]);return;case"stylesheet":this.styleSheetWord(t,e);return;case"listtable":this.listTableWord(t,e);return;case"listoverridetable":this.listOverrideWord(t,e);return;case"pict":this.pictWord(t,e);return;case"pn":this.pnWord(t,e);return;case"listtext":case"fldinst":case"meta":t==="tab"&&this.text(" ");return;case"revtbl":return}if(this.characterWord(t,e)){this.marksVersion++;return}this.paragraphWord(t,e)||this.structureWord(t,e)}}startDestination(t){const e=this.state;if(e.dest!=="body"&&mt.has(t))return e.dest="skip",!0;switch(t){case"fonttbl":return e.dest="fonttbl",e.capture={text:""},!0;case"colortbl":return e.dest="colortbl",this.colors=[],!0;case"expandedcolortbl":return e.dest="expandedcolortbl",this.expandedIndex=0,this.expandedParts=[],!0;case"stylesheet":return e.dest="stylesheet",!0;case"listtable":return e.dest="listtable",!0;case"listoverridetable":return e.dest="listoverridetable",!0;case"revtbl":return e.dest="revtbl",!0;case"pict":return e.dest="pict",e.pict={hex:[]},!0;case"shppict":case"shprslt":case"result":case"shp":case"object":case"field":return t==="field"&&(e.field={instr:""}),!0;case"fldinst":return e.dest="fldinst",e.capture={text:""},!0;case"fldrslt":{const s=e.field?.instr??"",r=/^\s*HYPERLINK\s+(?:\\[a-z]\s+)*"([^"]+)"/i.exec(s);return r&&!/^\s*HYPERLINK\s+\\l\b/i.test(s)&&(e.link=et(r[1])),/^\s*PAGE\b/i.test(s)&&(e.fieldKind="page"),/^\s*NUMPAGES\b/i.test(s)&&(e.fieldKind="numPages"),this.marksVersion++,!0}case"listtext":case"pntext":return e.dest="listtext",e.capture={text:""},!0;case"pn":return e.dest="pn",e.para.pn={kind:"number",level:0},!0;case"footnote":return this.openStory("footnote");case"annotation":return this.openStory("annotation");case"atnauthor":case"atnid":case"atnref":case"atndate":case"atrfstart":case"atrfend":return e.dest="meta",e.metaKind=t,e.capture={text:""},!0;default:return E.has(t)?(e.dest="body",e.opensStory=!0,e.storyRef={story:new L("header")},e.para={borders:{}},e.headerWord=t,!0):!1}}openStory(t){const e=this.state;return e.dest="body",e.opensStory=!0,e.storyRef={story:new L(t)},e.para={borders:{}},e.link=void 0,t==="annotation"&&(this.annotationRef=void 0,this.annotationDate=void 0),this.marksVersion++,!0}finishStory(t,e){const s=t.storyRef.story;if(this.flushRun(s),s.runs.some(i=>i.text.length>0)){const i=this.state;this.state=t,this.flushParagraph(s),this.state=i}const r=this.buildBlocks(s.items,s.kind);V(r);const n=e.storyRef.story;if(s.kind==="footnote"||s.kind==="endnote"){if(e.dest!=="body")return;this.flushRun(n),this.state=e,this.marksVersion++;const i=this.effectiveMarks(),o=this.notes.add(s.kind,r,i);n.runs.push(o),n.runMarks={},this.marksVersion++;return}if(s.kind==="header"){const i=t.headerWord??"header",o=E.get(i)??"default",c=r.filter(d=>d.type==="paragraph");if(c.some(d=>d.children.some(l=>l.text.trim()!==""||l.marks?.field))){const d=i.startsWith("footer")?this.footers:this.headers;d[o]=c}return}if(s.kind==="annotation"){const i=r.map(l=>l.type==="paragraph"?l.children.map(f=>f.text).join("").trim():"").filter(l=>l.length>0).join(`
4
+
5
+ `);this.annotationCounter++;const o=this.annotationRef;let c=`rtfcmt-${o??`point-${this.annotationCounter}`}`,d=o!==void 0&&this.commentRangeIds.has(o);if(this.commentIds.has(c)){d=!1;let l=this.annotationCounter;for(;this.commentIds.has(`${c}-${l}`);)l++;c=`${c}-${l}`}this.commentIds.add(c),this.comments.push({id:c,author:this.commentMeta.author||this.commentMeta.initials||"Unknown",...this.commentMeta.initials?{initials:this.commentMeta.initials}:{},createdAt:new Date(this.annotationDate!==void 0?H(this.annotationDate)??0:0).toISOString(),bodyMd:i,...d?{}:{anchorBlockId:n.paraId}}),this.commentMeta={}}}finishMeta(t,e){switch(t){case"atnauthor":this.commentMeta.author=e;break;case"atnid":this.commentMeta.initials=e;break;case"atnref":this.annotationRef=e;break;case"atndate":{const s=parseInt(e,10);Number.isFinite(s)&&(this.annotationDate=s);break}case"atrfstart":e&&(this.commentRangeIds.set(e,`rtfcmt-${e}`),this.openCommentRanges=[...this.openCommentRanges,`rtfcmt-${e}`],this.marksVersion++);break;case"atrfend":e&&(this.openCommentRanges=this.openCommentRanges.filter(s=>s!==`rtfcmt-${e}`),this.marksVersion++);break}}fontTableWord(t,e){if(t==="f"&&e!==null){const r=this.state.capture;r&&r.text.trim()&&this.currentFontEntry!==null&&this.finishFontName(r.text),this.currentFontEntry=e,this.fonts.has(e)||this.fonts.set(e,{name:""}),this.state.capture={text:""};return}const s=this.currentFontEntry!==null?this.fonts.get(this.currentFontEntry):void 0;if(s)if(t==="fcharset"&&e!==null){const r=dt[e];r&&(s.encoding=C(r)),e===2&&(s.encoding="windows-1252")}else t==="cpg"&&e!==null&&e>0&&(s.encoding=C(e))}finishFontName(t){if(this.currentFontEntry===null)return;const e=this.fonts.get(this.currentFontEntry),s=t.replace(/;$/,"").trim();e&&s&&!e.name&&(e.name=this.cocoa?St(s):s)}colorTableWord(t,e){if(e!==null){if(t==="red")this.colorParts.r=e;else if(t==="green")this.colorParts.g=e;else if(t==="blue")this.colorParts.b=e;else return;this.colorHasValue=!0}}styleSheetWord(t,e){const s=this.state;t==="s"&&e!==null?(this.currentStyle={index:e},s.capture={text:""}):t==="outlinelevel"&&e!==null&&this.currentStyle&&(this.currentStyle.outlineLevel=e)}finishStyle(t){if(!this.currentStyle)return;const e=t.replace(/;[\s\S]*$/,"").trim();this.styles.set(this.currentStyle.index,{name:e,outlineLevel:this.currentStyle.outlineLevel}),this.currentStyle=null}listTableWord(t,e){switch(t){case"list":this.currentList={def:{levels:[]}};break;case"listlevel":this.currentList?.def.levels.push({nfc:0,startAt:1});break;case"levelnfc":case"levelnfcn":{const s=this.currentList?.def.levels.at(-1);s&&e!==null&&(s.nfc=e);break}case"levelstartat":{const s=this.currentList?.def.levels.at(-1);s&&e!==null&&(s.startAt=e);break}case"listid":this.currentList&&e!==null&&(this.currentList.id=e,this.lists.set(e,this.currentList.def));break}}listOverrideWord(t,e){t==="listoverride"?this.currentOverride={}:t==="listid"&&this.currentOverride&&e!==null?this.currentOverride.listId=e:t==="ls"&&this.currentOverride&&e!==null&&(this.currentOverride.ls=e);const s=this.currentOverride;s?.listId!==void 0&&s.ls!==void 0&&this.listOverrides.set(s.ls,s.listId)}pnWord(t,e){const s=this.state.para.pn;if(!s)return;t==="pnlvlblt"?s.kind="bullet":/^pn(dec|ucltr|lcltr|ucrm|lcrm|ord|ordt|cardt)$/.test(t)?s.kind="number":t==="pnlvl"&&e!==null&&(s.level=Math.max(0,e-1));const r=this.stack[this.stack.length-1];r&&(r.para.pn={...s})}pictWord(t,e){const s=this.state.pict;if(s)switch(t){case"pngblip":s.format="png";break;case"jpegblip":s.format="jpeg";break;case"emfblip":s.format="emf";break;case"wmetafile":s.format="wmf";break;case"macpict":case"dibitmap":case"wbitmap":case"pmmetafile":s.format??(s.format="unsupported");break;case"picw":e!==null&&(s.picw=e);break;case"pich":e!==null&&(s.pich=e);break;case"picwgoal":e!==null&&(s.goalW=e);break;case"pichgoal":e!==null&&(s.goalH=e);break;case"picscalex":e!==null&&(s.scaleX=e);break;case"picscaley":e!==null&&(s.scaleY=e);break}}finishPicture(t,e){let s;if(t.binary&&t.binary.length>0){const b=t.binary.reduce((u,p)=>u+p.length,0);s=new Uint8Array(b);let h=0;for(const u of t.binary)s.set(u,h),h+=u.length}else s=vt(t.hex.join(""));if(s.length===0)return;const r=t.format&&t.format!=="unsupported"?t.format:void 0,n=st(s)??r;if(!n)return;const i=n==="emf"||n==="wmf",o=(t.scaleX??100)/100,c=(t.scaleY??100)/100,d=(b,h)=>b?k(b):h?i?h/2540*96:h:void 0,l=d(t.goalW,t.picw),f=d(t.goalH,t.pich),m=e.storyRef.story,M=e.para;if(this.flushRun(m),m.runs.some(b=>b.text.length>0)){const b=this.state;this.state=e,this.flushParagraph(m),this.state=b}else m.runs=[];const A=M.align==="justify"?void 0:M.align;m.items.push({kind:"image",image:rt(s,n,{width:l!==void 0?l*o:void 0,height:f!==void 0?f*c:void 0},{align:A}),inTable:!!M.inTable}),m.suppressEmptyPar=!0}characterWord(t,e){const s=this.state.chars,r=e!==0;if(bt.has(t))return s.underline=r,!0;switch(t){case"plain":{const{revised:n,deleted:i,revAuthor:o,revTime:c,revAuthorDel:d,revTimeDel:l}=s;return this.state.chars={revised:n,deleted:i,revAuthor:o,revTime:c,revAuthorDel:d,revTimeDel:l},!0}case"b":return s.bold=r,!0;case"i":return s.italic=r,!0;case"ulnone":return s.underline=!1,!0;case"strike":return s.strike=r,!0;case"striked":return s.dstrike=r,!0;case"super":return s.superscript=r,s.subscript=!1,!0;case"sub":return s.subscript=r,s.superscript=!1,!0;case"nosupersub":return s.superscript=!1,s.subscript=!1,!0;case"caps":return s.caps=r,!0;case"scaps":return s.scaps=r,!0;case"v":return s.hidden=r,!0;case"f":return e!==null&&(s.font=e),!0;case"loch":case"hich":case"dbch":return s.script=t,!0;case"rtlch":case"ltrch":return s.script=void 0,!0;case"af":return e!==null&&(s.script==="loch"||s.script==="hich")&&(s.lochFont=e),!0;case"fs":return e!==null&&(s.halfPoints=e),!0;case"fsmilli":return e!==null&&(s.halfPoints=e/1e3*2),!0;case"cf":return s.color=e??0,!0;case"highlight":return s.highlight=e??0,!0;case"cb":case"chcbpat":return s.background=e??0,!0;case"expndtw":return s.expandTwips=e??0,!0;case"expnd":return s.expandTwips===void 0&&e!==null&&(s.expandTwips=e*5),!0;case"revised":return s.revised=r,!0;case"deleted":return s.deleted=r,!0;case"revauth":return e!==null&&(s.revAuthor=e),!0;case"revdttm":return e!==null&&(s.revTime=e),!0;case"revauthdel":return e!==null&&(s.revAuthorDel=e),!0;case"revdttmdel":return e!==null&&(s.revTimeDel=e),!0;default:return!1}}paragraphWord(t,e){const s=this.state.para;switch(t){case"pard":return this.state.para={borders:{}},!0;case"qc":return s.align="center",!0;case"qr":return s.align="right",!0;case"qj":case"qd":return s.align="justify",!0;case"ql":return s.align=void 0,!0;case"li":case"lin":return e!==null&&(s.leftTwips=e),!0;case"fi":return e!==null&&(s.firstTwips=e),!0;case"sb":return e!==null&&(s.spaceBeforeTwips=e),!0;case"sa":return e!==null&&(s.spaceAfterTwips=e),!0;case"sl":return s.lineTwips=e??0,!0;case"slmult":return s.lineMultiple=e===1,!0;case"keepn":return s.keepNext=e!==0,!0;case"keep":return s.keepLines=e!==0,!0;case"rtlpar":return s.rtl=!0,!0;case"ltrpar":return s.rtl=!1,!0;case"s":return e!==null&&(s.style=e),!0;case"outlinelevel":return e!==null&&(s.outlineLevel=e),!0;case"intbl":return s.inTable=e!==0,!0;case"itap":return e!==null&&(s.inTable=e>0),!0;case"ls":return e!==null&&(s.ls=e),!0;case"ilvl":return e!==null&&(s.ilvl=e),!0;case"cbpat":return e!==null&&(s.shading=e),!0;case"pagebb":return s.pageBreakBefore=e!==0,!0;case"brdrt":case"brdrb":case"brdrl":case"brdrr":case"box":{const r=t==="box"?["top","bottom","left","right"]:[{brdrt:"top",brdrb:"bottom",brdrl:"left",brdrr:"right"}[t]];for(const n of r)s.borders[n]={style:"single",width:1,color:"#000000"};return s.borderTarget=t==="box"?"box":r[0],!0}case"brdrs":case"brdrth":case"brdrsh":case"brdrdb":case"brdrdash":case"brdrdashsm":case"brdrdot":case"brdrnone":case"brdrw":case"brdrcf":{const r=s.borderTarget;if(!r||r==="ignore")return!0;const n=r==="box"?["top","bottom","left","right"]:[r];for(const i of n){const o=s.borders[i];o&&(t==="brdrnone"?delete s.borders[i]:t==="brdrdb"?o.style="double":t==="brdrdash"||t==="brdrdashsm"?o.style="dashed":t==="brdrdot"?o.style="dotted":t==="brdrth"?(o.style="single",o.width=Math.max(o.width,2)):t==="brdrw"&&e!==null?o.width=Math.min(8,Math.max(1,Math.round(e/15))):t==="brdrcf"&&e!==null?o.color=this.colors[e]??o.color:(t==="brdrs"||t==="brdrsh")&&(o.style="single"))}return!0}default:return/^(tr|cl|pg)brdr[tblrhv]$|^brdrbtw$|^brdrbar$/.test(t)?(s.borderTarget="ignore",!(t.startsWith("cl")||t.startsWith("tr"))):!1}}structureWord(t,e){const s=this.state.storyRef.story,r=this.state.dest==="body";switch(t){case"par":r&&this.flushParagraph(s);return;case"sect":r&&(s.runs.length>0||s.runText)&&this.flushParagraph(s),this.sectionSeen=!0;return;case"line":this.text(`
6
+ `);return;case"tab":this.text(" ");return;case"page":if(!r||s.kind!=="body")return;this.flushRun(s),s.runs.some(n=>n.text.length>0)&&this.flushParagraph(s),s.runs=[],s.items.push({kind:"pagebreak",inTable:!!this.state.para.inTable}),s.suppressEmptyPar=!0;return;case"cell":case"nestcell":if(!r)return;this.flushParagraph(s,!0),t==="cell"&&s.items.push({kind:"cell"});return;case"row":if(!r)return;this.flushRun(s),s.runs.some(n=>n.text.length>0)&&(this.flushParagraph(s,!0),s.items.push({kind:"cell"})),s.runs=[],s.items.push({kind:"row",defs:this.rowDefs.slice(),header:this.rowIsHeader});return;case"trowd":this.rowDefs=[],this.pendingCellDef={},this.rowIsHeader=!1;return;case"trhdr":this.rowIsHeader=!0;return;case"clmgf":this.pendingCellDef.hmergeFirst=!0;return;case"clmrg":this.pendingCellDef.hmergeCont=!0;return;case"clvmgf":this.pendingCellDef.vmergeFirst=!0;return;case"clvmrg":this.pendingCellDef.vmergeCont=!0;return;case"clcbpat":e!==null&&(this.pendingCellDef.background=e);return;case"clvertalt":this.pendingCellDef.valign="top";return;case"clvertalc":this.pendingCellDef.valign="middle";return;case"clvertalb":this.pendingCellDef.valign="bottom";return;case"cellx":e!==null&&(this.rowDefs.push({right:e,...this.pendingCellDef}),this.pendingCellDef={});return;case"chftn":case"chatn":case"chpgn":t==="chpgn"&&r&&s.kind==="header"&&(this.state.fieldKind="page",this.marksVersion++,this.text("1"),this.state.fieldKind=void 0,this.marksVersion++);return;case"ftnalt":s.kind==="footnote"&&(s.kind="endnote");return;case"uc":this.state.unicodeSkip=e??1;return;case"deff":e!==null&&(this.defaultFont=e);return;case"paperw":case"pgwsxn":e!==null&&(!this.sectionSeen||this.page.widthTwips===void 0)&&(this.page.widthTwips=e);return;case"paperh":case"pghsxn":e!==null&&(!this.sectionSeen||this.page.heightTwips===void 0)&&(this.page.heightTwips=e);return;case"landscape":case"lndscpsxn":this.page.landscape=!0;return;case"margl":case"margr":case"margt":case"margb":case"marglsxn":case"margrsxn":case"margtsxn":case"margbsxn":{if(e===null)return;const n=t.slice(4,5);if(t.endsWith("sxn")&&this.sectionSeen)return;this.page.margins[n]=e;return}default:{const n=pt.get(t);n!==void 0&&this.text(n)}}}buildBlocks(t,e){const s=[],r=i=>i.kind==="cell"||i.kind==="row"||i.kind==="para"&&(!!i.para.inTable||!!i.forcedInTable)||(i.kind==="image"||i.kind==="pagebreak")&&i.inTable;let n=0;for(;n<t.length;){const i=t[n];if(e!=="header"&&r(i)){const o=n;for(;n<t.length&&r(t[n]);)n++;const c=this.buildTable(t.slice(o,n),e);c&&s.push(...c);continue}if(i.kind==="para"){const o=this.listInfo(i);if(o&&e!=="header"){const c=[{item:i,info:o}];for(n++;n<t.length;){const d=t[n];if(d.kind!=="para"||r(d))break;const l=this.listInfo(d);if(!l||l.key!==o.key)break;c.push({item:d,info:l}),n++}s.push(this.buildList(c));continue}i.para.pageBreakBefore&&e==="body"&&s.length>0&&s.push({type:"page-break",id:w()}),s.push(this.buildParagraph(i,e)),n++;continue}i.kind==="image"?s.push(i.image):i.kind==="pagebreak"&&s.push({type:"page-break",id:w()}),n++}return s}buildParagraph(t,e){const s=t.runs.length>0?t.runs:[{type:"text",text:"",marks:{}}],r=P(s);r.id=t.id;const n=t.para;if(n.align&&(r.align=n.align),n.rtl&&(r.direction="rtl"),e!=="header"){const i=this.headingLevel(n);if(i&&(r.heading=i),n.leftTwips!==void 0){const c=nt(k(n.leftTwips));c&&(r.leftIndent=c)}if(n.firstTwips!==void 0){const c=it(k(n.firstTwips));c&&(r.firstLineIndent=c)}n.spaceBeforeTwips!==void 0&&(r.spaceBefore=T(k(Math.max(0,n.spaceBeforeTwips)))),n.spaceAfterTwips!==void 0&&(r.spaceAfter=T(k(Math.max(0,n.spaceAfterTwips)))),n.lineMultiple&&n.lineTwips&&n.lineTwips>0&&(r.lineSpacing=T(n.lineTwips/240)),n.keepNext&&(r.keepNext=!0),n.keepLines&&(r.keepLines=!0);const o=n.shading?this.colors[n.shading]:void 0;o&&o!=="#ffffff"&&(r.shading=o),Object.keys(n.borders).length>0&&(r.borders=JSON.stringify(n.borders))}return r}headingLevel(t){let e;if(t.outlineLevel!==void 0&&t.outlineLevel<9&&(e=t.outlineLevel+1),e===void 0&&t.style!==void 0){const s=this.styles.get(t.style),r=s?.name&&/^heading\s*(\d)$/i.exec(s.name);r?e=parseInt(r[1],10):s?.outlineLevel!==void 0&&s.outlineLevel<9&&(e=s.outlineLevel+1)}if(!(!e||e<1))return Math.min(e,6)}listInfo(t){const e=t.para;if(!this.headingLevel(e)){if(e.ls!==void 0&&e.ls>0){const s=this.listOverrides.get(e.ls),r=s!==void 0?this.lists.get(s):void 0,n=Math.max(0,Math.min(8,e.ilvl??0));if(r){const i=r.levels[n]??r.levels[0];if(i&&i.nfc===255&&t.listText===void 0)return;const o=i?i.nfc!==23&&i.nfc!==255:!1;return{key:`ls${e.ls}`,ordered:o,level:n,startAt:r.levels[0]?.startAt??1,chain:`rtf-ls-${e.ls}`}}return{key:`ls${e.ls}`,ordered:t.listText!==void 0&&O(t.listText),level:n,startAt:1,chain:`rtf-ls-${e.ls}`}}if(e.pn)return{key:`pn-${e.pn.kind}`,ordered:e.pn.kind==="number",level:e.pn.level,startAt:1};if(t.listText!==void 0&&t.listText.trim()!==""){const s=O(t.listText);return{key:`lt-${s}`,ordered:s,level:0,startAt:1}}}}buildList(t){const e=t[0].info,s=t.map(({item:i,info:o})=>{const c=i.runs.length>0?i.runs:[{type:"text",text:"",marks:{}}];return{type:"list-item",id:i.id,children:c,...o.level>0?{indentLevel:o.level}:{},...i.para.rtl?{direction:"rtl"}:{}}}),r={type:"list",id:w(),variant:e.ordered?"ordered":"unordered",children:s};e.ordered&&e.chain?(r.numberingChainId=e.chain,this.chainsSeen.has(e.chain)||(this.chainsSeen.add(e.chain),e.startAt!==1&&(r.startNumber=e.startAt))):e.ordered&&e.startAt!==1&&(r.startNumber=e.startAt);const n=t[0].item.para;return n.spaceAfterTwips!==void 0&&(r.spaceAfter=T(k(Math.max(0,n.spaceAfterTwips)))),n.spaceBeforeTwips!==void 0&&(r.spaceBefore=T(k(Math.max(0,n.spaceBeforeTwips)))),n.lineMultiple&&n.lineTwips&&n.lineTwips>0&&(r.lineSpacing=T(n.lineTwips/240)),r}buildTable(t,e){const s=[];let r=[],n=[],i=[];for(const h of t)h.kind==="cell"?(r.push({items:n}),n=[]):h.kind==="row"?(n.length>0&&(r.push({items:n}),n=[]),s.push({cells:r,defs:h.defs.length>0?h.defs:i,header:h.header}),h.defs.length>0&&(i=h.defs),r=[]):n.push(h);if(n.length>0&&r.push({items:n}),r.length>0&&s.push({cells:r,defs:i,header:!1}),s.length===0)return null;const o=new Set([0]),c=s.map(h=>{const u=[];let p=0,g=0;const I=h.defs.length>0?h.defs[h.defs.length-1].right/Math.max(1,h.defs.length):1440;return h.cells.forEach((R,S)=>{const x=h.defs[S],v=x?x.right:g+Math.max(1,Math.round(I));if(x?.hmergeCont&&u.length>0){const N=u[u.length-1];N.right=v,N.items.push(...R.items.filter(q=>!wt(q)))}else u.push({left:p,right:Math.max(v,p+1),def:x,items:R.items});p=v,g=v}),u}),d=0;for(const h of c)for(const u of h)o.add(Math.max(d,u.left)),o.add(u.right);const l=xt(yt([...o].sort((h,u)=>h-u),30),at(c.length)),f=h=>{let u=0,p=l.length-1;for(;u<p;){const g=u+p>>1;l[g]<h?u=g+1:p=g}return u>0&&Math.abs(l[u-1]-h)<=Math.abs(l[u]-h)?u-1:u},m=[],M=new Map;c.forEach(h=>{const u=[];for(const p of h){const g=f(p.left),I=Math.max(g+1,f(p.right));if(p.def?.vmergeCont){const v=M.get(g);if(v){v.rowSpan=(v.rowSpan??1)+1;continue}}const R=this.buildBlocks(p.items.map(v=>Tt(v)),e);Mt(R);const S={type:"table-cell",id:w(),children:R.length>0?R:[P()]};I-g>1&&(S.colSpan=I-g);const x=p.def?.background?this.colors[p.def.background]:void 0;x&&x!=="#ffffff"&&(S.backgroundColor=x),p.def?.valign&&p.def.valign!=="top"&&(S.verticalAlign=p.def.valign),p.def?.vmergeFirst?M.set(g,S):M.delete(g),u.push(S)}m.push({type:"table-row",id:w(),children:u})});const A=[];for(let h=1;h<l.length;h++)A.push(l[h]-l[h-1]);const b=ot(m,{columnWidths:A,hasHeader:s[0]?.header});return b?[b]:null}pageLayout(){const t=this.page,e=s=>t.margins[s]!==void 0?k(t.margins[s]):void 0;return lt({widthPx:t.widthTwips?k(t.widthTwips):void 0,heightPx:t.heightTwips?k(t.heightTwips):void 0,landscape:t.landscape,marginTopPx:e("t"),marginRightPx:e("r"),marginBottomPx:e("b"),marginLeftPx:e("l")})}}function O(a){const t=a.replace(/[\t\s]+/g,"");return/^(\d+|[a-zA-Z]|[ivxlcdm]+|[IVXLCDM]+)[.)]?$/.test(t)&&t.length>0}function vt(a){const t=a.replace(/[^0-9a-fA-F]/g,""),e=new Uint8Array(t.length>>1);for(let s=0;s<e.length;s++)e[s]=parseInt(t.slice(s*2,s*2+2),16);return e}function yt(a,t){const e=[];for(const s of a)(e.length===0||s-e[e.length-1]>t)&&e.push(s);return e}function xt(a,t){if(a.length-1<=t)return a;const e=a.length-1,s=[];for(let r=0;r<=t;r++)s.push(a[Math.round(r*e/t)]);return s}function wt(a){return a.kind==="para"&&a.runs.every(t=>t.text.trim()==="")}function Tt(a){return a.kind==="para"?{...a,forcedInTable:!1,para:{...a.para,inTable:!1}}:a.kind==="image"||a.kind==="pagebreak"?{...a,inTable:!1}:a}function B(a){return a.type==="paragraph"&&!a.borders&&a.children.every(t=>t.text.trim()===""&&!t.marks?.footnoteRef)}function V(a){for(;a.length>0&&B(a[0]);)a.shift();for(;a.length>0&&B(a[a.length-1]);)a.pop()}function Mt(a){for(;a.length>1&&B(a[a.length-1]);)a.pop()}function H(a){const t=a>>>0;if(t===0)return;const e=t&63,s=t>>>6&31,r=t>>>11&31,n=t>>>16&15,i=(t>>>20&511)+1900;if(!(n<1||n>12||r<1))return Date.UTC(i,n-1,r,s,e)}function St(a){if(a.startsWith("."))return"";if(/\s/.test(a))return a;let t=a.replace(/-(Regular|Roman|Book|Bold|Italic|Oblique|BoldItalic|BoldOblique|Light|LightItalic|Medium|MediumItalic|Semibold|SemiBold|SemiboldItalic|Heavy|Black|Condensed|Thin|UltraLight)$/,"");return t=t.replace(/(PSMT|PS|MT)$/,""),t=t.replace(/([a-z])([A-Z])/g,"$1 $2"),t}const j=class{static async parseFile(t){const e=new Uint8Array(await t.arrayBuffer());let s="";const r=32768;for(let n=0;n<e.length;n+=r)s+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+r)));return F(s,{binary:!0})}static fromRtf(t){return F(t)}static toRtf(t){t=K(t),this.exportListNumbering=U(t);const e=[];for(const s of t.children){const r=this.blockToRtf(s,t);r!==null&&e.push(r)}return this.exportListNumbering=null,`{\\rtf1\\ansi\\ansicpg1252\\deff0\\uc1{\\fonttbl{\\f0\\froman Times New Roman;}{\\f1\\fmodern Courier New;}}
7
+ \\f0\\fs24
8
+ `+e.join(`
9
+ `)+`
10
+ }`}static blockToRtf(t,e){switch(t.type){case"paragraph":return z(t)?"\\pard\\brdrb\\brdrs\\brdrw15 \\par":this.paragraphToRtf(t);case"list":return this.listToRtf(t);case"table":return this.tableToRtf(t);case"code":return"\\pard{\\f1\\fs20 "+y(t.content).replace(/\n/g,"\\line ")+"}\\par";case"math":return"\\pard "+y(t.content)+"\\par";case"toc":{const s=G(e,t);return s.length===0?null:s.map(r=>`\\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"?"ri":"li"}${(r.level-1)*360} `+y(r.text)+"\\par").join(`
11
+ `)}case"image":return"\\pard{\\i [Image"+(t.alt?`: ${y(t.alt)}`:"")+"]}\\par";case"page-break":return"\\page";case"container":return t.children.map(s=>this.blockToRtf(s,e)).filter(s=>s!==null).join(`
12
+ `);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 s=this.inlineNodesToRtf(t.children);return t.heading&&(s=`{\\b\\fs${this.HEADING_HALF_POINTS[t.heading-1]} ${s}}`),`${e} ${s}\\par`}static listToRtf(t){const e=this.exportListNumbering?.get(t.id);let s=e?_(e):t.startNumber??1;const r=[];for(const n of t.children){if(n.type!=="list-item")continue;const i=((n.indentLevel??0)+1)*360;let o;t.variant==="ordered"?(o=`${s}. `,s++):t.variant==="todo"?o=n.checked?"[x] ":"[ ] ":o="\\bullet ",r.push(`\\pard\\li${i} ${o}`+this.inlineNodesToRtf(n.children)+"\\par")}return r.join(`
13
+ `)}static tableToRtf(t){if(!t.children||t.children.length===0)return"";const e=Y(t),s=9360,r=[];for(let n=0;n<e.rows;n++){const i=["\\trowd\\trgaph108"];for(let o=0;o<e.cols;o++)i.push(`\\cellx${Math.round(s*(o+1)/e.cols)}`);for(let o=0;o<e.cols;o++){const c=e.occupancy[n][o];let d="";c&&c.row===n&&c.col===o&&(d=c.cell.children.map(l=>l.type==="paragraph"?this.inlineNodesToRtf(l.children):l.type==="code"?y(l.content):"").filter(l=>l.length>0).join("\\line ")),i.push(`\\pard\\intbl ${d}\\cell`)}i.push("\\row"),r.push(i.join(""))}return r.join(`
14
+ `)+`
15
+ \\pard`}static inlineNodesToRtf(t){return t.map(e=>this.textNodeToRtf(e)).join("")}static textNodeToRtf(t){if(t.marks?.footnoteRef)return`{\\super ${y(t.text)}}`;const e=y(t.text).replace(/\n/g,"\\line ");if(!t.marks)return e;const s=[];t.marks.bold&&s.push("\\b"),t.marks.italic&&s.push("\\i"),t.marks.underline&&s.push("\\ul"),t.marks.strikethrough&&s.push("\\strike"),t.marks.superscript&&s.push("\\super"),t.marks.subscript&&s.push("\\sub"),t.marks.code&&s.push("\\f1");const r=s.length>0?`{${s.join("")} ${e}}`:e;return t.marks.link?`{\\field{\\*\\fldinst HYPERLINK "${y(t.marks.link)}"}{\\fldrslt ${r}}}`:r}};j.exportListNumbering=null,j.HEADING_HALF_POINTS=[32,28,26,24,22,22];let Rt=j;function y(a){let t="";for(let e=0;e<a.length;e++){const s=a[e];if(s==="\\"||s==="{"||s==="}"){t+="\\"+s;continue}const r=a.charCodeAt(e);if(r<128){t+=s;continue}t+=`\\u${r>32767?r-65536:r}?`}return t}export{Rt as RtfConverter,y as escapeRtfText};