@silurus/ooxml 0.75.5 → 0.76.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -28
- package/dist/bounded-raw-part-cache-C6ro6Ezf.js +254 -0
- package/dist/{find-cursor-Dc5iM6s7.js → canvas-viewer-mechanics-CwVSOYke.js} +192 -64
- package/dist/{document-pull-client-BcNYhoAG.js → document-pull-client-AAnwzlig.js} +3625 -3601
- package/dist/docx-CCksIXd5.js +1301 -0
- package/dist/docx.mjs +4 -6
- package/dist/docx_parser_bg.wasm +0 -0
- package/dist/index.mjs +3 -3
- package/dist/{line-distribute-B8sqT8kC.js → line-distribute-C1r2zvji.js} +141 -141
- package/dist/{line-metrics-D9gqQWHl.js → line-metrics-BdCACYlq.js} +4026 -1170
- package/dist/math.mjs +1 -1
- package/dist/node.mjs +779 -465
- package/dist/pptx-CKAk5e-J.js +1735 -0
- package/dist/pptx.mjs +5 -7
- package/dist/pptx_parser_bg.wasm +0 -0
- package/dist/{render-CalC7GX4.js → render-CLcpSi0m.js} +11 -18
- package/dist/render-worker-host-B8HAb_sK.js +27 -0
- package/dist/render-worker-host-Bkf1jUcW.js +27 -0
- package/dist/render-worker-host-CKOmXdyr.js +27 -0
- package/dist/resource-measurement-E_S_iau4.js +119 -0
- package/dist/session-B4Y54cbT.js +730 -0
- package/dist/{renderer-B9R6F_QY.js → slide-pull-client-WCuYCjio.js} +973 -820
- package/dist/types/docx.d.ts +1181 -3994
- package/dist/types/index.d.ts +2733 -8171
- package/dist/types/math.d.ts +8 -33
- package/dist/types/node.d.ts +1852 -4433
- package/dist/types/pptx.d.ts +1030 -3678
- package/dist/types/xlsx.d.ts +1291 -3262
- package/dist/worksheet-pull-client-YzjJMOns.js +455 -0
- package/dist/xlsx-BBmmZNQn.js +6362 -0
- package/dist/xlsx.mjs +5 -7
- package/dist/xlsx_parser_bg.wasm +0 -0
- package/package.json +14 -7
- package/dist/bounded-raw-part-cache-BTfZD_Sz.js +0 -1248
- package/dist/docx-DjF8FgoP.js +0 -1274
- package/dist/duotone-bitmap-by-path-CWsSJkJu.js +0 -28
- package/dist/hyperlink-D85FexTa.js +0 -27
- package/dist/pptx-C17xP8AV.js +0 -1705
- package/dist/pptx-Dl8tOSmP.js +0 -822
- package/dist/preload-BEouWnlI.js +0 -132
- package/dist/render-worker-host-BG3a7brz.js +0 -27
- package/dist/render-worker-host-CsB-dPJv.js +0 -27
- package/dist/render-worker-host-Cyv5Hkbh.js +0 -27
- package/dist/resource-measurement-6aReN3K0.js +0 -93
- package/dist/slide-pull-client-D_T0AIoX.js +0 -175
- package/dist/svg-image-by-path-C1M3N2pT.js +0 -1623
- package/dist/worksheet-pull-worker-DCei8u-4.js +0 -347
- package/dist/xlsx-BaH9irS0.js +0 -5515
- /package/dist/{highlight-rect-cCvVU-MW.js → highlight-rect-CAkCWJ37.js} +0 -0
- /package/dist/{mathjax-Dqo857oC.js → mathjax-CMjda8Ip.js} +0 -0
- /package/dist/{transfer-3QEJrsJa.js → transfer-DCu4c2BL.js} +0 -0
- /package/dist/{visible-index-CKvgpUrf.js → visible-index-CgyJLAS_.js} +0 -0
package/dist/docx-DjF8FgoP.js
DELETED
|
@@ -1,1274 +0,0 @@
|
|
|
1
|
-
import { t as e } from "./chunk-DmhlhrBa.js";
|
|
2
|
-
import { E as t, M as n, N as r, _ as i, c as a, l as o, t as s, u as c } from "./bounded-raw-part-cache-BTfZD_Sz.js";
|
|
3
|
-
import { a as l, c as u, d, f, h as p, i as m, l as h, m as g, n as _, o as v, p as y, r as b, s as x, t as ee, u as te } from "./find-cursor-Dc5iM6s7.js";
|
|
4
|
-
import { a as S, i as C, n as w, o as T, r as E, t as D } from "./preload-BEouWnlI.js";
|
|
5
|
-
import { a as ne, d as re, f as ie, g as ae, h as oe, i as se, l as ce, m as O, n as k, o as le, p as ue, r as de, s as A, t as j, u as M } from "./document-pull-client-BcNYhoAG.js";
|
|
6
|
-
import { f as N, i as P, p as F, t as I } from "./svg-image-by-path-C1M3N2pT.js";
|
|
7
|
-
import { M as L, lt as R } from "./line-metrics-D9gqQWHl.js";
|
|
8
|
-
import { n as z, r as B, t as V } from "./highlight-rect-cCvVU-MW.js";
|
|
9
|
-
import { r as H } from "./hyperlink-D85FexTa.js";
|
|
10
|
-
//#region packages/core/src/fonts/embedded.ts
|
|
11
|
-
function fe(e, t) {
|
|
12
|
-
let n = pe(t), r = e.slice(), i = Math.min(32, r.length);
|
|
13
|
-
for (let e = 0; e < i; e++) r[e] ^= n[e % 16];
|
|
14
|
-
return r;
|
|
15
|
-
}
|
|
16
|
-
function pe(e) {
|
|
17
|
-
let t = e.replace(/[{}\-\s]/g, "");
|
|
18
|
-
if (t.length !== 32 || /[^0-9a-fA-F]/.test(t)) throw Error(`invalid fontKey GUID: ${e}`);
|
|
19
|
-
let n = new Uint8Array(16);
|
|
20
|
-
for (let e = 0; e < 16; e++) n[e] = parseInt(t.slice(e * 2, e * 2 + 2), 16);
|
|
21
|
-
return n.reverse();
|
|
22
|
-
}
|
|
23
|
-
function me(e, t, n, r) {
|
|
24
|
-
let i = 2166136261;
|
|
25
|
-
for (let e = 0; e < r.length; e++) i ^= r[e], i = Math.imul(i, 16777619);
|
|
26
|
-
return `${e}|${t}|${n}|${r.length}|${(i >>> 0).toString(16)}`;
|
|
27
|
-
}
|
|
28
|
-
async function he(e, t = 30 * 1024 * 1024) {
|
|
29
|
-
let n = D();
|
|
30
|
-
if (!n || typeof FontFace > "u") return [];
|
|
31
|
-
let r = [], i = [], a = [];
|
|
32
|
-
for (let o of e) try {
|
|
33
|
-
if (o.bytes.length === 0 || o.bytes.length > t) {
|
|
34
|
-
a.push(o.family);
|
|
35
|
-
continue;
|
|
36
|
-
}
|
|
37
|
-
let e = o.odttf ? fe(o.bytes, o.fontKey ?? "") : o.bytes, { face: s, isNew: c } = T(`embedded:${me(o.family, o.weight, o.style, e)}`, n, () => {
|
|
38
|
-
let t = e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength), r = new FontFace(o.family, t, {
|
|
39
|
-
weight: o.weight,
|
|
40
|
-
style: o.style
|
|
41
|
-
});
|
|
42
|
-
return n.add(r), r;
|
|
43
|
-
});
|
|
44
|
-
r.push(s), c && i.push(s);
|
|
45
|
-
} catch {
|
|
46
|
-
a.push(o.family);
|
|
47
|
-
}
|
|
48
|
-
return i.length > 0 && await C(Promise.allSettled(i.map((e) => e.load())).then((e) => (e.forEach((e, t) => {
|
|
49
|
-
e.status === "rejected" && a.push(i[t].family);
|
|
50
|
-
}), n.ready))), a.length > 0 && console.warn(`[ooxml] failed to register embedded font(s): ${[...new Set(a)].join(", ")}; falling back to substitute fonts (text may shift or differ).`), r;
|
|
51
|
-
}
|
|
52
|
-
function ge(e) {
|
|
53
|
-
S(e);
|
|
54
|
-
}
|
|
55
|
-
//#endregion
|
|
56
|
-
//#region packages/docx/src/worker.ts?worker&inline
|
|
57
|
-
var U = "var e=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,n.unregister(this),e}free(){let e=this.__destroy_into_raw();v.__wbg_docxarchive_free(e,0)}acknowledge_document_chunk(e,t,n){let r=v.docxarchive_acknowledge_document_chunk(this.__wbg_ptr,e,t,n);if(r[1])throw f(r[0])}assert_healthy(){let e=v.docxarchive_assert_healthy(this.__wbg_ptr);if(e[1])throw f(e[0])}cancel_document_cursor(){v.docxarchive_cancel_document_cursor(this.__wbg_ptr)}close_document_session(){v.docxarchive_close_document_session(this.__wbg_ptr)}document_chunk_done(){let e=v.docxarchive_document_chunk_done(this.__wbg_ptr);if(e[2])throw f(e[1]);return e[0]!==0}document_cursor_resource_usage(){let e=v.docxarchive_document_cursor_resource_usage(this.__wbg_ptr);if(e[3])throw f(e[2]);var t=r(e[0],e[1]).slice();return v.__wbindgen_free(e[0],e[1]*1,1),t}extract_image(e){let t=d(e,v.__wbindgen_malloc,v.__wbindgen_realloc),n=_,i=v.docxarchive_extract_image(this.__wbg_ptr,t,n);if(i[3])throw f(i[2]);var a=r(i[0],i[1]).slice();return v.__wbindgen_free(i[0],i[1]*1,1),a}constructor(e,t,r){let i=u(e,v.__wbindgen_malloc),a=_,o=v.docxarchive_new(i,a,!l(t),l(t)?BigInt(0):t,!l(r),l(r)?BigInt(0):r);if(o[2])throw f(o[1]);return this.__wbg_ptr=o[0]>>>0,n.register(this,this.__wbg_ptr,this),this}open_document_cursor(e,t){let n=v.docxarchive_open_document_cursor(this.__wbg_ptr,e,t);if(n[1])throw f(n[0])}parse(){let e=v.docxarchive_parse(this.__wbg_ptr);if(e[3])throw f(e[2]);var t=r(e[0],e[1]).slice();return v.__wbindgen_free(e[0],e[1]*1,1),t}pull_document_chunk(e,t,n,i){let a=v.docxarchive_pull_document_chunk(this.__wbg_ptr,e,t,n,i);if(a[3])throw f(a[2]);var o=r(a[0],a[1]).slice();return v.__wbindgen_free(a[0],a[1]*1,1),o}resource_usage(){let e=v.docxarchive_resource_usage(this.__wbg_ptr);if(e[3])throw f(e[2]);var t=r(e[0],e[1]).slice();return v.__wbindgen_free(e[0],e[1]*1,1),t}to_markdown(){let e,t;try{let i=v.docxarchive_to_markdown(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,f(i[2]);return e=n,t=r,o(n,r)}finally{v.__wbindgen_free(e,t,1)}}};Symbol.dispose&&(e.prototype[Symbol.dispose]=e.prototype.free);function t(){return{__proto__:null,\"./docx_parser_bg.js\":{__proto__:null,__wbg___wbindgen_throw_6b64449b9b9ed33c:function(e,t){throw Error(o(e,t))},__wbg_error_a6fa202b58aa1cd3:function(e,t){let n,r;try{n=e,r=t,console.error(o(e,t))}finally{v.__wbindgen_free(n,r,1)}},__wbg_new_227d7c05414eb861:function(){return Error()},__wbg_stack_3b0d974bbf31e44f:function(e,t){let n=t.stack,r=d(n,v.__wbindgen_malloc,v.__wbindgen_realloc),i=_;a().setInt32(e+4,i,!0),a().setInt32(e+0,r,!0)},__wbindgen_cast_0000000000000001:function(e,t){return o(e,t)},__wbindgen_init_externref_table:function(){let e=v.__wbindgen_externrefs,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)}}}}const n=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>v.__wbg_docxarchive_free(e>>>0,1));function r(e,t){return e>>>=0,c().subarray(e/1,e/1+t)}let i=null;function a(){return(i===null||i.buffer.detached===!0||i.buffer.detached===void 0&&i.buffer!==v.memory.buffer)&&(i=new DataView(v.memory.buffer)),i}function o(e,t){return e>>>=0,h(e,t)}let s=null;function c(){return(s===null||s.byteLength===0)&&(s=new Uint8Array(v.memory.buffer)),s}function l(e){return e==null}function u(e,t){let n=t(e.length*1,1)>>>0;return c().set(e,n/1),_=e.length,n}function d(e,t,n){if(n===void 0){let n=g.encode(e),r=t(n.length,1)>>>0;return c().subarray(r,r+n.length).set(n),_=n.length,r}let r=e.length,i=t(r,1)>>>0,a=c(),o=0;for(;o<r;o++){let t=e.charCodeAt(o);if(t>127)break;a[i+o]=t}if(o!==r){o!==0&&(e=e.slice(o)),i=n(i,r,r=o+e.length*3,1)>>>0;let t=c().subarray(i+o,i+r),a=g.encodeInto(e,t);o+=a.written,i=n(i,r,o,1)>>>0}return _=o,i}function f(e){let t=v.__wbindgen_externrefs.get(e);return v.__externref_table_dealloc(e),t}let p=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0});p.decode();let m=0;function h(e,t){return m+=t,m>=2146435072&&(p=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}),p.decode(),m=t),p.decode(c().subarray(e,e+t))}const g=new TextEncoder;`encodeInto`in g||(g.encodeInto=function(e,t){let n=g.encode(e);return t.set(n),{read:e.length,written:n.length}});let _=0,v;function ee(e,t){return v=e.exports,i=null,s=null,v.__wbindgen_start(),v}async function y(e,t){if(typeof Response==`function`&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming==`function`)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if(e.ok&&n(e.type)&&e.headers.get(`Content-Type`)!==`application/wasm`)console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\",t);else throw t}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}function n(e){switch(e){case`basic`:case`cors`:case`default`:return!0}return!1}}async function b(e){if(v!==void 0)return v;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn(`using deprecated parameters for the initialization function; pass a single object instead`));let n=t();(typeof e==`string`||typeof Request==`function`&&e instanceof Request||typeof URL==`function`&&e instanceof URL)&&(e=fetch(e));let{instance:r,module:i}=await y(await e,n);return ee(r,i)}async function x(e){return v=void 0,i=null,s=null,b(e)}var S=class e extends Error{code;constructor(t,n){super(n),this.name=`OoxmlError`,this.code=t,Object.setPrototypeOf(this,e.prototype)}},C=class e extends Error{code=`ooxml-resource-limit`;details;constructor(t,n){super(t),this.name=`OoxmlResourceLimitError`;let r=n.violation,i=Object.freeze({format:r.format,operation:r.operation,resource:r.resource,metric:r.metric,...r.part===void 0?{}:{part:r.part},limit:r.limit,observed:r.observed,configurable:r.configurable,usage:Object.freeze({archiveEntryCount:r.usage.archiveEntryCount,declaredInflatedBytes:r.usage.declaredInflatedBytes,...r.usage.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:r.usage.largestInflatedEntryBytes},distinctInflatedBytes:r.usage.distinctInflatedBytes,operationInflatedBytes:r.usage.operationInflatedBytes})});this.details=Object.freeze({stage:n.stage,violation:i}),Object.setPrototypeOf(this,e.prototype)}},te=class e extends RangeError{code=`ooxml-decoded-image-limit`;constructor(t,n,r){super(`OOXML decoded image limit exceeded: ${t} ${r} > ${n}`),this.metric=t,this.limit=n,this.observed=r,this.name=`OoxmlDecodedImageLimitError`,Object.setPrototypeOf(this,e.prototype)}};function ne(e){if(!e.startsWith(`data:`))return null;let t=e.indexOf(`,`);if(t===-1)return null;let n=atob(e.slice(t+1)),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r.buffer}var re=class e extends Error{code=`parser-crashed`;constructor(t){super(t),this.name=`WasmTrapError`,Object.setPrototypeOf(this,e.prototype)}};function ie(e){let t=globalThis.WebAssembly?.RuntimeError;if(t&&e instanceof t||e instanceof RangeError)return!0;if(e instanceof Error){let t=e.name;if(t===`RuntimeError`||t===`CompileError`||t===`LinkError`||t===`InternalError`||t===`OOMError`)return!0}return!1}function w(e,t){return e({module_or_path:t})}var T=class{_init;_opts;_wasmInput=null;_initPromise=null;_poisoned=!1;_archive=null;constructor(e,t={}){this._init=e,this._opts=t}setWasmInput(e){this._wasmInput=e,this._poisoned=!1,this._initPromise=w(this._init,e)}setWasmUrl(e){this.setWasmInput(e)}get archive(){return this._archive}setArchive(e){this._freeArchive(),this._archive=e}disposeArchive(){this._freeArchive()}_freeArchive(){this._archive!=null&&this._opts.freeArchive&&this._opts.freeArchive(this._archive),this._archive=null}get poisoned(){return this._poisoned}async ensureReady(){if(this._poisoned){if(this._wasmInput===null)throw Error(`WasmParserHost: setWasmInput was never called`);let e=w(this._opts.reinit??this._init,this._wasmInput);this._initPromise=e,await e,this._poisoned=!1;return}if(this._initPromise===null)throw Error(`WasmParserHost: setWasmInput was never called`);await this._initPromise}run(e){try{return e()}catch(e){throw ie(e)?(this._poison(),new re(`WASM parser trapped and was recycled: ${e instanceof Error?e.message:String(e)}`)):e}}poison(){this._poison()}_poison(){if(this._poisoned=!0,this._initPromise=null,this._archive!=null&&this._opts.freeArchive)try{this._opts.freeArchive(this._archive)}catch{}this._archive=null}};function E(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function ae(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return E(t.requiredBytes)&&E(t.offeredBytes)&&t.requiredBytes>t.offeredBytes}var D=class e extends RangeError{code=`ooxml-insufficient-credit`;requiredBytes;offeredBytes;constructor(t){super(`Pull unit requires ${t.requiredBytes} bytes but credit is ${t.offeredBytes}`),this.name=`PullSessionInsufficientCreditError`,this.requiredBytes=t.requiredBytes,this.offeredBytes=t.offeredBytes,Object.setPrototypeOf(this,e.prototype)}};function O(e){if(e instanceof D)return e;let t=e instanceof Error?e.message:String(e);if(!t.startsWith(`OOXML_INSUFFICIENT_CREDIT:`))return;let n;try{n=JSON.parse(t.slice(26))}catch{return}if(!n||typeof n!=`object`||Array.isArray(n))return;let r=n;if(!(r.code!==`ooxml-insufficient-credit`||!ae(r)))return new D(r)}function oe(e,t,n){let r=O(e);if(!(!r||r.offeredBytes!==t||r.requiredBytes>n))return r}const k=`OOXML_RESOURCE_LIMIT:`;function A(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function j(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return A(t.archiveEntryCount)&&A(t.declaredInflatedBytes)&&(t.largestInflatedEntryBytes===void 0||A(t.largestInflatedEntryBytes))&&A(t.distinctInflatedBytes)&&A(t.operationInflatedBytes)}function M(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw TypeError(`OOXML resource usage checkpoint is not valid JSON`)}if(!j(t))throw TypeError(`OOXML resource usage checkpoint is invalid`);return t}function se(e){return e===`docx`||e===`xlsx`||e===`pptx`}function ce(e){return e===`container`||e===`decompression`||e===`parsing`||e===`serialization`||e===`layout`||e===`rendering`||e===`worker`}function N(e,t){return typeof e==`string`&&e.length>0&&e.length<=t&&!/[\\u0000-\\u001f\\u007f]/u.test(e)}function P(e){return N(e,128)&&/^[a-z0-9][a-z0-9-]*$/u.test(e)}function F(e){return!N(e,4096)||e.startsWith(`/`)||e.startsWith(`\\\\`)||e.includes(`\\\\`)||e.includes(`?`)||e.includes(`#`)||e.includes(`://`)||/^[a-z]:/iu.test(e)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}const I=new Map([[`archive-entry:declared-inflated-bytes`,{stage:`container`,part:`required`}],[`archive-entry:actual-inflated-bytes`,{stage:`decompression`,part:`required`}],[`archive:entry-count`,{stage:`container`,part:`forbidden`,configurable:!1}],[`archive:central-directory-bytes`,{stage:`container`,part:`forbidden`,configurable:!1}],[`archive:distinct-inflated-bytes`,{stage:`decompression`,part:`required`}],[`xml-event:bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`xml-context:bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`xml-tree:depth`,{stage:`parsing`,part:`optional`,configurable:!1}],[`worksheet-row:projected-bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`worksheet-shell:projected-bytes`,{stage:`parsing`,part:`optional`,configurable:!1}]]),L=new Set([...I.keys()].map(e=>e.slice(0,e.indexOf(`:`)))),R=new Set([...I.keys()].map(e=>e.slice(e.indexOf(`:`)+1)));function z(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return!se(t.format)||!N(t.operation,256)||!P(t.resource)||!P(t.metric)||!A(t.limit)||!A(t.observed)||typeof t.configurable!=`boolean`||!j(t.usage)?!1:!(`part`in t)||F(t.part)}function B(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;if(!ce(t.stage)||!z(t.violation))return!1;let n=t.violation,r=I.get(`${n.resource}:${n.metric}`);return r?t.stage!==r.stage||r.configurable===!1&&n.configurable!==!1?!1:r.part===`required`?n.part!==void 0:r.part===`forbidden`?n.part===void 0:!0:!(L.has(n.resource)&&R.has(n.metric))}function V(e){return{archiveEntryCount:e.archiveEntryCount,declaredInflatedBytes:e.declaredInflatedBytes,...e.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:e.largestInflatedEntryBytes},distinctInflatedBytes:e.distinctInflatedBytes,operationInflatedBytes:e.operationInflatedBytes}}function H(e){if(!B(e))return;let t=e.violation,n={stage:e.stage,violation:{format:t.format,operation:t.operation,resource:t.resource,metric:t.metric,...t.part===void 0?{}:{part:t.part},limit:t.limit,observed:t.observed,configurable:t.configurable,usage:V(t.usage)}};return B(n)?n:void 0}function U(e){let t=e.violation;return`OOXML resource limit exceeded${t.part?` for ${t.part}`:``}: ${t.metric} ${t.observed} > ${t.limit}`}function W(e){let t=e instanceof Error?e.message:String(e);if(!t.startsWith(k))return;let n;try{n=JSON.parse(t.slice(21))}catch{return}if(!n||typeof n!=`object`)return;let r=n;if(!(r.code!==`ooxml-resource-limit`||!B(r.details)))return new C(U(r.details),r.details)}function le(e){if(e instanceof te)return{message:e.message,errorName:e.name,code:e.code,decodedImage:{metric:e.metric,limit:e.limit,observed:e.observed}};let t=O(e);if(t)return{message:t.message,errorName:t.name,code:t.code,insufficientCredit:{requiredBytes:t.requiredBytes,offeredBytes:t.offeredBytes}};let n=e instanceof S||e instanceof C?e:W(e);if(n instanceof C){let e=H(n.details);return e?{message:typeof n.message==`string`?n.message:U(e),errorName:`OoxmlResourceLimitError`,code:`ooxml-resource-limit`,resourceLimit:e}:{message:`Invalid OOXML resource-limit error payload`,errorName:`Error`}}if(n instanceof S)return{message:typeof n.message==`string`?n.message:String(n.message),errorName:N(n.name,128)?n.name:`OoxmlError`,...P(n.code)?{code:n.code}:{}};let r=e instanceof Error?e.message:String(e);if(typeof r==`string`&&r.startsWith(k))return{message:`Invalid OOXML resource-limit payload`,errorName:`Error`};let i=e instanceof Error?e:Error(r),a=i;return{message:typeof i.message==`string`?i.message:String(i.message),errorName:N(i.name,128)?i.name:`Error`,...typeof a.code==`string`?{code:a.code}:{}}}function G(e){try{return le(e)}catch{return{message:`Worker operation failed with an unreadable error`,errorName:`Error`}}}function ue(e){return e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&e.buffer instanceof ArrayBuffer?e.buffer:e.slice().buffer}Object.freeze({maxArchiveEntryBytes:134217728,maxTotalInflatedBytes:268435456});function de(e){return[e.maxArchiveEntryBytes===null?0n:BigInt(e.maxArchiveEntryBytes),e.maxTotalInflatedBytes===null?0n:BigInt(e.maxTotalInflatedBytes)]}const K=`ooxml-pull-v1`;function q(e,t){if(!Number.isSafeInteger(e)||e<=0)throw RangeError(`${t} must be a positive safe integer`)}function fe(e){if(!(typeof e==`string`&&e.length>0||typeof e==`number`&&Number.isSafeInteger(e)&&e>0))throw RangeError(`session id must be a non-empty string or positive safe integer`)}var J=class{owner;queue=Promise.resolve();leases=new Map;retainedBytes=0;retainedCount=0;maxRetainedBytes;maxRetainedCount;cleanups=new Set;pendingFatalCleanups=[];poisonRunning=!1;fatal;constructor(e){this.maxRetainedBytes=e?.maxRetainedBytes??64*1024*1024,this.maxRetainedCount=e?.maxRetainedCount??256,q(this.maxRetainedBytes,`max retained lease bytes`),q(this.maxRetainedCount,`max retained lease count`)}enqueue(e){let t=this.queue.then(e,e);return this.queue=t.then(()=>void 0,()=>void 0),t}acquire(e){return this.owner===void 0?(this.owner=e,!0):this.owner===e}release(e){this.owner===e&&(this.owner=void 0)}retainLease(e,t,n){if(!Number.isSafeInteger(n)||n<0)throw RangeError(`retained lease bytes are invalid`);let r=this.leases.get(e)??new Map;if(r.has(t))throw Error(`driver returned a duplicate lease id`);if(this.retainedCount+1>this.maxRetainedCount)throw RangeError(`retained lease count exceeds limit`);if(this.retainedBytes+n>this.maxRetainedBytes)throw RangeError(`retained lease bytes exceed limit`);r.set(t,n),this.leases.set(e,r),this.retainedCount++,this.retainedBytes+=n}releaseLease(e,t){let n=this.leases.get(e),r=n?.get(t);r!==void 0&&(n?.delete(t),n?.size===0&&this.leases.delete(e),this.retainedCount--,this.retainedBytes-=r)}registerCleanup(e){return this.fatal?(this.poisonRunning?this.pendingFatalCleanups.push(e):this.enqueue(e).catch(()=>void 0),()=>void 0):(this.cleanups.add(e),()=>this.cleanups.delete(e))}get fatalError(){return this.fatal}get registeredHostCount(){return this.cleanups.size}async poison(e){if(this.fatal??=e,this.poisonRunning)return this.fatal;this.poisonRunning=!0,this.pendingFatalCleanups.push(...this.cleanups);try{let e;for(;(e=this.pendingFatalCleanups.shift())!==void 0;)await e().catch(()=>void 0)}finally{this.poisonRunning=!1}return this.fatal}},pe=class{options;coordinator;coordinatorOwner=Symbol(`pull-session-host`);unregisterCleanup;sequence=0;unacked;leases=new Map;activeDriverLeases=new Set;nextWireLeaseId;cancelRequested=!1;cancelComplete=!1;closeRequested=!1;closeComplete=!1;driverCancelComplete=!1;driverCloseComplete=!1;completed=!1;constructor(e){fe(e.sessionId),q(e.operationId,`operation id`),q(e.generation,`generation`),q(e.maxByteCredit,`max byte credit`),e.wireLeaseIdStart!==void 0&&q(e.wireLeaseIdStart,`wire lease id start`),this.options=e,this.coordinator=e.coordinator,this.nextWireLeaseId=e.wireLeaseIdStart??1,this.unregisterCleanup=this.coordinator.registerCleanup(()=>this.forceFatalCleanup())}dispatch(e,t){return this.coordinator.enqueue(async()=>{let n=await this.execute(e);try{t(n.response,n.transfer)}catch(e){throw await this.rollbackFailedPost(n),e}})}async rollbackFailedPost(e){let t=e.response;if(t.kind===`chunk`){let n=t.leaseId===void 0?void 0:this.leases.get(t.leaseId);try{await this.options.driver.disposeInvalidChunk?.({payload:t.payload,byteLength:t.byteLength,done:t.done,leaseId:n?.driverLeaseId,retainedBytes:n?.retainedBytes,transfer:e.transfer})}catch{}}this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);for(let[e,t]of[...this.leases])try{await this.options.driver.releaseLease?.(t.driverLeaseId)}catch{}finally{this.leases.delete(e),this.activeDriverLeases.delete(t.driverLeaseId),this.coordinator.releaseLease(this.coordinatorOwner,e)}if(this.cancelRequested=!0,!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch{}this.unregisterCleanup()}async execute(e){try{if(this.isStaleLifecycle(e)){let t=e.kind===`cancel`?`cancel`:`close`;return this.sameOperationIdentity(e)?{response:this.accepted(e,t,!0)}:{response:this.errorResponse(e,{message:`stale lifecycle targets another session or operation`,errorName:`PullSessionProtocolError`,code:`ooxml-stale-lifecycle`})}}this.validateCommandIdentity(e);let t=this.coordinator.fatalError;if(t)return e.kind===`pull`?{response:this.errorResponse(e,t)}:(e.kind===`cancel`?await this.cancel():e.kind===`close`?await this.close():e.kind===`release`&&await this.release(e.leaseId),{response:this.accepted(e,e.kind)});switch(e.kind){case`pull`:return await this.pull(e);case`ack`:return await this.ack(e.sequence),{response:this.accepted(e,`ack`)};case`release`:return await this.release(e.leaseId),{response:this.accepted(e,`release`)};case`cancel`:return await this.cancel(),{response:this.accepted(e,`cancel`)};case`close`:return await this.close(),{response:this.accepted(e,`close`)}}}catch(t){let n=G(t);return n.code===`ooxml-resource-limit`&&(n=await this.coordinator.poison(n)),{response:this.errorResponse(e,n)}}}async pull(e){if(this.closeRequested||this.cancelRequested||this.completed)throw Error(`pull session is closed`);if(this.unacked)throw Error(`previous chunk is not acknowledged`);if(!Number.isSafeInteger(e.sequence)||e.sequence<0||e.sequence!==this.sequence)throw Error(`pull command sequence mismatch`);if(this.validateHostCredit(e.byteCredit),!this.coordinator.acquire(this.coordinatorOwner))throw Error(`another operation has an unacknowledged package chunk`);let t;try{t=await this.options.driver.pull(e.byteCredit)}catch(e){throw this.coordinator.release(this.coordinatorOwner),e}let n=!1,r=!1,i,a;try{let o=this.options.driver.measureChunk(t),s=this.arrayBufferTransferBytes(t.transfer);if(o<s)throw RangeError(`measured chunk bytes are below ArrayBuffer transfer bytes`);if(a=Math.max(o,s),t.leaseId!==void 0){if(q(t.leaseId,`lease id`),t.retainedBytes===void 0)throw Error(`retained lease bytes are required`);if(this.activeDriverLeases.has(t.leaseId))throw r=!0,Error(`driver returned an active duplicate lease id`);i=this.allocateWireLeaseId(),this.coordinator.retainLease(this.coordinatorOwner,i,t.retainedBytes),this.leases.set(i,{driverLeaseId:t.leaseId,retainedBytes:t.retainedBytes}),this.activeDriverLeases.add(t.leaseId),n=!0}else if(t.retainedBytes!==void 0)throw Error(`retained lease bytes require a lease id`);if(!Number.isSafeInteger(a)||a<0)throw RangeError(`host chunk byte length must be a non-negative safe integer`);if(a>e.byteCredit)throw RangeError(`host chunk exceeds byte credit`)}catch(e){let a;try{await this.options.driver.disposeInvalidChunk?.(t)}catch(e){a=e}if(n&&i!==void 0)try{await this.release(i)}catch(e){a??=e}else if(t.leaseId!==void 0&&!r)try{await this.options.driver.releaseLease?.(t.leaseId)}catch(e){a??=e}if(r)try{await this.cancel()}catch(e){a??=e}throw this.coordinator.release(this.coordinatorOwner),a||e}return this.unacked={sequence:this.sequence,done:t.done},{response:{kind:`chunk`,protocol:K,...this.identity(),requestId:e.requestId,sequence:this.sequence,byteLength:a,done:t.done,payload:t.payload,leaseId:i,usage:this.resourceUsage()},transfer:t.transfer}}async ack(e){if(!Number.isSafeInteger(e)||e<0)throw RangeError(`invalid ack sequence`);if(e<this.sequence)return;if(!this.unacked||e!==this.sequence)throw Error(`ack sequence mismatch`);let t=this.unacked.done;await this.options.driver.acknowledge?.(e),this.unacked=void 0,this.coordinator.release(this.coordinatorOwner),this.sequence++,t&&(this.completed=!0,this.maybeUnregisterCompleted())}async release(e){q(e,`wire lease id`);let t=this.leases.get(e);t&&(await this.options.driver.releaseLease?.(t.driverLeaseId),this.leases.delete(e),this.activeDriverLeases.delete(t.driverLeaseId),this.coordinator.releaseLease(this.coordinatorOwner,e),this.maybeUnregisterCompleted())}async cancel(){if(this.cancelComplete)return;this.cancelRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;try{await this.releaseAllLeases()}catch(t){e=t}if(!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch(t){e??=t}if(e)throw e;this.cancelComplete=!0,this.unregisterCleanup()}async close(){if(this.closeComplete)return;this.closeRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;try{await this.releaseAllLeases()}catch(t){e=t}if(!this.driverCloseComplete)try{await this.options.driver.close?.(),this.driverCloseComplete=!0}catch(t){e??=t}if(e)throw e;this.closeComplete=!0,this.unregisterCleanup()}async releaseAllLeases(){let e;for(let t of[...this.leases.keys()])try{await this.release(t)}catch(t){e??=t}if(e)throw e}validateCommandIdentity(e){if(e.protocol!==`ooxml-pull-v1`||e.sessionId!==this.options.sessionId||e.operationId!==this.options.operationId||e.generation!==this.options.generation||!Number.isSafeInteger(e.requestId)||e.requestId<=0)throw Error(`stale or mismatched pull session command`)}validateHostCredit(e){if(q(e,`byte credit`),e>this.options.maxByteCredit)throw RangeError(`byte credit exceeds host maximum`)}accepted(e,t,n=!1){return{kind:`accepted`,protocol:K,...n?{sessionId:e.sessionId,operationId:e.operationId,generation:e.generation}:this.identity(),requestId:e.requestId,command:t,usage:this.resourceUsage()}}identity(){return{sessionId:this.options.sessionId,operationId:this.options.operationId,generation:this.options.generation}}isStaleLifecycle(e){return(e.kind===`cancel`||e.kind===`close`)&&e.protocol===`ooxml-pull-v1`&&Number.isSafeInteger(e.requestId)&&e.requestId>0&&Number.isSafeInteger(e.generation)&&e.generation>0&&e.generation<this.options.generation}sameOperationIdentity(e){return e.sessionId===this.options.sessionId&&e.operationId===this.options.operationId}errorResponse(e,t){return{kind:`error`,protocol:K,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:t,usage:this.errorResourceUsage()}}async forceFatalCleanup(){this.cancelRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;for(let t of[...this.leases.keys()])try{await this.release(t)}catch(t){e??=t}if(!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch(t){e??=t}if(e)throw e;this.unregisterCleanup()}allocateWireLeaseId(){if(!Number.isSafeInteger(this.nextWireLeaseId)||this.nextWireLeaseId<=0)throw RangeError(`wire lease id space exhausted`);return this.nextWireLeaseId++}arrayBufferTransferBytes(e){let t=0;for(let n of e??[])if(n instanceof ArrayBuffer&&(t+=n.byteLength,!Number.isSafeInteger(t)))throw RangeError(`ArrayBuffer transfer bytes overflow`);return t}maybeUnregisterCompleted(){this.completed&&this.leases.size===0&&this.unregisterCleanup()}resourceUsage(){return this.options.driver.resourceUsage?.()}errorResourceUsage(){try{return this.resourceUsage()}catch{return}}};const Y=67108864;var me=class{coordinator=new J;host=null;identity=null;constructor(e,t=e=>e(this.requireArchive())){this.archive=e,this.executeArchive=t}open(e){if(this.host)throw Error(`a DOCX document pull session is already active`);this.executeArchive(t=>{t.open_document_cursor(e.operationId,e.generation)});let t=0;this.identity=e,this.host=new pe({...e,maxByteCredit:Y,coordinator:this.coordinator,driver:{pull:n=>{let r;try{r=this.executeArchive(r=>r.pull_document_chunk(t,e.operationId,e.generation,n))}catch(e){throw oe(e,n,Y)||e}let i=ue(r);return{payload:i,byteLength:i.byteLength,done:this.executeArchive(e=>e.document_chunk_done()),transfer:[i]}},measureChunk:({payload:e})=>e.byteLength,acknowledge:n=>{if(n!==t)throw Error(`DOCX document acknowledgement sequence mismatch`);this.executeArchive(n=>n.acknowledge_document_chunk(t,e.operationId,e.generation)),t+=1},cancel:()=>this.executeArchive(e=>e.cancel_document_cursor()),close:()=>this.executeArchive(e=>e.close_document_session()),resourceUsage:()=>{let e=this.executeArchive(e=>e.document_cursor_resource_usage?.());return e?M(e):void 0}}})}dispatch(e,t){return!this.host||!this.identity?(t({protocol:K,kind:`error`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:G(Error(`DOCX document pull session is not open`))}),Promise.resolve()):this.host.dispatch(e,t)}async reset(){if(this.host)try{this.archive()&&this.executeArchive(e=>e.close_document_session())}finally{this.host=null,this.identity=null,this.coordinator=new J}}requireArchive(){let e=this.archive();if(!e)throw Error(`No docx loaded`);return e}};function he(e){return!!e&&typeof e==`object`&&e.protocol===`ooxml-pull-v1`}const X=new T(b,{freeArchive:e=>e.free(),reinit:x}),Z=new me(()=>X.archive,e=>X.run(()=>{let t=X.archive;if(!t)throw Error(`No docx loaded`);return e(t)}));let Q=0;const $=(e,t)=>self.postMessage(e,t);self.onmessage=async t=>{let n=t.data;if(he(n)){try{await Z.dispatch(n,$)}catch(e){$({protocol:K,kind:`error`,sessionId:n.sessionId,operationId:n.operationId,generation:n.generation,requestId:n.requestId,error:G(e)})}return}if(n.type===`init`){X.setWasmInput(ne(n.wasmUrl)??n.wasmUrl);return}let r=n.id;try{if(await X.ensureReady(),n.type!==`parse`&&X.archive){let e=X.archive;X.run(()=>e.assert_healthy())}if(n.type===`parse`){await Z.reset();let[t,i]=de(n.resourcePolicy),a=new Uint8Array(n.data);X.run(()=>{let n=new e(a,t,i);X.setArchive(n)}),Q+=1;let o={sessionId:Q,operationId:Q,generation:Q};Z.open(o),$({type:`documentSessionOpened`,id:r,...o});return}let t=X.archive;if(n.type===`extractImage`){if(!t)throw Error(`No docx loaded`);let e=X.run(()=>t.extract_image(n.path).buffer),i={type:`imageExtracted`,id:r,bytes:e};self.postMessage(i,[e]);return}if(n.type===`resourceUsage`){if(!t)throw Error(`No docx loaded`);$({type:`resourceUsage`,id:r,usage:M(X.run(()=>t.resource_usage()))});return}if(n.type===`toMarkdown`){if(!t)throw Error(`No docx loaded`);$({type:`markdownRendered`,id:r,markdown:X.run(()=>t.to_markdown())});return}}catch(e){$({type:`error`,id:r,...G(e)})}};", W = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", U], { type: "text/javascript;charset=utf-8" });
|
|
58
|
-
function _e(e) {
|
|
59
|
-
let t;
|
|
60
|
-
try {
|
|
61
|
-
if (t = W && (self.URL || self.webkitURL).createObjectURL(W), !t) throw "";
|
|
62
|
-
let n = new Worker(t, {
|
|
63
|
-
type: "module",
|
|
64
|
-
name: e?.name
|
|
65
|
-
});
|
|
66
|
-
return n.addEventListener("error", () => {
|
|
67
|
-
(self.URL || self.webkitURL).revokeObjectURL(t);
|
|
68
|
-
}), n;
|
|
69
|
-
} catch {
|
|
70
|
-
return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(U), {
|
|
71
|
-
type: "module",
|
|
72
|
-
name: e?.name
|
|
73
|
-
});
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
//#endregion
|
|
77
|
-
//#region packages/docx/src/wasm/docx_parser_bg.wasm?url
|
|
78
|
-
var ve = new URL("docx_parser_bg.wasm", import.meta.url).href;
|
|
79
|
-
//#endregion
|
|
80
|
-
//#region packages/docx/src/bookmark-nav.ts
|
|
81
|
-
function ye(e) {
|
|
82
|
-
let t = /* @__PURE__ */ new Map();
|
|
83
|
-
for (let n of e.pages) for (let e of n.bookmarkStarts) e.name !== "" && !t.has(e.name) && t.set(e.name, n.pageIndex);
|
|
84
|
-
return t;
|
|
85
|
-
}
|
|
86
|
-
//#endregion
|
|
87
|
-
//#region packages/docx/src/embedded-fonts.ts
|
|
88
|
-
async function be(e, t) {
|
|
89
|
-
let n = e.embeddedFonts;
|
|
90
|
-
if (!n || n.length === 0) return [];
|
|
91
|
-
let r = (await Promise.all(n.map(async (e) => {
|
|
92
|
-
try {
|
|
93
|
-
let n = await t(e.partPath);
|
|
94
|
-
return {
|
|
95
|
-
family: e.fontName,
|
|
96
|
-
bytes: n,
|
|
97
|
-
odttf: e.partPath.toLowerCase().endsWith(".odttf"),
|
|
98
|
-
fontKey: e.fontKey,
|
|
99
|
-
weight: xe(e.style),
|
|
100
|
-
style: G(e.style)
|
|
101
|
-
};
|
|
102
|
-
} catch {
|
|
103
|
-
return null;
|
|
104
|
-
}
|
|
105
|
-
}))).filter((e) => e !== null);
|
|
106
|
-
return r.length === 0 ? [] : he(r);
|
|
107
|
-
}
|
|
108
|
-
function xe(e) {
|
|
109
|
-
return e === "bold" || e === "boldItalic" ? "bold" : "normal";
|
|
110
|
-
}
|
|
111
|
-
function G(e) {
|
|
112
|
-
return e === "italic" || e === "boldItalic" ? "italic" : "normal";
|
|
113
|
-
}
|
|
114
|
-
//#endregion
|
|
115
|
-
//#region packages/docx/src/document.ts
|
|
116
|
-
var K = class e {
|
|
117
|
-
_metrics = null;
|
|
118
|
-
_document = null;
|
|
119
|
-
_source = null;
|
|
120
|
-
_meta = null;
|
|
121
|
-
_bookmarkPages = null;
|
|
122
|
-
_mode = "main";
|
|
123
|
-
_worker;
|
|
124
|
-
_bridge;
|
|
125
|
-
_rawParts = new s({
|
|
126
|
-
maxEntries: 64,
|
|
127
|
-
maxBytes: i
|
|
128
|
-
});
|
|
129
|
-
_embeddedFontFaces = [];
|
|
130
|
-
_googleFontFaces = [];
|
|
131
|
-
_localMetricFontFaces = [];
|
|
132
|
-
_fetchImage = (e, t) => this.getImage(e, t);
|
|
133
|
-
constructor(e, n, r, i) {
|
|
134
|
-
this._worker = e, this._mode = n, ue(this, r), this._bridge = new f(this._worker, {
|
|
135
|
-
correlate: (e) => "protocol" in e && e.protocol === "ooxml-pull-v1" ? e.requestId : "id" in e ? e.id : void 0,
|
|
136
|
-
toError: (e) => {
|
|
137
|
-
if (!("protocol" in e || e.type !== "error")) return Object.assign(t(e), {
|
|
138
|
-
...e.reason === void 0 ? {} : { reason: e.reason },
|
|
139
|
-
...e.outgoingColumnIndex === void 0 ? {} : { outgoingColumnIndex: e.outgoingColumnIndex },
|
|
140
|
-
...e.outgoingColumnCount === void 0 ? {} : { outgoingColumnCount: e.outgoingColumnCount },
|
|
141
|
-
...e.incomingColumnCount === void 0 ? {} : { incomingColumnCount: e.incomingColumnCount }
|
|
142
|
-
});
|
|
143
|
-
}
|
|
144
|
-
});
|
|
145
|
-
let a = new URL(i ?? ve, location.href).href;
|
|
146
|
-
this._bridge.post({
|
|
147
|
-
type: "init",
|
|
148
|
-
wasmUrl: a
|
|
149
|
-
});
|
|
150
|
-
}
|
|
151
|
-
static async load(t, n = {}) {
|
|
152
|
-
let r = c(n), i = Date.now(), o = n.mode ?? "main", s = new a({
|
|
153
|
-
enabled: !0,
|
|
154
|
-
format: "docx",
|
|
155
|
-
mode: o,
|
|
156
|
-
policy: r.policy,
|
|
157
|
-
onMetrics: r.onResourceMetrics,
|
|
158
|
-
emitToConsole: r.debug
|
|
159
|
-
});
|
|
160
|
-
try {
|
|
161
|
-
if (o === "worker" && (typeof Worker > "u" || typeof OffscreenCanvas > "u")) throw Error("mode: 'worker' requires Worker and OffscreenCanvas support");
|
|
162
|
-
let a;
|
|
163
|
-
if (typeof t == "string") {
|
|
164
|
-
let e = await fetch(t);
|
|
165
|
-
if (!e.ok) throw Error(`Failed to fetch: ${e.status} ${e.statusText}`);
|
|
166
|
-
a = await e.arrayBuffer();
|
|
167
|
-
} else a = t;
|
|
168
|
-
a = p(await g(a, n.password)), s.setSourceBytes(a.byteLength), s.checkpoint("container ready");
|
|
169
|
-
let c = o === "worker" ? (await import("./render-worker-host-Cyv5Hkbh.js")).createRenderWorker() : new _e(), l;
|
|
170
|
-
try {
|
|
171
|
-
if (l = new e(c, o, i, n.wasmUrl), l._metrics = s, await l._parse(a, r.policy, o === "worker" ? !!n.useGoogleFonts : !1, n.workerTimeoutMs, (e) => s.observeUsage(e)), o === "worker" && l._mode === "main" && (s.setMode("main"), console.warn("[ooxml] mode: 'worker' fell back to main-thread rendering because this document requires DOM OpenType vertical glyph selection.")), n.math && l._mode === "worker" && console.warn("[ooxml] the math engine is unavailable in mode: 'worker'; equations will be skipped. Use mode: 'main' for documents with equations."), l._mode === "main" && n.useGoogleFonts && l._document && (l._googleFontFaces = await w(re(l._document), M)), l._mode === "main" && l._document?.embeddedFonts?.length) {
|
|
172
|
-
let e = l;
|
|
173
|
-
l._embeddedFontFaces = await be(l._document, (t) => e.getFontBytes(t));
|
|
174
|
-
}
|
|
175
|
-
let t;
|
|
176
|
-
l._mode === "main" && l._document && (t = await ce(l._document), l._localMetricFontFaces = t.faces);
|
|
177
|
-
let u;
|
|
178
|
-
if (l._mode === "main" && n.math && l._document && se(l._document) && (u = await ne(l._document, n.math)), l._mode === "main" && l._document && l._source) {
|
|
179
|
-
let e = O(l);
|
|
180
|
-
e.services = A(l._source, {
|
|
181
|
-
localMetrics: t?.metrics,
|
|
182
|
-
useGoogleFonts: !!n.useGoogleFonts,
|
|
183
|
-
embeddedFaces: l._embeddedFontFaces,
|
|
184
|
-
googleFaces: l._googleFontFaces,
|
|
185
|
-
mathResources: u?.records,
|
|
186
|
-
mathDrawables: u?.drawables
|
|
187
|
-
});
|
|
188
|
-
let r = e.services;
|
|
189
|
-
de(l._source, r, e.defaultCurrentDateMs).layoutVariants.defaultLayout;
|
|
190
|
-
}
|
|
191
|
-
return await l._resourceUsage(n.workerTimeoutMs ?? 1e3).then((e) => s.observeUsage(e), () => void 0), s.checkpoint("model and layout ready"), s.succeed({ pages: l.pageCount }), l;
|
|
192
|
-
} catch (e) {
|
|
193
|
-
let t = l;
|
|
194
|
-
throw d(c, t ? () => t.destroy() : void 0), e;
|
|
195
|
-
}
|
|
196
|
-
} catch (e) {
|
|
197
|
-
throw s.fail(e), e;
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
async _parse(e, t, n = !1, r, i) {
|
|
201
|
-
let a = await this._bridge.request((r) => this._mode === "worker" ? {
|
|
202
|
-
type: "parse",
|
|
203
|
-
id: r,
|
|
204
|
-
data: e,
|
|
205
|
-
resourcePolicy: t,
|
|
206
|
-
useGoogleFonts: n,
|
|
207
|
-
defaultCurrentDateMs: O(this).defaultCurrentDateMs
|
|
208
|
-
} : {
|
|
209
|
-
type: "parse",
|
|
210
|
-
id: r,
|
|
211
|
-
data: e,
|
|
212
|
-
resourcePolicy: t
|
|
213
|
-
}, [e], { timeoutMs: r });
|
|
214
|
-
if ("protocol" in a) throw Error("DOCX parse open returned a pull-protocol response");
|
|
215
|
-
if (this._mode === "worker") if ("usage" in a && a.usage && i?.(a.usage), a.type === "mainThreadVerticalFallback") {
|
|
216
|
-
let e = await k(this._bridge.transport(j), a, {
|
|
217
|
-
timeoutMs: r,
|
|
218
|
-
onUsage: i
|
|
219
|
-
});
|
|
220
|
-
this._source = e.source, this._document = e.document, this._meta = null, this._mode = "main";
|
|
221
|
-
} else this._meta = a.meta;
|
|
222
|
-
else {
|
|
223
|
-
let e = a, t = await k(this._bridge.transport(j), e, {
|
|
224
|
-
timeoutMs: r,
|
|
225
|
-
onUsage: i
|
|
226
|
-
});
|
|
227
|
-
this._source = t.source, this._document = t.document;
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
destroy() {
|
|
231
|
-
this._bridge.terminate(), this._document = null, this._source = null, this._meta = null, O(this).services = null, this._bookmarkPages = null, this._rawParts.clear(), this._embeddedFontFaces.length > 0 && (ge(this._embeddedFontFaces), this._embeddedFontFaces = []), this._googleFontFaces.length > 0 && (E(this._googleFontFaces), this._googleFontFaces = []), this._localMetricFontFaces.length > 0 && (ae(this._localMetricFontFaces), this._localMetricFontFaces = []), P(this._fetchImage), I(this._fetchImage);
|
|
232
|
-
}
|
|
233
|
-
async getImage(e, t) {
|
|
234
|
-
return this._rawParts.get(e, t, () => this._bridge.request((t) => ({
|
|
235
|
-
type: "extractImage",
|
|
236
|
-
id: t,
|
|
237
|
-
path: e
|
|
238
|
-
})).then((e) => {
|
|
239
|
-
let n = e.bytes;
|
|
240
|
-
return new Blob([n], { type: t });
|
|
241
|
-
}));
|
|
242
|
-
}
|
|
243
|
-
async getFontBytes(e) {
|
|
244
|
-
let t = (await this._bridge.request((t) => ({
|
|
245
|
-
type: "extractImage",
|
|
246
|
-
id: t,
|
|
247
|
-
path: e
|
|
248
|
-
}))).bytes;
|
|
249
|
-
return new Uint8Array(t);
|
|
250
|
-
}
|
|
251
|
-
async _resourceUsage(e) {
|
|
252
|
-
return (await this._bridge.request((e) => ({
|
|
253
|
-
type: "resourceUsage",
|
|
254
|
-
id: e
|
|
255
|
-
}), void 0, { timeoutMs: e })).usage;
|
|
256
|
-
}
|
|
257
|
-
async getResourceMetrics() {
|
|
258
|
-
let e = this._metrics;
|
|
259
|
-
if (!e) throw Error("Document not loaded");
|
|
260
|
-
return o(e, (e) => this._resourceUsage(e));
|
|
261
|
-
}
|
|
262
|
-
async toMarkdown() {
|
|
263
|
-
return (await this._bridge.request((e) => ({
|
|
264
|
-
type: "toMarkdown",
|
|
265
|
-
id: e
|
|
266
|
-
}))).markdown;
|
|
267
|
-
}
|
|
268
|
-
get pageCount() {
|
|
269
|
-
return this._meta ? this._meta.pageCount : this._document ? this._getLayout()?.pages.length ?? 0 : 0;
|
|
270
|
-
}
|
|
271
|
-
get mode() {
|
|
272
|
-
return this._mode;
|
|
273
|
-
}
|
|
274
|
-
get document() {
|
|
275
|
-
if (this._meta && !this._document) throw Error("the raw document model stays in the worker in mode: 'worker'; use mode: 'main' if you need direct model access");
|
|
276
|
-
if (!this._document) throw Error("Document not loaded");
|
|
277
|
-
return this._document;
|
|
278
|
-
}
|
|
279
|
-
get comments() {
|
|
280
|
-
return this._meta?.comments ?? this._document?.comments ?? [];
|
|
281
|
-
}
|
|
282
|
-
get footnotes() {
|
|
283
|
-
return this._meta?.footnotes ?? this._document?.footnotes ?? [];
|
|
284
|
-
}
|
|
285
|
-
get endnotes() {
|
|
286
|
-
return this._meta?.endnotes ?? this._document?.endnotes ?? [];
|
|
287
|
-
}
|
|
288
|
-
_getLayout() {
|
|
289
|
-
if (!this._document) return null;
|
|
290
|
-
let e = O(this).services;
|
|
291
|
-
if (!e) throw Error("Document layout services are not initialized");
|
|
292
|
-
let t = oe(e);
|
|
293
|
-
if (!t) throw Error("Document layout variant store is not initialized");
|
|
294
|
-
return t.defaultLayout;
|
|
295
|
-
}
|
|
296
|
-
_getBookmarkPages() {
|
|
297
|
-
if (this._bookmarkPages) return this._bookmarkPages;
|
|
298
|
-
if (this._meta) return this._bookmarkPages = new Map(this._meta.bookmarkPages), this._bookmarkPages;
|
|
299
|
-
let e = this._getLayout();
|
|
300
|
-
return e ? (this._bookmarkPages = ye(e), this._bookmarkPages) : null;
|
|
301
|
-
}
|
|
302
|
-
getBookmarkPage(e) {
|
|
303
|
-
return this._getBookmarkPages()?.get(e);
|
|
304
|
-
}
|
|
305
|
-
pageSize(e) {
|
|
306
|
-
if (this._meta) {
|
|
307
|
-
let t = this._meta.pageSizes, n = t[Math.max(0, Math.min(e, t.length - 1))];
|
|
308
|
-
return n ? {
|
|
309
|
-
widthPt: n.widthPt,
|
|
310
|
-
heightPt: n.heightPt
|
|
311
|
-
} : {
|
|
312
|
-
widthPt: 0,
|
|
313
|
-
heightPt: 0
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
if (!this._document) return {
|
|
317
|
-
widthPt: 0,
|
|
318
|
-
heightPt: 0
|
|
319
|
-
};
|
|
320
|
-
let t = this._getLayout();
|
|
321
|
-
if (!t || t.pages.length === 0) return {
|
|
322
|
-
widthPt: 0,
|
|
323
|
-
heightPt: 0
|
|
324
|
-
};
|
|
325
|
-
let n = Math.max(0, Math.min(e, t.pages.length - 1)), r = t.pages[n].geometry;
|
|
326
|
-
return {
|
|
327
|
-
widthPt: r.widthPt,
|
|
328
|
-
heightPt: r.heightPt
|
|
329
|
-
};
|
|
330
|
-
}
|
|
331
|
-
renderPage(e, t, n = {}) {
|
|
332
|
-
if (this._mode === "worker") throw Error("renderPage(canvas) is unavailable in mode: 'worker'; use renderPageToBitmap() and paint it via an ImageBitmapRenderingContext");
|
|
333
|
-
if (!this._source) throw Error("Document not loaded");
|
|
334
|
-
return le(this._source, e, t, {
|
|
335
|
-
...n,
|
|
336
|
-
fetchImage: this._fetchImage,
|
|
337
|
-
layoutServices: O(this).services ?? void 0,
|
|
338
|
-
defaultCurrentDateMs: O(this).defaultCurrentDateMs
|
|
339
|
-
});
|
|
340
|
-
}
|
|
341
|
-
async renderPageToBitmap(e, t = {}) {
|
|
342
|
-
let { onTextRun: n, ...r } = t, i = {
|
|
343
|
-
...r,
|
|
344
|
-
dpr: r.dpr ?? L()
|
|
345
|
-
};
|
|
346
|
-
if (this._mode === "worker") {
|
|
347
|
-
let t = await this._bridge.request((t) => ({
|
|
348
|
-
type: "renderPage",
|
|
349
|
-
id: t,
|
|
350
|
-
pageIndex: e,
|
|
351
|
-
opts: i
|
|
352
|
-
}));
|
|
353
|
-
if (n) for (let e of t.runs) n(e);
|
|
354
|
-
return t.bitmap;
|
|
355
|
-
}
|
|
356
|
-
let a = new OffscreenCanvas(1, 1);
|
|
357
|
-
return await this.renderPage(a, e, {
|
|
358
|
-
...i,
|
|
359
|
-
onTextRun: n
|
|
360
|
-
}), a.transferToImageBitmap();
|
|
361
|
-
}
|
|
362
|
-
async collectPageRuns(e, t = {}) {
|
|
363
|
-
let n = {
|
|
364
|
-
...t,
|
|
365
|
-
dpr: t.dpr ?? L()
|
|
366
|
-
};
|
|
367
|
-
if (this._mode === "worker") return (await this._bridge.request((t) => ({
|
|
368
|
-
type: "collectRuns",
|
|
369
|
-
id: t,
|
|
370
|
-
pageIndex: e,
|
|
371
|
-
opts: n
|
|
372
|
-
}))).runs;
|
|
373
|
-
let r = O(this), i = r.services;
|
|
374
|
-
if (!i) throw Error("Document layout services are not initialized");
|
|
375
|
-
return ie(i, e, {
|
|
376
|
-
currentDate: n.currentDate,
|
|
377
|
-
defaultCurrentDateMs: r.defaultCurrentDateMs,
|
|
378
|
-
width: n.width
|
|
379
|
-
});
|
|
380
|
-
}
|
|
381
|
-
};
|
|
382
|
-
//#endregion
|
|
383
|
-
//#region packages/docx/src/tate-chu-yoko-overlay.ts
|
|
384
|
-
function q(e, t) {
|
|
385
|
-
if (!e.eastAsianVert) return 1;
|
|
386
|
-
let n = t(e.text);
|
|
387
|
-
return !(n > 0) || e.w >= n ? 1 : e.w / n;
|
|
388
|
-
}
|
|
389
|
-
//#endregion
|
|
390
|
-
//#region packages/docx/src/text-layer.ts
|
|
391
|
-
function J(e, t, n, r, i, a) {
|
|
392
|
-
e.innerHTML = "";
|
|
393
|
-
for (let o of t) {
|
|
394
|
-
let t = document.createElement("span");
|
|
395
|
-
t.textContent = o.text;
|
|
396
|
-
let s = o.transform ?? "";
|
|
397
|
-
if (a && o.eastAsianVert) {
|
|
398
|
-
let e = q(o, a(o.font));
|
|
399
|
-
e !== 1 && (s = `${s ? `${s} ` : ""}scaleX(${e})`);
|
|
400
|
-
}
|
|
401
|
-
let c = s ? `transform:${s};transform-origin:top left;` : "", l = i ? o.hyperlink : void 0, u = l ? "pointer" : "text", d = o.letterSpacingPx === void 0 ? "0" : `${o.letterSpacingPx}px`;
|
|
402
|
-
t.style.cssText = `position:absolute;left:${V(o.x, n)};top:${V(o.y, r)};font:${o.font};line-height:${o.h}px;letter-spacing:${d};` + c + `white-space:pre;color:transparent;cursor:${u};pointer-events:all;`, l && i && (t.title = l.kind === "external" ? l.url : l.ref, t.addEventListener("click", () => i(l))), e.appendChild(t);
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
function Y(e, t, n, r, i, a, o = {}) {
|
|
406
|
-
e.innerHTML = "";
|
|
407
|
-
let s = o.match ?? "rgba(255, 214, 0, 0.42)", c = o.active ?? "rgba(255, 140, 0, 0.55)";
|
|
408
|
-
for (let o of n) {
|
|
409
|
-
let n = o.active ? c : s;
|
|
410
|
-
for (let s of o.slices) {
|
|
411
|
-
let o = t[s.runIndex];
|
|
412
|
-
if (!o) continue;
|
|
413
|
-
let c = a(o.font), l = z(o.text, s.start, s.end, c), u = o.letterSpacingPx ?? 0, d = Math.max(0, Math.min(s.start, o.text.length)), f = Math.max(d, Math.min(s.end, o.text.length)), p = [...o.text.slice(0, d)].length, m = [...o.text.slice(d, f)].length, h = l.x + p * u, g = l.width + Math.max(0, m - 1) * u, _ = q(o, c), v = h * _, y = g * _;
|
|
414
|
-
if (y <= 0) continue;
|
|
415
|
-
let b = document.createElement("div"), x = o.transform ? `transform:${o.transform};transform-origin:top left;` : "";
|
|
416
|
-
b.style.cssText = `position:absolute;left:${V(o.x + v, r)};top:${V(o.y, i)};width:${V(y, r)};height:${V(o.h, i)};` + x + `background:${n};pointer-events:none;`, e.appendChild(b);
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
}
|
|
420
|
-
//#endregion
|
|
421
|
-
//#region packages/docx/src/find.ts
|
|
422
|
-
var X = class {
|
|
423
|
-
_pageRuns = /* @__PURE__ */ new Map();
|
|
424
|
-
_matches = [];
|
|
425
|
-
_active = -1;
|
|
426
|
-
_generation = 0;
|
|
427
|
-
_runsRevision = 0;
|
|
428
|
-
constructor(e, t) {
|
|
429
|
-
this._pageCount = e, this._collectPageRuns = t;
|
|
430
|
-
}
|
|
431
|
-
invalidate() {
|
|
432
|
-
this._generation++, this._runsRevision++, this._pageRuns.clear(), this._matches = [], this._active = -1;
|
|
433
|
-
}
|
|
434
|
-
pageRuns(e) {
|
|
435
|
-
return this._pageRuns.get(e);
|
|
436
|
-
}
|
|
437
|
-
setPageRuns(e, t) {
|
|
438
|
-
this._runsRevision++, this._pageRuns.set(e, t);
|
|
439
|
-
}
|
|
440
|
-
_matchAt(e) {
|
|
441
|
-
return this._matches[e];
|
|
442
|
-
}
|
|
443
|
-
pageHighlights(e) {
|
|
444
|
-
let t = [];
|
|
445
|
-
for (let n = 0; n < this._matches.length; n++) {
|
|
446
|
-
let r = this._matches[n];
|
|
447
|
-
r.page === e && t.push({
|
|
448
|
-
slices: r.slices,
|
|
449
|
-
active: n === this._active
|
|
450
|
-
});
|
|
451
|
-
}
|
|
452
|
-
return t;
|
|
453
|
-
}
|
|
454
|
-
activePage() {
|
|
455
|
-
let e = this._matchAt(this._active);
|
|
456
|
-
return e ? e.page : null;
|
|
457
|
-
}
|
|
458
|
-
matches() {
|
|
459
|
-
return this._matches.map((e, t) => ({
|
|
460
|
-
matchIndex: t,
|
|
461
|
-
text: e.text,
|
|
462
|
-
location: { page: e.page }
|
|
463
|
-
}));
|
|
464
|
-
}
|
|
465
|
-
async find(e, t = {}) {
|
|
466
|
-
let n = ++this._generation;
|
|
467
|
-
if (e.length === 0) return this._runsRevision++, this._pageRuns.clear(), this._matches = [], this._active = -1, [];
|
|
468
|
-
let r = this._runsRevision, i = new Map(this._pageRuns), a = this._pageCount();
|
|
469
|
-
for (let e = 0; e < a; e++) {
|
|
470
|
-
let t = i.get(e);
|
|
471
|
-
if (!t) {
|
|
472
|
-
if (t = await this._collectPageRuns(e), n !== this._generation) return [];
|
|
473
|
-
i.set(e, t);
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
if (n !== this._generation) return [];
|
|
477
|
-
let o = r === this._runsRevision ? i : new Map([...i, ...this._pageRuns]), s = [];
|
|
478
|
-
for (let n = 0; n < a; n++) {
|
|
479
|
-
let r = o.get(n) ?? [], i = b(r);
|
|
480
|
-
for (let a of m(i, e, t)) {
|
|
481
|
-
let e = a.slices.map((e) => r[e.runIndex].text.slice(e.start, e.end)).join("");
|
|
482
|
-
s.push({
|
|
483
|
-
page: n,
|
|
484
|
-
text: e,
|
|
485
|
-
slices: a.slices
|
|
486
|
-
});
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
return this._runsRevision++, this._pageRuns = o, this._matches = s, this._active = -1, this.matches();
|
|
490
|
-
}
|
|
491
|
-
next() {
|
|
492
|
-
return this._active = ee(this._active, this._matches.length), this._activePublic();
|
|
493
|
-
}
|
|
494
|
-
prev() {
|
|
495
|
-
return this._active = _(this._active, this._matches.length), this._activePublic();
|
|
496
|
-
}
|
|
497
|
-
_activePublic() {
|
|
498
|
-
let e = this._matchAt(this._active);
|
|
499
|
-
return e ? {
|
|
500
|
-
matchIndex: this._active,
|
|
501
|
-
text: e.text,
|
|
502
|
-
location: { page: e.page }
|
|
503
|
-
} : null;
|
|
504
|
-
}
|
|
505
|
-
}, Z = class {
|
|
506
|
-
_doc = null;
|
|
507
|
-
_currentPage = 0;
|
|
508
|
-
_scale = null;
|
|
509
|
-
_canvas;
|
|
510
|
-
_wrapper;
|
|
511
|
-
_originalParent = null;
|
|
512
|
-
_originalNextSibling = null;
|
|
513
|
-
_originalDisplay = "";
|
|
514
|
-
_textLayer = null;
|
|
515
|
-
_highlightLayer = null;
|
|
516
|
-
_find;
|
|
517
|
-
_measureCtx = null;
|
|
518
|
-
_opts;
|
|
519
|
-
_mode;
|
|
520
|
-
_bitmapCtx = null;
|
|
521
|
-
_destroyed = !1;
|
|
522
|
-
_loadGen = 0;
|
|
523
|
-
constructor(e, t = {}) {
|
|
524
|
-
this._canvas = e, this._opts = t, this._mode = t.mode ?? "main";
|
|
525
|
-
let n = e.parentElement;
|
|
526
|
-
this._originalParent = n, this._originalNextSibling = e.nextSibling, this._originalDisplay = e.style.display, this._wrapper = document.createElement("div"), this._wrapper.style.cssText = "position:relative;display:inline-block;vertical-align:top;", e.style.display || (e.style.display = "block"), n && n.insertBefore(this._wrapper, e), this._wrapper.appendChild(e), this._mode === "worker" && (this._bitmapCtx = e.getContext("bitmaprenderer")), t.enableTextSelection && (this._textLayer = document.createElement("div"), this._textLayer.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;user-select:text;-webkit-user-select:text;", this._wrapper.appendChild(this._textLayer)), this._highlightLayer = document.createElement("div"), this._highlightLayer.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;", this._wrapper.appendChild(this._highlightLayer), this._find = new X(() => this.pageCount, (e) => this._collectPageRuns(e));
|
|
527
|
-
}
|
|
528
|
-
async load(e) {
|
|
529
|
-
let t = ++this._loadGen, n = this._doc;
|
|
530
|
-
try {
|
|
531
|
-
let r = await K.load(e, {
|
|
532
|
-
useGoogleFonts: this._opts.useGoogleFonts,
|
|
533
|
-
maxZipEntryBytes: this._opts.maxZipEntryBytes,
|
|
534
|
-
resourceLimits: this._opts.resourceLimits,
|
|
535
|
-
debug: this._opts.debug,
|
|
536
|
-
onResourceMetrics: this._opts.onResourceMetrics,
|
|
537
|
-
workerTimeoutMs: this._opts.workerTimeoutMs,
|
|
538
|
-
wasmUrl: this._opts.wasmUrl,
|
|
539
|
-
math: this._opts.math,
|
|
540
|
-
mode: this._mode
|
|
541
|
-
});
|
|
542
|
-
if (t !== this._loadGen) {
|
|
543
|
-
r.destroy();
|
|
544
|
-
return;
|
|
545
|
-
}
|
|
546
|
-
this._doc = r, n?.destroy(), this._currentPage = 0, this._find.invalidate(), await this._render();
|
|
547
|
-
} catch (e) {
|
|
548
|
-
if (t !== this._loadGen) return;
|
|
549
|
-
let n = e instanceof Error ? e : Error(String(e));
|
|
550
|
-
if (this._opts.onError) {
|
|
551
|
-
this._opts.onError(n);
|
|
552
|
-
return;
|
|
553
|
-
}
|
|
554
|
-
throw n;
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
get pageCount() {
|
|
558
|
-
return this._doc?.pageCount ?? 0;
|
|
559
|
-
}
|
|
560
|
-
get currentPage() {
|
|
561
|
-
return this._currentPage;
|
|
562
|
-
}
|
|
563
|
-
get canvasElement() {
|
|
564
|
-
return this._canvas;
|
|
565
|
-
}
|
|
566
|
-
async goToPage(e) {
|
|
567
|
-
this._doc && (this._currentPage = Math.max(0, Math.min(e, this.pageCount - 1)), await this._render());
|
|
568
|
-
}
|
|
569
|
-
async nextPage() {
|
|
570
|
-
await this.goToPage(this._currentPage + 1);
|
|
571
|
-
}
|
|
572
|
-
async prevPage() {
|
|
573
|
-
await this.goToPage(this._currentPage - 1);
|
|
574
|
-
}
|
|
575
|
-
_naturalWidthPx() {
|
|
576
|
-
return !this._doc || this._doc.pageCount === 0 ? 0 : this._doc.pageSize(this._currentPage).widthPt * R;
|
|
577
|
-
}
|
|
578
|
-
_renderWidth() {
|
|
579
|
-
if (this._scale === null) return this._opts.width;
|
|
580
|
-
let e = this._naturalWidthPx();
|
|
581
|
-
return e <= 0 ? this._opts.width : Math.round(e * this._scale);
|
|
582
|
-
}
|
|
583
|
-
getScale() {
|
|
584
|
-
if (this._scale !== null) return this._scale;
|
|
585
|
-
let e = this._naturalWidthPx();
|
|
586
|
-
return e <= 0 ? 1 : this._opts.width && this._opts.width > 0 ? this._opts.width / e : 1;
|
|
587
|
-
}
|
|
588
|
-
_zoomMin() {
|
|
589
|
-
return this._opts.zoomMin ?? .1;
|
|
590
|
-
}
|
|
591
|
-
_zoomMax() {
|
|
592
|
-
return this._opts.zoomMax ?? 4;
|
|
593
|
-
}
|
|
594
|
-
async setScale(e) {
|
|
595
|
-
let t = l(e, this._zoomMin(), this._zoomMax()), n = t !== this.getScale();
|
|
596
|
-
this._scale = t, await this._render(), n && this._opts.onScaleChange?.(t);
|
|
597
|
-
}
|
|
598
|
-
async zoomIn() {
|
|
599
|
-
await this.setScale(x(this.getScale()));
|
|
600
|
-
}
|
|
601
|
-
async zoomOut() {
|
|
602
|
-
await this.setScale(u(this.getScale()));
|
|
603
|
-
}
|
|
604
|
-
async fitWidth() {
|
|
605
|
-
await this._fit("width");
|
|
606
|
-
}
|
|
607
|
-
async fitPage() {
|
|
608
|
-
await this._fit("page");
|
|
609
|
-
}
|
|
610
|
-
async _fit(e) {
|
|
611
|
-
if (!this._doc || this._doc.pageCount === 0) return;
|
|
612
|
-
let t = this._doc.pageSize(this._currentPage), n = this._fitContainer();
|
|
613
|
-
if (!n) return;
|
|
614
|
-
let r = v({
|
|
615
|
-
contentWidth: t.widthPt * R,
|
|
616
|
-
contentHeight: t.heightPt * R,
|
|
617
|
-
containerWidth: n.clientWidth,
|
|
618
|
-
containerHeight: n.clientHeight
|
|
619
|
-
}, e);
|
|
620
|
-
r <= 0 || await this.setScale(r);
|
|
621
|
-
}
|
|
622
|
-
_fitContainer() {
|
|
623
|
-
return this._opts.container ?? this._wrapper.parentElement ?? null;
|
|
624
|
-
}
|
|
625
|
-
async findText(e, t = {}) {
|
|
626
|
-
if (!this._doc) return [];
|
|
627
|
-
let n = await this._find.find(e, t);
|
|
628
|
-
return this._redrawHighlights(), n;
|
|
629
|
-
}
|
|
630
|
-
async findNext() {
|
|
631
|
-
return this._activateMatch(this._find.next());
|
|
632
|
-
}
|
|
633
|
-
async findPrev() {
|
|
634
|
-
return this._activateMatch(this._find.prev());
|
|
635
|
-
}
|
|
636
|
-
clearFind() {
|
|
637
|
-
this._find.invalidate(), this._redrawHighlights();
|
|
638
|
-
}
|
|
639
|
-
async _activateMatch(e) {
|
|
640
|
-
return e ? (e.location.page === this._currentPage ? this._redrawHighlights() : await this.goToPage(e.location.page), e) : (this._redrawHighlights(), null);
|
|
641
|
-
}
|
|
642
|
-
_redrawHighlights() {
|
|
643
|
-
let e = this._find.pageRuns(this._currentPage) ?? [];
|
|
644
|
-
this._buildHighlightLayer(e);
|
|
645
|
-
}
|
|
646
|
-
async getResourceMetrics() {
|
|
647
|
-
if (!this._doc) throw Error("Document not loaded");
|
|
648
|
-
return await this._doc.getResourceMetrics();
|
|
649
|
-
}
|
|
650
|
-
destroy() {
|
|
651
|
-
if (this._destroyed = !0, this._loadGen++, this._doc?.destroy(), this._doc = null, this._find.invalidate(), this._originalParent) {
|
|
652
|
-
let e = this._originalNextSibling && this._originalNextSibling.parentNode === this._originalParent ? this._originalNextSibling : null;
|
|
653
|
-
this._originalParent.insertBefore(this._canvas, e);
|
|
654
|
-
} else this._canvas.parentNode && this._canvas.parentNode.removeChild(this._canvas);
|
|
655
|
-
this._canvas.style.display = this._originalDisplay, this._wrapper.remove();
|
|
656
|
-
}
|
|
657
|
-
async _render() {
|
|
658
|
-
try {
|
|
659
|
-
await this._renderPage();
|
|
660
|
-
} catch (e) {
|
|
661
|
-
this._reportRenderError(e);
|
|
662
|
-
}
|
|
663
|
-
}
|
|
664
|
-
_reportRenderError(e) {
|
|
665
|
-
if (this._destroyed) return;
|
|
666
|
-
let t = e instanceof Error ? e : Error(String(e));
|
|
667
|
-
this._opts.onError ? this._opts.onError(t) : console.error("[ooxml] DocxViewer render failed:", t);
|
|
668
|
-
}
|
|
669
|
-
async _renderPage() {
|
|
670
|
-
if (!this._doc) return;
|
|
671
|
-
let e = this._mode === "worker", t = this._renderWidth(), n = [], r = (e) => n.push(e);
|
|
672
|
-
if (e) {
|
|
673
|
-
let e = this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1), n = await this._doc.renderPageToBitmap(this._currentPage, {
|
|
674
|
-
width: t,
|
|
675
|
-
dpr: this._opts.dpr,
|
|
676
|
-
defaultTextColor: this._opts.defaultTextColor,
|
|
677
|
-
showTrackChanges: this._opts.showTrackChanges,
|
|
678
|
-
currentDate: this._opts.currentDate,
|
|
679
|
-
onTextRun: r
|
|
680
|
-
});
|
|
681
|
-
this._canvas.width = n.width, this._canvas.height = n.height, this._canvas.style.width = `${Math.round(n.width / e)}px`, this._canvas.style.height = `${Math.round(n.height / e)}px`, this._bitmapCtx?.transferFromImageBitmap(n);
|
|
682
|
-
} else await this._doc.renderPage(this._canvas, this._currentPage, {
|
|
683
|
-
...this._opts,
|
|
684
|
-
width: t,
|
|
685
|
-
onTextRun: r
|
|
686
|
-
});
|
|
687
|
-
this._textLayer && this._buildTextLayer(this._textLayer, n), this._find.setPageRuns(this._currentPage, n), this._buildHighlightLayer(n), this._opts.onPageChange?.(this._currentPage, this.pageCount);
|
|
688
|
-
}
|
|
689
|
-
_buildHighlightLayer(e) {
|
|
690
|
-
let t = this._highlightLayer;
|
|
691
|
-
if (!t) return;
|
|
692
|
-
let { width: n, height: r } = this._canvasCssPx();
|
|
693
|
-
Y(t, e, this._find.pageHighlights(this._currentPage), n, r, (e) => this._measureForFont(e), this._opts.findHighlightColors);
|
|
694
|
-
}
|
|
695
|
-
_canvasCssPx() {
|
|
696
|
-
return {
|
|
697
|
-
width: parseFloat(this._canvas.style.width) || this._canvas.width,
|
|
698
|
-
height: parseFloat(this._canvas.style.height) || this._canvas.height
|
|
699
|
-
};
|
|
700
|
-
}
|
|
701
|
-
_measureForFont(e) {
|
|
702
|
-
this._measureCtx ||= document.createElement("canvas").getContext("2d");
|
|
703
|
-
let t = this._measureCtx;
|
|
704
|
-
return t ? (t.font = e, (e) => t.measureText(e).width) : (e) => e.length;
|
|
705
|
-
}
|
|
706
|
-
async _collectPageRuns(e) {
|
|
707
|
-
return this._doc ? this._doc.collectPageRuns(e, {
|
|
708
|
-
width: this._renderWidth(),
|
|
709
|
-
dpr: this._opts.dpr,
|
|
710
|
-
defaultTextColor: this._opts.defaultTextColor,
|
|
711
|
-
showTrackChanges: this._opts.showTrackChanges,
|
|
712
|
-
currentDate: this._opts.currentDate
|
|
713
|
-
}) : [];
|
|
714
|
-
}
|
|
715
|
-
_buildTextLayer(e, t) {
|
|
716
|
-
let { width: n, height: r } = this._canvasCssPx();
|
|
717
|
-
J(e, t, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e));
|
|
718
|
-
}
|
|
719
|
-
_hyperlinkHandler() {
|
|
720
|
-
return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
|
|
721
|
-
if (e.kind === "external") {
|
|
722
|
-
H(e.url);
|
|
723
|
-
return;
|
|
724
|
-
}
|
|
725
|
-
let t = this._doc?.getBookmarkPage(e.ref);
|
|
726
|
-
t !== void 0 && this.goToPage(t);
|
|
727
|
-
});
|
|
728
|
-
}
|
|
729
|
-
}, Se = 150, Ce = "0 1px 3px rgba(0,0,0,0.2)", Q = class {
|
|
730
|
-
_doc = null;
|
|
731
|
-
_injected;
|
|
732
|
-
_opts;
|
|
733
|
-
_container;
|
|
734
|
-
_wrapper;
|
|
735
|
-
_scrollHost;
|
|
736
|
-
_spacer;
|
|
737
|
-
_mode;
|
|
738
|
-
_scale = 1;
|
|
739
|
-
_scaleEstablished = !1;
|
|
740
|
-
_pendingScale = null;
|
|
741
|
-
_slots = /* @__PURE__ */ new Map();
|
|
742
|
-
_free = [];
|
|
743
|
-
_heights = [];
|
|
744
|
-
_lastRange = null;
|
|
745
|
-
_lastTopIndex = -1;
|
|
746
|
-
_scrollListener = null;
|
|
747
|
-
_destroyed = !1;
|
|
748
|
-
_measureCtx;
|
|
749
|
-
_loadGen = 0;
|
|
750
|
-
_bitmapInFlight = /* @__PURE__ */ new Set();
|
|
751
|
-
_renderEpoch = 0;
|
|
752
|
-
_settleTimer = null;
|
|
753
|
-
_wheelListener = null;
|
|
754
|
-
_pendingZoomAnchor = null;
|
|
755
|
-
_resizeObserver = null;
|
|
756
|
-
_prevBase = 0;
|
|
757
|
-
_lastFitWidth = 0;
|
|
758
|
-
_pageShadow;
|
|
759
|
-
_find = new X(() => this.pageCount, (e) => this._collectPageRuns(e));
|
|
760
|
-
_findActive = !1;
|
|
761
|
-
constructor(e, t = {}) {
|
|
762
|
-
if (e.tagName === "CANVAS") throw Error("DocxScrollViewer takes a container element (e.g. a <div>), not a <canvas> — the viewer creates and manages its own canvases. Pass a block container; for the single-page canvas API use DocxViewer.");
|
|
763
|
-
if (this._container = e, this._opts = t, this._pageShadow = t.pageShadow ?? Ce, this._injected = !!t.document, this._injected) {
|
|
764
|
-
let e = t.document;
|
|
765
|
-
if (t.mode !== void 0 && t.mode !== e.mode) throw Error(`DocxScrollViewer: opts.mode='${t.mode}' conflicts with the injected engine's mode='${e.mode}'. Omit opts.mode when injecting an engine — the engine owns its render mode.`);
|
|
766
|
-
this._doc = e, this._mode = e.mode;
|
|
767
|
-
} else this._mode = t.mode ?? "main";
|
|
768
|
-
this._wrapper = document.createElement("div"), this._wrapper.style.cssText = "position:relative;width:100%;height:100%;overflow:hidden;", this._scrollHost = document.createElement("div"), this._scrollHost.style.cssText = "position:absolute;inset:0;overflow:auto;", this._scrollHost.style.scrollbarGutter = "stable", t.background && (this._scrollHost.style.background = t.background), this._spacer = document.createElement("div"), this._spacer.style.cssText = "position:absolute;top:0;left:0;width:1px;height:0;pointer-events:none;", this._scrollHost.appendChild(this._spacer), this._wrapper.appendChild(this._scrollHost), this._container.appendChild(this._wrapper), this._scrollListener = () => this._onScroll(), this._scrollHost.addEventListener("scroll", this._scrollListener), this._opts.enableZoom !== !1 && (this._wheelListener = (e) => {
|
|
769
|
-
if (!(e.ctrlKey || e.metaKey) || (e.preventDefault(), e.deltaY === 0)) return;
|
|
770
|
-
let t = this._scrollHost.getBoundingClientRect(), n = e.clientX - t.left, r = e.clientY - t.top;
|
|
771
|
-
this._pendingZoomAnchor = Number.isFinite(n) && Number.isFinite(r) ? {
|
|
772
|
-
x: n,
|
|
773
|
-
y: r
|
|
774
|
-
} : null, this.setScale(te(this._scale, e.deltaY));
|
|
775
|
-
}, this._scrollHost.addEventListener("wheel", this._wheelListener, { passive: !1 })), typeof ResizeObserver < "u" && (this._resizeObserver = new ResizeObserver(() => this._onResize()), this._resizeObserver.observe(this._container)), this._injected && this.relayout();
|
|
776
|
-
}
|
|
777
|
-
async load(e) {
|
|
778
|
-
if (this._injected) throw Error("DocxScrollViewer.load() is unsupported when an engine is injected via opts.document; the injected engine is already loaded.");
|
|
779
|
-
let t = ++this._loadGen, n = this._doc;
|
|
780
|
-
try {
|
|
781
|
-
let r = await K.load(e, {
|
|
782
|
-
useGoogleFonts: this._opts.useGoogleFonts,
|
|
783
|
-
maxZipEntryBytes: this._opts.maxZipEntryBytes,
|
|
784
|
-
resourceLimits: this._opts.resourceLimits,
|
|
785
|
-
debug: this._opts.debug,
|
|
786
|
-
onResourceMetrics: this._opts.onResourceMetrics,
|
|
787
|
-
workerTimeoutMs: this._opts.workerTimeoutMs,
|
|
788
|
-
wasmUrl: this._opts.wasmUrl,
|
|
789
|
-
math: this._opts.math,
|
|
790
|
-
mode: this._mode
|
|
791
|
-
});
|
|
792
|
-
if (t !== this._loadGen) {
|
|
793
|
-
r.destroy();
|
|
794
|
-
return;
|
|
795
|
-
}
|
|
796
|
-
if (this._doc = r, n?.destroy(), this._find.invalidate(), this._findActive = !1, n) {
|
|
797
|
-
for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
|
|
798
|
-
this._lastTopIndex = -1;
|
|
799
|
-
}
|
|
800
|
-
this.relayout();
|
|
801
|
-
} catch (e) {
|
|
802
|
-
if (t !== this._loadGen) return;
|
|
803
|
-
let n = e instanceof Error ? e : Error(String(e));
|
|
804
|
-
if (this._opts.onError) {
|
|
805
|
-
this._opts.onError(n);
|
|
806
|
-
return;
|
|
807
|
-
}
|
|
808
|
-
throw n;
|
|
809
|
-
}
|
|
810
|
-
}
|
|
811
|
-
get pageCount() {
|
|
812
|
-
return this._doc?.pageCount ?? 0;
|
|
813
|
-
}
|
|
814
|
-
_pageWidthPx(e) {
|
|
815
|
-
return this._doc.pageSize(e).widthPt * R * this._scale;
|
|
816
|
-
}
|
|
817
|
-
_pageHeightPx(e) {
|
|
818
|
-
return this._doc.pageSize(e).heightPt * R * this._scale;
|
|
819
|
-
}
|
|
820
|
-
_fitWidthPx() {
|
|
821
|
-
if (this._opts.width && this._opts.width > 0) return this._opts.width;
|
|
822
|
-
let e = this._scrollHost.clientWidth || this._container.clientWidth;
|
|
823
|
-
if (e <= 0) return 0;
|
|
824
|
-
let { left: t, right: n } = this._padH(), r = e - t - n;
|
|
825
|
-
return r > 0 ? r : 0;
|
|
826
|
-
}
|
|
827
|
-
_baseScale() {
|
|
828
|
-
if (!this._doc || this._doc.pageCount === 0) return 0;
|
|
829
|
-
let e = this._fitWidthPx();
|
|
830
|
-
if (e <= 0) return 0;
|
|
831
|
-
let t = this._doc.pageSize(0).widthPt;
|
|
832
|
-
return t <= 0 ? 0 : e / (t * R);
|
|
833
|
-
}
|
|
834
|
-
relayout() {
|
|
835
|
-
if (this._doc) {
|
|
836
|
-
if (!this._scaleEstablished) {
|
|
837
|
-
let e = this._baseScale();
|
|
838
|
-
if (e > 0) {
|
|
839
|
-
if (this._scale = e, this._prevBase = e, this._lastFitWidth = this._fitWidthPx(), this._scaleEstablished = !0, this._pendingScale !== null) {
|
|
840
|
-
let e = this._pendingScale;
|
|
841
|
-
this._pendingScale = null, e !== this._scale && (this._scale = e, this._opts.onScaleChange?.(e));
|
|
842
|
-
}
|
|
843
|
-
} else return;
|
|
844
|
-
}
|
|
845
|
-
this._recomputeHeights(), this._syncSpacer(), this._mountVisible();
|
|
846
|
-
}
|
|
847
|
-
}
|
|
848
|
-
_recomputeHeights() {
|
|
849
|
-
let e = this._doc.pageCount, t = Array(e);
|
|
850
|
-
for (let n = 0; n < e; n++) t[n] = this._pageHeightPx(n);
|
|
851
|
-
this._heights = t;
|
|
852
|
-
}
|
|
853
|
-
_gap() {
|
|
854
|
-
return this._opts.gap ?? 16;
|
|
855
|
-
}
|
|
856
|
-
_overscan() {
|
|
857
|
-
return this._opts.overscan ?? 1;
|
|
858
|
-
}
|
|
859
|
-
_pad() {
|
|
860
|
-
let e = this._gap();
|
|
861
|
-
return {
|
|
862
|
-
leading: this._opts.paddingTop ?? e,
|
|
863
|
-
trailing: this._opts.paddingBottom ?? e
|
|
864
|
-
};
|
|
865
|
-
}
|
|
866
|
-
_padH() {
|
|
867
|
-
let e = this._gap();
|
|
868
|
-
return {
|
|
869
|
-
left: this._opts.paddingLeft ?? e,
|
|
870
|
-
right: this._opts.paddingRight ?? e
|
|
871
|
-
};
|
|
872
|
-
}
|
|
873
|
-
_pageIndexAtOffset(e, t) {
|
|
874
|
-
let { offsets: n } = e, r = 0, i = n.length - 1, a = 0;
|
|
875
|
-
for (; r <= i;) {
|
|
876
|
-
let e = r + i >> 1;
|
|
877
|
-
n[e] <= t ? (a = e, r = e + 1) : i = e - 1;
|
|
878
|
-
}
|
|
879
|
-
return a;
|
|
880
|
-
}
|
|
881
|
-
_range() {
|
|
882
|
-
return B(this._heights, this._gap(), this._scrollHost.scrollTop, this._scrollHost.clientHeight, this._overscan(), this._pad());
|
|
883
|
-
}
|
|
884
|
-
_syncSpacer() {
|
|
885
|
-
let e = this._range();
|
|
886
|
-
this._lastRange = e, this._spacer.style.height = `${e.totalHeight}px`, this._syncSpacerWidth();
|
|
887
|
-
}
|
|
888
|
-
_syncSpacerWidth() {
|
|
889
|
-
let { left: e, right: t } = this._padH(), n = 0;
|
|
890
|
-
for (let e = 0; e < this._heights.length; e++) {
|
|
891
|
-
let t = this._pageWidthPx(e);
|
|
892
|
-
t > n && (n = t);
|
|
893
|
-
}
|
|
894
|
-
this._spacer.style.width = `${n + e + t}px`;
|
|
895
|
-
}
|
|
896
|
-
_onScroll() {
|
|
897
|
-
!this._doc || !this._scaleEstablished || this._mountVisible();
|
|
898
|
-
}
|
|
899
|
-
_mountVisible() {
|
|
900
|
-
if (!this._doc || this._doc.pageCount === 0) return;
|
|
901
|
-
let e = this._range();
|
|
902
|
-
this._lastRange = e;
|
|
903
|
-
for (let [t, n] of [...this._slots]) (t < e.start || t > e.end) && this._recycleSlot(t, n);
|
|
904
|
-
for (let t = e.start; t <= e.end; t++) if (this._slots.has(t)) this._positionSlot(this._slots.get(t), t, e);
|
|
905
|
-
else {
|
|
906
|
-
let n = this._acquireSlot();
|
|
907
|
-
this._positionSlot(n, t, e), this._slots.set(t, n), this._renderSlot(t, n);
|
|
908
|
-
}
|
|
909
|
-
e.topIndex !== this._lastTopIndex && (this._lastTopIndex = e.topIndex, this._opts.onVisiblePageChange?.(e.topIndex, this._doc.pageCount));
|
|
910
|
-
}
|
|
911
|
-
_applyPageShadow(e) {
|
|
912
|
-
this._pageShadow !== !1 && (e.style.boxShadow = this._pageShadow);
|
|
913
|
-
}
|
|
914
|
-
_acquireSlot() {
|
|
915
|
-
let e = this._free.pop();
|
|
916
|
-
if (e) return this._scrollHost.appendChild(e.wrapper), e;
|
|
917
|
-
let t = document.createElement("div");
|
|
918
|
-
t.style.cssText = "position:absolute;";
|
|
919
|
-
let n = document.createElement("canvas");
|
|
920
|
-
n.style.cssText = "display:block;background:#fff;", this._applyPageShadow(n), t.appendChild(n);
|
|
921
|
-
let r = null;
|
|
922
|
-
this._opts.enableTextSelection && (r = document.createElement("div"), r.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;user-select:text;-webkit-user-select:text;", t.appendChild(r));
|
|
923
|
-
let i = document.createElement("div");
|
|
924
|
-
return i.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;", t.appendChild(i), this._scrollHost.appendChild(t), {
|
|
925
|
-
wrapper: t,
|
|
926
|
-
canvas: n,
|
|
927
|
-
textLayer: r,
|
|
928
|
-
highlightLayer: i,
|
|
929
|
-
renderedPage: -1,
|
|
930
|
-
renderedScale: -1,
|
|
931
|
-
bitmap: null,
|
|
932
|
-
bitmapCtx: null
|
|
933
|
-
};
|
|
934
|
-
}
|
|
935
|
-
_recycleSlot(e, t) {
|
|
936
|
-
this._slots.delete(e), t.bitmap &&= (t.bitmap.close(), null), t.textLayer && (t.textLayer.innerHTML = "", t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = ""), t.highlightLayer.innerHTML = "", t.highlightLayer.style.transform = "", t.highlightLayer.style.transformOrigin = "", t.renderedPage = -1, t.renderedScale = -1, t.wrapper.remove(), this._free.push(t);
|
|
937
|
-
}
|
|
938
|
-
_positionSlot(e, t, n) {
|
|
939
|
-
e.wrapper.style.top = `${n.offsets[t]}px`;
|
|
940
|
-
let r = this._pageWidthPx(t), i = this._pageHeightPx(t);
|
|
941
|
-
e.wrapper.style.width = `${r}px`, e.wrapper.style.height = `${i}px`;
|
|
942
|
-
let { left: a } = this._padH(), o = this._scrollHost.clientWidth;
|
|
943
|
-
e.wrapper.style.left = `${Math.max(a, (o - r) / 2)}px`;
|
|
944
|
-
}
|
|
945
|
-
_dpr() {
|
|
946
|
-
return this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1);
|
|
947
|
-
}
|
|
948
|
-
_renderSlot(e, t) {
|
|
949
|
-
if (!this._doc || t.renderedPage === e) return;
|
|
950
|
-
t.renderedPage = e;
|
|
951
|
-
let n = this._dpr(), r = this._pageWidthPx(e), i = this._renderEpoch, a = this._scale;
|
|
952
|
-
if (this._mode === "worker") {
|
|
953
|
-
this._renderSlotBitmap(e, t, r, n, a);
|
|
954
|
-
return;
|
|
955
|
-
}
|
|
956
|
-
let o = [], s = !!this._opts.enableTextSelection && !!t.textLayer, c = s || this._findActive, l = c ? (e) => o.push(e) : void 0;
|
|
957
|
-
this._doc.renderPage(t.canvas, e, {
|
|
958
|
-
width: r,
|
|
959
|
-
dpr: n,
|
|
960
|
-
defaultTextColor: this._opts.defaultTextColor,
|
|
961
|
-
showTrackChanges: this._opts.showTrackChanges,
|
|
962
|
-
onTextRun: l
|
|
963
|
-
}).then(() => {
|
|
964
|
-
if (!(i !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e)) {
|
|
965
|
-
if (t.renderedScale = a, s && t.textLayer) {
|
|
966
|
-
let { width: e, height: n } = this._canvasCssPx(t.canvas);
|
|
967
|
-
J(t.textLayer, o, e, n, this._hyperlinkHandler(), (e) => this._measureForFont(e));
|
|
968
|
-
}
|
|
969
|
-
c && this._refreshFindRuns(e, o), this._redrawSlotHighlights(e, t);
|
|
970
|
-
}
|
|
971
|
-
}).catch((e) => {
|
|
972
|
-
this._reportRenderError(e);
|
|
973
|
-
});
|
|
974
|
-
}
|
|
975
|
-
_hyperlinkHandler() {
|
|
976
|
-
return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
|
|
977
|
-
if (e.kind === "external") {
|
|
978
|
-
H(e.url);
|
|
979
|
-
return;
|
|
980
|
-
}
|
|
981
|
-
let t = this._doc?.getBookmarkPage(e.ref);
|
|
982
|
-
t !== void 0 && this.scrollToPage(t);
|
|
983
|
-
});
|
|
984
|
-
}
|
|
985
|
-
_measureForFont(e) {
|
|
986
|
-
this._measureCtx === void 0 && (this._measureCtx = document.createElement("canvas").getContext("2d"));
|
|
987
|
-
let t = this._measureCtx;
|
|
988
|
-
return !t || typeof t.measureText != "function" ? (e) => e.length : (t.font = e, (e) => t.measureText(e).width);
|
|
989
|
-
}
|
|
990
|
-
_canvasCssPx(e) {
|
|
991
|
-
return {
|
|
992
|
-
width: parseFloat(e.style.width) || e.width,
|
|
993
|
-
height: parseFloat(e.style.height) || e.height
|
|
994
|
-
};
|
|
995
|
-
}
|
|
996
|
-
_reportRenderError(e) {
|
|
997
|
-
if (this._destroyed) return;
|
|
998
|
-
let t = e instanceof Error ? e : Error(String(e));
|
|
999
|
-
this._opts.onError ? this._opts.onError(t) : console.error("[ooxml] DocxScrollViewer render failed:", t);
|
|
1000
|
-
}
|
|
1001
|
-
async _renderSlotBitmap(e, t, n, r, i) {
|
|
1002
|
-
if (this._bitmapInFlight.has(e) || this._slots.get(e) !== t) return;
|
|
1003
|
-
let a = this._renderEpoch;
|
|
1004
|
-
this._bitmapInFlight.add(e);
|
|
1005
|
-
let o = !1;
|
|
1006
|
-
t.bitmapCtx ||= t.canvas.getContext("bitmaprenderer");
|
|
1007
|
-
let s = !!this._opts.enableTextSelection && !!t.textLayer, c = s || this._findActive, l = [];
|
|
1008
|
-
try {
|
|
1009
|
-
let u = await this._doc.renderPageToBitmap(e, {
|
|
1010
|
-
width: n,
|
|
1011
|
-
dpr: r,
|
|
1012
|
-
defaultTextColor: this._opts.defaultTextColor,
|
|
1013
|
-
showTrackChanges: this._opts.showTrackChanges,
|
|
1014
|
-
onTextRun: c ? (e) => l.push(e) : void 0
|
|
1015
|
-
});
|
|
1016
|
-
if (a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
|
|
1017
|
-
u.close();
|
|
1018
|
-
return;
|
|
1019
|
-
}
|
|
1020
|
-
if (t.bitmap && t.bitmap.close(), t.bitmap = u, t.canvas.width = u.width, t.canvas.height = u.height, t.canvas.style.width = `${Math.round(u.width / r)}px`, t.canvas.style.height = `${Math.round(u.height / r)}px`, t.bitmapCtx?.transferFromImageBitmap(u), t.bitmap = null, t.renderedScale = i, t.textLayer && (t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = "", s)) {
|
|
1021
|
-
let { width: e, height: n } = this._canvasCssPx(t.canvas);
|
|
1022
|
-
J(t.textLayer, l, e, n, this._hyperlinkHandler(), (e) => this._measureForFont(e));
|
|
1023
|
-
}
|
|
1024
|
-
c && this._refreshFindRuns(e, l), this._redrawSlotHighlights(e, t), o = !0;
|
|
1025
|
-
} catch (e) {
|
|
1026
|
-
this._reportRenderError(e);
|
|
1027
|
-
} finally {
|
|
1028
|
-
this._bitmapInFlight.delete(e);
|
|
1029
|
-
let n = this._slots.get(e);
|
|
1030
|
-
!o && n && (n !== t || a !== this._renderEpoch) && !this._bitmapInFlight.has(e) && !this._destroyed && this._renderSlotBitmap(e, n, this._pageWidthPx(e), this._dpr(), this._scale);
|
|
1031
|
-
}
|
|
1032
|
-
}
|
|
1033
|
-
setScale(e) {
|
|
1034
|
-
let t = this._opts.zoomMin ?? .1, n = this._opts.zoomMax ?? 4, r = Math.min(n, Math.max(t, e)), i = this._pendingZoomAnchor;
|
|
1035
|
-
if (this._pendingZoomAnchor = null, !this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) {
|
|
1036
|
-
this._pendingScale = r;
|
|
1037
|
-
return;
|
|
1038
|
-
}
|
|
1039
|
-
if (r === this._scale) return;
|
|
1040
|
-
let a = this._scale, o = i ? i.y : 0, s = this._range(), c = this._scrollHost.scrollTop + o, l = this._pageIndexAtOffset(s, c), u = this._heights[l] || 0, d = u > 0 ? (c - s.offsets[l]) / u : 0;
|
|
1041
|
-
d = Math.min(1, Math.max(0, d));
|
|
1042
|
-
let f = this._padH().left, p = this._scrollHost.scrollLeft || 0;
|
|
1043
|
-
this._renderEpoch++, this._scale = r, this._recomputeHeights();
|
|
1044
|
-
let m = B(this._heights, this._gap(), 0, this._scrollHost.clientHeight, this._overscan(), this._pad());
|
|
1045
|
-
this._spacer.style.height = `${m.totalHeight}px`, this._syncSpacerWidth();
|
|
1046
|
-
let g = Math.max(0, m.totalHeight - this._scrollHost.clientHeight), _ = (m.offsets[l] ?? 0) + d * (this._heights[l] || 0);
|
|
1047
|
-
if (this._scrollHost.scrollTop = Math.min(g, Math.max(0, _ - o)), i) {
|
|
1048
|
-
let e = Math.max(0, (this._spacer.offsetWidth || 0) - this._scrollHost.clientWidth);
|
|
1049
|
-
this._scrollHost.scrollLeft = h(p, i.x - f, a, r, { maxScroll: e });
|
|
1050
|
-
}
|
|
1051
|
-
this._previewVisible(), this._scheduleSettle(), this._opts.onScaleChange?.(r);
|
|
1052
|
-
}
|
|
1053
|
-
getScale() {
|
|
1054
|
-
return this._scaleEstablished ? this._scale : this._pendingScale ?? 1;
|
|
1055
|
-
}
|
|
1056
|
-
zoomIn() {
|
|
1057
|
-
this.setScale(x(this.getScale()));
|
|
1058
|
-
}
|
|
1059
|
-
zoomOut() {
|
|
1060
|
-
this.setScale(u(this.getScale()));
|
|
1061
|
-
}
|
|
1062
|
-
fitWidth() {
|
|
1063
|
-
this._fit("width");
|
|
1064
|
-
}
|
|
1065
|
-
fitPage() {
|
|
1066
|
-
this._fit("page");
|
|
1067
|
-
}
|
|
1068
|
-
_fit(e) {
|
|
1069
|
-
if (!this._doc || this._doc.pageCount === 0) return;
|
|
1070
|
-
let t = this._doc.pageSize(0), n = v({
|
|
1071
|
-
contentWidth: t.widthPt * R,
|
|
1072
|
-
contentHeight: t.heightPt * R,
|
|
1073
|
-
containerWidth: this._fitWidthPx(),
|
|
1074
|
-
containerHeight: this._scrollHost.clientHeight
|
|
1075
|
-
}, e);
|
|
1076
|
-
n <= 0 || this.setScale(n);
|
|
1077
|
-
}
|
|
1078
|
-
_previewVisible() {
|
|
1079
|
-
if (!this._doc || this._doc.pageCount === 0) return;
|
|
1080
|
-
let e = this._range();
|
|
1081
|
-
this._lastRange = e;
|
|
1082
|
-
for (let [t, n] of [...this._slots]) (t < e.start || t > e.end) && this._recycleSlot(t, n);
|
|
1083
|
-
for (let t = e.start; t <= e.end; t++) {
|
|
1084
|
-
let n = this._slots.get(t);
|
|
1085
|
-
if (n) this._previewSlot(n, t, e);
|
|
1086
|
-
else {
|
|
1087
|
-
let n = this._acquireSlot();
|
|
1088
|
-
this._positionSlot(n, t, e), this._slots.set(t, n), this._renderSlot(t, n);
|
|
1089
|
-
}
|
|
1090
|
-
}
|
|
1091
|
-
e.topIndex !== this._lastTopIndex && (this._lastTopIndex = e.topIndex, this._opts.onVisiblePageChange?.(e.topIndex, this._doc.pageCount));
|
|
1092
|
-
}
|
|
1093
|
-
_previewSlot(e, t, n) {
|
|
1094
|
-
if (this._positionSlot(e, t, n), e.canvas.style.width = `${this._pageWidthPx(t)}px`, e.canvas.style.height = `${this._pageHeightPx(t)}px`, e.textLayer && e.renderedScale > 0) {
|
|
1095
|
-
let t = this._scale / e.renderedScale;
|
|
1096
|
-
e.textLayer.style.transformOrigin = "0 0", e.textLayer.style.transform = `scale(${t})`;
|
|
1097
|
-
}
|
|
1098
|
-
}
|
|
1099
|
-
_scheduleSettle() {
|
|
1100
|
-
this._settleTimer !== null && clearTimeout(this._settleTimer), this._settleTimer = setTimeout(() => {
|
|
1101
|
-
this._settleTimer = null, this._settleRender();
|
|
1102
|
-
}, Se);
|
|
1103
|
-
}
|
|
1104
|
-
_settleRender() {
|
|
1105
|
-
if (!(this._destroyed || !this._doc || this._doc.pageCount === 0)) for (let [e, t] of [...this._slots]) t.renderedScale !== this._scale && this._settleSlot(e, t);
|
|
1106
|
-
}
|
|
1107
|
-
_settleSlot(e, t) {
|
|
1108
|
-
if (!this._doc) return;
|
|
1109
|
-
let n = this._dpr(), r = this._pageWidthPx(e), i = this._scale, a = this._renderEpoch;
|
|
1110
|
-
if (this._mode === "worker") {
|
|
1111
|
-
this._renderSlotBitmap(e, t, r, n, i);
|
|
1112
|
-
return;
|
|
1113
|
-
}
|
|
1114
|
-
let o = document.createElement("canvas");
|
|
1115
|
-
o.style.cssText = "display:block;background:#fff;", this._applyPageShadow(o);
|
|
1116
|
-
let s = [], c = !!this._opts.enableTextSelection && !!t.textLayer, l = c || this._findActive, u = l ? (e) => s.push(e) : void 0;
|
|
1117
|
-
this._doc.renderPage(o, e, {
|
|
1118
|
-
width: r,
|
|
1119
|
-
dpr: n,
|
|
1120
|
-
defaultTextColor: this._opts.defaultTextColor,
|
|
1121
|
-
showTrackChanges: this._opts.showTrackChanges,
|
|
1122
|
-
onTextRun: u
|
|
1123
|
-
}).then(() => {
|
|
1124
|
-
if (a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) return;
|
|
1125
|
-
let n = t.canvas;
|
|
1126
|
-
if (t.wrapper.insertBefore(o, n), n.remove(), t.canvas = o, t.bitmapCtx = null, t.renderedScale = i, t.textLayer && (t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = "", c)) {
|
|
1127
|
-
let { width: e, height: n } = this._canvasCssPx(o);
|
|
1128
|
-
J(t.textLayer, s, e, n, this._hyperlinkHandler(), (e) => this._measureForFont(e));
|
|
1129
|
-
}
|
|
1130
|
-
l && this._refreshFindRuns(e, s), this._redrawSlotHighlights(e, t);
|
|
1131
|
-
}).catch((e) => {
|
|
1132
|
-
this._reportRenderError(e);
|
|
1133
|
-
});
|
|
1134
|
-
}
|
|
1135
|
-
scrollToPage(e, t) {
|
|
1136
|
-
if (!this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) return;
|
|
1137
|
-
let n = Math.max(0, Math.min(e, this._doc.pageCount - 1)), r = B(this._heights, this._gap(), 0, this._scrollHost.clientHeight, this._overscan(), this._pad()), i = r.offsets[n] ?? 0, a = Math.max(0, r.totalHeight - this._scrollHost.clientHeight), o = Math.min(a, Math.max(0, i)), s = this._scrollHost;
|
|
1138
|
-
typeof s.scrollTo == "function" ? s.scrollTo({
|
|
1139
|
-
top: o,
|
|
1140
|
-
behavior: t?.behavior ?? "auto"
|
|
1141
|
-
}) : this._scrollHost.scrollTop = o, this._mountVisible();
|
|
1142
|
-
}
|
|
1143
|
-
async findText(e, t = {}) {
|
|
1144
|
-
if (!this._doc) return [];
|
|
1145
|
-
this._findActive = e.length > 0;
|
|
1146
|
-
let n = await this._find.find(e, t);
|
|
1147
|
-
return this._redrawHighlights(), n;
|
|
1148
|
-
}
|
|
1149
|
-
async findNext() {
|
|
1150
|
-
return this._activateMatch(this._find.next());
|
|
1151
|
-
}
|
|
1152
|
-
async findPrev() {
|
|
1153
|
-
return this._activateMatch(this._find.prev());
|
|
1154
|
-
}
|
|
1155
|
-
clearFind() {
|
|
1156
|
-
this._findActive = !1, this._find.invalidate(), this._redrawHighlights();
|
|
1157
|
-
}
|
|
1158
|
-
async _activateMatch(e) {
|
|
1159
|
-
return e && this.scrollToPage(e.location.page), this._redrawHighlights(), e;
|
|
1160
|
-
}
|
|
1161
|
-
async _collectPageRuns(e) {
|
|
1162
|
-
return this._doc ? this._doc.collectPageRuns(e, {
|
|
1163
|
-
width: this._pageWidthPx(e),
|
|
1164
|
-
defaultTextColor: this._opts.defaultTextColor,
|
|
1165
|
-
showTrackChanges: this._opts.showTrackChanges
|
|
1166
|
-
}) : [];
|
|
1167
|
-
}
|
|
1168
|
-
_redrawHighlights() {
|
|
1169
|
-
for (let [e, t] of this._slots) this._redrawSlotHighlights(e, t);
|
|
1170
|
-
}
|
|
1171
|
-
_refreshFindRuns(e, t) {
|
|
1172
|
-
this._findActive && this._find.setPageRuns(e, t);
|
|
1173
|
-
}
|
|
1174
|
-
_redrawSlotHighlights(e, t) {
|
|
1175
|
-
if (!this._findActive) {
|
|
1176
|
-
t.highlightLayer.innerHTML = "";
|
|
1177
|
-
return;
|
|
1178
|
-
}
|
|
1179
|
-
let n = this._find.pageRuns(e);
|
|
1180
|
-
if (!n) {
|
|
1181
|
-
t.highlightLayer.innerHTML = "";
|
|
1182
|
-
return;
|
|
1183
|
-
}
|
|
1184
|
-
Y(t.highlightLayer, n, this._find.pageHighlights(e), this._pageWidthPx(e), this._pageHeightPx(e), (e) => this._measureForFont(e), this._opts.findHighlightColors);
|
|
1185
|
-
}
|
|
1186
|
-
_onResize() {
|
|
1187
|
-
if (!this._doc || this._doc.pageCount === 0) return;
|
|
1188
|
-
if (!this._scaleEstablished) {
|
|
1189
|
-
this.relayout();
|
|
1190
|
-
return;
|
|
1191
|
-
}
|
|
1192
|
-
if (this._opts.refitOnResize === !1) {
|
|
1193
|
-
this._lastFitWidth = this._fitWidthPx(), this._mountVisible();
|
|
1194
|
-
return;
|
|
1195
|
-
}
|
|
1196
|
-
let e = this._baseScale();
|
|
1197
|
-
if (e <= 0) return;
|
|
1198
|
-
let t = this._fitWidthPx();
|
|
1199
|
-
if (t === this._lastFitWidth) {
|
|
1200
|
-
this._mountVisible();
|
|
1201
|
-
return;
|
|
1202
|
-
}
|
|
1203
|
-
this._lastFitWidth = t;
|
|
1204
|
-
let n = this._prevBase > 0 ? this._scale / this._prevBase : 1;
|
|
1205
|
-
this._prevBase = e, this.setScale(e * n), this._mountVisible();
|
|
1206
|
-
}
|
|
1207
|
-
get topVisiblePage() {
|
|
1208
|
-
return this._lastRange?.topIndex ?? 0;
|
|
1209
|
-
}
|
|
1210
|
-
mountedPageIndicesForTest() {
|
|
1211
|
-
return [...this._slots.keys()];
|
|
1212
|
-
}
|
|
1213
|
-
scaleForTest() {
|
|
1214
|
-
return this._scale;
|
|
1215
|
-
}
|
|
1216
|
-
baseScaleForTest() {
|
|
1217
|
-
return this._baseScale();
|
|
1218
|
-
}
|
|
1219
|
-
renderEpochForTest() {
|
|
1220
|
-
return this._renderEpoch;
|
|
1221
|
-
}
|
|
1222
|
-
resizeForTest() {
|
|
1223
|
-
this._onResize();
|
|
1224
|
-
}
|
|
1225
|
-
contentAtViewportYForTest(e) {
|
|
1226
|
-
let t = this._range(), n = this._scrollHost.scrollTop + e, r = this._pageIndexAtOffset(t, n), i = this._heights[r] || 0;
|
|
1227
|
-
return {
|
|
1228
|
-
page: r,
|
|
1229
|
-
frac: i > 0 ? Math.min(1, Math.max(0, (n - t.offsets[r]) / i)) : 0
|
|
1230
|
-
};
|
|
1231
|
-
}
|
|
1232
|
-
viewportYOfForTest(e, t) {
|
|
1233
|
-
return (this._range().offsets[e] ?? 0) + t * (this._heights[e] || 0) - this._scrollHost.scrollTop;
|
|
1234
|
-
}
|
|
1235
|
-
async getResourceMetrics() {
|
|
1236
|
-
if (!this._doc) throw Error("Document not loaded");
|
|
1237
|
-
return await this._doc.getResourceMetrics();
|
|
1238
|
-
}
|
|
1239
|
-
destroy() {
|
|
1240
|
-
this._destroyed = !0, this._loadGen++, this._find.invalidate(), this._findActive = !1, this._scrollListener &&= (this._scrollHost.removeEventListener("scroll", this._scrollListener), null), this._wheelListener &&= (this._scrollHost.removeEventListener("wheel", this._wheelListener), null), this._resizeObserver?.disconnect(), this._resizeObserver = null, this._settleTimer !== null && (clearTimeout(this._settleTimer), this._settleTimer = null);
|
|
1241
|
-
for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
|
|
1242
|
-
this._free.length = 0, this._injected || this._doc?.destroy(), this._doc = null, this._wrapper.remove();
|
|
1243
|
-
}
|
|
1244
|
-
};
|
|
1245
|
-
//#endregion
|
|
1246
|
-
//#region packages/docx/src/types.ts
|
|
1247
|
-
function $(e) {
|
|
1248
|
-
let t = [];
|
|
1249
|
-
for (let n of e.content) {
|
|
1250
|
-
if (n.type !== "paragraph") continue;
|
|
1251
|
-
let e = "";
|
|
1252
|
-
for (let t of n.runs) t.type === "text" && !t.noteRef && (e += t.text);
|
|
1253
|
-
e = e.trim(), e && t.push(e);
|
|
1254
|
-
}
|
|
1255
|
-
return t.join(" ");
|
|
1256
|
-
}
|
|
1257
|
-
//#endregion
|
|
1258
|
-
//#region src/docx.ts
|
|
1259
|
-
var we = /* @__PURE__ */ e({
|
|
1260
|
-
DocxDocument: () => K,
|
|
1261
|
-
DocxScrollViewer: () => Q,
|
|
1262
|
-
DocxViewer: () => Z,
|
|
1263
|
-
OoxmlDecodedImageLimitError: () => N,
|
|
1264
|
-
OoxmlError: () => n,
|
|
1265
|
-
OoxmlResourceLimitError: () => r,
|
|
1266
|
-
autoResize: () => y,
|
|
1267
|
-
buildDocxHighlightLayer: () => Y,
|
|
1268
|
-
buildDocxTextLayer: () => J,
|
|
1269
|
-
isOoxmlDecodedImageLimitError: () => F,
|
|
1270
|
-
noteText: () => $,
|
|
1271
|
-
openExternalHyperlink: () => H
|
|
1272
|
-
});
|
|
1273
|
-
//#endregion
|
|
1274
|
-
export { Y as a, Z as i, $ as n, J as o, Q as r, K as s, we as t };
|