@silurus/ooxml 0.88.0 → 0.89.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +118 -23
  2. package/THIRD_PARTY_NOTICES.md +8 -7
  3. package/dist/abort-VrnK7mdP.js +10 -0
  4. package/dist/assets/render-worker-C5G_Nr_A.js +35 -0
  5. package/dist/assets/render-worker-DQfWdNsm.js +16 -0
  6. package/dist/assets/render-worker-Ds7LjwU-.js +15 -0
  7. package/dist/{hyperlink-Cxzhet30.js → bounded-raw-part-cache-CsnNptAy.js} +4937 -7458
  8. package/dist/bundled-asset-url-E2nXURF9.js +15 -0
  9. package/dist/canvas-viewer-mechanics-BZ8QCrRi.js +675 -0
  10. package/dist/cfb-guard-dNeUiANF.js +528 -0
  11. package/dist/chart-ex.mjs +667 -663
  12. package/dist/comment-overlay-controller-CBvQx-En.js +994 -0
  13. package/dist/comment-ui-runtime-B7ZvovcS.js +2 -0
  14. package/dist/{comment-ui-runtime-DcJOYlw-.js → comment-ui-runtime-BKidRH36.js} +5 -5
  15. package/dist/{comment-ui-runtime-CWGqn5Vr.js → comment-ui-runtime-C47QoDUy.js} +5 -5
  16. package/dist/delimited-text-worker-host-CikWU6_m.js +27 -0
  17. package/dist/document-model-source-MzFPrxt0.js +249 -0
  18. package/dist/document-pull-client-BoJeuURD.js +35941 -0
  19. package/dist/document-pull-worker-CaP8XESP.js +104 -0
  20. package/dist/docx-BN70UhvX.js +495 -0
  21. package/dist/docx-BRRtSvk3.js +3563 -0
  22. package/dist/docx-model-source-CTO9iw_W.js +98 -0
  23. package/dist/docx-source-worker.mjs +455 -0
  24. package/dist/docx.mjs +7 -7
  25. package/dist/docx_parser_bg.wasm +0 -0
  26. package/dist/drawingml-shape-CHmq8kpM.js +310 -0
  27. package/dist/duotone-DN8P4aXe.js +126 -0
  28. package/dist/emf-CGFQIz6c.js +1790 -0
  29. package/dist/font-preload-demand-Dmy31xt-.js +2058 -0
  30. package/dist/grid-geometry-C3IG20ut.js +384 -0
  31. package/dist/host-layout-DVMw8hDY.js +56 -0
  32. package/dist/host-layout-measure-DsuQ2UJs.js +7 -0
  33. package/dist/in-process-pull-transport-DuXcPZng.js +29 -0
  34. package/dist/index.mjs +4 -4
  35. package/dist/internal-companion.mjs +12 -0
  36. package/dist/line-distribute-Bu8psjGd.js +2799 -0
  37. package/dist/math.mjs +2 -2
  38. package/dist/mathjax-stix2.js +10 -10
  39. package/dist/model-source-kz_NkZqT.js +179 -0
  40. package/dist/model-source-s5hRpk4w.js +61 -0
  41. package/dist/model-source-session-6fuaqbGs.js +71 -0
  42. package/dist/model-source-session-DqrR4XHR.js +85 -0
  43. package/dist/model-source-session-cPJSF_Ak.js +58 -0
  44. package/dist/node.mjs +7 -1327
  45. package/dist/{pixel-budget-9P63Bsk5.js → pixel-budget-BpTYrepD.js} +13 -10
  46. package/dist/plot-area-frame-Bs_j4uu7.js +41811 -0
  47. package/dist/pptx-CaJ6ILnw.js +183 -0
  48. package/dist/pptx-_BOGcBym.js +2936 -0
  49. package/dist/pptx-model-source-B_9afw9R.js +37 -0
  50. package/dist/pptx-source-worker.mjs +446 -0
  51. package/dist/pptx.mjs +8 -7
  52. package/dist/pptx_parser_bg.wasm +0 -0
  53. package/dist/presentation-model-source-CGHLyX32.js +77 -0
  54. package/dist/raster-target-YQ4G6rxo.js +42 -0
  55. package/dist/region-map.mjs +117 -153
  56. package/dist/{render-D3iqVKCo.js → render-CzbDzRKa.js} +3 -3
  57. package/dist/{render-worker-host-B5wQfB7U.js → render-worker-host-B1u6BOUd.js} +1 -1
  58. package/dist/{render-worker-host-D4123J27.js → render-worker-host-C-EECo68.js} +1 -1
  59. package/dist/{render-worker-host-Di3LxLc0.js → render-worker-host-DDqZTCVf.js} +1 -1
  60. package/dist/renderer-CD2cvVAF.js +5823 -0
  61. package/dist/renderer-DRoeb14O.js +5170 -0
  62. package/dist/resource-measurement-Dhhm7P_l.js +772 -0
  63. package/dist/session-XPmC0CUd.js +656 -0
  64. package/dist/slide-pull-client-tq7U_fYg.js +6485 -0
  65. package/dist/three-d-BKwNPAP4.js +878 -0
  66. package/dist/three-d.mjs +925 -910
  67. package/dist/{raster-target-ojDdQizC.js → tiff-contract-C6M3QcPp.js} +1 -42
  68. package/dist/tiff.mjs +401 -248
  69. package/dist/types/chart-ex.d.ts +149 -2
  70. package/dist/types/docx.d.ts +333 -96
  71. package/dist/types/index.d.ts +566 -301
  72. package/dist/types/internal-companion.d.ts +11 -0
  73. package/dist/types/math.d.ts +1 -1
  74. package/dist/types/node.d.ts +422 -9
  75. package/dist/types/pptx.d.ts +302 -95
  76. package/dist/types/region-map.d.ts +149 -2
  77. package/dist/types/three-d.d.ts +149 -2
  78. package/dist/types/tiff.d.ts +1 -1
  79. package/dist/types/xlsx.d.ts +343 -132
  80. package/dist/wasm-loader-rlgHmcSv.js +35 -0
  81. package/dist/wasm-runtime-generation-D6TKZdNb.js +97 -0
  82. package/dist/workbook-model-source-BIGrfZy6.js +94 -0
  83. package/dist/worker-source-DrwhR9fw.js +22 -0
  84. package/dist/worker-source-SbudzjYL.js +22 -0
  85. package/dist/worker-source-UAi3GNcM.js +22 -0
  86. package/dist/worksheet-pull-client-ClvPO_Jf.js +579 -0
  87. package/dist/xlsx-CsmREBaZ.js +5819 -0
  88. package/dist/xlsx-DmHfeNNp.js +534 -0
  89. package/dist/xlsx-model-source-D1flORqy.js +309 -0
  90. package/dist/xlsx-source-worker.mjs +525 -0
  91. package/dist/xlsx.mjs +8 -7
  92. package/dist/xlsx_parser_bg.wasm +0 -0
  93. package/package.json +42 -16
  94. package/dist/assets/render-worker-1uPAxMZr.js +0 -31
  95. package/dist/assets/render-worker-BlvJybji.js +0 -10
  96. package/dist/assets/render-worker-CzmiJfFL.js +0 -11
  97. package/dist/bounded-raw-part-cache-Cg1BsSZQ.js +0 -119
  98. package/dist/canvas-viewer-mechanics-DbLz0rYW.js +0 -1384
  99. package/dist/cjk-fallback-bLI3z70h.js +0 -46
  100. package/dist/comment-occurrence-C8Y2uoVr.js +0 -6
  101. package/dist/comment-ui-runtime-BsK8pmUT.js +0 -2
  102. package/dist/comments-Diid5ujN.js +0 -246
  103. package/dist/delimited-text-worker-host-BVY-Ecni.js +0 -27
  104. package/dist/document-pull-client-B9PTM-pL.js +0 -27280
  105. package/dist/docx-BF9WXrYH.js +0 -3103
  106. package/dist/dom-interaction-boundary-Cnm8DSBN.js +0 -223
  107. package/dist/highlight-rect-C5hkRqUr.js +0 -13
  108. package/dist/line-distribute-D1WNHKz_.js +0 -1023
  109. package/dist/line-metrics-B60C86uh.js +0 -60
  110. package/dist/plot-area-frame-DLTYKHNP.js +0 -4354
  111. package/dist/pptx-DkyYBYoL.js +0 -3065
  112. package/dist/renderer-B4GZb5We.js +0 -6492
  113. package/dist/resource-measurement-SHQCbkh2.js +0 -150
  114. package/dist/session-BGq81gRQ.js +0 -743
  115. package/dist/slide-pull-client-DiPnm240.js +0 -6253
  116. package/dist/source-key-DIJG8BA0.js +0 -42
  117. package/dist/three-d-DJBl8g8M.js +0 -1162
  118. package/dist/transfer-p6iCC2R7.js +0 -6
  119. package/dist/units-BzZ0gAxs.js +0 -4
  120. package/dist/worksheet-pull-client-BM8ywvbu.js +0 -458
  121. package/dist/xlsx-C9NVjgaV.js +0 -8484
  122. /package/dist/{chunk-DmhlhrBa.js → chunk-Dy4uBu1J.js} +0 -0
  123. /package/dist/{mathjax-DoyWZbSp.js → mathjax-BhwN6ilc.js} +0 -0
  124. /package/dist/{read-only-comment-decoration-Dz7eTQ4d.js → read-only-comment-decoration-PidH0wnP.js} +0 -0
  125. /package/dist/{read-only-comment-margin-DkgzASAl.js → read-only-comment-margin-B52rDVKo.js} +0 -0
  126. /package/dist/{renderer-module-contract-D91rkYHH.js → renderer-module-contract-CWM7jv6d.js} +0 -0
  127. /package/dist/{visible-index-BgiHEc1z.js → visible-index-FeVA0mGE.js} +0 -0
@@ -1,3103 +0,0 @@
1
- import { t as e } from "./chunk-DmhlhrBa.js";
2
- import { $ as t, $t as n, L as r, R as i, U as a, _t as o, ft as s, ln as c, lt as l, r as u, un as d, z as f } from "./hyperlink-Cxzhet30.js";
3
- import { C as p, D as m, M as h, N as g, O as _, S as v, T as ee, _ as y, a as b, b as te, c as x, d as ne, f as re, g as ie, h as ae, i as S, l as C, m as oe, n as se, o as ce, p as le, r as ue, s as de, t as fe, u as pe, v as me, w as he, x as ge, y as _e } from "./canvas-viewer-mechanics-DbLz0rYW.js";
4
- import { c as ve, d as ye, f as be, i as xe, l as Se, n as Ce, o as w, r as we, s as Te, t as Ee, u as De } from "./dom-interaction-boundary-Cnm8DSBN.js";
5
- import { A as Oe, C as T, D as ke, E as Ae, M as je, O as E, S as Me, T as Ne, _ as Pe, a as Fe, b as Ie, c as Le, d as Re, f as ze, g as Be, h as Ve, j as He, k as Ue, l as We, m as Ge, n as Ke, o as qe, p as Je, s as Ye, t as Xe, v as Ze, w as Qe, x as $e, y as et } from "./document-pull-client-B9PTM-pL.js";
6
- import { n as tt } from "./cjk-fallback-bLI3z70h.js";
7
- import { a as D } from "./units-BzZ0gAxs.js";
8
- import { l as nt, s as rt } from "./pixel-budget-9P63Bsk5.js";
9
- import { i as it, s as at } from "./raster-target-ojDdQizC.js";
10
- import { n as ot } from "./renderer-module-contract-D91rkYHH.js";
11
- import { n as st, t as O } from "./highlight-rect-C5hkRqUr.js";
12
- import { t as ct } from "./bounded-raw-part-cache-Cg1BsSZQ.js";
13
- import { o as k } from "./source-key-DIJG8BA0.js";
14
- import { i as lt, n as A, r as ut, t as dt } from "./comments-Diid5ujN.js";
15
- //#region packages/core/src/fonts/open-type-metrics.ts
16
- var j = (e) => (e.charCodeAt(0) << 24 >>> 0 | e.charCodeAt(1) << 16 | e.charCodeAt(2) << 8 | e.charCodeAt(3)) >>> 0, ft = j("ttcf"), pt = j("OTTO"), mt = j("true"), ht = j("typ1"), gt = j("head"), _t = j("hhea"), vt = j("OS/2"), yt = j("cmap"), bt = j("fvar"), M = [
17
- [4352, 4607],
18
- [11904, 12287],
19
- [12352, 12543],
20
- [12544, 12591],
21
- [12592, 12687],
22
- [12704, 12735],
23
- [12784, 12799],
24
- [13312, 19903],
25
- [19968, 40959],
26
- [40960, 42191],
27
- [43360, 43391],
28
- [44032, 55203],
29
- [63744, 64255],
30
- [131072, 205743]
31
- ];
32
- function N(e, t, n) {
33
- return Number.isSafeInteger(t) && Number.isSafeInteger(n) && t >= 0 && n >= 0 && t <= e - n;
34
- }
35
- function xt(e, t, n) {
36
- if (n < 16) return !1;
37
- let r = e.getUint16(t + 2);
38
- if (r < 16 || r > n) return !1;
39
- let i = e.getUint16(t + 6);
40
- if (i === 0 || i % 2 != 0) return !1;
41
- let a = i / 2, o = t + 14, s = o + a * 2 + 2, c = s + a * 2, l = c + a * 2;
42
- if (l + a * 2 > t + r) return !1;
43
- let u = -1;
44
- for (let t = 0; t < a; t++) {
45
- let n = e.getUint16(s + t * 2), r = e.getUint16(o + t * 2);
46
- if (n > r || n <= u) return !1;
47
- u = r;
48
- }
49
- for (let n = 0; n < a; n++) {
50
- let i = e.getUint16(s + n * 2), a = e.getUint16(o + n * 2), u = e.getInt16(c + n * 2), d = l + n * 2, f = e.getUint16(d);
51
- for (let [n, o] of M) {
52
- let s = Math.max(i, n), c = Math.min(a, o);
53
- if (!(s > c)) {
54
- if (f === 0) {
55
- if (s < c || s + u & 65535) return !0;
56
- continue;
57
- }
58
- for (let n = s; n <= c; n++) {
59
- let a = d + f + (n - i) * 2;
60
- if (a + 2 > t + r) break;
61
- let o = e.getUint16(a);
62
- if (o !== 0 && o + u & 65535) return !0;
63
- }
64
- }
65
- }
66
- }
67
- return !1;
68
- }
69
- function St(e, t, n, r) {
70
- if (n < 16) return !1;
71
- let i = e.getUint32(t + 4), a = e.getUint32(t + 12);
72
- if (i < 16 || i > n || a > (i - 16) / 12) return !1;
73
- let o = -1;
74
- for (let n = 0; n < a; n++) {
75
- let i = t + 16 + n * 12, a = e.getUint32(i), s = e.getUint32(i + 4), c = e.getUint32(i + 8);
76
- if (a > s || s > 1114111 || a <= o) return !1;
77
- if (o = s, a > M[M.length - 1][1]) break;
78
- for (let [e, t] of M) {
79
- let n = Math.max(a, e), i = Math.min(s, t);
80
- if (!(n > i)) {
81
- if (r) {
82
- if (c !== 0) return !0;
83
- } else if (n < i || c + (n - a) !== 0) return !0;
84
- }
85
- }
86
- }
87
- return !1;
88
- }
89
- function Ct(e, t) {
90
- if (!t || t.length < 4) return !1;
91
- let n = e.getUint16(t.offset + 2);
92
- if (4 + n * 8 > t.length) return !1;
93
- for (let r = 0; r < n; r++) {
94
- let n = t.offset + 4 + r * 8, i = e.getUint16(n), a = e.getUint16(n + 2);
95
- if (i !== 0 && !(i === 3 && (a === 1 || a === 10))) continue;
96
- let o = e.getUint32(n + 4);
97
- if (o > t.length - 2) continue;
98
- let s = t.offset + o, c = t.length - o, l = e.getUint16(s);
99
- if (l === 4 && xt(e, s, c) || l === 12 && St(e, s, c, !1) || l === 13 && St(e, s, c, !0)) return !0;
100
- }
101
- return !1;
102
- }
103
- var P = 32768, wt = 4096, Tt = 8, Et = 262144;
104
- function Dt(e, t, n, r) {
105
- if (n < 16) return null;
106
- let i = e.getUint16(t + 2);
107
- if (i < 16 || i > n) return null;
108
- let a = e.getUint16(t + 6);
109
- if (a === 0 || a % 2 != 0) return null;
110
- let o = a / 2, s = t + 14, c = s + o * 2 + 2, l = c + o * 2, u = l + o * 2;
111
- if (u + o * 2 > t + i) return null;
112
- let d = [], f = -1, p = -1, m = (e) => {
113
- d.length > 0 && p + 1 === e ? (p = e, d[d.length - 1] = [f, p]) : (f = p = e, d.push([e, e]));
114
- }, h = -1;
115
- for (let n = 0; n < o; n++) {
116
- let a = e.getUint16(c + n * 2), o = e.getUint16(s + n * 2);
117
- if (a > o || a <= h) return null;
118
- h = o;
119
- let f = e.getInt16(l + n * 2), p = u + n * 2, g = e.getUint16(p);
120
- for (let n = a; n <= o && n < 65535; n++) if (--r.remaining < 0 || ((g === 0 ? n + f & 65535 : (() => {
121
- let r = p + g + (n - a) * 2;
122
- if (r + 2 > t + i) return 0;
123
- let o = e.getUint16(r);
124
- return o === 0 ? 0 : o + f & 65535;
125
- })()) !== 0 && m(n), d.length > P)) return null;
126
- }
127
- return d;
128
- }
129
- function Ot(e, t, n, r, i) {
130
- if (n < 16) return null;
131
- let a = e.getUint32(t + 4), o = e.getUint32(t + 12);
132
- if (a < 16 || a > n || o > (a - 16) / 12 || o > P) return null;
133
- let s = [], c = -1;
134
- for (let n = 0; n < o; n++) {
135
- if (--i.remaining < 0) return null;
136
- let a = t + 16 + n * 12, o = e.getUint32(a), l = e.getUint32(a + 4), u = e.getUint32(a + 8);
137
- if (o > l || l > 1114111 || o <= c) return null;
138
- if (c = l, r) u !== 0 && s.push([o, l]);
139
- else {
140
- let e = u === 0 ? o + 1 : o;
141
- e <= l && s.push([e, l]);
142
- }
143
- }
144
- return s;
145
- }
146
- function kt(e, t) {
147
- if (!t || t.length < 4) return [];
148
- let n = e.getUint16(t.offset + 2);
149
- if (n > wt || 4 + n * 8 > t.length) return [];
150
- let r = /* @__PURE__ */ new Set(), i = [];
151
- for (let a = 0; a < n; a++) {
152
- let n = t.offset + 4 + a * 8, o = e.getUint16(n), s = e.getUint16(n + 2);
153
- if (o !== 0 && !(o === 3 && (s === 1 || s === 10))) continue;
154
- let c = e.getUint32(n + 4);
155
- if (c > t.length - 2) return [];
156
- let l = t.offset + c, u = t.length - c, d = e.getUint16(l);
157
- if (!(o === 0 && s === 5 && d === 14)) {
158
- if (d !== 4 && d !== 12 && d !== 13) return [];
159
- if (!r.has(c)) {
160
- if (r.add(c), r.size > Tt) return [];
161
- i.push({
162
- subtable: l,
163
- availableLength: u,
164
- format: d
165
- });
166
- }
167
- }
168
- }
169
- let a = { remaining: Et }, o = null;
170
- for (let t of i) {
171
- let n = t.format === 4 ? Dt(e, t.subtable, t.availableLength, a) : Ot(e, t.subtable, t.availableLength, t.format === 13, a);
172
- if (!n?.length) return [];
173
- if (o === null) {
174
- o = n;
175
- continue;
176
- }
177
- let r = [], i = 0, s = 0;
178
- for (; i < o.length && s < n.length;) {
179
- if (--a.remaining < 0) return [];
180
- let e = o[i], t = n[s], c = Math.max(e[0], t[0]), l = Math.min(e[1], t[1]);
181
- if (c <= l) {
182
- let e = r.at(-1);
183
- if (e && e[1] + 1 === c) r[r.length - 1] = [e[0], l];
184
- else {
185
- if (r.length >= P) return [];
186
- r.push([c, l]);
187
- }
188
- }
189
- e[1] <= t[1] && i++, t[1] <= e[1] && s++;
190
- }
191
- if (!r.length) return [];
192
- o = r;
193
- }
194
- return Object.freeze((o ?? []).map((e) => Object.freeze(e)));
195
- }
196
- function At(e) {
197
- let t = 0, n = 0;
198
- for (; t < e.length && n < M.length;) {
199
- let [r, i] = e[t], [a, o] = M[n];
200
- if (i < a) t++;
201
- else if (o < r) n++;
202
- else return !0;
203
- }
204
- return !1;
205
- }
206
- function jt(e, t) {
207
- return Mt(e, t, !1);
208
- }
209
- function Mt(e, t, n) {
210
- if (t !== void 0 && (!Number.isSafeInteger(t) || t < 0) || e.byteLength < 12) return null;
211
- let r = new DataView(e.buffer, e.byteOffset, e.byteLength), i = 0;
212
- if (r.getUint32(0) === ft) {
213
- if (t === void 0 || e.byteLength < 12) return null;
214
- let n = r.getUint32(8);
215
- if (t >= n || !N(e.byteLength, 12, n * 4)) return null;
216
- i = r.getUint32(12 + t * 4);
217
- } else if (t !== void 0 && t !== 0) return null;
218
- if (!N(e.byteLength, i, 12)) return null;
219
- let a = r.getUint32(i);
220
- if (a !== 65536 && a !== pt && a !== mt && a !== ht) return null;
221
- let o = r.getUint16(i + 4);
222
- if (!N(e.byteLength, i + 12, o * 16)) return null;
223
- let s = /* @__PURE__ */ new Map();
224
- for (let t = 0; t < o; t++) {
225
- let n = i + 12 + t * 16, a = r.getUint32(n), o = r.getUint32(n + 8), c = r.getUint32(n + 12);
226
- if (s.has(a) || !N(e.byteLength, o, c)) return null;
227
- s.set(a, {
228
- offset: o,
229
- length: c
230
- });
231
- }
232
- if (n && s.has(bt)) return null;
233
- let c = s.get(gt), l = s.get(_t);
234
- if (!c || c.length < 20 || !l || l.length < 10) return null;
235
- let u = r.getUint16(c.offset + 18);
236
- if (u < 16 || u > 16384) return null;
237
- let d = s.get(vt), f = d !== void 0 && d.length >= 78, p = n ? kt(r, s.get(yt)) : void 0;
238
- return Object.freeze({
239
- unitsPerEm: u,
240
- hheaAscent: r.getInt16(l.offset + 4),
241
- hheaDescent: r.getInt16(l.offset + 6),
242
- hheaLineGap: r.getInt16(l.offset + 8),
243
- hasEastAsianCmap: p ? At(p) : Ct(r, s.get(yt)),
244
- ...p === void 0 ? {} : { unicodeRanges: p },
245
- ...f ? {
246
- typoAscent: r.getInt16(d.offset + 68),
247
- typoDescent: r.getInt16(d.offset + 70),
248
- typoLineGap: r.getInt16(d.offset + 72),
249
- winAscent: r.getUint16(d.offset + 74),
250
- winDescent: r.getUint16(d.offset + 76),
251
- useTypoMetrics: (r.getUint16(d.offset + 62) & 128) != 0
252
- } : {}
253
- });
254
- }
255
- //#endregion
256
- //#region packages/docx/src/worker.ts?worker&inline
257
- var Nt = "var e=(e,t)=>()=>(e&&(t=e(e=0)),t),t=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,r.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 p(r[0])}assert_healthy(){let e=v.docxarchive_assert_healthy(this.__wbg_ptr);if(e[1])throw p(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 p(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 p(e[2]);var t=i(e[0],e[1]).slice();return v.__wbindgen_free(e[0],e[1]*1,1),t}extract_image(e){let t=f(e,v.__wbindgen_malloc,v.__wbindgen_realloc),n=_,r=v.docxarchive_extract_image(this.__wbg_ptr,t,n);if(r[3])throw p(r[2]);var a=i(r[0],r[1]).slice();return v.__wbindgen_free(r[0],r[1]*1,1),a}constructor(e,t,n,i){let a=d(e,v.__wbindgen_malloc),o=_,s=v.docxarchive_new(a,o,!u(t),u(t)?BigInt(0):t,!u(n),u(n)?BigInt(0):n,!u(i),u(i)?BigInt(0):i);if(s[2])throw p(s[1]);return this.__wbg_ptr=s[0]>>>0,r.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 p(n[0])}parse(){let e=v.docxarchive_parse(this.__wbg_ptr);if(e[3])throw p(e[2]);var t=i(e[0],e[1]).slice();return v.__wbindgen_free(e[0],e[1]*1,1),t}pull_document_chunk(e,t,n,r){let a=v.docxarchive_pull_document_chunk(this.__wbg_ptr,e,t,n,r);if(a[3])throw p(a[2]);var o=i(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 p(e[2]);var t=i(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,p(i[2]);return e=n,t=r,s(n,r)}finally{v.__wbindgen_free(e,t,1)}}};Symbol.dispose&&(t.prototype[Symbol.dispose]=t.prototype.free);function n(){return{__proto__:null,\"./docx_parser_bg.js\":{__proto__:null,__wbg___wbindgen_throw_6b64449b9b9ed33c:function(e,t){throw Error(s(e,t))},__wbg_error_a6fa202b58aa1cd3:function(e,t){let n,r;try{n=e,r=t,console.error(s(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=f(n,v.__wbindgen_malloc,v.__wbindgen_realloc),i=_;o().setInt32(e+4,i,!0),o().setInt32(e+0,r,!0)},__wbindgen_cast_0000000000000001:function(e,t){return s(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 r=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>v.__wbg_docxarchive_free(e>>>0,1));function i(e,t){return e>>>=0,l().subarray(e/1,e/1+t)}let a=null;function o(){return(a===null||a.buffer.detached===!0||a.buffer.detached===void 0&&a.buffer!==v.memory.buffer)&&(a=new DataView(v.memory.buffer)),a}function s(e,t){return e>>>=0,ee(e,t)}let c=null;function l(){return(c===null||c.byteLength===0)&&(c=new Uint8Array(v.memory.buffer)),c}function u(e){return e==null}function d(e,t){let n=t(e.length*1,1)>>>0;return l().set(e,n/1),_=e.length,n}function f(e,t,n){if(n===void 0){let n=g.encode(e),r=t(n.length,1)>>>0;return l().subarray(r,r+n.length).set(n),_=n.length,r}let r=e.length,i=t(r,1)>>>0,a=l(),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=l().subarray(i+o,i+r),a=g.encodeInto(e,t);o+=a.written,i=n(i,r,o,1)>>>0}return _=o,i}function p(e){let t=v.__wbindgen_externrefs.get(e);return v.__externref_table_dealloc(e),t}let m=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0});m.decode();let h=0;function ee(e,t){return h+=t,h>=2146435072&&(m=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}),m.decode(),h=t),m.decode(l().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 te(e,t){return v=e.exports,a=null,c=null,v.__wbindgen_start(),v}async function ne(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 y(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 t=n();(typeof e==`string`||typeof Request==`function`&&e instanceof Request||typeof URL==`function`&&e instanceof URL)&&(e=fetch(e));let{instance:r,module:i}=await ne(await e,t);return te(r,i)}async function b(e){return v=void 0,a=null,c=null,y(e)}var x=class e extends Error{code;constructor(t,n){super(n),this.name=`OoxmlError`,this.code=t,Object.setPrototypeOf(this,e.prototype)}},S=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)}};function re(e){return e===`image-dimension`||e===`image-pixels`||e===`active-decoded-bytes`}function C(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function ie(e){if(!(!e||typeof e!=`object`))try{let t=e,n=t.code,r=t.metric,i=t.limit,a=t.observed;return n!==`ooxml-decoded-image-limit`||!re(r)||!C(i)||!C(a)||a<=i?void 0:{metric:r,limit:i,observed:a}}catch{return}}var w,T,E,D=e((()=>{w=1<<25,T=1<<27,w*4,T*4,E=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 O(e){if(!(typeof e!=`object`||!e))try{let t=e,n=t.code,r=t.message;return n===`ooxml-tiff-decode`&&typeof r==`string`?{message:r}:void 0}catch{return}}var ae=e((()=>{}));function oe(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 se=class{state=`uninitialized`;generationValue=0;readiness;poisonListeners=new Set;constructor(e,t,n){this.initialize=e,this.reinitialize=t,this.normalizeFailure=n}get generation(){return this.generationValue}get poisoned(){return this.state===`poisoned`}onPoison(e){return this.poisonListeners.add(e),()=>this.poisonListeners.delete(e)}async ensureReady(){if(this.state!==`ready`){if(!this.readiness){let e=this.state===`uninitialized`?this.initialize:this.reinitialize;this.readiness=Promise.resolve().then(e).then(()=>{this.generationValue+=1,this.state=`ready`,this.readiness=void 0},e=>{throw this.readiness=void 0,e})}await this.readiness}}run(e){try{return e()}catch(e){let t=this.normalizeFailure(e);throw t?(this.poison(t),t):e}}tryRunReady(e){if(this.state!==`ready`)return{current:!1};let t=this.generationValue,n=this.run(e);return this.state!==`ready`||t!==this.generationValue?{current:!1}:{current:!0,generation:t,value:n}}poison(e){this.state=`poisoned`,this.readiness=void 0;for(let t of this.poisonListeners)t(e)}assertCurrent(e){if(this.state!==`ready`||e!==this.generationValue)throw Error(`WASM archive session belongs to a discarded runtime generation`)}},k=class e extends Error{code=`parser-crashed`;constructor(t){super(t),this.name=`WasmTrapError`,Object.setPrototypeOf(this,e.prototype)}};function ce(e){let t=globalThis.WebAssembly?.RuntimeError;return t&&e instanceof t||e instanceof RangeError?!0:e instanceof Error?e.name===`RuntimeError`||e.name===`CompileError`||e.name===`LinkError`||e.name===`InternalError`||e.name===`OOMError`:!1}function le(e){try{if((typeof e!=`object`||!e)&&typeof e!=`function`)return;let t=Reflect.get(e,`__destroy_into_raw`);typeof t==`function`&&Reflect.apply(t,e,[])}catch{}}function ue(e,t){return e({module_or_path:t})}var de=class{runtime;wasmInput=null;currentArchive=null;constructor(e,t={}){this.init=e,this.options=t,this.runtime=new se(()=>this.invokeConfigured(this.init),()=>this.invokeConfigured(this.options.reinit??this.init),fe),this.runtime.onPoison(()=>this.dropPoisonedArchive())}setWasmInput(e){this.wasmInput=e,this.runtime.ensureReady().catch(()=>void 0)}setWasmUrl(e){this.setWasmInput(e)}get archive(){return this.currentArchive}setArchive(e){this.freeArchive(),this.currentArchive=e}disposeArchive(){this.freeArchive()}get poisoned(){return this.runtime.poisoned}async ensureReady(){await this.runtime.ensureReady()}run(e){return this.runtime.run(e)}poison(){this.runtime.poison(new k(`WASM parser was recycled`))}invokeConfigured(e){return this.wasmInput===null?Promise.reject(Error(`WasmParserHost: setWasmInput was never called`)):ue(e,this.wasmInput)}freeArchive(){this.currentArchive!==null&&this.options.freeArchive&&this.options.freeArchive(this.currentArchive),this.currentArchive=null}dropPoisonedArchive(){let e=this.currentArchive;this.currentArchive=null,le(e)}};function fe(e){return ce(e)?new k(`WASM parser trapped and was recycled: ${e instanceof Error?e.message:String(e)}`):null}function A(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function pe(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return A(t.requiredBytes)&&A(t.offeredBytes)&&t.requiredBytes>t.offeredBytes}var j=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 M(e){if(e instanceof j)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`||!pe(r)))return new j(r)}function me(e,t,n){let r=M(e);if(!(!r||r.offeredBytes!==t||r.requiredBytes>n))return r}D(),ae();const N=`OOXML_RESOURCE_LIMIT:`;function P(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function F(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return P(t.archiveEntryCount)&&P(t.declaredInflatedBytes)&&(t.largestInflatedEntryBytes===void 0||P(t.largestInflatedEntryBytes))&&P(t.distinctInflatedBytes)&&P(t.operationInflatedBytes)}function I(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw TypeError(`OOXML resource usage checkpoint is not valid JSON`)}if(!F(t))throw TypeError(`OOXML resource usage checkpoint is invalid`);return t}function L(e){return e===`docx`||e===`xlsx`||e===`pptx`}function R(e){return e===`container`||e===`decompression`||e===`parsing`||e===`serialization`||e===`layout`||e===`rendering`||e===`worker`}function z(e,t){return typeof e==`string`&&e.length>0&&e.length<=t&&!/[\\u0000-\\u001f\\u007f]/u.test(e)}function B(e){return z(e,128)&&/^[a-z0-9][a-z0-9-]*$/u.test(e)}function he(e){return!z(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 V=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`}],[`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}]]),ge=new Set([...V.keys()].map(e=>e.slice(0,e.indexOf(`:`)))),_e=new Set([...V.keys()].map(e=>e.slice(e.indexOf(`:`)+1)));function ve(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return!L(t.format)||!z(t.operation,256)||!B(t.resource)||!B(t.metric)||!P(t.limit)||!P(t.observed)||typeof t.configurable!=`boolean`||!F(t.usage)?!1:!(`part`in t)||he(t.part)}function H(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;if(!R(t.stage)||!ve(t.violation))return!1;let n=t.violation,r=V.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:!(ge.has(n.resource)&&_e.has(n.metric))}function ye(e){return{archiveEntryCount:e.archiveEntryCount,declaredInflatedBytes:e.declaredInflatedBytes,...e.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:e.largestInflatedEntryBytes},distinctInflatedBytes:e.distinctInflatedBytes,operationInflatedBytes:e.operationInflatedBytes}}function be(e){if(!H(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:ye(t.usage)}};return H(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 xe(e){let t=e instanceof Error?e.message:String(e);if(!t.startsWith(N))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`||!H(r.details)))return new S(U(r.details),r.details)}function Se(e){let t=ie(e);if(t){let e=new E(t.metric,t.limit,t.observed);return{message:e.message,errorName:e.name,code:e.code,decodedImage:t}}let n=O(e);if(n)return{message:n.message,errorName:`TiffDecodeError`,code:`ooxml-tiff-decode`};let r=M(e);if(r)return{message:r.message,errorName:r.name,code:r.code,insufficientCredit:{requiredBytes:r.requiredBytes,offeredBytes:r.offeredBytes}};let i=e instanceof x||e instanceof S?e:xe(e);if(i instanceof S){let e=be(i.details);return e?{message:typeof i.message==`string`?i.message:U(e),errorName:`OoxmlResourceLimitError`,code:`ooxml-resource-limit`,resourceLimit:e}:{message:`Invalid OOXML resource-limit error payload`,errorName:`Error`}}if(i instanceof x)return{message:typeof i.message==`string`?i.message:String(i.message),errorName:z(i.name,128)?i.name:`OoxmlError`,...B(i.code)?{code:i.code}:{}};let a=e instanceof Error?e.message:String(e);if(typeof a==`string`&&a.startsWith(N))return{message:`Invalid OOXML resource-limit payload`,errorName:`Error`};let o=e instanceof Error?e:Error(a),s=o;return{message:typeof o.message==`string`?o.message:String(o.message),errorName:z(o.name,128)?o.name:`Error`,...typeof s.code==`string`?{code:s.code}:{}}}function W(e){try{return Se(e)}catch{return{message:`Worker operation failed with an unreadable error`,errorName:`Error`}}}function Ce(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,maxArchiveEntries:4096});function we(e){return[e.maxArchiveEntryBytes===null?0n:BigInt(e.maxArchiveEntryBytes),e.maxTotalInflatedBytes===null?0n:BigInt(e.maxTotalInflatedBytes),e.maxArchiveEntries===null?0n:BigInt(e.maxArchiveEntries)]}const G=`ooxml-pull-v1`;function K(e,t){if(!Number.isSafeInteger(e)||e<=0)throw RangeError(`${t} must be a positive safe integer`)}function Te(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 q=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,K(this.maxRetainedBytes,`max retained lease bytes`),K(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}},Ee=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){Te(e.sessionId),K(e.operationId,`operation id`),K(e.generation,`generation`),K(e.maxByteCredit,`max byte credit`),e.wireLeaseIdStart!==void 0&&K(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=W(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(K(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:G,...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){K(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(K(e,`byte credit`),e>this.options.maxByteCredit)throw RangeError(`byte credit exceeds host maximum`)}accepted(e,t,n=!1){return{kind:`accepted`,protocol:G,...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:G,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}}};function De(e){try{let t=e(e=>e.document_cursor_resource_usage?.());return t?I(t):void 0}catch(e){if(String(e).includes(`document cursor usage is unavailable`))return;throw e}}const J=67108864;var Y=class{coordinator=new q;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 Ee({...e,maxByteCredit:J,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 me(e,n,J)||e}let i=Ce(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:()=>De(this.executeArchive)}})}dispatch(e,t){return!this.host||!this.identity?(t({protocol:G,kind:`error`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:W(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 q}}requireArchive(){let e=this.archive();if(!e)throw Error(`No docx loaded`);return e}};function Oe(e){return!!e&&typeof e==`object`&&e.protocol===`ooxml-pull-v1`}const X=new de(y,{freeArchive:e=>e.free(),reinit:b}),Z=new Y(()=>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 e=>{let n=e.data;if(Oe(n)){try{await Z.dispatch(n,$)}catch(e){$({protocol:G,kind:`error`,sessionId:n.sessionId,operationId:n.operationId,generation:n.generation,requestId:n.requestId,error:W(e)})}return}if(n.type===`init`){X.setWasmInput(oe(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[e,i,a]=we(n.resourcePolicy),o=new Uint8Array(n.data);X.run(()=>{let n=new t(o,e,i,a);X.setArchive(n)}),Q+=1;let s={sessionId:Q,operationId:Q,generation:Q};Z.open(s),$({type:`documentSessionOpened`,id:r,...s});return}let e=X.archive;if(n.type===`extractImage`){if(!e)throw Error(`No docx loaded`);let t=X.run(()=>e.extract_image(n.path).buffer),i={type:`imageExtracted`,id:r,bytes:t};self.postMessage(i,[t]);return}if(n.type===`resourceUsage`){if(!e)throw Error(`No docx loaded`);$({type:`resourceUsage`,id:r,usage:I(X.run(()=>e.resource_usage()))});return}if(n.type===`toMarkdown`){if(!e)throw Error(`No docx loaded`);$({type:`markdownRendered`,id:r,markdown:X.run(()=>e.to_markdown())});return}}catch(e){$({type:`error`,id:r,...W(e)})}};", Pt = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", Nt], { type: "text/javascript;charset=utf-8" });
258
- function Ft(e) {
259
- let t;
260
- try {
261
- if (t = Pt && (self.URL || self.webkitURL).createObjectURL(Pt), !t) throw "";
262
- let n = new Worker(t, {
263
- type: "module",
264
- name: e?.name
265
- });
266
- return n.addEventListener("error", () => {
267
- (self.URL || self.webkitURL).revokeObjectURL(t);
268
- }), n;
269
- } catch {
270
- return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(Nt), {
271
- type: "module",
272
- name: e?.name
273
- });
274
- }
275
- }
276
- //#endregion
277
- //#region packages/docx/src/wasm/docx_parser_bg.wasm?url
278
- var It = new URL("docx_parser_bg.wasm", import.meta.url).href;
279
- //#endregion
280
- //#region packages/docx/src/bookmark-nav.ts
281
- function Lt(e) {
282
- let t = /* @__PURE__ */ new Map();
283
- for (let n of e.pages) for (let e of n.bookmarkStarts) e.name !== "" && !t.has(e.name) && t.set(e.name, n.pageIndex);
284
- return t;
285
- }
286
- //#endregion
287
- //#region packages/docx/src/embedded-fonts.ts
288
- async function Rt(e, t) {
289
- let n = e.embeddedFonts;
290
- if (!n || n.length === 0) return {
291
- faces: [],
292
- metrics: {}
293
- };
294
- let r = [], i = /* @__PURE__ */ new Set();
295
- for (let e of n) {
296
- let t = zt(e.style) === "bold" ? 700 : 400, n = Bt(e.style), a = `${je(e.fontName)}:${t}:${n}`;
297
- i.has(a) || (i.add(a), r.push(e));
298
- }
299
- let a = (await Promise.all(r.map(async (e) => {
300
- try {
301
- let n = await t(e.partPath), r = e.partPath.toLowerCase().endsWith(".odttf"), i = {
302
- family: e.fontName,
303
- bytes: n,
304
- odttf: r,
305
- fontKey: e.fontKey,
306
- weight: zt(e.style),
307
- style: Bt(e.style)
308
- };
309
- if (!De(n)) return {
310
- face: i,
311
- metric: null
312
- };
313
- let a = i, o = null;
314
- try {
315
- let t = r ? Se(n, e.fontKey ?? "") : n;
316
- a = {
317
- ...i,
318
- bytes: t,
319
- odttf: !1,
320
- fontKey: ""
321
- };
322
- let s = jt(t), c = s?.hasEastAsianCmap ? Ne(s) : 0;
323
- c > 0 && (o = Object.freeze({
324
- family: e.fontName,
325
- requestedFamily: e.fontName,
326
- weight: a.weight === "bold" ? 700 : 400,
327
- style: a.style,
328
- sourceIdentity: `embedded:${e.partPath}`,
329
- synthesized: !1,
330
- eastAsianLineHeightRatio: c
331
- }));
332
- } catch {}
333
- return {
334
- face: a,
335
- metric: o
336
- };
337
- } catch {
338
- return null;
339
- }
340
- }))).filter((e) => e !== null);
341
- if (a.length === 0) return {
342
- faces: [],
343
- metrics: {}
344
- };
345
- let o = await ye(a.map((e) => e.face)), s = new Set(o.map((e) => {
346
- let t = e.family.trim().replace(/^(['"])(.*)\1$/, "$2"), n = e.weight === "bold" ? 700 : Number(e.weight) || 400, r = e.style === "italic" ? "italic" : "normal";
347
- return `${je(t)}:${n}:${r}`;
348
- })), c = {};
349
- for (let e of a) {
350
- if (!e.metric) continue;
351
- let t = je(e.face.family), n = e.face.weight === "bold" ? 700 : 400, r = e.face.style, i = `${t}:${n}:${r}`;
352
- s.has(i) && (c[n === 400 && r === "normal" ? t : i] = e.metric);
353
- }
354
- return {
355
- faces: o,
356
- metrics: Object.freeze(c)
357
- };
358
- }
359
- function zt(e) {
360
- return e === "bold" || e === "boldItalic" ? "bold" : "normal";
361
- }
362
- function Bt(e) {
363
- return e === "italic" || e === "boldItalic" ? "italic" : "normal";
364
- }
365
- //#endregion
366
- //#region packages/docx/src/element-context.ts
367
- var F = pe, Vt = 16384;
368
- function Ht(e, t) {
369
- let n = Math.min(e.length, t);
370
- if (n > 0 && n < e.length) {
371
- let t = e.charCodeAt(n - 1), r = e.charCodeAt(n);
372
- t >= 55296 && t <= 56319 && r >= 56320 && r <= 57343 && n--;
373
- }
374
- return e.slice(0, n);
375
- }
376
- function Ut(e, t) {
377
- let n = [], r = 0, i = !1;
378
- for (let a of e) {
379
- if (a.length === 0) continue;
380
- if (r > 0) {
381
- if (r >= t) {
382
- i = !0;
383
- break;
384
- }
385
- n.push("\n"), r++;
386
- }
387
- let e = Ht(a, Math.max(0, t - r));
388
- if (n.push(e), r += e.length, e.length < a.length) {
389
- i = !0;
390
- break;
391
- }
392
- }
393
- let a = n.join("");
394
- return {
395
- ...a.length === 0 ? {} : { text: a },
396
- truncated: i
397
- };
398
- }
399
- function* I(e) {
400
- if (e.kind === "paragraph") {
401
- for (let t of e.lines) {
402
- let e = t.placements.flatMap((e) => e.kind === "text" ? [e.text] : []).join("");
403
- e && (yield e);
404
- }
405
- return;
406
- }
407
- if (e.kind === "table") {
408
- for (let t of e.rows) for (let e of t.cells) for (let t of e.blocks) yield* I(t.layout);
409
- return;
410
- }
411
- if (e.kind === "note" || e.kind === "textbox") for (let t of e.story.blocks) yield* I(t);
412
- }
413
- function* Wt(e) {
414
- for (let t of e.drawing.commands) (t.kind === "text" || t.kind === "watermark-text") && (yield t.text);
415
- for (let t of e.textBoxes) yield* I(t);
416
- }
417
- function Gt(e) {
418
- let t = e ?? Vt;
419
- if (!Number.isFinite(t) || t < 0) throw RangeError("maxTextCharacters must be a finite non-negative number.");
420
- return Math.min(F, Math.floor(t));
421
- }
422
- function Kt(e) {
423
- return {
424
- story: e.story,
425
- storyInstance: e.storyInstance,
426
- path: [...e.path]
427
- };
428
- }
429
- function qt(e) {
430
- return "drawing" in e ? e.drawing.inkBounds : e.placement.bounds;
431
- }
432
- function Jt(e) {
433
- let t = qt(e), n = [
434
- T(e.pointToPage, t),
435
- T(e.pointToPage, {
436
- xPt: t.xPt + t.widthPt,
437
- yPt: t.yPt
438
- }),
439
- T(e.pointToPage, {
440
- xPt: t.xPt,
441
- yPt: t.yPt + t.heightPt
442
- }),
443
- T(e.pointToPage, {
444
- xPt: t.xPt + t.widthPt,
445
- yPt: t.yPt + t.heightPt
446
- })
447
- ], r = Math.min(...n.map((e) => e.xPt)), i = Math.min(...n.map((e) => e.yPt)), a = Math.max(...n.map((e) => e.xPt)), o = Math.max(...n.map((e) => e.yPt));
448
- return {
449
- xPt: r,
450
- yPt: i,
451
- widthPt: a - r,
452
- heightPt: o - i
453
- };
454
- }
455
- function L(e, t) {
456
- return t.xPt >= e.xPt && t.xPt <= e.xPt + e.widthPt && t.yPt >= e.yPt && t.yPt <= e.yPt + e.heightPt;
457
- }
458
- function Yt(e, t) {
459
- let n = !1;
460
- for (let r = 0, i = t.length - 1; r < t.length; i = r++) {
461
- let a = t[r], o = t[i];
462
- a.yPt > e.yPt != o.yPt > e.yPt && e.xPt < (o.xPt - a.xPt) * (e.yPt - a.yPt) / (o.yPt - a.yPt) + a.xPt && (n = !n);
463
- }
464
- return n;
465
- }
466
- function Xt(e, t) {
467
- return L(e.inkBounds, t) ? e.clip ? e.clip.kind === "rect" ? L(e.clip.rect, t) : Yt(t, e.clip.points) : !0 : !1;
468
- }
469
- function Zt(e, t, n) {
470
- for (let n of e.clips) {
471
- let e = Me(n.pointToPage, t);
472
- if (!e || !L(n.bounds, e)) return !1;
473
- }
474
- return "drawing" in e ? Xt(e.drawing, n) : L(e.placement.bounds, n);
475
- }
476
- function R(e, t) {
477
- return e.commands.find((e) => e.kind === "resource" && e.resourceKind === t);
478
- }
479
- function Qt(e) {
480
- return R(e, "chart") ? "chart" : e.commands.some((e) => e.kind === "drawingml-shape" || e.kind === "drawingml-image-fill" || e.kind === "fill-rect" || e.kind === "stroke-rect" || e.kind === "text" || e.kind === "watermark-text") ? "shape" : R(e, "image") ? "image" : null;
481
- }
482
- function $t(e, t, n, r, i, a) {
483
- let o = "drawing" in e ? Qt(e.drawing) : e.placement.resourceKind;
484
- if (!o) return null;
485
- let s, c = !1, l, u;
486
- if (o === "chart") {
487
- let t = "drawing" in e ? R(e.drawing, "chart").resourceKey : e.placement.resourceKey, n = i.resolve(t, "chart"), r = ne(n.model, a);
488
- s = r.text, c = r.truncated, u = n.model.series.length;
489
- } else if (o === "image") {
490
- let t = "drawing" in e ? R(e.drawing, "image").resourceKey : e.placement.resourceKey, n = i.descriptors.find((e) => e.resourceKey === t && e.kind === "image" && "mimeType" in e);
491
- if (!n) throw Error(`Unknown image paint resource: ${t}`);
492
- l = n.mimeType;
493
- } else {
494
- let t = Ut(Wt(e), a);
495
- s = t.text, c = t.truncated;
496
- }
497
- return {
498
- format: "docx",
499
- kind: "element",
500
- pageIndex: t,
501
- elementIndex: n,
502
- elementType: o,
503
- point: { ...r },
504
- bounds: Jt(e),
505
- source: Kt("drawing" in e ? e.drawing.source : e.source),
506
- ...s === void 0 ? {} : { text: s },
507
- ...l === void 0 ? {} : { mimeType: l },
508
- ...u === void 0 ? {} : { seriesCount: u },
509
- truncated: c,
510
- truncationReasons: c ? ["text"] : [],
511
- textCharacters: s?.length ?? 0,
512
- maxTextCharacters: a
513
- };
514
- }
515
- function en(e, t, n, r, i = {}) {
516
- if (!Number.isFinite(n.xPt) || !Number.isFinite(n.yPt)) throw RangeError("DOCX hit-test point must contain finite page coordinates.");
517
- let a = Gt(i.maxTextCharacters), o = Ie(e, t);
518
- for (let e = o.length - 1; e >= 0; e--) {
519
- let i = o[e], s = Me(i.pointToPage, n);
520
- if (!s || !Zt(i, n, s)) continue;
521
- let c = $t(i, t, e, n, r, a);
522
- if (c) return c;
523
- }
524
- return null;
525
- }
526
- function tn(e, t, n, r) {
527
- return en(Qe(e, {
528
- currentDate: r.currentDate,
529
- defaultCurrentDateMs: r.defaultCurrentDateMs,
530
- showTrackedChanges: r.showTrackedChanges
531
- }, t).layout, t, n, Oe(e), r);
532
- }
533
- function nn(e, t) {
534
- let n = Gt(t), r = e.text === void 0 ? void 0 : Ht(e.text, n), i = e.truncated || e.text !== void 0 && r.length < e.text.length;
535
- return {
536
- ...structuredClone(e),
537
- ...r === void 0 ? {} : { text: r },
538
- truncated: i,
539
- truncationReasons: i ? ["text"] : [],
540
- textCharacters: r?.length ?? 0,
541
- maxTextCharacters: n
542
- };
543
- }
544
- //#endregion
545
- //#region packages/docx/src/revisions.ts
546
- function z(e) {
547
- let t = lt(e.id);
548
- return t === void 0 ? void 0 : `${e.kind}\u0000${t}`;
549
- }
550
- function B(e) {
551
- return Object.freeze({
552
- ...e,
553
- path: Object.freeze([...e.path])
554
- });
555
- }
556
- function rn(e, t) {
557
- return e !== void 0 && e.story === t.story && e.storyInstance === t.storyInstance && e.path.length === t.path.length && e.path.every((e, n) => e === t.path[n]);
558
- }
559
- function V(e, t) {
560
- let n = 0, r = e.length;
561
- for (; n < r;) {
562
- let i = n + Math.floor((r - n) / 2);
563
- e[i] < t ? n = i + 1 : r = i;
564
- }
565
- return n;
566
- }
567
- function an(e, t) {
568
- let n = Array(e.length), r;
569
- for (let i = e.length - 1; i >= 0; --i) {
570
- n[i] = r;
571
- let a = e[i], o = t.get(k(a.source))?.[0];
572
- o !== void 0 && (r = Object.freeze({
573
- source: B(a.source),
574
- sourceRunIndex: o
575
- }));
576
- }
577
- let i = Array(e.length), a;
578
- for (let n = 0; n < e.length; n += 1) {
579
- i[n] = a;
580
- let r = e[n], o = t.get(k(r.source))?.at(-1);
581
- o !== void 0 && (a = Object.freeze({
582
- source: B(r.source),
583
- sourceRunIndex: o
584
- }));
585
- }
586
- return {
587
- following: n,
588
- preceding: i
589
- };
590
- }
591
- function on(e, t, n, r, i, a) {
592
- let o = r[e], s = i.get(k(o.source)) ?? [], c = s[V(s, n)], l = s[V(s, t) - 1], u = c ?? l;
593
- return u === void 0 ? a.following[e] ?? a.preceding[e] : Object.freeze({
594
- source: B(o.source),
595
- sourceRunIndex: u
596
- });
597
- }
598
- function sn(e, t, n = /* @__PURE__ */ new Map()) {
599
- let r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Set();
600
- e.forEach((e, t) => {
601
- let n = z(e);
602
- n === void 0 || i.has(n) || (r.has(n) ? (r.delete(n), i.add(n)) : r.set(n, t));
603
- });
604
- let a = t.blocks.sources.flatMap((e) => {
605
- if (e.story !== "body") return [];
606
- let n = t.blocks.resolve(e);
607
- return n.type === "paragraph" ? [{
608
- source: e,
609
- runs: n.runs
610
- }] : [];
611
- }), o = new Map([...n].map(([e, t]) => [e, Object.freeze([...t].sort((e, t) => e - t))])), s = an(a, o), c = [];
612
- for (let [e, t] of a.entries()) {
613
- let n = 0;
614
- for (; n < t.runs.length;) {
615
- let i = t.runs[n], l = i.revision?.kind ? z({
616
- kind: i.revision.kind,
617
- id: i.revision.id
618
- }) : void 0, u = l === void 0 ? void 0 : r.get(l);
619
- if (u === void 0) {
620
- n += 1;
621
- continue;
622
- }
623
- let d = n;
624
- for (n += 1; n < t.runs.length;) {
625
- let e = t.runs[n].revision;
626
- if (!e?.kind || z({
627
- kind: e.kind,
628
- id: e.id
629
- }) !== l) break;
630
- n += 1;
631
- }
632
- let f = n, p = o.get(k(t.source)) ?? [], m = (p[V(p, d)] ?? f) < f ? void 0 : on(e, d, f, a, o, s);
633
- c.push(Object.freeze({
634
- revisionIndex: u,
635
- source: B(t.source),
636
- startRunIndex: d,
637
- endRunIndex: f,
638
- ...m === void 0 ? {} : { geometryFallback: m }
639
- }));
640
- }
641
- }
642
- return c;
643
- }
644
- function cn(e, t, n = /* @__PURE__ */ new Map(), r = {}) {
645
- if ((e?.length ?? 0) === 0) return [];
646
- let i = sn(e ?? [], t, n), a = r.completedSourceKeys;
647
- return a === void 0 ? i : i.filter((e) => {
648
- let t = n.get(k(e.source));
649
- return t !== void 0 && [...t].some((t) => t >= e.startRunIndex && t < e.endRunIndex) || a.has(k(e.source));
650
- });
651
- }
652
- function ln(e, t) {
653
- let n = t.filter((t) => t.sourceRunIndex !== void 0 && rn(t.source, e.source) && t.sourceRunIndex >= e.startRunIndex && t.sourceRunIndex < e.endRunIndex);
654
- if (n.length > 0) return n;
655
- let r = e.geometryFallback;
656
- return r === void 0 ? [] : t.filter((e) => e.sourceRunIndex === r.sourceRunIndex && rn(e.source, r.source));
657
- }
658
- //#endregion
659
- //#region packages/docx/src/layout/progressive.ts
660
- var un = 12;
661
- async function dn(e, t, n, r = {}) {
662
- let { onPreview: i, scheduler: a } = r;
663
- return Be(Pe(e, t, n, i && e.sequence.length > un ? { onPages: (e, t) => {
664
- i(Object.freeze({
665
- layout: e,
666
- exact: !1,
667
- coveredEntries: t
668
- }));
669
- } } : void 0), a);
670
- }
671
- //#endregion
672
- //#region packages/docx/src/document-layout-events.ts
673
- var H = /* @__PURE__ */ new WeakMap();
674
- function U(e, t) {
675
- let n = Object.freeze({ ...t });
676
- for (let t of [...H.get(e) ?? []]) try {
677
- t.notify(n);
678
- } catch (e) {
679
- try {
680
- t.report(e);
681
- } catch {}
682
- }
683
- }
684
- function fn(e, t, n, r) {
685
- let i = H.get(e);
686
- i || (i = /* @__PURE__ */ new Set(), H.set(e, i));
687
- let a = Object.freeze({
688
- notify: n,
689
- report: r
690
- });
691
- i.add(a);
692
- try {
693
- n(Object.freeze({ ...t() }));
694
- } catch (e) {
695
- try {
696
- r(e);
697
- } catch {}
698
- }
699
- return () => {
700
- i?.delete(a), i?.size === 0 && H.delete(e);
701
- };
702
- }
703
- //#endregion
704
- //#region packages/docx/src/document-layout-view.ts
705
- var W = /* @__PURE__ */ new WeakMap(), pn = /* @__PURE__ */ new WeakMap(), mn = Symbol("docxLayoutViewRequester");
706
- function G(e) {
707
- let t = E(e), n = t.activeLayoutOptions;
708
- return {
709
- showTrackedChanges: n?.showTrackedChanges === !0,
710
- currentDate: n?.currentDateMs ?? t.defaultCurrentDateMs
711
- };
712
- }
713
- async function K(e, t, n) {
714
- let r = E(e), i = Ae(t.currentDate, r.defaultCurrentDateMs, t.showTrackedChanges === !0), a = Object.freeze({
715
- showTrackedChanges: i.showTrackedChanges === !0,
716
- currentDate: i.currentDateMs
717
- }), o = {
718
- showTrackedChanges: a.showTrackedChanges,
719
- currentDate: a.currentDate,
720
- [mn]: n
721
- };
722
- await e.setLayoutView(o);
723
- let s = G(e);
724
- return s.currentDate === a.currentDate && s.showTrackedChanges === a.showTrackedChanges;
725
- }
726
- function hn(e, t) {
727
- let n = Object.freeze({ ...G(e) }), r = (pn.get(e) ?? 0) + 1;
728
- pn.set(e, r);
729
- let i = Object.freeze({
730
- view: n,
731
- generation: r,
732
- requester: t
733
- });
734
- for (let t of [...W.get(e) ?? []]) try {
735
- t.notify(i);
736
- } catch (e) {
737
- try {
738
- t.report(e);
739
- } catch {}
740
- }
741
- }
742
- function gn(e, t, n) {
743
- let r = W.get(e);
744
- r || (r = /* @__PURE__ */ new Set(), W.set(e, r));
745
- let i = Object.freeze({
746
- notify: t,
747
- report: n
748
- });
749
- return r.add(i), () => {
750
- r?.delete(i), r?.size === 0 && W.delete(e);
751
- };
752
- }
753
- //#endregion
754
- //#region packages/docx/src/document.ts
755
- function _n(e, t) {
756
- return e !== null && e.currentDateMs === t.currentDateMs && e.showTrackedChanges === !0 == (t.showTrackedChanges === !0);
757
- }
758
- function vn() {
759
- let e, t;
760
- return {
761
- promise: new Promise((n, r) => {
762
- e = n, t = r;
763
- }),
764
- resolve: e,
765
- reject: t
766
- };
767
- }
768
- var yn = Object.freeze([]), bn = Object.freeze([]), xn = Object.freeze({
769
- comments: Object.freeze([]),
770
- revisions: Object.freeze([])
771
- });
772
- function q(e, t) {
773
- return He({
774
- comments: e,
775
- revisions: t
776
- }, "DOCX review metadata");
777
- }
778
- var J = class e {
779
- _metrics = null;
780
- _cjkFallback = "jp";
781
- _document = null;
782
- _source = null;
783
- _meta = null;
784
- _review = xn;
785
- _layoutLifecycle = new xe();
786
- _layoutObservers = new we();
787
- _layoutCompletion = null;
788
- _layoutAbort = null;
789
- _bookmarkPages = null;
790
- _commentAnchorRanges = null;
791
- _revisionAnchorRanges = null;
792
- _reviewProjectionIndex = null;
793
- _parseRequestId = null;
794
- _progressive = null;
795
- _parseWatchdog;
796
- _parseWatchdogMs;
797
- _layoutViewGeneration = 0;
798
- _mode = "main";
799
- _threeD;
800
- _regionMap;
801
- _chartEx;
802
- _tiff;
803
- _worker;
804
- _bridge;
805
- _rawParts = new ct({
806
- maxEntries: 64,
807
- maxBytes: n
808
- });
809
- _embeddedFontFaces = [];
810
- _googleFontFaces = [];
811
- _fetchImage = (e, t) => this.getImage(e, t);
812
- constructor(e, t, n, r) {
813
- this._worker = e, this._mode = t, ke(this, n), this._bridge = new he(this._worker, {
814
- correlate: (e) => "protocol" in e && e.protocol === "ooxml-pull-v1" ? e.requestId : "id" in e ? e.id : void 0,
815
- onUnsolicited: (e) => this._onWorkerLayoutPush(e),
816
- toError: (e) => {
817
- if (!("protocol" in e || e.type !== "error")) return Object.assign(a(e), {
818
- ...e.reason === void 0 ? {} : { reason: e.reason },
819
- ...e.outgoingColumnIndex === void 0 ? {} : { outgoingColumnIndex: e.outgoingColumnIndex },
820
- ...e.outgoingColumnCount === void 0 ? {} : { outgoingColumnCount: e.outgoingColumnCount },
821
- ...e.incomingColumnCount === void 0 ? {} : { incomingColumnCount: e.incomingColumnCount }
822
- });
823
- }
824
- });
825
- let i = new URL(r ?? It, location.href).href;
826
- this._bridge.post({
827
- type: "init",
828
- wasmUrl: i
829
- });
830
- }
831
- static async load(t, n = {}) {
832
- let i = tt(n.cjkFallback), a = f(n), o = Date.now(), s = n.mode ?? "main", c = new r({
833
- enabled: !0,
834
- format: "docx",
835
- mode: s,
836
- policy: a.policy,
837
- onMetrics: a.onResourceMetrics,
838
- emitToConsole: a.debug
839
- });
840
- try {
841
- if (s === "worker" && (typeof Worker > "u" || typeof OffscreenCanvas > "u")) throw Error("mode: 'worker' requires Worker and OffscreenCanvas support");
842
- let r;
843
- if (typeof t == "string") {
844
- let e = await fetch(t);
845
- if (!e.ok) throw Error(`Failed to fetch: ${e.status} ${e.statusText}`);
846
- r = await e.arrayBuffer();
847
- } else r = t;
848
- r = g(await h(r, n.password)), c.setSourceBytes(r.byteLength), c.checkpoint("container ready");
849
- let l = s === "worker" ? (await import("./render-worker-host-Di3LxLc0.js")).createRenderWorker() : new Ft(), u = s === "worker" ? ot(n) : void 0, d = s === "worker" && !!n.progressiveLayout, f;
850
- try {
851
- f = new e(l, s, o, n.wasmUrl), f._metrics = c, f._cjkFallback = i;
852
- let t = E(f), p = Ae(n.currentDate, t.defaultCurrentDateMs, n.showTrackedChanges === !0);
853
- t.activeLayoutOptions = p, await f._parse(r, a.policy, s === "worker" ? !!n.useGoogleFonts : !1, n.workerTimeoutMs, (e) => c.observeUsage(e), u, d ? {
854
- onPartial: n.onLayoutPartial,
855
- onComplete: n.onLayoutComplete,
856
- onProgress: n.onLayoutProgress,
857
- layoutOptions: p,
858
- abort: new AbortController(),
859
- firstPublication: vn(),
860
- published: !1,
861
- settled: !1
862
- } : void 0), s === "worker" && f._mode === "main" && (c.setMode("main"), console.warn("[ooxml] mode: 'worker' fell back to main-thread rendering because this document requires DOM OpenType vertical glyph selection.")), n.math && f._mode === "worker" && !u?.math && console.warn("[ooxml] a custom math renderer cannot cross the worker boundary; equations will be skipped in mode: 'worker'. Use the math renderer from @silurus/ooxml/math."), n.threeD && f._mode === "worker" && !u?.threeD && console.warn("[ooxml] a custom 3-D chart renderer cannot cross the worker boundary; charts use their 2-D family fallback in mode: 'worker'. Use the renderer from @silurus/ooxml/three-d."), f._threeD = f._mode === "worker" ? void 0 : n.threeD, n.regionMap && f._mode === "worker" && !u?.regionMap && console.warn("[ooxml] a custom Region Map renderer cannot cross the worker boundary; geospatial charts use the unsupported-chart placeholder in mode: 'worker'. Use the renderer from @silurus/ooxml/region-map."), f._regionMap = f._mode === "worker" ? void 0 : n.regionMap, n.chartEx && f._mode === "worker" && !u?.chartEx && console.warn("[ooxml] a custom ChartEx renderer cannot cross the worker boundary; ChartEx charts use the unsupported-chart placeholder in mode: 'worker'. Use the renderer from @silurus/ooxml/chart-ex."), f._chartEx = f._mode === "worker" ? void 0 : n.chartEx, n.tiff && f._mode === "worker" && !u?.tiff && console.warn("[ooxml] a custom TIFF codec cannot cross the worker boundary; recognized TIFF images will use an unavailable-image placeholder in mode: 'worker'. Use the codec from @silurus/ooxml/tiff to display them."), f._tiff = f._mode === "worker" ? void 0 : n.tiff, f._mode === "main" && n.useGoogleFonts && f._document && (f._googleFontFaces = await m(ze(f._document, i), Re));
863
- let h;
864
- if (f._mode === "main" && f._document?.embeddedFonts?.length) {
865
- let e = f, t = await Rt(f._document, (t) => e.getFontBytes(t));
866
- f._embeddedFontFaces = t.faces, h = t.metrics;
867
- }
868
- let g;
869
- if (f._mode === "main" && n.math && f._document && qe(f._document) && (g = await Ye(f._document, n.math)), f._mode === "main" && f._document && f._source) {
870
- let e = f, t = E(f);
871
- t.services = We(f._source, {
872
- fontMetrics: h,
873
- measureResolvedFontMetrics: !0,
874
- resolvedFontMetricCandidates: Je(f._document, f._source.fontFamilyCharsets),
875
- useGoogleFonts: !!n.useGoogleFonts,
876
- cjkFallback: i,
877
- embeddedFaces: f._embeddedFontFaces,
878
- googleFaces: f._googleFontFaces,
879
- mathResources: g?.records,
880
- mathDrawables: g?.drawables
881
- });
882
- let r = t.services, a = Fe(f._source, r, t.defaultCurrentDateMs), o = f._source.fatalParse === null, s = t.activeLayoutOptions;
883
- if (!s) throw Error("Active layout view was not recorded at load");
884
- let c = { onProgress: n.onLayoutProgress ? (t) => e._layoutObservers.notify("onLayoutProgress", n.onLayoutProgress, { committedUnits: t }) : void 0 };
885
- if (o && n.progressiveLayout) {
886
- let e = a.layoutVariants, t = f, i = new AbortController();
887
- t._layoutAbort = i;
888
- let o = vn(), l = null, u = !0;
889
- t._layoutCompletion = dn(f._source.bodyLayoutInput, r, s, {
890
- scheduler: {
891
- ...c,
892
- signal: i.signal
893
- },
894
- onPreview: (r) => {
895
- if (!u) return;
896
- let i = l === null, a = t._replaceMainLayoutPublication(e, s, l, r.layout);
897
- if (a === null) {
898
- u = !1;
899
- return;
900
- }
901
- if (l = a, i) t._layoutLifecycle.begin(), U(t, {
902
- pageCount: r.layout.pages.length,
903
- exact: r.exact,
904
- complete: !1
905
- }), o.resolve();
906
- else {
907
- if (!t._isLayoutViewActive(s)) return;
908
- U(t, {
909
- pageCount: r.layout.pages.length,
910
- exact: r.exact,
911
- complete: !1
912
- }), t._layoutObservers.notify("onLayoutPartial", n.onLayoutPartial, {
913
- availableUnits: r.layout.pages.length,
914
- exact: r.exact
915
- });
916
- }
917
- }
918
- }).then((r) => {
919
- u && t._replaceMainLayoutPublication(e, s, l, r) === null && (u = !1), t._layoutLifecycle.succeed(), U(t, {
920
- pageCount: t.pageCount,
921
- exact: !0,
922
- complete: !0
923
- }), t._layoutObservers.notify("onLayoutComplete", n.onLayoutComplete), o.resolve();
924
- }).catch((e) => {
925
- if (l === null) {
926
- o.reject(e);
927
- return;
928
- }
929
- if (e instanceof Ve) {
930
- t._layoutLifecycle.succeed();
931
- return;
932
- }
933
- let r = t._layoutLifecycle.fail(e);
934
- U(t, {
935
- pageCount: t.pageCount,
936
- exact: !1,
937
- complete: !1,
938
- error: r
939
- }), t._layoutObservers.notify("onLayoutComplete", n.onLayoutComplete, r);
940
- }), await o.promise;
941
- } else if (o && (n.sliceLayout || n.onLayoutProgress)) {
942
- let e = await Ge(f._source.bodyLayoutInput, r, s, c);
943
- a.layoutVariants.prime(s, e);
944
- } else a.layoutVariants.layoutFor(s);
945
- }
946
- return await f._resourceUsage(n.workerTimeoutMs ?? 1e3).then((e) => c.observeUsage(e), () => void 0), c.checkpoint("model and layout ready"), c.succeed({ pages: f.pageCount }), f;
947
- } catch (e) {
948
- let t = f;
949
- throw p(l, t ? () => t.destroy() : void 0), e;
950
- }
951
- } catch (e) {
952
- throw c.fail(e), e;
953
- }
954
- }
955
- async _parse(e, t, n = !1, r, i, a, o) {
956
- if (o) {
957
- await this._parseProgressively(e, t, n, r, i, a, o);
958
- return;
959
- }
960
- let s = await this._bridge.request((r) => this._mode === "worker" ? {
961
- type: "parse",
962
- id: r,
963
- data: e,
964
- resourcePolicy: t,
965
- useGoogleFonts: n,
966
- cjkFallback: this._cjkFallback,
967
- defaultCurrentDateMs: E(this).defaultCurrentDateMs,
968
- ...this._parseViewFields(),
969
- renderers: a
970
- } : {
971
- type: "parse",
972
- id: r,
973
- data: e,
974
- resourcePolicy: t
975
- }, [e], { timeoutMs: r });
976
- if ("protocol" in s) throw Error("DOCX parse open returned a pull-protocol response");
977
- if (this._mode === "worker") if ("usage" in s && s.usage && i?.(s.usage), s.type === "mainThreadVerticalFallback") {
978
- let e = await Ke(this._bridge.transport(Xe), s, {
979
- timeoutMs: r,
980
- onUsage: i
981
- });
982
- this._source = e.source, this._document = e.document, this._meta = null, this._mode = "main";
983
- } else this._meta = s.meta;
984
- else {
985
- let e = s, t = await Ke(this._bridge.transport(Xe), e, {
986
- timeoutMs: r,
987
- onUsage: i
988
- });
989
- this._source = t.source, this._document = t.document;
990
- }
991
- this._review = q(this._meta?.comments ?? this._document?.comments ?? [], this._meta?.revisions ?? this._document?.revisions ?? []);
992
- }
993
- _onWorkerLayoutPush(e) {
994
- if (v((e, t) => this._worker.postMessage(e, t), e) || !("forId" in e) || e.forId !== this._parseRequestId) return;
995
- this._rearmParseWatchdog();
996
- let t = this._progressive;
997
- if (t?.settled) return;
998
- if (e.type === "layoutProgress") {
999
- this._layoutObservers.notify("onLayoutProgress", t?.onProgress, { committedUnits: e.committedPages });
1000
- return;
1001
- }
1002
- if (e.type !== "layoutPartial" || !t) return;
1003
- let n = !t.published || this._isLayoutViewActive(t.layoutOptions);
1004
- if (n && this._applyLayoutPartial(e.partial), t.published) {
1005
- if (!n) return;
1006
- U(this, {
1007
- pageCount: e.partial.pageCount,
1008
- exact: e.partial.exact,
1009
- complete: !1
1010
- }), this._layoutObservers.notify("onLayoutPartial", t.onPartial, {
1011
- availableUnits: e.partial.pageCount,
1012
- exact: e.partial.exact
1013
- });
1014
- return;
1015
- }
1016
- t.published = !0, this._layoutLifecycle.begin(), U(this, {
1017
- pageCount: e.partial.pageCount,
1018
- exact: e.partial.exact,
1019
- complete: !1
1020
- }), t.firstPublication.resolve();
1021
- }
1022
- _applyLayoutPartial(e) {
1023
- let t = e.review ?? this._meta;
1024
- this._meta = {
1025
- pageCount: e.pageCount,
1026
- pageSizes: e.pageSizes,
1027
- bookmarkPages: e.bookmarkPages,
1028
- revisions: t?.revisions ?? [],
1029
- comments: t?.comments ?? [],
1030
- footnotes: t?.footnotes ?? [],
1031
- endnotes: t?.endnotes ?? [],
1032
- commentAnchorRanges: e.commentAnchorRanges,
1033
- revisionAnchorRanges: e.revisionAnchorRanges
1034
- }, e.review && (this._review = q(e.review.comments, e.review.revisions)), this._invalidateLayoutDerivedCaches();
1035
- }
1036
- _onAuthoritativeMeta(e) {
1037
- this._clearParseWatchdog();
1038
- let t = this._progressive;
1039
- if (!t?.settled) {
1040
- if (!t || this._isLayoutViewActive(t.layoutOptions) || !this._meta) this._meta = e;
1041
- else {
1042
- let t = this._meta;
1043
- this._meta = {
1044
- ...e,
1045
- pageCount: t.pageCount,
1046
- pageSizes: t.pageSizes,
1047
- bookmarkPages: t.bookmarkPages,
1048
- commentAnchorRanges: t.commentAnchorRanges,
1049
- revisionAnchorRanges: t.revisionAnchorRanges
1050
- };
1051
- }
1052
- this._invalidateLayoutDerivedCaches(), this._review = q(e.comments, e.revisions), t && (t.settled = !0, this._layoutLifecycle.succeed(), U(this, {
1053
- pageCount: this.pageCount,
1054
- exact: !0,
1055
- complete: !0
1056
- }), t.firstPublication.resolve(), this._layoutObservers.notify("onLayoutComplete", t.onComplete));
1057
- }
1058
- }
1059
- _invalidateLayoutDerivedCaches() {
1060
- this._bookmarkPages = null, this._commentAnchorRanges = null, this._revisionAnchorRanges = null, this._reviewProjectionIndex = null;
1061
- }
1062
- _replaceMainLayoutPublication(e, t, n, r) {
1063
- let i = e.replaceIfCurrent(t, n, r);
1064
- return i !== null && this._isLayoutViewActive(t) && this._invalidateLayoutDerivedCaches(), i;
1065
- }
1066
- _isLayoutViewActive(e) {
1067
- return _n(E(this).activeLayoutOptions, e);
1068
- }
1069
- _rearmParseWatchdog() {
1070
- this._parseWatchdogMs !== void 0 && (clearTimeout(this._parseWatchdog), this._parseWatchdog = setTimeout(() => this._onParseWentSilent(), this._parseWatchdogMs));
1071
- }
1072
- _clearParseWatchdog() {
1073
- clearTimeout(this._parseWatchdog), this._parseWatchdog = void 0, this._parseWatchdogMs = void 0;
1074
- }
1075
- _onParseWentSilent() {
1076
- let e = this._progressive, t = this._parseWatchdogMs;
1077
- this._clearParseWatchdog();
1078
- let n = /* @__PURE__ */ Error(`worker layout produced no progress for ${t}ms`);
1079
- e && this._failWorkerProgressive(e, n), this._bridge.terminate();
1080
- }
1081
- _failWorkerProgressive(e, t) {
1082
- if (e.settled) return;
1083
- if (e.settled = !0, this._clearParseWatchdog(), !e.published) {
1084
- e.firstPublication.reject(t);
1085
- return;
1086
- }
1087
- let n = this._layoutLifecycle.fail(t);
1088
- U(this, {
1089
- pageCount: this.pageCount,
1090
- exact: !1,
1091
- complete: !1,
1092
- error: n
1093
- }), this._layoutObservers.notify("onLayoutComplete", e.onComplete, n);
1094
- }
1095
- _parseViewFields() {
1096
- let e = E(this), t = e.activeLayoutOptions;
1097
- return t ? {
1098
- ...t.currentDateMs === e.defaultCurrentDateMs ? {} : { currentDateMs: t.currentDateMs },
1099
- ...t.showTrackedChanges === !0 ? { showTrackedChanges: !0 } : {}
1100
- } : {};
1101
- }
1102
- async _parseProgressively(e, t, n, r, i, a, o) {
1103
- this._progressive = o, this._layoutAbort = o.abort, this._parseWatchdogMs = r, this._layoutCompletion = this._bridge.request((r) => (this._parseRequestId = r, {
1104
- type: "parse",
1105
- id: r,
1106
- data: e,
1107
- resourcePolicy: t,
1108
- useGoogleFonts: n,
1109
- cjkFallback: this._cjkFallback,
1110
- defaultCurrentDateMs: E(this).defaultCurrentDateMs,
1111
- ...this._parseViewFields(),
1112
- renderers: a,
1113
- progressiveLayout: !0
1114
- }), [e], { timeoutMs: !1 }).then(async (e) => {
1115
- if (this._parseRequestId = null, "protocol" in e) throw Error("DOCX parse open returned a pull-protocol response");
1116
- if ("usage" in e && e.usage && i?.(e.usage), e.type === "mainThreadVerticalFallback") {
1117
- this._clearParseWatchdog(), o.settled = !0, this._progressive = null, this._layoutAbort = null;
1118
- let t = await Ke(this._bridge.transport(Xe), e, {
1119
- timeoutMs: r,
1120
- onUsage: i
1121
- });
1122
- this._source = t.source, this._document = t.document, this._meta = null, this._mode = "main", this._review = q(t.document.comments ?? [], t.document.revisions ?? []), o.firstPublication.resolve();
1123
- return;
1124
- }
1125
- this._onAuthoritativeMeta(e.meta);
1126
- }, (e) => {
1127
- if (this._parseRequestId = null, this._clearParseWatchdog(), !o.settled) {
1128
- if (o.abort.signal.aborted) {
1129
- o.settled = !0, this._layoutLifecycle.succeed(), o.firstPublication.resolve();
1130
- return;
1131
- }
1132
- this._failWorkerProgressive(o, e);
1133
- }
1134
- }), this._rearmParseWatchdog(), await o.firstPublication.promise;
1135
- }
1136
- destroy() {
1137
- this._layoutAbort?.abort(), this._layoutAbort = null, this._clearParseWatchdog(), this._parseRequestId = null, this._progressive = null, this._layoutViewGeneration++, this._bridge.terminate(), this._document = null, this._source = null, this._meta = null, this._review = xn, E(this).services = null, this._bookmarkPages = null, this._commentAnchorRanges = null, this._revisionAnchorRanges = null, this._reviewProjectionIndex = null, this._rawParts.clear(), this._embeddedFontFaces.length > 0 && (be(this._embeddedFontFaces), this._embeddedFontFaces = []), this._googleFontFaces.length > 0 && (_(this._googleFontFaces), this._googleFontFaces = []), s(this._fetchImage), l(this._fetchImage);
1138
- }
1139
- async getImage(e, t) {
1140
- return this._rawParts.get(e, t, () => this._bridge.request((t) => ({
1141
- type: "extractImage",
1142
- id: t,
1143
- path: e
1144
- })).then((e) => {
1145
- let n = e.bytes;
1146
- return new Blob([n], { type: t });
1147
- }));
1148
- }
1149
- async getFontBytes(e) {
1150
- let t = (await this._bridge.request((t) => ({
1151
- type: "extractImage",
1152
- id: t,
1153
- path: e
1154
- }))).bytes;
1155
- return new Uint8Array(t);
1156
- }
1157
- async _resourceUsage(e) {
1158
- return (await this._bridge.request((e) => ({
1159
- type: "resourceUsage",
1160
- id: e
1161
- }), void 0, { timeoutMs: e })).usage;
1162
- }
1163
- async getResourceMetrics() {
1164
- let e = this._metrics;
1165
- if (!e) throw Error("Document not loaded");
1166
- return i(e, (e) => this._resourceUsage(e));
1167
- }
1168
- async toMarkdown() {
1169
- return (await this._bridge.request((e) => ({
1170
- type: "toMarkdown",
1171
- id: e
1172
- }))).markdown;
1173
- }
1174
- get pageCount() {
1175
- return this._meta ? this._meta.pageCount : this._document ? this._getLayout()?.pages.length ?? 0 : 0;
1176
- }
1177
- get layoutComplete() {
1178
- return this._layoutLifecycle.complete;
1179
- }
1180
- async waitUntilLayoutComplete() {
1181
- this._layoutCompletion && await this._layoutCompletion, this._layoutLifecycle.throwIfFailed();
1182
- }
1183
- get mode() {
1184
- return this._mode;
1185
- }
1186
- get document() {
1187
- 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");
1188
- if (!this._document) throw Error("Document not loaded");
1189
- return this._document;
1190
- }
1191
- get comments() {
1192
- return this._reviewSnapshot().comments;
1193
- }
1194
- get revisions() {
1195
- return this._reviewSnapshot().revisions;
1196
- }
1197
- commentAnchorRanges() {
1198
- if (this._meta) return this._meta.commentAnchorRanges ?? yn;
1199
- if (!this._document || !this._source) return [];
1200
- let e = this._reviewSnapshot().comments;
1201
- if (e.length === 0) return yn;
1202
- let t = E(this), n = t.services;
1203
- if (!n) throw Error("Document layout services are not initialized");
1204
- let r = Ue(n);
1205
- if (!r) throw Error("Document layout variant store is not initialized");
1206
- let i = t.activeLayoutOptions, a = i ? r.layoutFor(i) : r.defaultLayout;
1207
- this._reviewProjectionIndex ??= $e(a);
1208
- let o = this._layoutLifecycle?.complete ?? !0 ? void 0 : { completedSourceKeys: this._reviewProjectionIndex.completedSourceKeys };
1209
- return this._commentAnchorRanges ??= dt(e, this._source, this._reviewProjectionIndex.renderedRunIndex, o), this._commentAnchorRanges;
1210
- }
1211
- revisionAnchorRanges() {
1212
- if (this._meta) return this._meta.revisionAnchorRanges ?? bn;
1213
- if (!this._document || !this._source) return [];
1214
- let e = this._reviewSnapshot().revisions;
1215
- if (e.length === 0) return bn;
1216
- let t = E(this), n = t.services;
1217
- if (!n) throw Error("Document layout services are not initialized");
1218
- let r = Ue(n);
1219
- if (!r) throw Error("Document layout variant store is not initialized");
1220
- let i = t.activeLayoutOptions, a = i ? r.layoutFor(i) : r.defaultLayout;
1221
- this._reviewProjectionIndex ??= $e(a);
1222
- let o = this._layoutLifecycle?.complete ?? !0 ? void 0 : { completedSourceKeys: this._reviewProjectionIndex.completedSourceKeys };
1223
- return this._revisionAnchorRanges ??= cn(e, this._source, this._reviewProjectionIndex.renderedRunIndex, o), this._revisionAnchorRanges;
1224
- }
1225
- _reviewSnapshot() {
1226
- return this._review ||= q(this._meta?.comments ?? this._document?.comments ?? [], this._meta?.revisions ?? this._document?.revisions ?? []), this._review;
1227
- }
1228
- get footnotes() {
1229
- return this._meta?.footnotes ?? this._document?.footnotes ?? [];
1230
- }
1231
- get endnotes() {
1232
- return this._meta?.endnotes ?? this._document?.endnotes ?? [];
1233
- }
1234
- _getLayout() {
1235
- if (!this._document) return null;
1236
- let e = E(this), t = e.services;
1237
- if (!t) throw Error("Document layout services are not initialized");
1238
- let n = Ue(t);
1239
- if (!n) throw Error("Document layout variant store is not initialized");
1240
- let r = e.activeLayoutOptions;
1241
- return r ? n.layoutFor(r) : n.defaultLayout;
1242
- }
1243
- async setLayoutView(e = {}) {
1244
- let t = e[mn], n = E(this), r = Ae(e.currentDate, n.defaultCurrentDateMs, e.showTrackedChanges === !0), i = ++this._layoutViewGeneration, a = n.activeLayoutOptions;
1245
- if (!_n(a, r)) {
1246
- if (this._mode === "worker" && this._meta) {
1247
- let e = await this._bridge.request((e) => ({
1248
- type: "selectLayoutView",
1249
- id: e,
1250
- currentDateMs: r.currentDateMs,
1251
- showTrackedChanges: r.showTrackedChanges === !0
1252
- }));
1253
- if (i !== this._layoutViewGeneration) return;
1254
- let a = e;
1255
- n.activeLayoutOptions = r, this._meta = {
1256
- ...this._meta,
1257
- ...a.meta
1258
- }, this._invalidateLayoutDerivedCaches(), hn(this, t);
1259
- return;
1260
- }
1261
- n.activeLayoutOptions = r, this._invalidateLayoutDerivedCaches(), hn(this, t);
1262
- }
1263
- }
1264
- _getBookmarkPages() {
1265
- if (this._bookmarkPages) return this._bookmarkPages;
1266
- if (this._meta) return this._bookmarkPages = new Map(this._meta.bookmarkPages), this._bookmarkPages;
1267
- let e = this._getLayout();
1268
- return e ? (this._bookmarkPages = Lt(e), this._bookmarkPages) : null;
1269
- }
1270
- getBookmarkPage(e) {
1271
- return this._getBookmarkPages()?.get(e);
1272
- }
1273
- pageSize(e) {
1274
- if (this._meta) {
1275
- let t = this._meta.pageSizes, n = t[Math.max(0, Math.min(e, t.length - 1))];
1276
- return n ? {
1277
- widthPt: n.widthPt,
1278
- heightPt: n.heightPt
1279
- } : {
1280
- widthPt: 0,
1281
- heightPt: 0
1282
- };
1283
- }
1284
- if (!this._document) return {
1285
- widthPt: 0,
1286
- heightPt: 0
1287
- };
1288
- let t = this._getLayout();
1289
- if (!t || t.pages.length === 0) return {
1290
- widthPt: 0,
1291
- heightPt: 0
1292
- };
1293
- let n = Math.max(0, Math.min(e, t.pages.length - 1)), r = t.pages[n].geometry;
1294
- return {
1295
- widthPt: r.widthPt,
1296
- heightPt: r.heightPt
1297
- };
1298
- }
1299
- _withActiveView(e) {
1300
- let t = E(this).activeLayoutOptions;
1301
- if (!t) return e;
1302
- let n = { ...e };
1303
- return e.currentDate === void 0 && (n.currentDate = t.currentDateMs), e.showTrackedChanges === void 0 && t.showTrackedChanges === !0 && (n.showTrackedChanges = !0), n;
1304
- }
1305
- renderPage(e, t, n = {}) {
1306
- if (this._mode === "worker") throw Error("renderPage(canvas) is unavailable in mode: 'worker'; use renderPageToBitmap() and paint it via an ImageBitmapRenderingContext");
1307
- if (!this._source) throw Error("Document not loaded");
1308
- return Le(this._source, e, t, {
1309
- ...this._withActiveView(n),
1310
- fetchImage: this._fetchImage,
1311
- layoutServices: E(this).services ?? void 0,
1312
- defaultCurrentDateMs: E(this).defaultCurrentDateMs,
1313
- threeD: this._threeD,
1314
- regionMap: this._regionMap,
1315
- chartEx: this._chartEx,
1316
- tiff: this._tiff
1317
- });
1318
- }
1319
- async renderPageToBitmap(e, n = {}) {
1320
- let { onTextRun: r, ...i } = n, a = {
1321
- ...this._withActiveView(i),
1322
- dpr: i.dpr ?? t()
1323
- };
1324
- if (this._mode === "worker") {
1325
- let t = await this._bridge.request((t) => ({
1326
- type: "renderPage",
1327
- id: t,
1328
- pageIndex: e,
1329
- opts: a
1330
- }));
1331
- try {
1332
- if (r) for (let e of t.runs) r(e);
1333
- } catch (e) {
1334
- throw o(t.bitmap), e;
1335
- }
1336
- return t.bitmap;
1337
- }
1338
- let s = new OffscreenCanvas(1, 1);
1339
- return await this.renderPage(s, e, {
1340
- ...a,
1341
- onTextRun: r
1342
- }), s.transferToImageBitmap();
1343
- }
1344
- async collectPageRuns(e, t = {}) {
1345
- let n = { ...this._withActiveView(t) };
1346
- if (this._mode === "worker") return (await this._bridge.request((t) => ({
1347
- type: "collectRuns",
1348
- id: t,
1349
- pageIndex: e,
1350
- opts: n
1351
- }))).runs;
1352
- let r = E(this), i = r.services;
1353
- if (!i) throw Error("Document layout services are not initialized");
1354
- return et(i, e, {
1355
- currentDate: n.currentDate,
1356
- defaultCurrentDateMs: r.defaultCurrentDateMs,
1357
- width: n.width,
1358
- showTrackedChanges: n.showTrackedChanges
1359
- });
1360
- }
1361
- async getCommentThreads(e, t = {}) {
1362
- let { includeResolved: n, ...r } = t, i = await this.collectPageRuns(e, r);
1363
- return ut(this.comments, this.commentAnchorRanges(), i, { includeResolved: n });
1364
- }
1365
- async getElementContextAt(e, t, n = {}) {
1366
- let r = this._withActiveView(n);
1367
- if (this._mode === "worker") return (await this._bridge.request((n) => ({
1368
- type: "hitTestElement",
1369
- id: n,
1370
- pageIndex: e,
1371
- point: t,
1372
- opts: r
1373
- }))).context;
1374
- let i = E(this), a = i.services;
1375
- if (!a) throw Error("Document layout services are not initialized");
1376
- return tn(a, e, t, {
1377
- ...r,
1378
- defaultCurrentDateMs: i.defaultCurrentDateMs
1379
- });
1380
- }
1381
- };
1382
- //#endregion
1383
- //#region packages/docx/src/tate-chu-yoko-overlay.ts
1384
- function Sn(e, t) {
1385
- if (!e.eastAsianVert) return 1;
1386
- let n = t(e.text);
1387
- return !(n > 0) || e.w >= n ? 1 : e.w / n;
1388
- }
1389
- //#endregion
1390
- //#region packages/docx/src/text-layer.ts
1391
- function Y(e, t, n) {
1392
- e.dataset ? n === void 0 ? delete e.dataset[t] : e.dataset[t] = n : n !== void 0 && e.setAttribute?.(`data-${t.replace(/[A-Z]/g, (e) => `-${e.toLowerCase()}`)}`, n);
1393
- }
1394
- function X(e, t, n, r, i, a, o) {
1395
- e.innerHTML = "", Y(e, "ooxmlSelectionSurface", "docx"), Y(e, "pageIndex", o === void 0 ? void 0 : String(o));
1396
- let s = e.ownerDocument ?? document;
1397
- for (let [o, c] of t.entries()) {
1398
- let t = s.createElement("span");
1399
- Y(t, "ooxmlSelectionRun", "docx"), Y(t, "runIndex", String(o)), c.paragraphId !== void 0 && Y(t, "paragraphId", c.paragraphId), c.source !== void 0 && (Y(t, "sourceStory", c.source.story), Y(t, "sourceStoryInstance", c.source.storyInstance), Y(t, "sourcePath", JSON.stringify(c.source.path))), t.textContent = c.text;
1400
- let l = c.transform ?? "";
1401
- if (a && c.eastAsianVert) {
1402
- let e = Sn(c, a(c.font));
1403
- e !== 1 && (l = `${l ? `${l} ` : ""}scaleX(${e})`);
1404
- }
1405
- let u = l ? `transform:${l};transform-origin:top left;` : "", d = i ? c.hyperlink : void 0, f = d ? "pointer" : "text", p = c.letterSpacingPx === void 0 ? "0" : `${c.letterSpacingPx}px`;
1406
- t.style.cssText = `position:absolute;left:${O(c.x, n)};top:${O(c.y, r)};font:${c.font};line-height:${c.h}px;letter-spacing:${p};` + u + `white-space:pre;color:transparent;cursor:${f};pointer-events:all;`, d && i && (t.title = d.kind === "external" ? d.url : d.ref, t.addEventListener("click", (e) => {
1407
- e.preventDefault(), i(d);
1408
- })), e.appendChild(t);
1409
- }
1410
- }
1411
- function Z(e, t, n, r, i, a, o = {}) {
1412
- e.innerHTML = "";
1413
- let s = o.match ?? "rgba(255, 214, 0, 0.42)", c = o.active ?? "rgba(255, 140, 0, 0.55)";
1414
- for (let o of n) {
1415
- let n = o.active ? c : s;
1416
- for (let s of o.slices) {
1417
- let o = t[s.runIndex];
1418
- if (!o) continue;
1419
- let c = a(o.font), l = st(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, _ = Sn(o, c), v = h * _, ee = g * _;
1420
- if (ee <= 0) continue;
1421
- let y = document.createElement("div"), b = o.transform ? `transform:${o.transform};transform-origin:top left;` : "";
1422
- y.style.cssText = `position:absolute;left:${O(o.x + v, r)};top:${O(o.y, i)};width:${O(ee, r)};height:${O(o.h, i)};` + b + `background:${n};pointer-events:none;`, e.appendChild(y);
1423
- }
1424
- }
1425
- }
1426
- //#endregion
1427
- //#region packages/docx/src/find.ts
1428
- var Cn = class {
1429
- _pageRuns = /* @__PURE__ */ new Map();
1430
- _matches = [];
1431
- _active = -1;
1432
- _generation = 0;
1433
- _runsRevision = 0;
1434
- constructor(e, t) {
1435
- this._pageCount = e, this._collectPageRuns = t;
1436
- }
1437
- invalidate() {
1438
- this._generation++, this._runsRevision++, this._pageRuns.clear(), this._matches = [], this._active = -1;
1439
- }
1440
- pageRuns(e) {
1441
- return this._pageRuns.get(e);
1442
- }
1443
- setPageRuns(e, t) {
1444
- this._runsRevision++, this._pageRuns.set(e, t);
1445
- }
1446
- _matchAt(e) {
1447
- return this._matches[e];
1448
- }
1449
- pageHighlights(e) {
1450
- let t = [];
1451
- for (let n = 0; n < this._matches.length; n++) {
1452
- let r = this._matches[n];
1453
- r.page === e && t.push({
1454
- slices: r.slices,
1455
- active: n === this._active
1456
- });
1457
- }
1458
- return t;
1459
- }
1460
- activePage() {
1461
- let e = this._matchAt(this._active);
1462
- return e ? e.page : null;
1463
- }
1464
- matches() {
1465
- return this._matches.map((e, t) => ({
1466
- matchIndex: t,
1467
- text: e.text,
1468
- location: { page: e.page }
1469
- }));
1470
- }
1471
- async find(e, t = {}) {
1472
- let n = ++this._generation;
1473
- if (e.length === 0) return this._runsRevision++, this._pageRuns.clear(), this._matches = [], this._active = -1, [];
1474
- let r = this._runsRevision, i = new Map(this._pageRuns), a = this._pageCount();
1475
- for (let e = 0; e < a; e++) {
1476
- let t = i.get(e);
1477
- if (!t) {
1478
- try {
1479
- t = await this._collectPageRuns(e);
1480
- } catch (e) {
1481
- if (n !== this._generation) return [];
1482
- throw e;
1483
- }
1484
- if (n !== this._generation) return [];
1485
- i.set(e, t);
1486
- }
1487
- }
1488
- if (n !== this._generation) return [];
1489
- let o = r === this._runsRevision ? i : new Map([...i, ...this._pageRuns]), s = [];
1490
- for (let n = 0; n < a; n++) {
1491
- let r = o.get(n) ?? [], i = oe(r);
1492
- for (let a of ae(i, e, t)) {
1493
- let e = a.slices.map((e) => r[e.runIndex].text.slice(e.start, e.end)).join("");
1494
- s.push({
1495
- page: n,
1496
- text: e,
1497
- slices: a.slices
1498
- });
1499
- }
1500
- }
1501
- return this._runsRevision++, this._pageRuns = o, this._matches = s, this._active = -1, this.matches();
1502
- }
1503
- next() {
1504
- return this._active = re(this._active, this._matches.length), this._activePublic();
1505
- }
1506
- prev() {
1507
- return this._active = le(this._active, this._matches.length), this._activePublic();
1508
- }
1509
- _activePublic() {
1510
- let e = this._matchAt(this._active);
1511
- return e ? {
1512
- matchIndex: this._active,
1513
- text: e.text,
1514
- location: { page: e.page }
1515
- } : null;
1516
- }
1517
- };
1518
- //#endregion
1519
- //#region packages/docx/src/selection-context.ts
1520
- function wn(e, t, n, r, i = {}) {
1521
- let a = e.find((e) => e.id === n && e.parentId === void 0);
1522
- if (!a) return null;
1523
- let o = new Map(e.map((e) => [e.id, e])), s = e.filter((e) => {
1524
- if (e.parentId === void 0) return !1;
1525
- let t = e, n = /* @__PURE__ */ new Set();
1526
- for (; t.parentId !== void 0 && !n.has(t.id);) {
1527
- n.add(t.id);
1528
- let e = o.get(t.parentId);
1529
- if (!e) return !1;
1530
- if (e.id === a.id) return !0;
1531
- t = e;
1532
- }
1533
- return !1;
1534
- }), c = Ce({
1535
- id: a.id,
1536
- author: a.author,
1537
- date: a.date,
1538
- text: a.paragraphs?.join("\n") ?? a.text,
1539
- status: a.resolved ? "resolved" : "active"
1540
- }, s.map((e) => ({
1541
- id: e.id,
1542
- author: e.author,
1543
- date: e.date,
1544
- text: e.paragraphs?.join("\n") ?? e.text,
1545
- status: e.resolved ? "resolved" : "active"
1546
- })), i.maxTextCharacters), l = t.find((e) => e.commentId === n)?.source;
1547
- return Object.freeze({
1548
- format: "docx",
1549
- kind: "comment",
1550
- pageIndex: r,
1551
- commentId: n,
1552
- ...l ? { source: Object.freeze({
1553
- ...l,
1554
- path: Object.freeze([...l.path])
1555
- }) } : {},
1556
- thread: c.thread,
1557
- truncated: c.truncated,
1558
- truncationReasons: c.truncated ? ["text"] : [],
1559
- textCharacters: c.textCharacters,
1560
- maxTextCharacters: c.maxTextCharacters
1561
- });
1562
- }
1563
- function Tn(e) {
1564
- if (e === void 0 || !/^\d+$/.test(e)) return null;
1565
- let t = Number(e);
1566
- return Number.isSafeInteger(t) ? t : null;
1567
- }
1568
- function En(e) {
1569
- for (let t = e; t; t = t.parentElement) {
1570
- let e = Tn(t.dataset.pageIndex);
1571
- if (e !== null) return e;
1572
- }
1573
- return null;
1574
- }
1575
- var Dn = new Set([
1576
- "body",
1577
- "header",
1578
- "footer",
1579
- "footnote",
1580
- "endnote",
1581
- "textbox"
1582
- ]);
1583
- function On(e) {
1584
- let t = e.dataset.sourceStory, n = e.dataset.sourceStoryInstance, r = e.dataset.sourcePath;
1585
- if (!t || !Dn.has(t) || !n || !r) return null;
1586
- try {
1587
- let e = JSON.parse(r);
1588
- return !Array.isArray(e) || e.length === 0 || e.length > 32 || !e.every((e) => Number.isSafeInteger(e) && e >= 0) ? null : {
1589
- story: t,
1590
- storyInstance: n,
1591
- path: [...e]
1592
- };
1593
- } catch {
1594
- return null;
1595
- }
1596
- }
1597
- function Q(e, t, n = {}) {
1598
- let r = de(e, t, (e) => {
1599
- let t = En(e), n = Tn(e.dataset.runIndex);
1600
- return t === null || n === null ? null : {
1601
- pageIndex: t,
1602
- runIndex: n,
1603
- ...e.dataset.paragraphId === void 0 ? {} : { paragraphId: e.dataset.paragraphId },
1604
- ...On(e) === null ? {} : { source: On(e) }
1605
- };
1606
- }, {
1607
- maxChars: n.maxTextCharacters,
1608
- maxLocators: n.maxRunLocators
1609
- });
1610
- if (!r) return null;
1611
- let i = [...r.locators].sort((e, t) => e.pageIndex - t.pageIndex || e.runIndex - t.runIndex);
1612
- return {
1613
- format: "docx",
1614
- kind: "text",
1615
- text: r.text,
1616
- pageIndexes: [...new Set(i.map((e) => e.pageIndex))],
1617
- paragraphIds: [...new Set(i.flatMap((e) => e.paragraphId ? [e.paragraphId] : []))],
1618
- runs: i,
1619
- truncated: r.truncated,
1620
- truncationReasons: r.truncationReasons,
1621
- textCharacters: r.textCharacters,
1622
- maxTextCharacters: r.maxTextCharacters,
1623
- maxRunLocators: r.maxLocators
1624
- };
1625
- }
1626
- //#endregion
1627
- //#region packages/docx/src/focused-view-runtime.ts
1628
- function $(e, t, n, r, i) {
1629
- return r === "worker" ? e.renderPageToBitmap(n, i) : e.renderPage(t, n, i);
1630
- }
1631
- //#endregion
1632
- //#region packages/docx/src/viewer.ts
1633
- var kn = Symbol("DocxViewer.borrowedDocument"), An = class e {
1634
- _documentOwner;
1635
- get _doc() {
1636
- return this._documentOwner.current;
1637
- }
1638
- _borrowed;
1639
- _hostWindow;
1640
- _currentPage = 0;
1641
- _scale = null;
1642
- _canvas;
1643
- _wrapper;
1644
- _canvasMount;
1645
- _textLayer = null;
1646
- _highlightLayer = null;
1647
- _elementLayer = null;
1648
- _find;
1649
- _findRequestGeneration = 0;
1650
- _measureCtx = null;
1651
- _opts;
1652
- _mode;
1653
- _renderDispatcher;
1654
- _errorRouter;
1655
- _destroyed = !1;
1656
- _selectionChangeListener = null;
1657
- _selectionContextKey = "null";
1658
- _elementContext = null;
1659
- _elementHitGeneration = 0;
1660
- _layoutViewGeneration = 0;
1661
- _layoutViewPublicationGeneration = 0;
1662
- _navigationGeneration = 0;
1663
- _layoutUnsubscribe = null;
1664
- _internalHyperlinkGeneration = 0;
1665
- _layoutWaiters = /* @__PURE__ */ new Set();
1666
- _layoutFailed = !1;
1667
- _loadingLayer;
1668
- _elementClickListener = null;
1669
- _contextMenuListener = null;
1670
- static fromDocument(t, n, r = {}) {
1671
- let i = G(n);
1672
- return new e(t, {
1673
- ...r,
1674
- currentDate: i.currentDate,
1675
- showTrackedChanges: i.showTrackedChanges,
1676
- [kn]: n
1677
- });
1678
- }
1679
- constructor(e, t = {}) {
1680
- this._canvas = e, this._opts = t;
1681
- let n = t[kn];
1682
- this._borrowed = n !== void 0, this._mode = C("DocxViewer", t.mode, n), this._documentOwner = new b("DocxViewer", n ?? null, !1);
1683
- let r = e.ownerDocument?.defaultView ?? (typeof window < "u" ? window : null);
1684
- if (!r) throw Error("DocxViewer requires a canvas with an active Window");
1685
- this._hostWindow = r, this._canvasMount = new fe(e, {
1686
- wrapperCssText: "position:relative;display:inline-block;vertical-align:top;",
1687
- forceDisplayBlock: !0
1688
- }), this._wrapper = this._canvasMount.wrapper, this._renderDispatcher = new S(e, this._mode === "worker"), this._errorRouter = new ue("DocxViewer", t.onError);
1689
- let i = new se(this._wrapper, t.enableTextSelection === !0, t.enableElementSelection === !0);
1690
- this._textLayer = i.textLayer, this._highlightLayer = i.highlightLayer, this._elementLayer = i.elementLayer, this._loadingLayer = this._wrapper.ownerDocument.createElement("div"), this._loadingLayer.style.cssText = [
1691
- "position:absolute",
1692
- "inset:0",
1693
- "display:none",
1694
- "align-items:center",
1695
- "justify-content:center",
1696
- "background:rgba(255,255,255,0.72)",
1697
- "pointer-events:none",
1698
- "z-index:4"
1699
- ].join(";"), this._loadingLayer.setAttribute("role", "status"), this._loadingLayer.setAttribute("aria-live", "polite"), this._loadingLayer.setAttribute("aria-label", "Loading page");
1700
- let a = this._wrapper.ownerDocument.createElement("progress");
1701
- a.setAttribute("aria-hidden", "true"), this._loadingLayer.appendChild(a), this._wrapper.insertBefore(this._loadingLayer, this._elementLayer), this._textLayer && (t.onSelectionContextChange || t.enableElementSelection) && (this._selectionChangeListener = () => this._emitSelectionContextChange(), this._wrapper.ownerDocument.addEventListener("selectionchange", this._selectionChangeListener)), t.enableElementSelection && (this._elementClickListener = (e) => {
1702
- this._onElementClick(e).catch((e) => this._reportRenderError(e));
1703
- }, this._wrapper.addEventListener("click", this._elementClickListener)), t.onContextMenu && (this._contextMenuListener = (e) => this._onContextMenu(e), this._wrapper.addEventListener("contextmenu", this._contextMenuListener)), this._find = new Cn(() => this.pageCount, (e) => this._collectPageRuns(e)), n && this._bindLayoutDocument(n);
1704
- }
1705
- async load(e) {
1706
- if (this._destroyed) throw Error("DocxViewer is destroyed");
1707
- if (this._borrowed) throw Error("DocxViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
1708
- let t = !1;
1709
- try {
1710
- let n = await this._documentOwner.replace(() => J.load(e, {
1711
- password: this._opts.password,
1712
- useGoogleFonts: this._opts.useGoogleFonts,
1713
- cjkFallback: this._opts.cjkFallback,
1714
- maxZipEntryBytes: this._opts.maxZipEntryBytes,
1715
- resourceLimits: this._opts.resourceLimits,
1716
- debug: this._opts.debug,
1717
- onResourceMetrics: this._opts.onResourceMetrics,
1718
- workerTimeoutMs: this._opts.workerTimeoutMs,
1719
- wasmUrl: this._opts.wasmUrl,
1720
- math: this._opts.math,
1721
- threeD: this._opts.threeD,
1722
- regionMap: this._opts.regionMap,
1723
- chartEx: this._opts.chartEx,
1724
- tiff: this._opts.tiff,
1725
- mode: this._mode,
1726
- ...this._opts.progressiveLayout ? { progressiveLayout: !0 } : {},
1727
- ...this._opts.sliceLayout ? { sliceLayout: !0 } : {},
1728
- onLayoutProgress: this._opts.onLayoutProgress,
1729
- onLayoutPartial: this._opts.onLayoutPartial,
1730
- onLayoutComplete: this._opts.onLayoutComplete,
1731
- ...this._opts.showTrackedChanges === !0 ? { showTrackedChanges: !0 } : {},
1732
- ...this._opts.currentDate === void 0 ? {} : { currentDate: this._opts.currentDate }
1733
- }), () => {
1734
- this._invalidateElementContext(!1), t = !0, this._renderDispatcher.begin(), this._findRequestGeneration++, this._find.invalidate(), this._unbindLayoutDocument();
1735
- });
1736
- if (!n) return;
1737
- if (this._destroyed) throw Error("DocxViewer is destroyed");
1738
- this._currentPage = 0, this._bindLayoutDocument(n), this._find.invalidate(), await this._render();
1739
- } catch (e) {
1740
- throw this._destroyed ? Error("DocxViewer is destroyed") : e instanceof Error ? e : Error(String(e));
1741
- }
1742
- t && !this._destroyed && this._emitSelectionContextChange();
1743
- }
1744
- get pageCount() {
1745
- return this._doc?.pageCount ?? 0;
1746
- }
1747
- get currentPage() {
1748
- return this._currentPage;
1749
- }
1750
- get layoutComplete() {
1751
- return this._doc?.layoutComplete ?? !0;
1752
- }
1753
- async waitUntilLayoutComplete() {
1754
- await this._errorRouter.ownBackgroundLifecycle(async () => {
1755
- await this._doc?.waitUntilLayoutComplete?.();
1756
- });
1757
- }
1758
- get canvasElement() {
1759
- return this._canvas;
1760
- }
1761
- async goToPage(e) {
1762
- let t = this._doc;
1763
- if (!t) return;
1764
- let n = this._cancelPendingNavigation(), r = Math.max(0, Number.isNaN(e) ? 0 : Math.trunc(e));
1765
- if (r >= this.pageCount && !this.layoutComplete) {
1766
- this._setLoading(!0);
1767
- try {
1768
- await this._waitForPage(t, r, n);
1769
- } finally {
1770
- n === this._navigationGeneration && this._setLoading(!1);
1771
- }
1772
- }
1773
- if (this._destroyed || n !== this._navigationGeneration || t !== this._doc) return;
1774
- let i = Math.max(0, Math.min(r, this.pageCount - 1)), a = i !== this._currentPage;
1775
- a && this._invalidateElementContext(!1), this._currentPage = i, await this._render(), a && !this._destroyed && this._emitSelectionContextChange();
1776
- }
1777
- async nextPage() {
1778
- await this.goToPage(this._currentPage + 1);
1779
- }
1780
- async prevPage() {
1781
- await this.goToPage(this._currentPage - 1);
1782
- }
1783
- _naturalWidthPx() {
1784
- return !this._doc || this._doc.pageCount === 0 ? 0 : this._doc.pageSize(this._currentPage).widthPt * D;
1785
- }
1786
- _renderWidth() {
1787
- if (this._scale === null) return this._opts.width;
1788
- let e = this._naturalWidthPx();
1789
- return e <= 0 ? this._opts.width : Math.round(e * this._scale);
1790
- }
1791
- getScale() {
1792
- if (this._scale !== null) return this._scale;
1793
- let e = this._naturalWidthPx();
1794
- return e <= 0 ? 1 : this._opts.width && this._opts.width > 0 ? this._opts.width / e : 1;
1795
- }
1796
- _zoomMin() {
1797
- return this._opts.zoomMin ?? .1;
1798
- }
1799
- _zoomMax() {
1800
- return this._opts.zoomMax ?? 4;
1801
- }
1802
- async setScale(e) {
1803
- let t = ie(e, this._zoomMin(), this._zoomMax()), n = t !== this.getScale();
1804
- this._scale = t, await this._render(), n && this._opts.onScaleChange?.(t);
1805
- }
1806
- async zoomIn() {
1807
- await this.setScale(me(this.getScale()));
1808
- }
1809
- async zoomOut() {
1810
- await this.setScale(_e(this.getScale()));
1811
- }
1812
- async fitWidth() {
1813
- await this._fit("width");
1814
- }
1815
- async fitPage() {
1816
- await this._fit("page");
1817
- }
1818
- async _fit(e) {
1819
- if (!this._doc || this._doc.pageCount === 0) return;
1820
- let t = this._doc.pageSize(this._currentPage), n = this._fitContainer();
1821
- if (!n) return;
1822
- let r = y({
1823
- contentWidth: t.widthPt * D,
1824
- contentHeight: t.heightPt * D,
1825
- containerWidth: n.clientWidth,
1826
- containerHeight: n.clientHeight
1827
- }, e);
1828
- r <= 0 || await this.setScale(r);
1829
- }
1830
- _fitContainer() {
1831
- return this._opts.container ?? this._wrapper.parentElement ?? null;
1832
- }
1833
- async findText(e, t = {}) {
1834
- let n = this._doc;
1835
- if (!n) return [];
1836
- let r = ++this._findRequestGeneration;
1837
- if (e.length > 0 && !n.layoutComplete && (await this._errorRouter.ownBackgroundLifecycle(() => n.waitUntilLayoutComplete()), this._destroyed || this._doc !== n || r !== this._findRequestGeneration)) return [];
1838
- let i = await this._errorRouter.ownAwaitable(() => this._find.find(e, t));
1839
- return this._redrawHighlights(), i;
1840
- }
1841
- async findNext() {
1842
- return this._activateMatch(this._find.next());
1843
- }
1844
- async findPrev() {
1845
- return this._activateMatch(this._find.prev());
1846
- }
1847
- clearFind() {
1848
- this._findRequestGeneration++, this._find.invalidate(), this._redrawHighlights();
1849
- }
1850
- async _activateMatch(e) {
1851
- return e ? (e.location.page === this._currentPage ? this._redrawHighlights() : await this.goToPage(e.location.page), e) : (this._redrawHighlights(), null);
1852
- }
1853
- _redrawHighlights() {
1854
- let e = this._find.pageRuns(this._currentPage) ?? [];
1855
- this._buildHighlightLayer(e);
1856
- }
1857
- async getResourceMetrics() {
1858
- if (!this._doc) throw Error("Document not loaded");
1859
- return await this._doc.getResourceMetrics();
1860
- }
1861
- getSelectionContext(e = {}) {
1862
- if (this._destroyed) throw Error("DocxViewer is destroyed");
1863
- return (this._textLayer ? Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null, e) : null) ?? (this._elementContext ? nn(this._elementContext, e.maxTextCharacters) : null);
1864
- }
1865
- _emitSelectionContextChange() {
1866
- let e = this.getSelectionContext();
1867
- e?.kind === "text" && (this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutline());
1868
- let t = JSON.stringify(e);
1869
- t !== this._selectionContextKey && (this._selectionContextKey = t, this._opts.onSelectionContextChange?.(e ? structuredClone(e) : null));
1870
- }
1871
- _setElementContext(e) {
1872
- this._elementContext = e ? structuredClone(e) : null, this._redrawElementOutline(), this._emitSelectionContextChange();
1873
- }
1874
- _invalidateElementContext(e = !0) {
1875
- this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutline(), e && this._emitSelectionContextChange();
1876
- }
1877
- _redrawElementOutline() {
1878
- let e = this._elementContext, t = this._doc;
1879
- if (!e || !t || e.pageIndex !== this._currentPage) {
1880
- x(this._elementLayer, null);
1881
- return;
1882
- }
1883
- let n = t.pageSize(e.pageIndex);
1884
- x(this._elementLayer, {
1885
- x: e.bounds.xPt / n.widthPt,
1886
- y: e.bounds.yPt / n.heightPt,
1887
- width: e.bounds.widthPt / n.widthPt,
1888
- height: e.bounds.heightPt / n.heightPt
1889
- });
1890
- }
1891
- async _onElementClick(e) {
1892
- this._destroyed || e.defaultPrevented || e.button !== 0 || await this._resolveContextAt(e);
1893
- }
1894
- _onContextMenu(e) {
1895
- let t;
1896
- this._opts.onContextMenu?.({
1897
- originalEvent: e,
1898
- getContext: () => t ??= this._resolveContextAt(e)
1899
- });
1900
- }
1901
- async _resolveContextAt(e) {
1902
- let t = this._doc;
1903
- if (this._destroyed || !t) return null;
1904
- if (this._textLayer && Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null)) return this._emitSelectionContextChange(), this._destroyed ? null : this.getSelectionContext();
1905
- if (!this._opts.enableElementSelection) return this.getSelectionContext();
1906
- let n = this._canvas.getBoundingClientRect();
1907
- if (n.width <= 0 || n.height <= 0) return this._invalidateElementContext(), null;
1908
- let r = e.clientX - n.left, i = e.clientY - n.top;
1909
- if (r < 0 || i < 0 || r > n.width || i > n.height) return this._invalidateElementContext(), null;
1910
- let a = ++this._elementHitGeneration, o = this._currentPage, s = t.pageSize(o), c;
1911
- try {
1912
- c = await t.getElementContextAt(o, {
1913
- xPt: r / n.width * s.widthPt,
1914
- yPt: i / n.height * s.heightPt
1915
- }, {
1916
- currentDate: this._opts.currentDate,
1917
- showTrackedChanges: this._opts.showTrackedChanges,
1918
- maxTextCharacters: F
1919
- });
1920
- } catch (e) {
1921
- if (this._destroyed || a !== this._elementHitGeneration || o !== this._currentPage || t !== this._doc) return null;
1922
- throw e;
1923
- }
1924
- return this._destroyed || a !== this._elementHitGeneration || o !== this._currentPage || t !== this._doc ? null : (this._setElementContext(c), this._destroyed ? null : this.getSelectionContext());
1925
- }
1926
- destroy() {
1927
- this._destroyed || (this._destroyed = !0, this._findRequestGeneration++, this._layoutViewGeneration++, this._unbindLayoutDocument(), this._errorRouter.close(), this._renderDispatcher.destroy(), Ze(this._canvas), this._documentOwner.close(), this._find.invalidate(), this._selectionChangeListener &&= (this._wrapper.ownerDocument.removeEventListener("selectionchange", this._selectionChangeListener), null), this._elementHitGeneration++, this._elementClickListener &&= (this._wrapper.removeEventListener("click", this._elementClickListener), null), this._contextMenuListener &&= (this._wrapper.removeEventListener("contextmenu", this._contextMenuListener), null), this._elementContext = null, this._canvasMount.restore());
1928
- }
1929
- async _render() {
1930
- let e = this._renderDispatcher.begin();
1931
- try {
1932
- await this._renderPage(e);
1933
- } catch (t) {
1934
- if (!this._renderDispatcher.isCurrent(e)) return;
1935
- throw t;
1936
- }
1937
- }
1938
- _reportRenderError(e) {
1939
- this._errorRouter.report(e);
1940
- }
1941
- async _renderPage(e) {
1942
- if (!this._doc) return;
1943
- let t = this._mode === "worker", n = this._renderWidth(), r = this._doc.pageSize(this._currentPage), i = n ?? r.widthPt * 1.3333333333333333, a = r.widthPt > 0 ? i * r.heightPt / r.widthPt : 0, o = [], s = (e) => o.push(e), c = this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1), l = {
1944
- width: n,
1945
- dpr: this._opts.dpr,
1946
- imageResources: this._opts.imageResources,
1947
- defaultTextColor: this._opts.defaultTextColor,
1948
- currentDate: this._opts.currentDate,
1949
- showTrackedChanges: this._opts.showTrackedChanges,
1950
- onTextRun: s
1951
- };
1952
- if (t) {
1953
- let t = await $(this._doc, this._canvas, this._currentPage, "worker", l);
1954
- if (!this._renderDispatcher.commitBitmap(e, t, {
1955
- cssWidth: i > 0 ? i : Math.round(t.width / c),
1956
- cssHeight: a > 0 ? a : Math.round(t.height / c)
1957
- })) return;
1958
- } else if (await $(this._doc, this._canvas, this._currentPage, "main", l), !this._renderDispatcher.isCurrent(e)) return;
1959
- this._textLayer && this._buildTextLayer(this._textLayer, o), this._find.setPageRuns(this._currentPage, o), this._buildHighlightLayer(o), this._opts.onPageChange?.(this._currentPage, this.pageCount, this.layoutComplete);
1960
- }
1961
- _bindLayoutDocument(e) {
1962
- this._unbindLayoutDocument(), this._layoutFailed = !1, this._layoutViewPublicationGeneration = 0;
1963
- let t = gn(e, (t) => this._onLayoutViewPublication(e, t), (e) => this._reportRenderError(e)), n = !0, r = fn(e, () => ({
1964
- pageCount: e.pageCount,
1965
- exact: e.layoutComplete,
1966
- complete: e.layoutComplete
1967
- }), (t) => {
1968
- if (n) {
1969
- n = !1;
1970
- return;
1971
- }
1972
- this._onLayoutPublication(e, t);
1973
- }, (e) => this._reportRenderError(e));
1974
- this._layoutUnsubscribe = () => {
1975
- r(), t();
1976
- };
1977
- }
1978
- _unbindLayoutDocument() {
1979
- this._layoutUnsubscribe?.(), this._layoutUnsubscribe = null, this._layoutFailed = !1, this._cancelPendingNavigation();
1980
- }
1981
- _onLayoutPublication(e, t) {
1982
- if (!(this._destroyed || e !== this._doc)) {
1983
- if (this._wakeLayoutWaiters(), t.error !== void 0) {
1984
- this._layoutFailed = !0, this._errorRouter.reportBackground(t.error, this._opts.onLayoutComplete !== void 0);
1985
- return;
1986
- }
1987
- this._find.invalidate(), this._currentPage = Math.max(0, Math.min(this._currentPage, t.pageCount - 1)), this._render().catch((e) => this._reportRenderError(e));
1988
- }
1989
- }
1990
- _onLayoutViewPublication(e, t) {
1991
- this._destroyed || e !== this._doc || t.generation <= this._layoutViewPublicationGeneration || (this._layoutViewPublicationGeneration = t.generation, t.requester !== this && (this._layoutViewGeneration++, this._opts = {
1992
- ...this._opts,
1993
- currentDate: t.view.currentDate,
1994
- showTrackedChanges: t.view.showTrackedChanges
1995
- }, this._find.invalidate(), this._currentPage = Math.max(0, Math.min(this._currentPage, e.pageCount - 1)), this._render().catch((e) => this._reportRenderError(e))));
1996
- }
1997
- async _waitForPage(e, t, n) {
1998
- await this._errorRouter.ownBackgroundLifecycle(async () => {
1999
- for (; !this._destroyed && n === this._navigationGeneration && e === this._doc && t >= e.pageCount && !e.layoutComplete && !this._layoutFailed;) await new Promise((e) => {
2000
- this._layoutWaiters.add(e);
2001
- });
2002
- e === this._doc && (e.layoutComplete || this._layoutFailed) && await e.waitUntilLayoutComplete();
2003
- });
2004
- }
2005
- _wakeLayoutWaiters() {
2006
- for (let e of this._layoutWaiters) e();
2007
- this._layoutWaiters.clear();
2008
- }
2009
- _cancelPendingNavigation() {
2010
- let e = ++this._navigationGeneration;
2011
- return this._wakeLayoutWaiters(), this._setLoading(!1), e;
2012
- }
2013
- _setLoading(e) {
2014
- this._loadingLayer.style.display = e ? "flex" : "none";
2015
- }
2016
- async setShowTrackedChanges(e) {
2017
- let t = ++this._layoutViewGeneration, n = this._doc;
2018
- if (this._opts.showTrackedChanges === !0 === e) {
2019
- n && await K(n, {
2020
- showTrackedChanges: e,
2021
- currentDate: this._opts.currentDate
2022
- }, this);
2023
- return;
2024
- }
2025
- let r = {
2026
- ...this._opts,
2027
- showTrackedChanges: e
2028
- };
2029
- (!n || await K(n, {
2030
- showTrackedChanges: e,
2031
- currentDate: r.currentDate
2032
- }, this)) && (this._destroyed || t !== this._layoutViewGeneration || n !== this._doc || (this._opts = r, this._find.invalidate(), this._currentPage = Math.max(0, Math.min(this._currentPage, this.pageCount - 1)), await this._render()));
2033
- }
2034
- _buildHighlightLayer(e) {
2035
- let t = this._highlightLayer;
2036
- if (!t) return;
2037
- let { width: n, height: r } = this._canvasCssPx();
2038
- Z(t, e, this._find.pageHighlights(this._currentPage), n, r, (e) => this._measureForFont(e), this._opts.findHighlightColors);
2039
- }
2040
- _canvasCssPx() {
2041
- return {
2042
- width: parseFloat(this._canvas.style.width) || this._canvas.width,
2043
- height: parseFloat(this._canvas.style.height) || this._canvas.height
2044
- };
2045
- }
2046
- _measureForFont(e) {
2047
- this._measureCtx ||= document.createElement("canvas").getContext("2d");
2048
- let t = this._measureCtx;
2049
- return t ? (t.font = e, (e) => t.measureText(e).width) : (e) => e.length;
2050
- }
2051
- async _collectPageRuns(e) {
2052
- return this._doc ? this._doc.collectPageRuns(e, {
2053
- width: this._renderWidth(),
2054
- currentDate: this._opts.currentDate,
2055
- showTrackedChanges: this._opts.showTrackedChanges
2056
- }) : [];
2057
- }
2058
- _buildTextLayer(e, t) {
2059
- let { width: n, height: r } = this._canvasCssPx();
2060
- X(e, t, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), this._currentPage);
2061
- }
2062
- _hyperlinkHandler() {
2063
- return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
2064
- if (e.kind === "external") {
2065
- u(e.url, void 0, this._hostWindow);
2066
- return;
2067
- }
2068
- let t = this._doc;
2069
- if (!t) return;
2070
- let n = ++this._internalHyperlinkGeneration;
2071
- this._navigateInternalHyperlink(t, e.ref, n).catch((e) => this._reportRenderError(e));
2072
- });
2073
- }
2074
- async _navigateInternalHyperlink(e, t, n) {
2075
- if (e.layoutComplete || await e.waitUntilLayoutComplete(), this._destroyed || this._doc !== e || n !== this._internalHyperlinkGeneration) return;
2076
- let r = e.getBookmarkPage(t);
2077
- r !== void 0 && await this.goToPage(r);
2078
- }
2079
- }, jn = 150, Mn = "0 1px 3px rgba(0,0,0,0.2)", Nn = 12, Pn = 13, Fn = Symbol("DocxScrollViewer.borrowedDocument"), In;
2080
- function Ln() {
2081
- return In ??= import("./comment-ui-runtime-DcJOYlw-.js");
2082
- }
2083
- var Rn = class e {
2084
- _documentOwner;
2085
- get _doc() {
2086
- return this._documentOwner.current;
2087
- }
2088
- _borrowed;
2089
- _opts;
2090
- _errorRouter;
2091
- _container;
2092
- _wrapper;
2093
- _scrollHost;
2094
- _spacer;
2095
- _mode;
2096
- _scale = 1;
2097
- _scaleEstablished = !1;
2098
- _pendingScale = null;
2099
- _slots = /* @__PURE__ */ new Map();
2100
- _free = [];
2101
- _heights = [];
2102
- _scrollGeometry = {
2103
- offsets: [],
2104
- totalHeight: 0
2105
- };
2106
- _lastRange = null;
2107
- _lastTopIndex = -1;
2108
- _lastReportedTotal = -1;
2109
- _lastReportedLayoutComplete = null;
2110
- _layoutUnsubscribe = null;
2111
- _presentedPageCount = 0;
2112
- _scrollListener = null;
2113
- _selectionChangeListener = null;
2114
- _selectionContextKey = "null";
2115
- _elementClickListener = null;
2116
- _contextMenuListener = null;
2117
- _commentOutsidePointerListener = null;
2118
- _elementContext = null;
2119
- _activeCommentId = null;
2120
- _activeCommentPage = null;
2121
- _commentUi = null;
2122
- _commentPageById = /* @__PURE__ */ new Map();
2123
- _commentRunsByPage = /* @__PURE__ */ new Map();
2124
- _commentIndexedPages = /* @__PURE__ */ new Set();
2125
- _commentScanFrontier = 0;
2126
- _commentNavigationGeneration = 0;
2127
- _internalHyperlinkGeneration = 0;
2128
- _commentAnchorRangesForMargin = null;
2129
- _commentAnchorIds = /* @__PURE__ */ new Set();
2130
- _reviewOriginPx = 0;
2131
- _commentGeometryScheduled = !1;
2132
- _commentGeometryFrame = null;
2133
- _pendingCommentGeometry = /* @__PURE__ */ new Map();
2134
- _elementHitGeneration = 0;
2135
- _destroyed = !1;
2136
- _measureCtx;
2137
- _bitmapInFlight = /* @__PURE__ */ new Set();
2138
- _renderEpoch = 0;
2139
- _settleTimer = null;
2140
- _wheelListener = null;
2141
- _pendingZoomAnchor = null;
2142
- _resizeObserver = null;
2143
- _prevBase = 0;
2144
- _lastFitWidth = 0;
2145
- _pageShadow;
2146
- _find = new Cn(() => this.pageCount, (e) => this._collectPageRuns(e));
2147
- _findActive = !1;
2148
- _findRequestGeneration = 0;
2149
- _showTrackedChanges;
2150
- _currentDate;
2151
- _layoutViewGeneration = 0;
2152
- _layoutViewPublicationGeneration = 0;
2153
- static fromDocument(t, n, r = {}) {
2154
- let i = G(n);
2155
- return new e(t, {
2156
- ...r,
2157
- currentDate: i.currentDate,
2158
- showTrackedChanges: i.showTrackedChanges,
2159
- [Fn]: n
2160
- });
2161
- }
2162
- constructor(e, t = {}) {
2163
- 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.");
2164
- this._container = e, this._opts = t, this._errorRouter = new ue("DocxScrollViewer", t.onError), this._showTrackedChanges = t.showTrackedChanges === !0, this._currentDate = t.currentDate, this._pageShadow = t.pageShadow ?? Mn;
2165
- let n = t[Fn];
2166
- this._borrowed = n !== void 0, n ? (this._documentOwner = new b("DocxScrollViewer", n, !1), this._mode = C("DocxScrollViewer", t.mode, n)) : (this._documentOwner = new b("DocxScrollViewer"), this._mode = C("DocxScrollViewer", t.mode, void 0)), 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._commentsEnabled() && Ln().then((e) => {
2167
- if (!this._destroyed) {
2168
- this._commentUi = e;
2169
- for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
2170
- }
2171
- }).catch((e) => this._reportRenderError(e)), t.enableTextSelection && (t.onSelectionContextChange || t.enableElementSelection) && (this._selectionChangeListener = () => this._emitSelectionContextChange(), this._wrapper.ownerDocument.addEventListener("selectionchange", this._selectionChangeListener)), t.enableElementSelection && (this._elementClickListener = (e) => {
2172
- this._onElementClick(e).catch((e) => this._reportRenderError(e));
2173
- }, this._scrollHost.addEventListener("click", this._elementClickListener)), t.onContextMenu && (this._contextMenuListener = (e) => this._onContextMenu(e), this._scrollHost.addEventListener("contextmenu", this._contextMenuListener)), this._scrollListener = () => this._onScroll(), this._scrollHost.addEventListener("scroll", this._scrollListener), t.comments && (this._commentOutsidePointerListener = (e) => {
2174
- if (!Ee(e, this._wrapper, "ooxmlCommentId") && this._activeCommentId !== null) {
2175
- this._activeCommentId = null, this._activeCommentPage = null;
2176
- for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
2177
- this._emitSelectionContextChange();
2178
- }
2179
- }, this._wrapper.ownerDocument.addEventListener("pointerdown", this._commentOutsidePointerListener)), this._opts.enableZoom !== !1 && (this._wheelListener = (e) => {
2180
- if (!(e.ctrlKey || e.metaKey) || (e.preventDefault(), e.deltaY === 0)) return;
2181
- let t = this._scrollHost.getBoundingClientRect(), n = e.clientX - t.left, r = e.clientY - t.top;
2182
- this._pendingZoomAnchor = Number.isFinite(n) && Number.isFinite(r) ? {
2183
- x: n,
2184
- y: r
2185
- } : null, this.setScale(ge(this._scale, e.deltaY, e.deltaMode));
2186
- }, this._scrollHost.addEventListener("wheel", this._wheelListener, { passive: !1 })), typeof ResizeObserver < "u" && (this._resizeObserver = new ResizeObserver(() => this._onResize()), this._resizeObserver.observe(this._container)), this._borrowed && (this._bindLayoutDocument(n), this.relayout());
2187
- }
2188
- async load(e) {
2189
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2190
- if (this._borrowed) throw Error("DocxScrollViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
2191
- let t = !1;
2192
- try {
2193
- let n = await this._documentOwner.replace(() => J.load(e, {
2194
- password: this._opts.password,
2195
- useGoogleFonts: this._opts.useGoogleFonts,
2196
- cjkFallback: this._opts.cjkFallback,
2197
- maxZipEntryBytes: this._opts.maxZipEntryBytes,
2198
- resourceLimits: this._opts.resourceLimits,
2199
- debug: this._opts.debug,
2200
- onResourceMetrics: this._opts.onResourceMetrics,
2201
- workerTimeoutMs: this._opts.workerTimeoutMs,
2202
- wasmUrl: this._opts.wasmUrl,
2203
- math: this._opts.math,
2204
- threeD: this._opts.threeD,
2205
- regionMap: this._opts.regionMap,
2206
- chartEx: this._opts.chartEx,
2207
- tiff: this._opts.tiff,
2208
- mode: this._mode,
2209
- ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2210
- ...this._currentDate === void 0 ? {} : { currentDate: this._currentDate },
2211
- ...this._opts.progressiveLayout ? { progressiveLayout: !0 } : {},
2212
- ...this._opts.sliceLayout ? { sliceLayout: !0 } : {},
2213
- onLayoutProgress: this._opts.onLayoutProgress,
2214
- onLayoutPartial: this._opts.onLayoutPartial,
2215
- onLayoutComplete: this._opts.onLayoutComplete
2216
- }), (e) => {
2217
- if (this._invalidateElementContext(!1), t = !0, this._findRequestGeneration++, this._find.invalidate(), this._findActive = !1, this._activeCommentId = null, this._activeCommentPage = null, this._resetCommentNavigation(), this._unbindLayoutDocument(), e) {
2218
- for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
2219
- this._lastTopIndex = -1, this._lastReportedTotal = -1, this._lastReportedLayoutComplete = null;
2220
- }
2221
- });
2222
- if (!n) return;
2223
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2224
- this._bindLayoutDocument(n), this._find.invalidate(), this._findActive = !1, this._activeCommentId = null, this._activeCommentPage = null, this._resetCommentNavigation();
2225
- let r = [];
2226
- this._relayout(r), await Promise.all(r);
2227
- } catch (e) {
2228
- throw this._destroyed ? Error("DocxScrollViewer is destroyed") : e instanceof Error ? e : Error(String(e));
2229
- }
2230
- t && !this._destroyed && this._emitSelectionContextChange();
2231
- }
2232
- get pageCount() {
2233
- return this._doc?.pageCount ?? 0;
2234
- }
2235
- get layoutComplete() {
2236
- return this._doc?.layoutComplete ?? !0;
2237
- }
2238
- async waitUntilLayoutComplete() {
2239
- await this._errorRouter.ownBackgroundLifecycle(async () => {
2240
- await this._doc?.waitUntilLayoutComplete?.();
2241
- });
2242
- }
2243
- _bindLayoutDocument(e) {
2244
- this._unbindLayoutDocument(), this._layoutViewPublicationGeneration = 0, this._presentedPageCount = e.pageCount;
2245
- let t = gn(e, (t) => this._onLayoutViewPublication(e, t), (e) => this._reportRenderError(e)), n = !0, r = fn(e, () => ({
2246
- pageCount: e.pageCount,
2247
- exact: e.layoutComplete,
2248
- complete: e.layoutComplete
2249
- }), (t) => {
2250
- if (n) {
2251
- n = !1;
2252
- return;
2253
- }
2254
- this._onLayoutPublication(e, t);
2255
- }, (e) => this._reportRenderError(e));
2256
- this._layoutUnsubscribe = () => {
2257
- r(), t();
2258
- };
2259
- }
2260
- _unbindLayoutDocument() {
2261
- this._layoutUnsubscribe?.(), this._layoutUnsubscribe = null, this._presentedPageCount = 0;
2262
- }
2263
- _onLayoutPublication(e, t) {
2264
- if (!(this._destroyed || e !== this._doc)) {
2265
- if (t.error !== void 0) {
2266
- this._errorRouter.reportBackground(t.error, this._opts.onLayoutComplete !== void 0);
2267
- return;
2268
- }
2269
- this._find.invalidate(), this._refreshCommentSurface(), this._applyLayoutPublication(t);
2270
- }
2271
- }
2272
- _onLayoutViewPublication(e, t) {
2273
- this._destroyed || e !== this._doc || t.generation <= this._layoutViewPublicationGeneration || (this._layoutViewPublicationGeneration = t.generation, t.requester !== this && (this._layoutViewGeneration++, this._showTrackedChanges = t.view.showTrackedChanges, this._currentDate = t.view.currentDate, this._find.invalidate(), this._applyLayoutPublication({
2274
- pageCount: e.pageCount,
2275
- exact: !0,
2276
- complete: e.layoutComplete
2277
- })));
2278
- }
2279
- _refreshCommentSurface() {
2280
- if (!(!this._commentsEnabled() || this._slots.size === 0)) {
2281
- this._syncSpacerWidth();
2282
- for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
2283
- }
2284
- }
2285
- _applyLayoutPublication(e) {
2286
- let t = [...this._slots];
2287
- this._presentedPageCount = e.pageCount, this._renderEpoch++, this.relayout();
2288
- for (let [e, n] of t) e >= this._presentedPageCount || this._slots.get(e) !== n || this._refreshSlotAtomically(e, n);
2289
- }
2290
- _pageWidthPx(e) {
2291
- return this._doc.pageSize(e).widthPt * D * this._scale;
2292
- }
2293
- _pageHeightPx(e) {
2294
- return this._doc.pageSize(e).heightPt * D * this._scale;
2295
- }
2296
- _fitWidthPx() {
2297
- if (this._opts.width && this._opts.width > 0) return this._opts.width;
2298
- let e = this._scrollHost.clientWidth || this._container.clientWidth;
2299
- if (e <= 0) return 0;
2300
- let { left: t, right: n } = this._padH(), r = e - t - n;
2301
- return r <= 0 ? 0 : r;
2302
- }
2303
- _hasCommentMargin() {
2304
- return this._hasDisplayableComments() && this._commentsOptions()?.cards !== !1;
2305
- }
2306
- _hasDisplayableComments() {
2307
- if (!this._commentsEnabled()) return !1;
2308
- let e = this._doc;
2309
- if (!e) return !1;
2310
- let t = e.commentAnchorRanges();
2311
- if (this._commentAnchorRangesForMargin !== t && (this._commentAnchorRangesForMargin = t, this._commentAnchorIds = new Set(t.map((e) => e.commentId))), this._commentAnchorIds.size === 0) return !1;
2312
- let n = this._commentsOptions()?.includeResolved === !0;
2313
- return e.comments.some((e) => this._commentAnchorIds.has(e.id) && e.parentId === void 0 && (n || e.resolved !== !0));
2314
- }
2315
- _commentMarginExtent() {
2316
- return this._hasCommentMargin() ? (Nn + 280) * this._commentZoom() : 0;
2317
- }
2318
- _commentZoom() {
2319
- return this._scaleEstablished ? this._scale : 1;
2320
- }
2321
- _commentsEnabled() {
2322
- return this._opts.comments === !0 || typeof this._opts.comments == "object";
2323
- }
2324
- _commentsOptions() {
2325
- return typeof this._opts.comments == "object" ? this._opts.comments : void 0;
2326
- }
2327
- _commentSide() {
2328
- let e = this._commentsOptions()?.side;
2329
- return e === "left" || e === "right" ? e : (this._container.ownerDocument.defaultView?.getComputedStyle?.(this._container).direction || this._container.dir || this._container.style.direction) === "rtl" ? "left" : "right";
2330
- }
2331
- _syncCommentMarginGeometry(e) {
2332
- if (!e) return;
2333
- e.style.display = this._hasCommentMargin() ? "" : "none";
2334
- let t = this._commentZoom(), n = `calc(100% + ${Nn * t}px)`;
2335
- e.style.left = this._commentSide() === "right" ? n : "", e.style.right = this._commentSide() === "left" ? n : "", e.style.width = `${280 * t}px`, e.style.fontSize = `${Pn}px`, e.dataset.ooxmlCommentZoom = String(t);
2336
- }
2337
- _widestPageWidthPt() {
2338
- if (!this._doc) return 0;
2339
- let e = 0, t = this._presentedPageCount || this._doc.pageCount;
2340
- for (let n = 0; n < t; n++) {
2341
- let t = this._doc.pageSize(n).widthPt;
2342
- t > e && (e = t);
2343
- }
2344
- return e;
2345
- }
2346
- _baseScale() {
2347
- if (!this._doc || this._doc.pageCount === 0) return 0;
2348
- let e = this._fitWidthPx();
2349
- if (e <= 0) return 0;
2350
- let t = this._widestPageWidthPt();
2351
- return t <= 0 ? 0 : e / (t * D);
2352
- }
2353
- relayout() {
2354
- this._relayout();
2355
- }
2356
- _relayout(e) {
2357
- if (this._doc) {
2358
- if (this._doc.layoutComplete !== !1 && (this._presentedPageCount = this._doc.pageCount), this._scaleEstablished) {
2359
- let e = this._baseScale();
2360
- if (e > 0 && e !== this._prevBase) {
2361
- let t = this._prevBase > 0 ? this._scale / this._prevBase : 1;
2362
- this._prevBase = e, this.setScale(e * t);
2363
- }
2364
- } else {
2365
- let e = this._baseScale();
2366
- if (e > 0) {
2367
- if (this._scale = e, this._prevBase = e, this._lastFitWidth = this._fitWidthPx(), this._scaleEstablished = !0, this._pendingScale !== null) {
2368
- let e = this._pendingScale;
2369
- this._pendingScale = null, e !== this._scale && (this._scale = e, this._opts.onScaleChange?.(e));
2370
- }
2371
- } else return;
2372
- }
2373
- this._recomputeHeights(), this._syncSpacer(), this._mountVisible(e);
2374
- for (let [e, t] of this._slots) t.renderedPage === e && t.renderedScale >= 0 && this._redrawSlotComments(e, t);
2375
- }
2376
- }
2377
- _recomputeHeights() {
2378
- let e = Math.min(this._presentedPageCount, this._doc.pageCount), t = Array(e);
2379
- for (let n = 0; n < e; n++) t[n] = this._pageHeightPx(n);
2380
- this._heights = t, this._scrollGeometry = Te(t, this._gap(), this._pad());
2381
- }
2382
- _gap() {
2383
- return this._opts.gap ?? 16;
2384
- }
2385
- _overscan() {
2386
- return this._opts.overscan ?? 1;
2387
- }
2388
- _pad() {
2389
- let e = this._gap();
2390
- return {
2391
- leading: this._opts.paddingTop ?? e,
2392
- trailing: this._opts.paddingBottom ?? e
2393
- };
2394
- }
2395
- _padH() {
2396
- let e = this._gap();
2397
- return {
2398
- left: this._opts.paddingLeft ?? e,
2399
- right: this._opts.paddingRight ?? e
2400
- };
2401
- }
2402
- _pageIndexAtOffset(e, t) {
2403
- let { offsets: n } = e, r = 0, i = n.length - 1, a = 0;
2404
- for (; r <= i;) {
2405
- let e = r + i >> 1;
2406
- n[e] <= t ? (a = e, r = e + 1) : i = e - 1;
2407
- }
2408
- return a;
2409
- }
2410
- _range() {
2411
- return w(this._scrollGeometry, this._scrollHost.scrollTop, this._scrollHost.clientHeight, this._overscan());
2412
- }
2413
- _syncSpacer() {
2414
- let e = this._range();
2415
- this._lastRange = e, this._spacer.style.height = `${e.totalHeight}px`, this._syncSpacerWidth();
2416
- }
2417
- _syncSpacerWidth() {
2418
- let { left: e, right: t } = this._padH(), n = 0;
2419
- for (let e = 0; e < this._heights.length; e++) {
2420
- let t = this._pageWidthPx(e);
2421
- t > n && (n = t);
2422
- }
2423
- let r = this._commentMarginExtent(), i = this._commentSide() === "left" ? r : 0, a = i - this._reviewOriginPx, o = Math.max(0, this._scrollHost.scrollLeft + a);
2424
- this._spacer.style.width = `${n + r + e + t}px`, a !== 0 && (this._reviewOriginPx = i, this._scrollHost.style["--ooxml-review-origin-x"] = `${i}px`, this._scrollHost.scrollLeft = o);
2425
- }
2426
- _onScroll() {
2427
- !this._doc || !this._scaleEstablished || this._mountVisible(void 0, !1);
2428
- }
2429
- _mountVisible(e, t = !0) {
2430
- if (!this._doc || this._doc.pageCount === 0) return;
2431
- let n = this._range();
2432
- this._lastRange = n;
2433
- for (let [e, t] of [...this._slots]) (e < n.start || e > n.end) && this._recycleSlot(e, t);
2434
- for (let r = n.start; r <= n.end; r++) if (!this._slots.has(r)) {
2435
- let t = this._acquireSlot();
2436
- this._positionSlot(t, r, n), this._slots.set(r, t);
2437
- let i = this._renderSlot(r, t, e === void 0);
2438
- e && i && e.push(i);
2439
- } else if (t) {
2440
- let t = this._slots.get(r);
2441
- this._positionSlot(t, r, n);
2442
- let i = this._renderSlot(r, t, e === void 0);
2443
- e && i && e.push(i);
2444
- }
2445
- this._emitVisiblePageChange(n);
2446
- }
2447
- _emitVisiblePageChange(e) {
2448
- if (!this._doc) return;
2449
- let t = this._doc.pageCount, n = this.layoutComplete;
2450
- e.topIndex === this._lastTopIndex && t === this._lastReportedTotal && n === this._lastReportedLayoutComplete || (this._lastTopIndex = e.topIndex, this._lastReportedTotal = t, this._lastReportedLayoutComplete = n, this._opts.onVisiblePageChange?.(e.topIndex, t, n));
2451
- }
2452
- _applyPageShadow(e) {
2453
- this._pageShadow !== !1 && (e.style.boxShadow = this._pageShadow);
2454
- }
2455
- _acquireSlot() {
2456
- let e = this._free.pop();
2457
- if (e) return this._scrollHost.appendChild(e.wrapper), e;
2458
- let t = document.createElement("div");
2459
- t.style.cssText = "position:absolute;";
2460
- let n = document.createElement("canvas");
2461
- n.style.cssText = "display:block;background:#fff;", this._applyPageShadow(n), t.appendChild(n);
2462
- let r = null;
2463
- 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));
2464
- let i = document.createElement("div");
2465
- i.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;", t.appendChild(i);
2466
- let a = null, o = null, s = null;
2467
- this._commentsEnabled() && (a = document.createElement("div"), a.style.cssText = "position:absolute;inset:0;overflow:hidden;pointer-events:none;", t.appendChild(a), this._commentsOptions()?.cards !== !1 && (o = document.createElement("div"), o.style.cssText = "position:absolute;top:0;height:100%;box-sizing:border-box;overflow-x:hidden;overflow-y:auto;pointer-events:auto;", this._syncCommentMarginGeometry(o), this._commentsOptions()?.connectors !== void 0 && (s = document.createElement("div"), s.style.cssText = "position:absolute;top:0;left:0;overflow:visible;pointer-events:none;", t.appendChild(s)), t.appendChild(o)));
2468
- let c = ce(t, this._opts.enableElementSelection === !0);
2469
- return this._scrollHost.appendChild(t), {
2470
- wrapper: t,
2471
- canvas: n,
2472
- textLayer: r,
2473
- highlightLayer: i,
2474
- elementLayer: c,
2475
- commentTintLayer: a,
2476
- commentMargin: o,
2477
- commentDecorationLayer: s,
2478
- commentRuns: Object.freeze([]),
2479
- commentGeometry: null,
2480
- renderedPage: -1,
2481
- renderedScale: -1,
2482
- dispatcher: new S(n, this._mode === "worker")
2483
- };
2484
- }
2485
- _recycleSlot(e, t) {
2486
- this._slots.delete(e), t.dispatcher.destroy(), this._destroyed || (t.dispatcher = new S(t.canvas, this._mode === "worker")), t.textLayer && (t.textLayer.innerHTML = "", this._clearTextLayerPreview(t.textLayer)), t.highlightLayer.innerHTML = "", t.highlightLayer.style.transform = "", t.highlightLayer.style.transformOrigin = "", t.commentTintLayer && (t.commentTintLayer.replaceChildren(), t.commentTintLayer.style.transform = "", t.commentTintLayer.style.transformOrigin = "", t.commentTintLayer.style.visibility = ""), t.commentMargin && (this._commentUi?.disposeReadOnlyCommentMargin(t.commentMargin), this._commentUi || t.commentMargin.replaceChildren(), t.commentMargin.style.visibility = ""), t.commentDecorationLayer && (this._commentUi?.disposeReadOnlyCommentDecoration(t.commentDecorationLayer), this._commentUi || t.commentDecorationLayer.replaceChildren()), t.commentRuns = Object.freeze([]), t.commentGeometry = null, x(t.elementLayer, null), t.renderedPage = -1, t.renderedScale = -1, t.wrapper.remove(), this._free.push(t);
2487
- }
2488
- _positionSlot(e, t, n) {
2489
- e.wrapper.style.top = `${n.offsets[t]}px`;
2490
- let r = this._pageWidthPx(t), i = this._pageHeightPx(t);
2491
- if (e.wrapper.style.width = `${r}px`, e.wrapper.style.height = `${i}px`, this._syncCommentMarginGeometry(e.commentMargin), e.commentDecorationLayer) {
2492
- let t = this._commentMarginExtent();
2493
- e.commentDecorationLayer.style.left = this._commentSide() === "left" ? `${-t}px` : "0px", e.commentDecorationLayer.style.width = `${r + t}px`, e.commentDecorationLayer.style.height = `${i}px`;
2494
- }
2495
- this._redrawElementOutlineForSlot(t, e);
2496
- let { left: a } = this._padH(), o = Math.max(a, (this._scrollHost.clientWidth - r) / 2);
2497
- e.wrapper.style.left = this._commentSide() === "left" && this._commentsEnabled() ? `calc(${o}px + var(--ooxml-review-origin-x, 0px))` : `${o}px`;
2498
- }
2499
- _dpr() {
2500
- return this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1);
2501
- }
2502
- _renderSlot(e, t, n = !0) {
2503
- if (!this._doc || t.renderedPage === e) return null;
2504
- t.renderedPage = e;
2505
- let r = this._dpr(), i = this._pageWidthPx(e), a = this._renderEpoch, o = this._scale, s = t.dispatcher, c = s.begin();
2506
- if (this._mode === "worker") return this._renderSlotBitmap(e, t, i, r, o, s, c, n);
2507
- let l = [], u = !!this._opts.enableTextSelection && !!t.textLayer, d = u || this._findActive || !!t.commentTintLayer, f = d ? (e) => l.push(e) : void 0, p;
2508
- try {
2509
- p = $(this._doc, t.canvas, e, "main", {
2510
- width: i,
2511
- dpr: r,
2512
- imageResources: this._opts.imageResources,
2513
- defaultTextColor: this._opts.defaultTextColor,
2514
- currentDate: this._currentDate,
2515
- ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2516
- onTextRun: f
2517
- });
2518
- } catch (e) {
2519
- return n ? (this._reportRenderError(e), Promise.resolve()) : Promise.reject(e);
2520
- }
2521
- return p.then(() => {
2522
- if (!(!s.isCurrent(c) || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e)) {
2523
- if (t.renderedScale = o, u && t.textLayer) {
2524
- let { width: n, height: r } = this._canvasCssPx(t.canvas);
2525
- X(t.textLayer, l, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
2526
- }
2527
- d && this._refreshFindRuns(e, l), this._commitCommentRuns(e, t, l), this._redrawSlotHighlights(e, t);
2528
- }
2529
- }).catch((r) => {
2530
- if (s.isCurrent(c) && a === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e) if (n) this._reportRenderError(r);
2531
- else throw r;
2532
- });
2533
- }
2534
- _hyperlinkHandler() {
2535
- return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
2536
- if (e.kind === "external") {
2537
- u(e.url);
2538
- return;
2539
- }
2540
- let t = this._doc;
2541
- if (!t) return;
2542
- let n = ++this._internalHyperlinkGeneration;
2543
- this._navigateInternalHyperlink(t, e.ref, n).catch((e) => this._reportRenderError(e));
2544
- });
2545
- }
2546
- async _navigateInternalHyperlink(e, t, n) {
2547
- if (e.layoutComplete || await e.waitUntilLayoutComplete(), this._destroyed || this._doc !== e || n !== this._internalHyperlinkGeneration) return;
2548
- let r = e.getBookmarkPage(t);
2549
- r !== void 0 && this.scrollToPage(r);
2550
- }
2551
- _measureForFont(e) {
2552
- this._measureCtx === void 0 && (this._measureCtx = document.createElement("canvas").getContext("2d"));
2553
- let t = this._measureCtx;
2554
- return !t || typeof t.measureText != "function" ? (e) => e.length : (t.font = e, (e) => t.measureText(e).width);
2555
- }
2556
- _canvasCssPx(e) {
2557
- return {
2558
- width: parseFloat(e.style.width) || e.width,
2559
- height: parseFloat(e.style.height) || e.height
2560
- };
2561
- }
2562
- _reportRenderError(e) {
2563
- this._errorRouter.report(e);
2564
- }
2565
- async _renderSlotBitmap(e, t, n, r, i, a = t.dispatcher, o = a.begin(), s = !0) {
2566
- if (this._bitmapInFlight.has(e) || this._slots.get(e) !== t) return;
2567
- let c = this._renderEpoch, l = this._pageHeightPx(e);
2568
- this._bitmapInFlight.add(e);
2569
- let u = !1, d = !!this._opts.enableTextSelection && !!t.textLayer, f = d || this._findActive || !!t.commentTintLayer, p = [];
2570
- try {
2571
- let s = await $(this._doc, t.canvas, e, "worker", {
2572
- width: n,
2573
- dpr: r,
2574
- imageResources: this._opts.imageResources,
2575
- defaultTextColor: this._opts.defaultTextColor,
2576
- currentDate: this._currentDate,
2577
- ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2578
- onTextRun: f ? (e) => p.push(e) : void 0
2579
- });
2580
- if (!a.isCurrent(o) || c !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
2581
- s.close();
2582
- return;
2583
- }
2584
- if (!a.commitBitmap(o, s, {
2585
- cssWidth: n,
2586
- cssHeight: l
2587
- })) return;
2588
- if (t.renderedScale = i, t.textLayer && (this._clearTextLayerPreview(t.textLayer), d)) {
2589
- let { width: n, height: r } = this._canvasCssPx(t.canvas);
2590
- X(t.textLayer, p, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
2591
- }
2592
- f && this._refreshFindRuns(e, p), this._commitCommentRuns(e, t, p), this._redrawSlotHighlights(e, t), u = !0;
2593
- } catch (n) {
2594
- if (a.isCurrent(o) && c === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e) if (s) this._reportRenderError(n);
2595
- else throw n;
2596
- } finally {
2597
- this._bitmapInFlight.delete(e);
2598
- let n = this._slots.get(e);
2599
- if (!u && n && (n !== t || c !== this._renderEpoch || !a.isCurrent(o)) && !this._bitmapInFlight.has(e) && !this._destroyed) {
2600
- let t = n.dispatcher;
2601
- await this._renderSlotBitmap(e, n, this._pageWidthPx(e), this._dpr(), this._scale, t, t.begin(), s);
2602
- }
2603
- }
2604
- }
2605
- setScale(e) {
2606
- let t = this._effectiveZoomMin(), n = this._opts.zoomMax ?? 4, r = Math.min(n, Math.max(t, e)), i = this._pendingZoomAnchor;
2607
- if (this._pendingZoomAnchor = null, !this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) {
2608
- this._pendingScale = r;
2609
- return;
2610
- }
2611
- if (r === this._scale) return;
2612
- let a = this._scale, o = i ? i.y : 0, s = this._range(), c = this._scrollHost.scrollTop, l = c + o, u = this._pageIndexAtOffset(s, l), d = this._heights[u] || 0, f = d > 0 ? (l - s.offsets[u]) / d : 0;
2613
- f = Math.min(1, Math.max(0, f));
2614
- let p = this._padH().left, m = this._scrollHost.scrollLeft || 0;
2615
- this._renderEpoch++, this._scale = r, this._recomputeHeights();
2616
- let h = w(this._scrollGeometry, 0, this._scrollHost.clientHeight, this._overscan());
2617
- this._spacer.style.height = `${h.totalHeight}px`, this._syncSpacerWidth();
2618
- let g = Math.max(0, h.totalHeight - this._scrollHost.clientHeight), _ = (h.offsets[u] ?? 0) + f * (this._heights[u] || 0), v = l < (s.offsets[0] ?? 0) ? c : _ - o;
2619
- if (this._scrollHost.scrollTop = Math.min(g, Math.max(0, v)), i) {
2620
- let e = Math.max(0, (this._spacer.offsetWidth || 0) - this._scrollHost.clientWidth);
2621
- this._scrollHost.scrollLeft = te(m, i.x - p, a, r, { maxScroll: e });
2622
- }
2623
- this._previewVisible(), this._scheduleSettle(), this._opts.onScaleChange?.(r);
2624
- }
2625
- getScale() {
2626
- return this._scaleEstablished ? this._scale : this._pendingScale ?? 1;
2627
- }
2628
- zoomIn() {
2629
- this.setScale(me(this.getScale()));
2630
- }
2631
- zoomOut() {
2632
- this.setScale(_e(this.getScale(), this._effectiveZoomMin()));
2633
- }
2634
- _effectiveZoomMin() {
2635
- let e = this._opts.zoomMin ?? .1;
2636
- return this._scaleEstablished && this._prevBase > 0 ? Math.min(e, this._prevBase) : e;
2637
- }
2638
- fitWidth() {
2639
- this._fit("width");
2640
- }
2641
- fitPage() {
2642
- this._fit("page");
2643
- }
2644
- _fit(e) {
2645
- if (!this._doc || this._doc.pageCount === 0) return;
2646
- let t = this._doc.pageSize(0), n = y({
2647
- contentWidth: (e === "width" ? this._widestPageWidthPt() : t.widthPt) * D,
2648
- contentHeight: t.heightPt * D,
2649
- containerWidth: this._fitWidthPx(),
2650
- containerHeight: this._scrollHost.clientHeight
2651
- }, e);
2652
- n <= 0 || this.setScale(n);
2653
- }
2654
- _previewVisible() {
2655
- if (!this._doc || this._doc.pageCount === 0) return;
2656
- let e = this._range();
2657
- this._lastRange = e;
2658
- for (let [t, n] of [...this._slots]) (t < e.start || t > e.end) && this._recycleSlot(t, n);
2659
- for (let t = e.start; t <= e.end; t++) {
2660
- let n = this._slots.get(t);
2661
- if (n) this._previewSlot(n, t, e);
2662
- else {
2663
- let n = this._acquireSlot();
2664
- this._positionSlot(n, t, e), this._slots.set(t, n), this._renderSlot(t, n);
2665
- }
2666
- }
2667
- this._emitVisiblePageChange(e);
2668
- }
2669
- _previewSlot(e, t, n) {
2670
- if (this._positionSlot(e, t, n), e.canvas.style.width = `${this._pageWidthPx(t)}px`, e.canvas.style.height = `${this._pageHeightPx(t)}px`, e.renderedScale > 0) {
2671
- let n = this._scale / e.renderedScale;
2672
- e.textLayer && (e.textLayer.style.transformOrigin = "0 0", e.textLayer.style.width = `${this._pageWidthPx(t) / n}px`, e.textLayer.style.height = `${this._pageHeightPx(t) / n}px`, e.textLayer.style.transform = `scale(${n})`), e.commentMargin && this._commentUi?.previewReadOnlyCommentMargin(e.commentMargin, n);
2673
- for (let t of e.commentTintLayer?.children ?? []) t.dataset.ooxmlCommentMarker !== void 0 && (t.style.transform = `translate(-50%,-50%) scale(${n})`);
2674
- e.commentTintLayer && (e.commentTintLayer.style.visibility = ""), e.commentMargin && (e.commentMargin.style.visibility = ""), e.commentDecorationLayer && (e.commentDecorationLayer.style.visibility = "");
2675
- return;
2676
- }
2677
- e.commentTintLayer && (e.commentTintLayer.style.visibility = "hidden"), e.commentMargin && (e.commentMargin.style.visibility = "hidden"), e.commentDecorationLayer && (e.commentDecorationLayer.style.visibility = "hidden");
2678
- }
2679
- _clearTextLayerPreview(e) {
2680
- e.style.transform = "", e.style.transformOrigin = "", e.style.width = "100%", e.style.height = "100%";
2681
- }
2682
- _scheduleSettle() {
2683
- this._settleTimer !== null && clearTimeout(this._settleTimer), this._settleTimer = setTimeout(() => {
2684
- this._settleTimer = null, this._settleRender();
2685
- }, jn);
2686
- }
2687
- _settleRender() {
2688
- if (!(this._destroyed || !this._doc || this._doc.pageCount === 0)) for (let [e, t] of [...this._slots]) t.renderedScale !== this._scale && this._refreshSlotAtomically(e, t);
2689
- }
2690
- _refreshSlotAtomically(e, t) {
2691
- if (!this._doc) return;
2692
- let n = this._dpr(), r = this._pageWidthPx(e), i = this._scale, a = this._renderEpoch;
2693
- if (this._mode === "worker") {
2694
- this._renderSlotBitmap(e, t, r, n, i);
2695
- return;
2696
- }
2697
- let o = document.createElement("canvas");
2698
- o.style.cssText = "display:block;background:#fff;", this._applyPageShadow(o);
2699
- let s = new S(o, !1), c = s.begin(), l = [], u = !!this._opts.enableTextSelection && !!t.textLayer, d = u || this._findActive || !!t.commentTintLayer, f = d ? (e) => l.push(e) : void 0;
2700
- $(this._doc, o, e, "main", {
2701
- width: r,
2702
- dpr: n,
2703
- imageResources: this._opts.imageResources,
2704
- defaultTextColor: this._opts.defaultTextColor,
2705
- currentDate: this._currentDate,
2706
- ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2707
- onTextRun: f
2708
- }).then(() => {
2709
- if (!s.isCurrent(c) || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
2710
- s.destroy();
2711
- return;
2712
- }
2713
- let n = t.canvas;
2714
- if (t.dispatcher.destroy(), t.wrapper.insertBefore(o, n), n.remove(), t.canvas = o, t.dispatcher = s, t.renderedScale = i, t.textLayer && (this._clearTextLayerPreview(t.textLayer), u)) {
2715
- let { width: n, height: r } = this._canvasCssPx(o);
2716
- X(t.textLayer, l, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
2717
- }
2718
- d && this._refreshFindRuns(e, l), this._commitCommentRuns(e, t, l), this._redrawSlotHighlights(e, t);
2719
- }).catch((n) => {
2720
- s.isCurrent(c) && a === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e && this._reportRenderError(n), s.destroy();
2721
- });
2722
- }
2723
- async setShowTrackedChanges(e) {
2724
- let t = ++this._layoutViewGeneration, n = this._doc;
2725
- if (this._showTrackedChanges === e) {
2726
- n && await K(n, {
2727
- showTrackedChanges: e,
2728
- currentDate: this._currentDate
2729
- }, this);
2730
- return;
2731
- }
2732
- (!n || await K(n, {
2733
- showTrackedChanges: e,
2734
- currentDate: this._currentDate
2735
- }, this)) && (this._destroyed || t !== this._layoutViewGeneration || n !== this._doc || (this._showTrackedChanges = e, this._find.invalidate(), this._applyLayoutPublication({
2736
- pageCount: n?.pageCount ?? 0,
2737
- exact: !0,
2738
- complete: n?.layoutComplete !== !1
2739
- })));
2740
- }
2741
- scrollToPage(e, t) {
2742
- if (!this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) return;
2743
- let n = Math.max(0, Math.min(e, this._doc.pageCount - 1)), r = w(this._scrollGeometry, 0, this._scrollHost.clientHeight, this._overscan()), i = ve(r.offsets[n] ?? 0, Math.max(0, r.totalHeight - this._scrollHost.clientHeight)), a = this._scrollHost;
2744
- typeof a.scrollTo == "function" ? a.scrollTo({
2745
- top: i,
2746
- behavior: t?.behavior ?? "auto"
2747
- }) : this._scrollHost.scrollTop = i, this._mountVisible();
2748
- }
2749
- _scrollToPageTarget(e, t, n) {
2750
- let r = w(this._scrollGeometry, 0, this._scrollHost.clientHeight, this._overscan()), i = this._pageWidthPx(e), { left: a } = this._padH(), o = Math.max(a, (this._scrollHost.clientWidth - i) / 2) + this._reviewOriginPx, s = Math.max(0, r.totalHeight - this._scrollHost.clientHeight), c = this._spacer.offsetWidth || Number.parseFloat(this._spacer.style.width) || 0, l = Math.max(0, c - this._scrollHost.clientWidth), u = Math.min(s, Math.max(0, (r.offsets[e] ?? 0) + t.y + t.h / 2 - this._scrollHost.clientHeight / 2)), d = Math.min(l, Math.max(0, o + t.x + t.w / 2 - this._scrollHost.clientWidth / 2)), f = this._scrollHost;
2751
- typeof f.scrollTo == "function" ? f.scrollTo({
2752
- top: u,
2753
- left: d,
2754
- behavior: n?.behavior ?? "auto"
2755
- }) : (this._scrollHost.scrollTop = u, this._scrollHost.scrollLeft = d), this._mountVisible();
2756
- }
2757
- _resetCommentNavigation() {
2758
- this._commentNavigationGeneration++, this._commentPageById.clear(), this._commentRunsByPage.clear(), this._commentIndexedPages.clear(), this._commentScanFrontier = 0;
2759
- }
2760
- _advanceCommentScanFrontier() {
2761
- for (; this._commentIndexedPages.has(this._commentScanFrontier);) this._commentScanFrontier++;
2762
- }
2763
- _indexCommentPages(e, t, n) {
2764
- if (!this._commentIndexedPages.has(e)) {
2765
- for (let r of n) this._commentPageById.has(r.commentId) || A(r, t).length > 0 && this._commentPageById.set(r.commentId, e);
2766
- this._commentIndexedPages.add(e), this._advanceCommentScanFrontier();
2767
- }
2768
- }
2769
- async _commentRunsForPage(e, t) {
2770
- for (; !this._destroyed && this._doc === t;) {
2771
- let n = this._scale, r = this._commentRunsByPage.get(e);
2772
- (!r || r.scale !== n) && (r = {
2773
- scale: n,
2774
- runs: t.collectPageRuns(e, {
2775
- width: this._pageWidthPx(e),
2776
- currentDate: this._currentDate,
2777
- ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {}
2778
- })
2779
- }, this._commentRunsByPage.set(e, r));
2780
- try {
2781
- let e = await r.runs;
2782
- if (this._destroyed || this._doc !== t) return null;
2783
- if (this._scale !== n) continue;
2784
- return e;
2785
- } catch (t) {
2786
- throw this._commentRunsByPage.get(e) === r && this._commentRunsByPage.delete(e), t;
2787
- }
2788
- }
2789
- return null;
2790
- }
2791
- async goToComment(e, t) {
2792
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2793
- let n = this._doc;
2794
- if (!n || !n.comments.some((t) => t.id === e && t.parentId === void 0)) return !1;
2795
- let r = ++this._commentNavigationGeneration, i = !n.layoutComplete, a = n.commentAnchorRanges().filter((t) => t.commentId === e), o = t?.pageIndex;
2796
- if (o !== void 0 && (!Number.isInteger(o) || o < 0)) return !1;
2797
- let s = o ?? this._commentPageById.get(e), c, l = async () => {
2798
- let t = n.commentAnchorRanges();
2799
- for (; s === void 0 && this._commentScanFrontier < n.pageCount;) {
2800
- let i = this._commentScanFrontier, a = await this._commentRunsForPage(i, n);
2801
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2802
- if (this._doc !== n || r !== this._commentNavigationGeneration || !a) return;
2803
- this._indexCommentPages(i, a, t), s = this._commentPageById.get(e);
2804
- }
2805
- return s;
2806
- };
2807
- if (o === void 0 && s === void 0 && a.length > 0 && await l(), i && (o !== void 0 && o >= n.pageCount || o === void 0 && s === void 0)) {
2808
- if (await this._errorRouter.ownBackgroundLifecycle(() => n.waitUntilLayoutComplete()), this._destroyed) throw Error("DocxScrollViewer is destroyed");
2809
- if (this._doc !== n || r !== this._commentNavigationGeneration) return !1;
2810
- a = n.commentAnchorRanges().filter((t) => t.commentId === e), this._commentPageById.clear(), this._commentRunsByPage.clear(), this._commentIndexedPages.clear(), this._commentScanFrontier = 0, s = o, o === void 0 && a.length > 0 && await l();
2811
- }
2812
- if (a.length === 0 || o !== void 0 && o >= n.pageCount || s === void 0) return !1;
2813
- let u = await this._commentRunsForPage(s, n);
2814
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2815
- if (this._doc !== n || r !== this._commentNavigationGeneration || !u || (c = a.flatMap((e) => A(e, u))[0], !c)) return !1;
2816
- this._activeCommentId = e, this._activeCommentPage = s, this._elementContext = null, this._scrollToPageTarget(s, c, t);
2817
- for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
2818
- return this._emitSelectionContextChange(), !0;
2819
- }
2820
- async findText(e, t = {}) {
2821
- if (!this._doc) return [];
2822
- let n = ++this._findRequestGeneration;
2823
- if (this._doc.layoutComplete === !1) {
2824
- let e = this._doc;
2825
- if (await this._errorRouter.ownBackgroundLifecycle(() => e.waitUntilLayoutComplete()), this._destroyed || this._doc !== e || n !== this._findRequestGeneration) return [];
2826
- }
2827
- this._findActive = e.length > 0;
2828
- let r = await this._errorRouter.ownAwaitable(() => this._find.find(e, t));
2829
- return this._redrawHighlights(), r;
2830
- }
2831
- async findNext() {
2832
- return this._activateMatch(this._find.next());
2833
- }
2834
- async findPrev() {
2835
- return this._activateMatch(this._find.prev());
2836
- }
2837
- clearFind() {
2838
- this._findRequestGeneration++, this._findActive = !1, this._find.invalidate(), this._redrawHighlights();
2839
- }
2840
- async _activateMatch(e) {
2841
- return e && this.scrollToPage(e.location.page), this._redrawHighlights(), e;
2842
- }
2843
- async _collectPageRuns(e) {
2844
- return this._doc ? this._doc.collectPageRuns(e, {
2845
- width: this._pageWidthPx(e),
2846
- currentDate: this._currentDate,
2847
- ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {}
2848
- }) : [];
2849
- }
2850
- _redrawHighlights() {
2851
- for (let [e, t] of this._slots) this._redrawSlotHighlights(e, t);
2852
- }
2853
- _refreshFindRuns(e, t) {
2854
- this._findActive && this._find.setPageRuns(e, t);
2855
- }
2856
- _commitCommentRuns(e, t, n) {
2857
- t.commentTintLayer && (t.commentRuns = Object.freeze([...n]), this._commentRunsByPage.set(e, {
2858
- scale: this._scale,
2859
- runs: Promise.resolve(t.commentRuns)
2860
- }), this._doc && e === this._commentScanFrontier && this._indexCommentPages(e, t.commentRuns, this._doc.commentAnchorRanges()), t.commentTintLayer.style.transform = "", t.commentTintLayer.style.transformOrigin = "", this._redrawSlotComments(e, t), t.commentTintLayer.style.visibility = "", t.commentMargin && (t.commentMargin.style.visibility = ""), t.commentDecorationLayer && (t.commentDecorationLayer.style.visibility = ""));
2861
- }
2862
- _redrawSlotComments(e, t) {
2863
- if (!this._doc || !t.commentTintLayer) return;
2864
- this._syncCommentMarginGeometry(t.commentMargin);
2865
- let n = this._commentUi;
2866
- if (!n) {
2867
- t.commentTintLayer.replaceChildren(), t.commentMargin?.replaceChildren(), t.commentDecorationLayer?.replaceChildren(), t.commentGeometry = null;
2868
- return;
2869
- }
2870
- t.commentGeometry = n.buildDocxCommentMargin(t.commentTintLayer, t.commentMargin, t.commentRuns, {
2871
- comments: this._doc.comments,
2872
- anchors: this._doc.commentAnchorRanges()
2873
- }, this._pageWidthPx(e), this._pageHeightPx(e), this._activeCommentId, (t, n) => {
2874
- let r = n ? t : this._activeCommentId === t ? null : this._activeCommentId;
2875
- if (r !== this._activeCommentId) {
2876
- this._activeCommentId = r, this._activeCommentPage = r ? e : null, this._elementContext = null;
2877
- for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
2878
- this._emitSelectionContextChange();
2879
- }
2880
- }, this._commentZoom(), 280, this._commentsOptions()?.markers !== !1, this._commentsOptions()?.includeResolved === !0, t.commentDecorationLayer ? () => this._scheduleCommentGeometry(e, t, !1) : void 0, t.commentDecorationLayer ? () => this._scheduleCommentGeometry(e, t, !0) : void 0), this._redrawSlotCommentConnectors(e, t);
2881
- }
2882
- _redrawSlotCommentConnectors(e, t) {
2883
- let n = t.commentDecorationLayer, r = t.commentMargin, i = t.commentGeometry, a = this._commentsOptions()?.connectors;
2884
- if (!n || !r || !i || !a) return;
2885
- let o = this._pageWidthPx(e), s = this._pageHeightPx(e), c = this._commentSide(), l = this._commentMarginExtent(), u = this._commentUi;
2886
- u && u.buildReadOnlyCommentDecoration(n, Object.freeze({
2887
- surfaceBounds: Object.freeze({
2888
- x: c === "left" ? -l : 0,
2889
- y: 0,
2890
- width: o + l,
2891
- height: s
2892
- }),
2893
- contentBounds: Object.freeze({
2894
- x: 0,
2895
- y: 0,
2896
- width: o,
2897
- height: s
2898
- }),
2899
- side: c,
2900
- threads: u.projectReadOnlyCommentMarginScroll(i, r.scrollTop)
2901
- }), {
2902
- route: a.route ?? "bezier",
2903
- stroke: a.stroke ?? "solid",
2904
- color: a.color,
2905
- activeColor: a.activeColor
2906
- });
2907
- }
2908
- _scheduleCommentGeometry(e, t, n = !1) {
2909
- let r = this._pendingCommentGeometry.get(e);
2910
- if (this._pendingCommentGeometry.set(e, {
2911
- slot: t,
2912
- connectorsOnly: r?.slot === t ? r.connectorsOnly && n : n
2913
- }), this._commentGeometryScheduled) return;
2914
- this._commentGeometryScheduled = !0;
2915
- let i = () => {
2916
- this._commentGeometryScheduled = !1, this._commentGeometryFrame = null;
2917
- let e = [...this._pendingCommentGeometry];
2918
- if (this._pendingCommentGeometry.clear(), !this._destroyed) for (let [t, n] of e) {
2919
- let { slot: e, connectorsOnly: r } = n;
2920
- this._slots.get(t) === e && e.renderedScale === this._scale && (r ? this._redrawSlotCommentConnectors(t, e) : this._redrawSlotComments(t, e));
2921
- }
2922
- }, a = this._wrapper.ownerDocument.defaultView;
2923
- a?.requestAnimationFrame ? this._commentGeometryFrame = a.requestAnimationFrame(i) : queueMicrotask(i);
2924
- }
2925
- _redrawSlotHighlights(e, t) {
2926
- if (!this._findActive) {
2927
- t.highlightLayer.innerHTML = "";
2928
- return;
2929
- }
2930
- let n = this._find.pageRuns(e);
2931
- if (!n) {
2932
- t.highlightLayer.innerHTML = "";
2933
- return;
2934
- }
2935
- Z(t.highlightLayer, n, this._find.pageHighlights(e), this._pageWidthPx(e), this._pageHeightPx(e), (e) => this._measureForFont(e), this._opts.findHighlightColors);
2936
- }
2937
- _onResize() {
2938
- if (!this._doc || this._doc.pageCount === 0) return;
2939
- if (!this._scaleEstablished) {
2940
- this.relayout();
2941
- return;
2942
- }
2943
- if (this._opts.refitOnResize === !1) {
2944
- this._lastFitWidth = this._fitWidthPx(), this._mountVisible();
2945
- return;
2946
- }
2947
- let e = this._baseScale();
2948
- if (e <= 0) return;
2949
- let t = this._fitWidthPx();
2950
- if (t === this._lastFitWidth) {
2951
- this._mountVisible();
2952
- return;
2953
- }
2954
- this._lastFitWidth = t;
2955
- let n = this._prevBase > 0 ? this._scale / this._prevBase : 1;
2956
- this._prevBase = e, this.setScale(e * n), this._mountVisible();
2957
- }
2958
- get topVisiblePage() {
2959
- return this._lastRange?.topIndex ?? 0;
2960
- }
2961
- mountedPageIndicesForTest() {
2962
- return [...this._slots.keys()];
2963
- }
2964
- scaleForTest() {
2965
- return this._scale;
2966
- }
2967
- baseScaleForTest() {
2968
- return this._baseScale();
2969
- }
2970
- renderEpochForTest() {
2971
- return this._renderEpoch;
2972
- }
2973
- resizeForTest() {
2974
- this._onResize();
2975
- }
2976
- contentAtViewportYForTest(e) {
2977
- let t = this._range(), n = this._scrollHost.scrollTop + e, r = this._pageIndexAtOffset(t, n), i = this._heights[r] || 0;
2978
- return {
2979
- page: r,
2980
- frac: i > 0 ? Math.min(1, Math.max(0, (n - t.offsets[r]) / i)) : 0
2981
- };
2982
- }
2983
- viewportYOfForTest(e, t) {
2984
- return (this._range().offsets[e] ?? 0) + t * (this._heights[e] || 0) - this._scrollHost.scrollTop;
2985
- }
2986
- async getResourceMetrics() {
2987
- if (!this._doc) throw Error("Document not loaded");
2988
- return await this._doc.getResourceMetrics();
2989
- }
2990
- getSelectionContext(e = {}) {
2991
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2992
- return (this._doc && this._activeCommentId !== null && this._activeCommentPage !== null ? wn(this._doc.comments, this._doc.commentAnchorRanges(), this._activeCommentId, this._activeCommentPage, e) : null) || ((this._opts.enableTextSelection ? Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null, e) : null) ?? (this._elementContext ? nn(this._elementContext, e.maxTextCharacters) : null));
2993
- }
2994
- _emitSelectionContextChange() {
2995
- let e = this.getSelectionContext();
2996
- e?.kind === "text" && (this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutlines());
2997
- let t = JSON.stringify(e);
2998
- t !== this._selectionContextKey && (this._selectionContextKey = t, this._opts.onSelectionContextChange?.(e ? structuredClone(e) : null));
2999
- }
3000
- _setElementContext(e) {
3001
- this._elementContext = e ? structuredClone(e) : null, this._redrawElementOutlines(), this._emitSelectionContextChange();
3002
- }
3003
- _invalidateElementContext(e = !0) {
3004
- this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutlines(), e && this._emitSelectionContextChange();
3005
- }
3006
- _redrawElementOutlines() {
3007
- for (let [e, t] of this._slots) this._redrawElementOutlineForSlot(e, t);
3008
- }
3009
- _redrawElementOutlineForSlot(e, t) {
3010
- let n = this._elementContext, r = this._doc;
3011
- if (!n || !r || n.pageIndex !== e) {
3012
- x(t.elementLayer, null);
3013
- return;
3014
- }
3015
- let i = r.pageSize(e);
3016
- x(t.elementLayer, {
3017
- x: n.bounds.xPt / i.widthPt,
3018
- y: n.bounds.yPt / i.heightPt,
3019
- width: n.bounds.widthPt / i.widthPt,
3020
- height: n.bounds.heightPt / i.heightPt
3021
- });
3022
- }
3023
- async _onElementClick(e) {
3024
- this._destroyed || e.defaultPrevented || e.button !== 0 || await this._resolveContextAt(e);
3025
- }
3026
- _onContextMenu(e) {
3027
- let t;
3028
- this._opts.onContextMenu?.({
3029
- originalEvent: e,
3030
- getContext: () => t ??= this._resolveContextAt(e)
3031
- });
3032
- }
3033
- async _resolveContextAt(e) {
3034
- let t = this._doc;
3035
- if (this._destroyed || !t) return null;
3036
- if (this._opts.enableTextSelection && Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null)) return this._emitSelectionContextChange(), this._destroyed ? null : this.getSelectionContext();
3037
- if (!this._opts.enableElementSelection) return this.getSelectionContext();
3038
- let n = e.target, r = [...this._slots].find(([, e]) => n !== null && e.wrapper.contains(n));
3039
- if (!r) return this._invalidateElementContext(), null;
3040
- let [i, a] = r, o = a.canvas.getBoundingClientRect();
3041
- if (o.width <= 0 || o.height <= 0) return this._invalidateElementContext(), null;
3042
- let s = e.clientX - o.left, c = e.clientY - o.top;
3043
- if (s < 0 || c < 0 || s > o.width || c > o.height) return this._invalidateElementContext(), null;
3044
- let l = ++this._elementHitGeneration, u = t.pageSize(i), d;
3045
- try {
3046
- d = await t.getElementContextAt(i, {
3047
- xPt: s / o.width * u.widthPt,
3048
- yPt: c / o.height * u.heightPt
3049
- }, {
3050
- currentDate: this._currentDate,
3051
- ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
3052
- maxTextCharacters: F
3053
- });
3054
- } catch (e) {
3055
- if (this._destroyed || l !== this._elementHitGeneration || t !== this._doc) return null;
3056
- throw e;
3057
- }
3058
- return this._destroyed || l !== this._elementHitGeneration || t !== this._doc ? null : (this._setElementContext(d), this._destroyed ? null : this.getSelectionContext());
3059
- }
3060
- destroy() {
3061
- if (!this._destroyed) {
3062
- this._destroyed = !0, this._findRequestGeneration++, this._errorRouter.close(), this._unbindLayoutDocument(), this._layoutViewGeneration++, this._resetCommentNavigation(), this._find.invalidate(), this._findActive = !1, this._selectionChangeListener &&= (this._wrapper.ownerDocument.removeEventListener("selectionchange", this._selectionChangeListener), null), this._elementHitGeneration++, this._elementClickListener &&= (this._scrollHost.removeEventListener("click", this._elementClickListener), null), this._contextMenuListener &&= (this._scrollHost.removeEventListener("contextmenu", this._contextMenuListener), null), this._commentOutsidePointerListener &&= (this._wrapper.ownerDocument.removeEventListener("pointerdown", this._commentOutsidePointerListener), null), this._commentGeometryFrame !== null && (this._wrapper.ownerDocument.defaultView?.cancelAnimationFrame?.(this._commentGeometryFrame), this._commentGeometryFrame = null), this._commentGeometryScheduled = !1, this._pendingCommentGeometry.clear(), this._elementContext = null, 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);
3063
- for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
3064
- this._free.length = 0, this._documentOwner.close(), this._wrapper.remove();
3065
- }
3066
- }
3067
- };
3068
- //#endregion
3069
- //#region packages/docx/src/types.ts
3070
- function zn(e) {
3071
- let t = [];
3072
- for (let n of e.content) {
3073
- if (n.type !== "paragraph") continue;
3074
- let e = "";
3075
- for (let t of n.runs) t.type === "text" && !t.noteRef && (e += t.text);
3076
- e = e.trim(), e && t.push(e);
3077
- }
3078
- return t.join(" ");
3079
- }
3080
- //#endregion
3081
- //#region src/docx.ts
3082
- var Bn = /* @__PURE__ */ e({
3083
- DocxDocument: () => J,
3084
- DocxScrollViewer: () => Rn,
3085
- DocxViewer: () => An,
3086
- OoxmlDecodedImageLimitError: () => rt,
3087
- OoxmlError: () => c,
3088
- OoxmlResourceLimitError: () => d,
3089
- TiffDecodeError: () => it,
3090
- autoResize: () => ee,
3091
- buildDocxHighlightLayer: () => Z,
3092
- buildDocxTextLayer: () => X,
3093
- isOoxmlDecodedImageLimitError: () => nt,
3094
- isTiffDecodeError: () => at,
3095
- noteText: () => zn,
3096
- openExternalHyperlink: () => u,
3097
- readDocxTextSelectionContext: () => Q,
3098
- resolveCommentAnchorRuns: () => A,
3099
- resolveDocxCommentThreads: () => ut,
3100
- resolveRevisionAnchorRuns: () => ln
3101
- });
3102
- //#endregion
3103
- export { Q as a, J as c, An as i, ln as l, zn as n, Z as o, Rn as r, X as s, Bn as t };