@silurus/ooxml 0.88.0 → 0.89.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/README.md +118 -23
  2. package/THIRD_PARTY_NOTICES.md +7 -6
  3. package/dist/abort-VrnK7mdP.js +10 -0
  4. package/dist/assets/render-worker-CUOU6mL2.js +16 -0
  5. package/dist/assets/render-worker-DOqrFhSU.js +15 -0
  6. package/dist/assets/render-worker-DvWUdZUN.js +35 -0
  7. package/dist/bounded-raw-part-cache-B7JoC1CD.js +64586 -0
  8. package/dist/bundled-asset-url-E2nXURF9.js +15 -0
  9. package/dist/canvas-viewer-mechanics-DfQqRKkD.js +675 -0
  10. package/dist/cfb-guard-9QTRTg7f.js +528 -0
  11. package/dist/chart-ex.mjs +692 -688
  12. package/dist/comment-overlay-controller-B5_zGgG5.js +994 -0
  13. package/dist/comment-ui-runtime-B7ZvovcS.js +2 -0
  14. package/dist/{comment-ui-runtime-DcJOYlw-.js → comment-ui-runtime-D_sb2K6s.js} +5 -5
  15. package/dist/{comment-ui-runtime-CWGqn5Vr.js → comment-ui-runtime-Jy-3goA9.js} +5 -5
  16. package/dist/delimited-text-worker-host-CikWU6_m.js +27 -0
  17. package/dist/document-model-source-BKNrXjAL.js +249 -0
  18. package/dist/document-pull-client-CxONDGbk.js +37833 -0
  19. package/dist/document-pull-worker-AMyXYpPq.js +104 -0
  20. package/dist/docx-D91ER1_S.js +495 -0
  21. package/dist/docx-DhDnKEI6.js +3563 -0
  22. package/dist/docx-model-source-CdrSt3hF.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-ChcGZNd8.js +310 -0
  27. package/dist/duotone-ekYik4ix.js +126 -0
  28. package/dist/emf-UT6I8rVi.js +1790 -0
  29. package/dist/font-preload-demand-CdJZUMCT.js +2058 -0
  30. package/dist/grid-geometry-uQOgViJU.js +384 -0
  31. package/dist/host-layout-DVMw8hDY.js +56 -0
  32. package/dist/host-layout-measure-CCEgaC_v.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-CPOV6csk.js +2716 -0
  37. package/dist/math.mjs +2 -2
  38. package/dist/mathjax-stix2.js +10 -10
  39. package/dist/model-source-DJGzDtGb.js +61 -0
  40. package/dist/model-source-kz_NkZqT.js +179 -0
  41. package/dist/model-source-session-Bu9CHFHc.js +71 -0
  42. package/dist/model-source-session-CDuijwv1.js +85 -0
  43. package/dist/model-source-session-sKpNiIJI.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-CaJFvZ7p.js +8502 -0
  47. package/dist/pptx-CDP9dZHe.js +2936 -0
  48. package/dist/pptx-C_uxLVKB.js +183 -0
  49. package/dist/pptx-model-source-O7LhpOjz.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-tmROzteR.js +77 -0
  54. package/dist/raster-target-YQ4G6rxo.js +42 -0
  55. package/dist/region-map.mjs +114 -150
  56. package/dist/{render-D3iqVKCo.js → render-CJVglUHl.js} +3 -3
  57. package/dist/{render-worker-host-B5wQfB7U.js → render-worker-host-BseIaVvm.js} +1 -1
  58. package/dist/{render-worker-host-D4123J27.js → render-worker-host-CyxPU4JU.js} +1 -1
  59. package/dist/{render-worker-host-Di3LxLc0.js → render-worker-host-aF6aWkC0.js} +1 -1
  60. package/dist/renderer-CkGLj0CC.js +5170 -0
  61. package/dist/renderer-Czw1cCC7.js +5823 -0
  62. package/dist/resource-measurement-mXw-WjMF.js +771 -0
  63. package/dist/session-Csv9maad.js +656 -0
  64. package/dist/slide-pull-client-DRZYwBTu.js +6515 -0
  65. package/dist/three-d-BK5siJgJ.js +878 -0
  66. package/dist/three-d.mjs +960 -945
  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-DX4y0Ecl.js +97 -0
  82. package/dist/workbook-model-source-BTC4ISTS.js +94 -0
  83. package/dist/worker-source-I1cIYBel.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-CkHgbtyM.js +579 -0
  87. package/dist/xlsx-CpSDPAEU.js +5809 -0
  88. package/dist/xlsx-D5569TPf.js +534 -0
  89. package/dist/xlsx-model-source-DPSkjFic.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/hyperlink-Cxzhet30.js +0 -36446
  109. package/dist/line-distribute-D1WNHKz_.js +0 -1023
  110. package/dist/line-metrics-B60C86uh.js +0 -60
  111. package/dist/plot-area-frame-DLTYKHNP.js +0 -4354
  112. package/dist/pptx-DkyYBYoL.js +0 -3065
  113. package/dist/renderer-B4GZb5We.js +0 -6492
  114. package/dist/resource-measurement-SHQCbkh2.js +0 -150
  115. package/dist/session-BGq81gRQ.js +0 -743
  116. package/dist/slide-pull-client-DiPnm240.js +0 -6253
  117. package/dist/source-key-DIJG8BA0.js +0 -42
  118. package/dist/three-d-DJBl8g8M.js +0 -1162
  119. package/dist/transfer-p6iCC2R7.js +0 -6
  120. package/dist/units-BzZ0gAxs.js +0 -4
  121. package/dist/worksheet-pull-client-BM8ywvbu.js +0 -458
  122. package/dist/xlsx-C9NVjgaV.js +0 -8484
  123. /package/dist/{chunk-DmhlhrBa.js → chunk-Dy4uBu1J.js} +0 -0
  124. /package/dist/{mathjax-DoyWZbSp.js → mathjax-BhwN6ilc.js} +0 -0
  125. /package/dist/{read-only-comment-decoration-Dz7eTQ4d.js → read-only-comment-decoration-PidH0wnP.js} +0 -0
  126. /package/dist/{read-only-comment-margin-DkgzASAl.js → read-only-comment-margin-B52rDVKo.js} +0 -0
  127. /package/dist/{renderer-module-contract-D91rkYHH.js → renderer-module-contract-CWM7jv6d.js} +0 -0
  128. /package/dist/{visible-index-BgiHEc1z.js → visible-index-FeVA0mGE.js} +0 -0
@@ -0,0 +1,3563 @@
1
+ import { t as e } from "./chunk-Dy4uBu1J.js";
2
+ import { $a as t, Sa as n, eo as r } from "./plot-area-frame-CaJFvZ7p.js";
3
+ import { F as i, Hn as a, N as o, P as s, Q as c, U as l, Un as u, W as d, Wn as f, cn as p, dn as m, fn as h, jn as g, pt as _, t as ee, u as v, un as y, ut as b, vt as te } from "./bounded-raw-part-cache-B7JoC1CD.js";
4
+ import { n as x, t as ne } from "./cfb-guard-9QTRTg7f.js";
5
+ import { A as re, C as S, D as ie, E as C, M as ae, N as oe, P as w, S as se, T, _ as ce, a as le, b as ue, c as de, d as fe, f as pe, g as me, h as he, i as ge, j as _e, k as ve, l as ye, m as be, n as xe, o as Se, p as Ce, r as we, t as Te, u as Ee, v as De, w as Oe, x as ke, y as Ae } from "./comment-overlay-controller-B5_zGgG5.js";
6
+ import { A as je, B as Me, C as Ne, D as E, E as Pe, F as Fe, I as Ie, L as D, M as Le, N as O, O as Re, P as ze, R as Be, S as Ve, T as He, V as k, _ as Ue, a as We, b as Ge, c as Ke, f as qe, h as Je, j as A, k as Ye, l as Xe, m as Ze, n as Qe, o as $e, p as et, s as tt, t as nt, u as rt, v as it, w as at, x as ot, y as j, z as st } from "./document-pull-client-CxONDGbk.js";
7
+ import { f as ct, u as lt } from "./pixel-budget-BpTYrepD.js";
8
+ import { i as ut, t as dt } from "./tiff-contract-C6M3QcPp.js";
9
+ import { D as ft, E as pt, T as mt, a as ht, b as gt, c as _t, d as vt, f as yt, i as bt, l as xt, n as St, o as Ct, p as wt, r as Tt, s as Et, t as Dt, u as Ot, v as kt, w as At, x as jt, y as Mt } from "./canvas-viewer-mechanics-DfQqRKkD.js";
10
+ import { n as Nt } from "./renderer-module-contract-CWM7jv6d.js";
11
+ //#region packages/core/src/fonts/open-type-metrics.ts
12
+ var M = (e) => (e.charCodeAt(0) << 24 >>> 0 | e.charCodeAt(1) << 16 | e.charCodeAt(2) << 8 | e.charCodeAt(3)) >>> 0, Pt = M("ttcf"), Ft = M("OTTO"), It = M("true"), Lt = M("typ1"), Rt = M("head"), zt = M("hhea"), Bt = M("OS/2"), Vt = M("cmap"), Ht = M("fvar"), N = [
13
+ [4352, 4607],
14
+ [11904, 12287],
15
+ [12352, 12543],
16
+ [12544, 12591],
17
+ [12592, 12687],
18
+ [12704, 12735],
19
+ [12784, 12799],
20
+ [13312, 19903],
21
+ [19968, 40959],
22
+ [40960, 42191],
23
+ [43360, 43391],
24
+ [44032, 55203],
25
+ [63744, 64255],
26
+ [131072, 205743]
27
+ ];
28
+ function P(e, t, n) {
29
+ return Number.isSafeInteger(t) && Number.isSafeInteger(n) && t >= 0 && n >= 0 && t <= e - n;
30
+ }
31
+ function Ut(e, t, n) {
32
+ if (n < 16) return !1;
33
+ let r = e.getUint16(t + 2);
34
+ if (r < 16 || r > n) return !1;
35
+ let i = e.getUint16(t + 6);
36
+ if (i === 0 || i % 2 != 0) return !1;
37
+ let a = i / 2, o = t + 14, s = o + a * 2 + 2, c = s + a * 2, l = c + a * 2;
38
+ if (l + a * 2 > t + r) return !1;
39
+ let u = -1;
40
+ for (let t = 0; t < a; t++) {
41
+ let n = e.getUint16(s + t * 2), r = e.getUint16(o + t * 2);
42
+ if (n > r || n <= u) return !1;
43
+ u = r;
44
+ }
45
+ for (let n = 0; n < a; n++) {
46
+ 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);
47
+ for (let [n, o] of N) {
48
+ let s = Math.max(i, n), c = Math.min(a, o);
49
+ if (!(s > c)) {
50
+ if (f === 0) {
51
+ if (s < c || s + u & 65535) return !0;
52
+ continue;
53
+ }
54
+ for (let n = s; n <= c; n++) {
55
+ let a = d + f + (n - i) * 2;
56
+ if (a + 2 > t + r) break;
57
+ let o = e.getUint16(a);
58
+ if (o !== 0 && o + u & 65535) return !0;
59
+ }
60
+ }
61
+ }
62
+ }
63
+ return !1;
64
+ }
65
+ function Wt(e, t, n, r) {
66
+ if (n < 16) return !1;
67
+ let i = e.getUint32(t + 4), a = e.getUint32(t + 12);
68
+ if (i < 16 || i > n || a > (i - 16) / 12) return !1;
69
+ let o = -1;
70
+ for (let n = 0; n < a; n++) {
71
+ let i = t + 16 + n * 12, a = e.getUint32(i), s = e.getUint32(i + 4), c = e.getUint32(i + 8);
72
+ if (a > s || s > 1114111 || a <= o) return !1;
73
+ if (o = s, a > N[N.length - 1][1]) break;
74
+ for (let [e, t] of N) {
75
+ let n = Math.max(a, e), i = Math.min(s, t);
76
+ if (!(n > i)) {
77
+ if (r) {
78
+ if (c !== 0) return !0;
79
+ } else if (n < i || c + (n - a) !== 0) return !0;
80
+ }
81
+ }
82
+ }
83
+ return !1;
84
+ }
85
+ function Gt(e, t) {
86
+ if (!t || t.length < 4) return !1;
87
+ let n = e.getUint16(t.offset + 2);
88
+ if (4 + n * 8 > t.length) return !1;
89
+ for (let r = 0; r < n; r++) {
90
+ let n = t.offset + 4 + r * 8, i = e.getUint16(n), a = e.getUint16(n + 2);
91
+ if (i !== 0 && !(i === 3 && (a === 1 || a === 10))) continue;
92
+ let o = e.getUint32(n + 4);
93
+ if (o > t.length - 2) continue;
94
+ let s = t.offset + o, c = t.length - o, l = e.getUint16(s);
95
+ if (l === 4 && Ut(e, s, c) || l === 12 && Wt(e, s, c, !1) || l === 13 && Wt(e, s, c, !0)) return !0;
96
+ }
97
+ return !1;
98
+ }
99
+ var Kt = 32768, qt = 4096, Jt = 8, Yt = 262144;
100
+ function Xt(e, t, n, r) {
101
+ if (n < 16) return null;
102
+ let i = e.getUint16(t + 2);
103
+ if (i < 16 || i > n) return null;
104
+ let a = e.getUint16(t + 6);
105
+ if (a === 0 || a % 2 != 0) return null;
106
+ let o = a / 2, s = t + 14, c = s + o * 2 + 2, l = c + o * 2, u = l + o * 2;
107
+ if (u + o * 2 > t + i) return null;
108
+ let d = [], f = -1, p = -1, m = (e) => {
109
+ d.length > 0 && p + 1 === e ? (p = e, d[d.length - 1] = [f, p]) : (f = p = e, d.push([e, e]));
110
+ }, h = -1;
111
+ for (let n = 0; n < o; n++) {
112
+ let a = e.getUint16(c + n * 2), o = e.getUint16(s + n * 2);
113
+ if (a > o || a <= h) return null;
114
+ h = o;
115
+ let f = e.getInt16(l + n * 2), p = u + n * 2, g = e.getUint16(p);
116
+ for (let n = a; n <= o && n < 65535; n++) if (--r.remaining < 0 || ((g === 0 ? n + f & 65535 : (() => {
117
+ let r = p + g + (n - a) * 2;
118
+ if (r + 2 > t + i) return 0;
119
+ let o = e.getUint16(r);
120
+ return o === 0 ? 0 : o + f & 65535;
121
+ })()) !== 0 && m(n), d.length > Kt)) return null;
122
+ }
123
+ return d;
124
+ }
125
+ function Zt(e, t, n, r, i) {
126
+ if (n < 16) return null;
127
+ let a = e.getUint32(t + 4), o = e.getUint32(t + 12);
128
+ if (a < 16 || a > n || o > (a - 16) / 12 || o > Kt) return null;
129
+ let s = [], c = -1;
130
+ for (let n = 0; n < o; n++) {
131
+ if (--i.remaining < 0) return null;
132
+ let a = t + 16 + n * 12, o = e.getUint32(a), l = e.getUint32(a + 4), u = e.getUint32(a + 8);
133
+ if (o > l || l > 1114111 || o <= c) return null;
134
+ if (c = l, r) u !== 0 && s.push([o, l]);
135
+ else {
136
+ let e = u === 0 ? o + 1 : o;
137
+ e <= l && s.push([e, l]);
138
+ }
139
+ }
140
+ return s;
141
+ }
142
+ function Qt(e, t) {
143
+ if (!t || t.length < 4) return [];
144
+ let n = e.getUint16(t.offset + 2);
145
+ if (n > qt || 4 + n * 8 > t.length) return [];
146
+ let r = /* @__PURE__ */ new Set(), i = [];
147
+ for (let a = 0; a < n; a++) {
148
+ let n = t.offset + 4 + a * 8, o = e.getUint16(n), s = e.getUint16(n + 2);
149
+ if (o !== 0 && !(o === 3 && (s === 1 || s === 10))) continue;
150
+ let c = e.getUint32(n + 4);
151
+ if (c > t.length - 2) return [];
152
+ let l = t.offset + c, u = t.length - c, d = e.getUint16(l);
153
+ if (!(o === 0 && s === 5 && d === 14)) {
154
+ if (d !== 4 && d !== 12 && d !== 13) return [];
155
+ if (!r.has(c)) {
156
+ if (r.add(c), r.size > Jt) return [];
157
+ i.push({
158
+ subtable: l,
159
+ availableLength: u,
160
+ format: d
161
+ });
162
+ }
163
+ }
164
+ }
165
+ let a = { remaining: Yt }, o = null;
166
+ for (let t of i) {
167
+ let n = t.format === 4 ? Xt(e, t.subtable, t.availableLength, a) : Zt(e, t.subtable, t.availableLength, t.format === 13, a);
168
+ if (!n?.length) return [];
169
+ if (o === null) {
170
+ o = n;
171
+ continue;
172
+ }
173
+ let r = [], i = 0, s = 0;
174
+ for (; i < o.length && s < n.length;) {
175
+ if (--a.remaining < 0) return [];
176
+ let e = o[i], t = n[s], c = Math.max(e[0], t[0]), l = Math.min(e[1], t[1]);
177
+ if (c <= l) {
178
+ let e = r.at(-1);
179
+ if (e && e[1] + 1 === c) r[r.length - 1] = [e[0], l];
180
+ else {
181
+ if (r.length >= Kt) return [];
182
+ r.push([c, l]);
183
+ }
184
+ }
185
+ e[1] <= t[1] && i++, t[1] <= e[1] && s++;
186
+ }
187
+ if (!r.length) return [];
188
+ o = r;
189
+ }
190
+ return Object.freeze((o ?? []).map((e) => Object.freeze(e)));
191
+ }
192
+ function $t(e) {
193
+ let t = 0, n = 0;
194
+ for (; t < e.length && n < N.length;) {
195
+ let [r, i] = e[t], [a, o] = N[n];
196
+ if (i < a) t++;
197
+ else if (o < r) n++;
198
+ else return !0;
199
+ }
200
+ return !1;
201
+ }
202
+ function en(e, t) {
203
+ return tn(e, t, !0);
204
+ }
205
+ function tn(e, t, n) {
206
+ if (t !== void 0 && (!Number.isSafeInteger(t) || t < 0) || e.byteLength < 12) return null;
207
+ let r = new DataView(e.buffer, e.byteOffset, e.byteLength), i = 0;
208
+ if (r.getUint32(0) === Pt) {
209
+ if (t === void 0 || e.byteLength < 12) return null;
210
+ let n = r.getUint32(8);
211
+ if (t >= n || !P(e.byteLength, 12, n * 4)) return null;
212
+ i = r.getUint32(12 + t * 4);
213
+ } else if (t !== void 0 && t !== 0) return null;
214
+ if (!P(e.byteLength, i, 12)) return null;
215
+ let a = r.getUint32(i);
216
+ if (a !== 65536 && a !== Ft && a !== It && a !== Lt) return null;
217
+ let o = r.getUint16(i + 4);
218
+ if (!P(e.byteLength, i + 12, o * 16)) return null;
219
+ let s = /* @__PURE__ */ new Map();
220
+ for (let t = 0; t < o; t++) {
221
+ let n = i + 12 + t * 16, a = r.getUint32(n), o = r.getUint32(n + 8), c = r.getUint32(n + 12);
222
+ if (s.has(a) || !P(e.byteLength, o, c)) return null;
223
+ s.set(a, {
224
+ offset: o,
225
+ length: c
226
+ });
227
+ }
228
+ if (n && s.has(Ht)) return null;
229
+ let c = s.get(Rt), l = s.get(zt);
230
+ if (!c || c.length < 20 || !l || l.length < 10) return null;
231
+ let u = r.getUint16(c.offset + 18);
232
+ if (u < 16 || u > 16384) return null;
233
+ let d = s.get(Bt), f = d !== void 0 && d.length >= 4 ? r.getInt16(d.offset + 2) : 0, p = d !== void 0 && d.length >= 78, m = d !== void 0 && d.length >= 86 && r.getUint16(d.offset) >= 1, h = n ? Qt(r, s.get(Vt)) : void 0;
234
+ return Object.freeze({
235
+ unitsPerEm: u,
236
+ ...f > 0 ? { averageCharWidthRatio: f / u } : {},
237
+ hheaAscent: r.getInt16(l.offset + 4),
238
+ hheaDescent: r.getInt16(l.offset + 6),
239
+ hheaLineGap: r.getInt16(l.offset + 8),
240
+ farEastCodePage: m ? (r.getUint32(d.offset + 78) & 1966080) != 0 : null,
241
+ hasEastAsianCmap: h ? $t(h) : Gt(r, s.get(Vt)),
242
+ ...h === void 0 ? {} : { unicodeRanges: h },
243
+ ...p ? {
244
+ typoAscent: r.getInt16(d.offset + 68),
245
+ typoDescent: r.getInt16(d.offset + 70),
246
+ typoLineGap: r.getInt16(d.offset + 72),
247
+ winAscent: r.getUint16(d.offset + 74),
248
+ winDescent: r.getUint16(d.offset + 76),
249
+ useTypoMetrics: (r.getUint16(d.offset + 62) & 128) != 0
250
+ } : {}
251
+ });
252
+ }
253
+ //#endregion
254
+ //#region packages/docx/src/host-font-line-metrics.ts
255
+ function nn(e, t) {
256
+ if (e.metric.lineHeightRatio != null || !t) return e.metric;
257
+ let n = h(e.requestedFamily, {
258
+ weight: e.weight,
259
+ style: e.style
260
+ });
261
+ if (e.source !== "substitute" && n.some((e) => e.farEastCodePage !== !1)) return e.metric;
262
+ let r = t.ascentRatio + t.lineGapRatio, i = t.descentRatio;
263
+ return Number.isFinite(r) && Number.isFinite(i) && r >= 0 && i >= 0 && r + i > 0 ? Object.freeze({
264
+ ...e.metric,
265
+ requiresGlyphCoverage: !0,
266
+ lineHeightRatio: r + i,
267
+ designAscentRatio: r,
268
+ designDescentRatio: i,
269
+ lineGapRatio: t.lineGapRatio,
270
+ ...n.length > 0 && e.source === "local" ? { farEastCodePage: !1 } : {}
271
+ }) : e.metric;
272
+ }
273
+ function rn(e) {
274
+ if (e.metric.lineHeightRatio != null) return;
275
+ let t = h(e.requestedFamily, {
276
+ weight: e.weight,
277
+ style: e.style
278
+ });
279
+ return e.source === "substitute" || t.every((e) => e.farEastCodePage === !1) ? t[0]?.unitsPerEm : void 0;
280
+ }
281
+ async function an(e) {
282
+ let t = typeof document > "u" ? null : document;
283
+ return Promise.all(e.map(async (e) => {
284
+ let n = rn(e), r = sn(e), i = t?.body && r && n ? await Me(r, e.family, e.weight, e.style, n, t) : null;
285
+ return {
286
+ resourceIdentity: e.resourceIdentity,
287
+ weight: e.weight,
288
+ style: e.style,
289
+ measured: i
290
+ };
291
+ }));
292
+ }
293
+ function on(e) {
294
+ if (e.source !== "local" || e.weight !== 400 || e.style !== "normal") return !1;
295
+ let t = h(e.requestedFamily);
296
+ return !t.some((e) => e.weight >= 600 && e.style === "normal") || !t.some((e) => e.style === "italic");
297
+ }
298
+ function sn(e) {
299
+ return e.source === "local" && e.resourceIdentity.startsWith("office-local:local(") ? e.resourceIdentity.slice(13) : void 0;
300
+ }
301
+ async function cn(e, t, n) {
302
+ let r = typeof document > "u" ? null : document;
303
+ if (!t) return e;
304
+ let i = r?.body && r.fonts === t ? r.createElement("canvas").getContext("2d") : null, a = /* @__PURE__ */ new Map(), o = await Promise.all(Object.entries(e.routes).map(async ([o, s]) => {
305
+ let c = e.faces.find((e) => e.family === s.family), l = rn(s), u = n?.find((e) => e.resourceIdentity === s.resourceIdentity && e.weight === s.weight && e.style === s.style), d = nn(s, c && l && i && r?.body ? st(c, t, i, l, r) : u?.measured ?? null), f = sn(s), p = null, m;
306
+ if (c && f && on(s)) {
307
+ let e = a.get(c);
308
+ e || (e = Be(c, f, t), a.set(c, e)), m = (await e)?.family;
309
+ }
310
+ if (d !== s.metric) {
311
+ if (c && f) {
312
+ let e = a.get(c);
313
+ e || (e = Be(c, f, t), a.set(c, e)), p = await e;
314
+ }
315
+ d = p ? Object.freeze({
316
+ ...d,
317
+ glyphCoverageProbeFamily: p.family
318
+ }) : s.metric;
319
+ }
320
+ return {
321
+ key: o,
322
+ route: {
323
+ ...s,
324
+ metric: d,
325
+ ...m ? { coverageProbeFamily: m } : {}
326
+ },
327
+ probe: p
328
+ };
329
+ })), s = {};
330
+ for (let e of o) s[e.key] = e.route;
331
+ for (let t of a.values()) {
332
+ let n = await t;
333
+ n && e.faces.push(n);
334
+ }
335
+ return {
336
+ ...e,
337
+ routes: s
338
+ };
339
+ }
340
+ async function ln(...e) {
341
+ return cn(await y(...e), e[1] === void 0 ? a() : e[1]);
342
+ }
343
+ //#endregion
344
+ //#region packages/docx/src/resource-diagnostics.ts
345
+ var un = /* @__PURE__ */ new WeakMap();
346
+ function F(e, t = []) {
347
+ let n = un.get(e) ?? [], r = new Map(n.map((e) => [JSON.stringify(e), e]));
348
+ for (let e of t) r.set(JSON.stringify(e), Object.freeze({ ...e }));
349
+ un.set(e, Object.freeze([...r.values()]));
350
+ }
351
+ function dn(e) {
352
+ return un.get(e) ?? [];
353
+ }
354
+ //#endregion
355
+ //#region packages/docx/src/worker.ts?worker&inline
356
+ var fn = "var e=(e,t)=>()=>(e&&(t=e(e=0)),t);function t(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 n,r,i=e((()=>{n=class e extends Error{code;details;constructor(t,n,r){super(n),this.name=`OoxmlError`,this.code=t,t===`unsupported-content`&&r&&(this.details=Object.freeze({format:r.format,reason:r.reason})),Object.setPrototypeOf(this,e.prototype)}},r=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 a(e){return e===`image-dimension`||e===`image-pixels`||e===`active-decoded-bytes`||e===`image-effect-count`||e===`image-effect-work`||e===`tiff-lzw-work`||e===`metafile-path-commands`||e===`metafile-record-points`||e===`metafile-record-polygons`||e===`metafile-record-rectangles`||e===`metafile-record-text-units`}function o(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function s(e){if(!(!e||typeof e!=`object`))try{let t=e,n=t.code,r=t.metric,i=t.limit,s=t.observed;return n!==`ooxml-decoded-image-limit`||!a(r)||!o(i)||!o(s)||s<=i?void 0:{metric:r,limit:i,observed:s}}catch{return}}var c,l,u,d,f,ee=e((()=>{c=1<<25,l=1<<27,c*4,l*4,u=Math.floor(c/4),d=l,d/u,f=class e extends RangeError{metric;limit;observed;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 te(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 ne=e((()=>{}));function p(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function re(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return p(t.requiredBytes)&&p(t.offeredBytes)&&t.requiredBytes>t.offeredBytes}var m=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 h(e){if(e instanceof m)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`||!re(r)))return new m(r)}function ie(e,t,n){let r=h(e);if(!(!r||r.offeredBytes!==t||r.requiredBytes>n))return r}i(),ee(),ne();const g=`OOXML_RESOURCE_LIMIT:`;function _(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function v(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return _(t.archiveEntryCount)&&_(t.declaredInflatedBytes)&&(t.largestInflatedEntryBytes===void 0||_(t.largestInflatedEntryBytes))&&_(t.distinctInflatedBytes)&&_(t.operationInflatedBytes)}function y(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw TypeError(`OOXML resource usage checkpoint is not valid JSON`)}if(!v(t))throw TypeError(`OOXML resource usage checkpoint is invalid`);return t}function ae(e){return e===`docx`||e===`xlsx`||e===`pptx`}function oe(e){return e===`container`||e===`decompression`||e===`parsing`||e===`serialization`||e===`layout`||e===`rendering`||e===`worker`}function b(e,t){return typeof e==`string`&&e.length>0&&e.length<=t&&!/[\\u0000-\\u001f\\u007f]/u.test(e)}function x(e){return b(e,128)&&/^[a-z0-9][a-z0-9-]*$/u.test(e)}function se(e){return!b(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 S=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}],[`image-effect:work`,{stage:`parsing`,part:`forbidden`,configurable:!1}],[`chartex-allocation:elements`,{stage:`parsing`,part:`forbidden`,configurable:!1}],[`chartex-allocation:bytes`,{stage:`parsing`,part:`forbidden`,configurable:!1}],[`chart-cache:points`,{stage:`parsing`,part:`forbidden`,configurable:!1}],[`numbering-marker:bytes`,{stage:`parsing`,part:`forbidden`,configurable:!1}],[`chart-style-formats:entries`,{stage:`parsing`,part:`required`,configurable:!1}],[`chart-custom-number-formats:entries`,{stage:`parsing`,part:`required`,configurable:!1}],[`chart-number-format-bytes:bytes`,{stage:`parsing`,part:`required`,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}],[`theme-style-reparse:bytes`,{stage:`parsing`,part:`forbidden`,configurable:!1}],[`style-inheritance:depth`,{stage:`parsing`,part:`required`,configurable:!1}],[`complex-field:depth`,{stage:`parsing`,part:`forbidden`,configurable:!1}]]),ce=new Set([...S.keys()].map(e=>e.slice(0,e.indexOf(`:`)))),le=new Set([...S.keys()].map(e=>e.slice(e.indexOf(`:`)+1)));function ue(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return!ae(t.format)||!b(t.operation,256)||!x(t.resource)||!x(t.metric)||!_(t.limit)||!_(t.observed)||typeof t.configurable!=`boolean`||!v(t.usage)?!1:!(`part`in t)||se(t.part)}function C(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;if(!oe(t.stage)||!ue(t.violation))return!1;let n=t.violation,r=S.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:!(ce.has(n.resource)&&le.has(n.metric))}function de(e){return{archiveEntryCount:e.archiveEntryCount,declaredInflatedBytes:e.declaredInflatedBytes,...e.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:e.largestInflatedEntryBytes},distinctInflatedBytes:e.distinctInflatedBytes,operationInflatedBytes:e.operationInflatedBytes}}function fe(e){if(!C(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:de(t.usage)}};return C(n)?n:void 0}function pe(e){let t=e.violation;return`OOXML resource limit exceeded${t.part?` for ${t.part}`:``} (${t.resource}, ${e.stage}): ${t.metric} ${t.observed} > ${t.limit}`}function w(e){let t=e instanceof Error?e.message:String(e);if(!t.startsWith(g))return;let n;try{n=JSON.parse(t.slice(21))}catch{return}if(!n||typeof n!=`object`)return;let i=n;if(!(i.code!==`ooxml-resource-limit`||!C(i.details)))return new r(pe(i.details),i.details)}function me(e){try{return e()}catch(e){throw e instanceof r||typeof e!=`string`&&!(e instanceof Error)?e:w(e)??e}}function he(e){let t=e instanceof Error?e.message:String(e);if(t.startsWith(`OOXML_NOT_OOXML:`))return new n(`not-ooxml`,`This file is not an Office Open XML document: ${t.slice(16)}`)}function T(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=t.format,r=t.reason;if(!(!x(n)||r!==`source-subset`))return{format:n,reason:r}}function E(e){return new n(`unsupported-content`,`Input is outside the source’s supported subset.`,e)}function ge(e){let t=typeof e==`string`?e:e instanceof Error?e.message:``;if(!(!t.startsWith(`MODEL_SOURCE_UNSUPPORTED:`)||t.length>1024))try{let e=T(JSON.parse(t.slice(25)));return e?E(e):void 0}catch{return}}function _e(e){return e===`OOXML_SOURCE_UNSUPPORTED_ENCRYPTION`||e instanceof Error&&e.message===`OOXML_SOURCE_UNSUPPORTED_ENCRYPTION`?new n(`unsupported-encryption`,`The configured source cannot decrypt this input.`):ge(e)??w(e)??he(e)}function ve(e){let t=s(e);if(t){let e=new f(t.metric,t.limit,t.observed);return{message:e.message,errorName:e.name,code:e.code,decodedImage:t}}let i=te(e);if(i)return{message:i.message,errorName:`TiffDecodeError`,code:`ooxml-tiff-decode`};let a=h(e);if(a)return{message:a.message,errorName:a.name,code:a.code,insufficientCredit:{requiredBytes:a.requiredBytes,offeredBytes:a.offeredBytes}};let o=e instanceof n||e instanceof r?e:_e(e),c=o??e;if(o instanceof r||c&&typeof c==`object`&&c.code===`ooxml-resource-limit`){let e=c,t=fe(e.details);return t?{message:typeof e.message==`string`?e.message:pe(t),errorName:`OoxmlResourceLimitError`,code:`ooxml-resource-limit`,resourceLimit:t}:{message:`Invalid OOXML resource-limit error payload`,errorName:`Error`}}if(c&&typeof c==`object`&&c.code===`unsupported-content`){let e=T(c.details);return e?{message:E(e).message,code:`unsupported-content`,unsupportedContent:e}:{message:`Invalid unsupported-content error payload`,errorName:`Error`}}if(o instanceof n)return{message:typeof o.message==`string`?o.message:String(o.message),errorName:b(o.name,128)?o.name:`OoxmlError`,...x(o.code)?{code:o.code}:{}};let l=e instanceof Error?e.message:String(e);if(typeof l==`string`&&l.startsWith(g))return{message:`Invalid OOXML resource-limit payload`,errorName:`Error`};let u=e instanceof Error?e:Error(l),d=u;return{message:typeof u.message==`string`?u.message:String(u.message),errorName:b(u.name,128)?u.name:`Error`,...typeof d.code==`string`?{code:d.code}:{}}}function D(e){try{return ve(e)}catch{return{message:`Worker operation failed with an unreadable error`,errorName:`Error`}}}var ye=class{initialize;reinitialize;normalizeFailure;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`)}},O=class e extends Error{code=`parser-crashed`;constructor(t){super(t),this.name=`WasmTrapError`,Object.setPrototypeOf(this,e.prototype)}};function be(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 xe(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 Se(e,t){return e({module_or_path:t})}var Ce=class{init;options;runtime;wasmInput=null;currentArchive=null;constructor(e,t={}){this.init=e,this.options=t,this.runtime=new ye(()=>this.invokeConfigured(this.init),()=>this.invokeConfigured(this.options.reinit??this.init),we),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 me(()=>this.runtime.run(e))}poison(){this.runtime.poison(new O(`WASM parser was recycled`))}invokeConfigured(e){return this.wasmInput===null?Promise.reject(Error(`WasmParserHost: setWasmInput was never called`)):Se(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,xe(e)}};function we(e){return be(e)?new O(`WASM parser trapped and was recycled: ${e instanceof Error?e.message:String(e)}`):null}function Te(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 Ee(e){return[e.maxArchiveEntryBytes===null?0n:BigInt(e.maxArchiveEntryBytes),e.maxTotalInflatedBytes===null?0n:BigInt(e.maxTotalInflatedBytes),e.maxArchiveEntries===null?0n:BigInt(e.maxArchiveEntries)]}const k=`ooxml-pull-v1`;function A(e,t){if(!Number.isSafeInteger(e)||e<=0)throw RangeError(`${t} must be a positive safe integer`)}function De(e){if(!(typeof e==`string`&&e.length>0||typeof e==`number`&&Number.isSafeInteger(e)&&e>0))throw RangeError(`session id must be a non-empty string or positive safe integer`)}var j=class{owner;queue=Promise.resolve();leases=new Map;retainedBytes=0;retainedCount=0;maxRetainedBytes;maxRetainedCount;cleanups=new Set;pendingFatalCleanups=[];poisonRunning=!1;fatal;constructor(e){this.maxRetainedBytes=e?.maxRetainedBytes??64*1024*1024,this.maxRetainedCount=e?.maxRetainedCount??256,A(this.maxRetainedBytes,`max retained lease bytes`),A(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}},Oe=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){De(e.sessionId),A(e.operationId,`operation id`),A(e.generation,`generation`),A(e.maxByteCredit,`max byte credit`),e.wireLeaseIdStart!==void 0&&A(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=D(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(A(t.leaseId,`lease id`),t.retainedBytes===void 0)throw Error(`retained lease bytes are required`);if(this.activeDriverLeases.has(t.leaseId))throw r=!0,Error(`driver returned an active duplicate lease id`);i=this.allocateWireLeaseId(),this.coordinator.retainLease(this.coordinatorOwner,i,t.retainedBytes),this.leases.set(i,{driverLeaseId:t.leaseId,retainedBytes:t.retainedBytes}),this.activeDriverLeases.add(t.leaseId),n=!0}else if(t.retainedBytes!==void 0)throw Error(`retained lease bytes require a lease id`);if(!Number.isSafeInteger(a)||a<0)throw RangeError(`host chunk byte length must be a non-negative safe integer`);if(a>e.byteCredit)throw RangeError(`host chunk exceeds byte credit`)}catch(e){let a;try{await this.options.driver.disposeInvalidChunk?.(t)}catch(e){a=e}if(n&&i!==void 0)try{await this.release(i)}catch(e){a??=e}else if(t.leaseId!==void 0&&!r)try{await this.options.driver.releaseLease?.(t.leaseId)}catch(e){a??=e}if(r)try{await this.cancel()}catch(e){a??=e}throw this.coordinator.release(this.coordinatorOwner),a||e}return this.unacked={sequence:this.sequence,done:t.done},{response:{kind:`chunk`,protocol:k,...this.identity(),requestId:e.requestId,sequence:this.sequence,byteLength:a,done:t.done,payload:t.payload,leaseId:i,usage:this.resourceUsage()},transfer:t.transfer}}async ack(e){if(!Number.isSafeInteger(e)||e<0)throw RangeError(`invalid ack sequence`);if(e<this.sequence)return;if(!this.unacked||e!==this.sequence)throw Error(`ack sequence mismatch`);let t=this.unacked.done;await this.options.driver.acknowledge?.(e),this.unacked=void 0,this.coordinator.release(this.coordinatorOwner),this.sequence++,t&&(this.completed=!0,this.maybeUnregisterCompleted())}async release(e){A(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(A(e,`byte credit`),e>this.options.maxByteCredit)throw RangeError(`byte credit exceeds host maximum`)}accepted(e,t,n=!1){return{kind:`accepted`,protocol:k,...n?{sessionId:e.sessionId,operationId:e.operationId,generation:e.generation}:this.identity(),requestId:e.requestId,command:t,usage:this.resourceUsage()}}identity(){return{sessionId:this.options.sessionId,operationId:this.options.operationId,generation:this.options.generation}}isStaleLifecycle(e){return(e.kind===`cancel`||e.kind===`close`)&&e.protocol===`ooxml-pull-v1`&&Number.isSafeInteger(e.requestId)&&e.requestId>0&&Number.isSafeInteger(e.generation)&&e.generation>0&&e.generation<this.options.generation}sameOperationIdentity(e){return e.sessionId===this.options.sessionId&&e.operationId===this.options.operationId}errorResponse(e,t){return{kind:`error`,protocol:k,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:t,usage:this.errorResourceUsage()}}async forceFatalCleanup(){this.cancelRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;for(let t of[...this.leases.keys()])try{await this.release(t)}catch(t){e??=t}if(!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch(t){e??=t}if(e)throw e;this.unregisterCleanup()}allocateWireLeaseId(){if(!Number.isSafeInteger(this.nextWireLeaseId)||this.nextWireLeaseId<=0)throw RangeError(`wire lease id space exhausted`);return this.nextWireLeaseId++}arrayBufferTransferBytes(e){let t=0;for(let n of e??[])if(n instanceof ArrayBuffer&&(t+=n.byteLength,!Number.isSafeInteger(t)))throw RangeError(`ArrayBuffer transfer bytes overflow`);return t}maybeUnregisterCompleted(){this.completed&&this.leases.size===0&&this.unregisterCleanup()}resourceUsage(){return this.options.driver.resourceUsage?.()}errorResourceUsage(){try{return this.resourceUsage()}catch{return}}};i();function ke(e){let t=e instanceof Error?e.message:String(e);if(!t.startsWith(`OOXML_DOCX_ILVL:`))return;let r=t.slice(16);if(r===`repair-required:level-definition`)return new n(`invalid-numbering`,`The DOCX defines a numbering level outside Word’s supported 0–8 range and requires repair.`);if(r===`cannot-open:whitespace`||r===`cannot-open:non-decimal`)return new n(`invalid-numbering`,`Word cannot open this DOCX numbering level (${r.slice(12)}).`)}function M(e){try{return ke(e)??e}catch{return e}}function Ae(e){try{return e()}catch(e){throw M(e)}}var N=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,P.unregister(this),e}free(){let e=this.__destroy_into_raw();J.__wbg_docxarchive_free(e,0)}acknowledge_document_chunk(e,t,n){let r=J.docxarchive_acknowledge_document_chunk(this.__wbg_ptr,e,t,n);if(r[1])throw U(r[0])}assert_healthy(){let e=J.docxarchive_assert_healthy(this.__wbg_ptr);if(e[1])throw U(e[0])}cancel_document_cursor(){J.docxarchive_cancel_document_cursor(this.__wbg_ptr)}close_document_session(){J.docxarchive_close_document_session(this.__wbg_ptr)}document_chunk_done(){let e=J.docxarchive_document_chunk_done(this.__wbg_ptr);if(e[2])throw U(e[1]);return e[0]!==0}document_cursor_resource_usage(){let e=J.docxarchive_document_cursor_resource_usage(this.__wbg_ptr);if(e[3])throw U(e[2]);let t;return e[0]!==0&&(t=F(e[0],e[1]).slice(),J.__wbindgen_free(e[0],e[1]*1,1)),t}extract_image(e){let t=H(e,J.__wbindgen_malloc,J.__wbindgen_realloc),n=q,r=J.docxarchive_extract_image(this.__wbg_ptr,t,n);if(r[3])throw U(r[2]);var i=F(r[0],r[1]).slice();return J.__wbindgen_free(r[0],r[1]*1,1),i}constructor(e,t,n,r){let i=Me(e,J.__wbindgen_malloc),a=q,o=J.docxarchive_new(i,a,!V(t),V(t)?BigInt(0):t,!V(n),V(n)?BigInt(0):n,!V(r),V(r)?BigInt(0):r);if(o[2])throw U(o[1]);return this.__wbg_ptr=o[0]>>>0,P.register(this,this.__wbg_ptr,this),this}open_document_cursor(e,t){let n=J.docxarchive_open_document_cursor(this.__wbg_ptr,e,t);if(n[1])throw U(n[0])}parse(){let e=J.docxarchive_parse(this.__wbg_ptr);if(e[3])throw U(e[2]);var t=F(e[0],e[1]).slice();return J.__wbindgen_free(e[0],e[1]*1,1),t}pull_document_chunk(e,t,n,r){let i=J.docxarchive_pull_document_chunk(this.__wbg_ptr,e,t,n,r);if(i[3])throw U(i[2]);var a=F(i[0],i[1]).slice();return J.__wbindgen_free(i[0],i[1]*1,1),a}resource_usage(){let e=J.docxarchive_resource_usage(this.__wbg_ptr);if(e[3])throw U(e[2]);var t=F(e[0],e[1]).slice();return J.__wbindgen_free(e[0],e[1]*1,1),t}to_markdown(){let e,t;try{let i=J.docxarchive_to_markdown(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,U(i[2]);return e=n,t=r,R(n,r)}finally{J.__wbindgen_free(e,t,1)}}};Symbol.dispose&&(N.prototype[Symbol.dispose]=N.prototype.free);function je(){return{__proto__:null,\"./docx_parser_bg.js\":{__proto__:null,__wbg___wbindgen_throw_6b64449b9b9ed33c:function(e,t){throw Error(R(e,t))},__wbg_error_a6fa202b58aa1cd3:function(e,t){let n,r;try{n=e,r=t,console.error(R(e,t))}finally{J.__wbindgen_free(n,r,1)}},__wbg_new_227d7c05414eb861:function(){return Error()},__wbg_stack_3b0d974bbf31e44f:function(e,t){let n=t.stack,r=H(n,J.__wbindgen_malloc,J.__wbindgen_realloc),i=q;L().setInt32(e+4,i,!0),L().setInt32(e+0,r,!0)},__wbindgen_cast_0000000000000001:function(e,t){return R(e,t)},__wbindgen_init_externref_table:function(){let e=J.__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 P=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>J.__wbg_docxarchive_free(e>>>0,1));function F(e,t){return e>>>=0,B().subarray(e/1,e/1+t)}let I=null;function L(){return(I===null||I.buffer.detached===!0||I.buffer.detached===void 0&&I.buffer!==J.memory.buffer)&&(I=new DataView(J.memory.buffer)),I}function R(e,t){return e>>>=0,Ne(e,t)}let z=null;function B(){return(z===null||z.byteLength===0)&&(z=new Uint8Array(J.memory.buffer)),z}function V(e){return e==null}function Me(e,t){let n=t(e.length*1,1)>>>0;return B().set(e,n/1),q=e.length,n}function H(e,t,n){if(n===void 0){let n=K.encode(e),r=t(n.length,1)>>>0;return B().subarray(r,r+n.length).set(n),q=n.length,r}let r=e.length,i=t(r,1)>>>0,a=B(),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=B().subarray(i+o,i+r),a=K.encodeInto(e,t);o+=a.written,i=n(i,r,o,1)>>>0}return q=o,i}function U(e){let t=J.__wbindgen_externrefs.get(e);return J.__externref_table_dealloc(e),t}let W=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0});W.decode();let G=0;function Ne(e,t){return G+=t,G>=2146435072&&(W=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}),W.decode(),G=t),W.decode(B().subarray(e,e+t))}const K=new TextEncoder;`encodeInto`in K||(K.encodeInto=function(e,t){let n=K.encode(e);return t.set(n),{read:e.length,written:n.length}});let q=0,J;function Pe(e,t){return J=e.exports,I=null,z=null,J.__wbindgen_start(),J}async function Fe(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(J!==void 0)return J;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=je();(typeof e==`string`||typeof Request==`function`&&e instanceof Request||typeof URL==`function`&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await Fe(await e,t);return Pe(n,r)}async function Ie(e){return J=void 0,I=null,z=null,Y(e)}function Le(e){let t=e(e=>e.document_cursor_resource_usage?.());return t?y(t):void 0}const Re=67108864;var ze=class{archive;coordinator=new j;host=null;identity=null;executeArchive;constructor(e,t=e=>e(this.requireArchive())){this.archive=e,this.executeArchive=e=>Ae(()=>t(e))}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 Oe({...e,maxByteCredit:Re,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 ie(e,n,Re)||e}let i=Te(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:()=>Le(this.executeArchive)}})}dispatch(e,t){return!this.host||!this.identity?(t({protocol:k,kind:`error`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:D(Error(`DOCX document pull session is not open`))}),Promise.resolve()):this.host.dispatch(e,t)}async reset(){if(this.host)try{this.archive()&&this.executeArchive(e=>e.close_document_session())}finally{this.host=null,this.identity=null,this.coordinator=new j}}requireArchive(){let e=this.archive();if(!e)throw Error(`No docx loaded`);return e}};function Be(e){return!!e&&typeof e==`object`&&e.protocol===`ooxml-pull-v1`}const X=new Ce(Y,{freeArchive:e=>e.free(),reinit:Ie}),Z=new ze(()=>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(Be(n)){try{await Z.dispatch(n,$)}catch(e){$({protocol:k,kind:`error`,sessionId:n.sessionId,operationId:n.operationId,generation:n.generation,requestId:n.requestId,error:D(M(e))})}return}if(n.type===`init`){X.setWasmInput(t(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,t,i]=Ee(n.resourcePolicy),a=new Uint8Array(n.data);X.run(()=>{let n=new N(a,e,t,i);X.setArchive(n)}),Q+=1;let o={sessionId:Q,operationId:Q,generation:Q};Z.open(o),$({type:`documentSessionOpened`,id:r,...o});return}let 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:y(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,...D(M(e))})}};", pn = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", fn], { type: "text/javascript;charset=utf-8" });
357
+ function mn(e) {
358
+ let t;
359
+ try {
360
+ if (t = pn && (self.URL || self.webkitURL).createObjectURL(pn), !t) throw "";
361
+ let n = new Worker(t, {
362
+ type: "module",
363
+ name: e?.name
364
+ });
365
+ return n.addEventListener("error", () => {
366
+ (self.URL || self.webkitURL).revokeObjectURL(t);
367
+ }), n;
368
+ } catch {
369
+ return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(fn), {
370
+ type: "module",
371
+ name: e?.name
372
+ });
373
+ }
374
+ }
375
+ //#endregion
376
+ //#region packages/docx/src/wasm/docx_parser_bg.wasm?url
377
+ var hn = new URL("docx_parser_bg.wasm", import.meta.url).href;
378
+ //#endregion
379
+ //#region packages/docx/src/main-thread-fallback.ts
380
+ function gn(e) {
381
+ return e === "nativeRouteSentinels" ? "[ooxml] mode: 'worker' fell back to main-thread rendering because the worker cannot register the font probes that size absent-font lines." : "[ooxml] mode: 'worker' fell back to main-thread rendering because this document requires DOM OpenType vertical glyph selection.";
382
+ }
383
+ //#endregion
384
+ //#region packages/docx/src/bookmark-nav.ts
385
+ function _n(e) {
386
+ let t = /* @__PURE__ */ new Map();
387
+ for (let n of e.pages) for (let e of n.bookmarkStarts) e.name !== "" && !t.has(e.name) && t.set(e.name, n.pageIndex);
388
+ return t;
389
+ }
390
+ //#endregion
391
+ //#region packages/core/src/crypto/sha256.ts
392
+ var vn = new Uint32Array([
393
+ 1116352408,
394
+ 1899447441,
395
+ 3049323471,
396
+ 3921009573,
397
+ 961987163,
398
+ 1508970993,
399
+ 2453635748,
400
+ 2870763221,
401
+ 3624381080,
402
+ 310598401,
403
+ 607225278,
404
+ 1426881987,
405
+ 1925078388,
406
+ 2162078206,
407
+ 2614888103,
408
+ 3248222580,
409
+ 3835390401,
410
+ 4022224774,
411
+ 264347078,
412
+ 604807628,
413
+ 770255983,
414
+ 1249150122,
415
+ 1555081692,
416
+ 1996064986,
417
+ 2554220882,
418
+ 2821834349,
419
+ 2952996808,
420
+ 3210313671,
421
+ 3336571891,
422
+ 3584528711,
423
+ 113926993,
424
+ 338241895,
425
+ 666307205,
426
+ 773529912,
427
+ 1294757372,
428
+ 1396182291,
429
+ 1695183700,
430
+ 1986661051,
431
+ 2177026350,
432
+ 2456956037,
433
+ 2730485921,
434
+ 2820302411,
435
+ 3259730800,
436
+ 3345764771,
437
+ 3516065817,
438
+ 3600352804,
439
+ 4094571909,
440
+ 275423344,
441
+ 430227734,
442
+ 506948616,
443
+ 659060556,
444
+ 883997877,
445
+ 958139571,
446
+ 1322822218,
447
+ 1537002063,
448
+ 1747873779,
449
+ 1955562222,
450
+ 2024104815,
451
+ 2227730452,
452
+ 2361852424,
453
+ 2428436474,
454
+ 2756734187,
455
+ 3204031479,
456
+ 3329325298
457
+ ]);
458
+ function yn(e) {
459
+ let t = new Uint32Array([
460
+ 1779033703,
461
+ 3144134277,
462
+ 1013904242,
463
+ 2773480762,
464
+ 1359893119,
465
+ 2600822924,
466
+ 528734635,
467
+ 1541459225
468
+ ]), n = new Uint32Array(64), r = Math.ceil((e.length + 9) / 64) * 64, i = e.length * 8, a = (t) => t < e.length ? e[t] : t === e.length ? 128 : t >= r - 8 ? Math.floor(i / 2 ** ((r - t - 1) * 8)) & 255 : 0, o = (e, t) => e >>> t | e << 32 - t;
469
+ for (let e = 0; e < r; e += 64) {
470
+ for (let t = 0; t < 16; t++) {
471
+ let r = e + t * 4;
472
+ n[t] = a(r) << 24 | a(r + 1) << 16 | a(r + 2) << 8 | a(r + 3);
473
+ }
474
+ for (let e = 16; e < 64; e++) {
475
+ let t = n[e - 15], r = n[e - 2], i = o(t, 7) ^ o(t, 18) ^ t >>> 3, a = o(r, 17) ^ o(r, 19) ^ r >>> 10;
476
+ n[e] = n[e - 16] + i + n[e - 7] + a >>> 0;
477
+ }
478
+ let [r, i, s, c, l, u, d, f] = t;
479
+ for (let e = 0; e < 64; e++) {
480
+ let t = o(l, 6) ^ o(l, 11) ^ o(l, 25), a = l & u ^ ~l & d, p = f + t + a + vn[e] + n[e] >>> 0, m = (o(r, 2) ^ o(r, 13) ^ o(r, 22)) + (r & i ^ r & s ^ i & s) >>> 0;
481
+ f = d, d = u, u = l, l = c + p >>> 0, c = s, s = i, i = r, r = p + m >>> 0;
482
+ }
483
+ t[0] = t[0] + r >>> 0, t[1] = t[1] + i >>> 0, t[2] = t[2] + s >>> 0, t[3] = t[3] + c >>> 0, t[4] = t[4] + l >>> 0, t[5] = t[5] + u >>> 0, t[6] = t[6] + d >>> 0, t[7] = t[7] + f >>> 0;
484
+ }
485
+ let s = new Uint8Array(32), c = new DataView(s.buffer);
486
+ return t.forEach((e, t) => c.setUint32(t * 4, e)), s;
487
+ }
488
+ //#endregion
489
+ //#region packages/docx/src/embedded-fonts.ts
490
+ var bn = g, xn = 64, I = 2;
491
+ async function Sn(e, t) {
492
+ let n;
493
+ try {
494
+ n = globalThis.crypto?.subtle ? new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", e.slice().buffer)) : yn(e);
495
+ } catch {
496
+ n = yn(e);
497
+ }
498
+ let r = Array.from(n, (e) => e.toString(16).padStart(2, "0")).join(""), i = 2166136261;
499
+ for (let e of t.trim().toLowerCase()) i ^= e.codePointAt(0), i = Math.imul(i, 16777619);
500
+ return `__ooxml_docx_embedded_${r}_${(i >>> 0).toString(16)}`;
501
+ }
502
+ async function Cn(e, t) {
503
+ let n = e.embeddedFonts;
504
+ if (!n || n.length === 0) return {
505
+ faces: [],
506
+ metrics: {},
507
+ routes: []
508
+ };
509
+ let i = [], a = /* @__PURE__ */ new Set();
510
+ for (let e of n) {
511
+ let t = wn(e.style) === "bold" ? 700 : 400, n = Tn(e.style), r = `${k(e.fontName)}:${t}:${n}`;
512
+ a.has(r) || (a.add(r), i.push(e));
513
+ }
514
+ let o = [], s = 0, c = Math.min(i.length, xn), l = i.length - c;
515
+ for (let e = 0; e < c; e += I) {
516
+ let n = i.slice(e, Math.min(e + I, c)), a = await Promise.all(n.map(async (e) => {
517
+ try {
518
+ return await t(e.partPath);
519
+ } catch (e) {
520
+ if (e instanceof r || ct(e)) throw e;
521
+ let t = d(e);
522
+ if (t) throw t;
523
+ return null;
524
+ }
525
+ }));
526
+ for (let e = 0; e < n.length; e++) {
527
+ let t = n[e], r = a[e];
528
+ if (r) {
529
+ if (!ae(r) || r.byteLength > bn - s) {
530
+ l++;
531
+ continue;
532
+ }
533
+ try {
534
+ let e = t.partPath.toLowerCase().endsWith(".odttf") ? _e(r, t.fontKey ?? "") : r, n = await Sn(e, t.fontName), i = {
535
+ family: n,
536
+ bytes: e,
537
+ odttf: !1,
538
+ fontKey: "",
539
+ weight: wn(t.style),
540
+ style: Tn(t.style)
541
+ }, a = null;
542
+ try {
543
+ let r = en(e), o = r?.farEastCodePage == null ? null : je({
544
+ ...r,
545
+ farEastCodePage: r.farEastCodePage
546
+ });
547
+ (o || r?.averageCharWidthRatio != null) && (a = Object.freeze({
548
+ family: n,
549
+ requestedFamily: t.fontName,
550
+ weight: i.weight === "bold" ? 700 : 400,
551
+ style: i.style,
552
+ sourceIdentity: `embedded:${n}`,
553
+ synthesized: !1,
554
+ ...o ? {
555
+ lineHeightRatio: o.lineHeightRatio,
556
+ designAscentRatio: o.designAscentRatio,
557
+ designDescentRatio: o.designDescentRatio
558
+ } : {},
559
+ ...r?.averageCharWidthRatio == null ? {} : { averageCharWidthRatio: r.averageCharWidthRatio },
560
+ unicodeRanges: r?.unicodeRanges ?? [],
561
+ ...o && r?.hasEastAsianCmap ? { eastAsianLineHeightRatio: o.lineHeightRatio } : {}
562
+ }));
563
+ } catch {}
564
+ o.push({
565
+ face: i,
566
+ metric: a,
567
+ route: {
568
+ requestedFamily: t.fontName,
569
+ resolvedFamily: i.family,
570
+ weight: i.weight === "bold" ? 700 : 400,
571
+ style: i.style,
572
+ resourceIdentity: `embedded:${i.family}`
573
+ }
574
+ }), s += r.byteLength;
575
+ } catch {
576
+ continue;
577
+ }
578
+ }
579
+ }
580
+ }
581
+ let u = Object.freeze(l > 0 ? [Object.freeze({
582
+ code: "MISSING_RESOURCE",
583
+ severity: "warning",
584
+ message: `Skipped ${l} embedded font face(s) under the document font resource limits; fallback fonts are used`
585
+ })] : []), f = o;
586
+ if (f.length === 0) return {
587
+ faces: [],
588
+ metrics: {},
589
+ routes: [],
590
+ diagnostics: u
591
+ };
592
+ let p = [], m = /* @__PURE__ */ new Set();
593
+ try {
594
+ for (let e = 0; e < f.length; e += I) {
595
+ let t = f.slice(e, e + I);
596
+ for (let e of await oe(t.map((e) => e.face))) m.has(e) ? w([e]) : (m.add(e), p.push(e));
597
+ }
598
+ } catch (e) {
599
+ throw w(p), e;
600
+ }
601
+ let h = new Set(p.map((e) => {
602
+ let t = e.family.trim().replace(/^(['"])(.*)\1$/, "$2"), n = e.weight === "bold" ? 700 : Number(e.weight) || 400, r = e.style === "italic" ? "italic" : "normal";
603
+ return `${k(t)}:${n}:${r}`;
604
+ })), g = {}, _ = [];
605
+ for (let e of f) {
606
+ let t = k(e.face.family), n = e.face.weight === "bold" ? 700 : 400, r = e.face.style, i = `${t}:${n}:${r}`;
607
+ if (!h.has(i) || (_.push(Object.freeze(e.route)), !e.metric)) continue;
608
+ let a = k(e.route.requestedFamily);
609
+ g[n === 400 && r === "normal" ? a : `${a}:${n}:${r}`] = e.metric;
610
+ }
611
+ return {
612
+ faces: p,
613
+ metrics: Object.freeze(g),
614
+ routes: Object.freeze(_),
615
+ diagnostics: u
616
+ };
617
+ }
618
+ function wn(e) {
619
+ return e === "bold" || e === "boldItalic" ? "bold" : "normal";
620
+ }
621
+ function Tn(e) {
622
+ return e === "italic" || e === "boldItalic" ? "italic" : "normal";
623
+ }
624
+ //#endregion
625
+ //#region packages/docx/src/element-context.ts
626
+ var En = vt, Dn = 16384;
627
+ function On(e, t) {
628
+ let n = [], r = 0, i = !1;
629
+ for (let a of e) {
630
+ if (a.length === 0) continue;
631
+ if (r > 0) {
632
+ if (r >= t) {
633
+ i = !0;
634
+ break;
635
+ }
636
+ n.push("\n"), r++;
637
+ }
638
+ let e = wt(a, Math.max(0, t - r));
639
+ if (n.push(e), r += e.length, e.length < a.length) {
640
+ i = !0;
641
+ break;
642
+ }
643
+ }
644
+ let a = n.join("");
645
+ return {
646
+ ...a.length === 0 ? {} : { text: a },
647
+ truncated: i
648
+ };
649
+ }
650
+ function* L(e) {
651
+ if (e.kind === "paragraph") {
652
+ for (let t of e.lines) {
653
+ let e = t.placements.flatMap((e) => e.kind === "text" && !e.optionalHyphenGlyph ? [e.text] : []).join("");
654
+ e && (yield e);
655
+ }
656
+ return;
657
+ }
658
+ if (e.kind === "table") {
659
+ for (let t of e.rows) for (let e of t.cells) for (let t of e.blocks) yield* L(t.layout);
660
+ return;
661
+ }
662
+ if (e.kind === "note") {
663
+ e.leading?.paragraph && (yield* L(e.leading.paragraph));
664
+ for (let t of e.story.blocks) yield* L(t);
665
+ e.trailing?.paragraph && (yield* L(e.trailing.paragraph));
666
+ } else if (e.kind === "textbox") for (let t of e.story.blocks) yield* L(t);
667
+ }
668
+ function* kn(e) {
669
+ for (let t of e.drawing.commands) (t.kind === "text" || t.kind === "watermark-text") && (yield t.text);
670
+ for (let t of e.textBoxes) yield* L(t);
671
+ }
672
+ function An(e) {
673
+ let t = e ?? Dn;
674
+ if (!Number.isFinite(t) || t < 0) throw RangeError("maxTextCharacters must be a finite non-negative number.");
675
+ return Math.min(En, Math.floor(t));
676
+ }
677
+ function jn(e) {
678
+ return {
679
+ story: e.story,
680
+ storyInstance: e.storyInstance,
681
+ path: [...e.path]
682
+ };
683
+ }
684
+ function Mn(e) {
685
+ return "drawing" in e ? e.drawing.inkBounds : e.placement.bounds;
686
+ }
687
+ function Nn(e) {
688
+ let t = Mn(e), n = [
689
+ E(e.pointToPage, t),
690
+ E(e.pointToPage, {
691
+ xPt: t.xPt + t.widthPt,
692
+ yPt: t.yPt
693
+ }),
694
+ E(e.pointToPage, {
695
+ xPt: t.xPt,
696
+ yPt: t.yPt + t.heightPt
697
+ }),
698
+ E(e.pointToPage, {
699
+ xPt: t.xPt + t.widthPt,
700
+ yPt: t.yPt + t.heightPt
701
+ })
702
+ ], 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));
703
+ return {
704
+ xPt: r,
705
+ yPt: i,
706
+ widthPt: a - r,
707
+ heightPt: o - i
708
+ };
709
+ }
710
+ function R(e, t) {
711
+ return t.xPt >= e.xPt && t.xPt <= e.xPt + e.widthPt && t.yPt >= e.yPt && t.yPt <= e.yPt + e.heightPt;
712
+ }
713
+ function Pn(e, t) {
714
+ let n = !1;
715
+ for (let r = 0, i = t.length - 1; r < t.length; i = r++) {
716
+ let a = t[r], o = t[i];
717
+ 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);
718
+ }
719
+ return n;
720
+ }
721
+ function Fn(e, t) {
722
+ return R(e.inkBounds, t) ? e.clip ? e.clip.kind === "rect" ? R(e.clip.rect, t) : Pn(t, e.clip.points) : !0 : !1;
723
+ }
724
+ function In(e, t, n) {
725
+ for (let n of e.clips) {
726
+ let e = Pe(n.pointToPage, t);
727
+ if (!e || !R(n.bounds, e)) return !1;
728
+ }
729
+ return "drawing" in e ? Fn(e.drawing, n) : R(e.placement.bounds, n);
730
+ }
731
+ function z(e, t) {
732
+ return e.commands.find((e) => e.kind === "resource" && e.resourceKind === t);
733
+ }
734
+ function Ln(e) {
735
+ return z(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" : z(e, "image") ? "image" : null;
736
+ }
737
+ function Rn(e, t, n, r, i, a) {
738
+ let o = "drawing" in e ? Ln(e.drawing) : e.placement.resourceKind;
739
+ if (!o) return null;
740
+ let s, c = !1, l, u;
741
+ if (o === "chart") {
742
+ let t = "drawing" in e ? z(e.drawing, "chart").resourceKey : e.placement.resourceKey, n = i.resolve(t, "chart"), r = yt(n.model, a);
743
+ s = r.text, c = r.truncated, u = n.model.series.length;
744
+ } else if (o === "image") {
745
+ let t = "drawing" in e ? z(e.drawing, "image").resourceKey : e.placement.resourceKey, n = i.descriptors.find((e) => e.resourceKey === t && e.kind === "image" && "mimeType" in e);
746
+ if (!n) throw Error(`Unknown image paint resource: ${t}`);
747
+ l = n.mimeType;
748
+ } else {
749
+ let t = On(kn(e), a);
750
+ s = t.text, c = t.truncated;
751
+ }
752
+ return {
753
+ format: "docx",
754
+ kind: "element",
755
+ pageIndex: t,
756
+ elementIndex: n,
757
+ elementType: o,
758
+ point: { ...r },
759
+ bounds: Nn(e),
760
+ source: jn("drawing" in e ? e.drawing.source : e.source),
761
+ ...s === void 0 ? {} : { text: s },
762
+ ...l === void 0 ? {} : { mimeType: l },
763
+ ...u === void 0 ? {} : { seriesCount: u },
764
+ truncated: c,
765
+ truncationReasons: c ? ["text"] : [],
766
+ textCharacters: s?.length ?? 0,
767
+ maxTextCharacters: a
768
+ };
769
+ }
770
+ function zn(e, t, n, r, i = {}) {
771
+ if (!Number.isFinite(n.xPt) || !Number.isFinite(n.yPt)) throw RangeError("DOCX hit-test point must contain finite page coordinates.");
772
+ let a = An(i.maxTextCharacters), o = at(e, t);
773
+ for (let e = o.length - 1; e >= 0; e--) {
774
+ let i = o[e], s = Pe(i.pointToPage, n);
775
+ if (!s || !In(i, n, s)) continue;
776
+ let c = Rn(i, t, e, n, r, a);
777
+ if (c) return c;
778
+ }
779
+ return null;
780
+ }
781
+ function Bn(e, t, n, r) {
782
+ return zn(Re(e, {
783
+ currentDate: r.currentDate,
784
+ defaultCurrentDateMs: r.defaultCurrentDateMs,
785
+ showTrackedChanges: r.showTrackedChanges
786
+ }, t).layout, t, n, Fe(e), r);
787
+ }
788
+ function Vn(e, t) {
789
+ let n = An(t), r = e.text === void 0 ? void 0 : wt(e.text, n), i = e.truncated || e.text !== void 0 && r.length < e.text.length;
790
+ return {
791
+ ...structuredClone(e),
792
+ ...r === void 0 ? {} : { text: r },
793
+ truncated: i,
794
+ truncationReasons: i ? ["text"] : [],
795
+ textCharacters: r?.length ?? 0,
796
+ maxTextCharacters: n
797
+ };
798
+ }
799
+ //#endregion
800
+ //#region packages/docx/src/review-id.ts
801
+ function Hn(e) {
802
+ if (e === void 0) return;
803
+ let t = e.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");
804
+ if (/^[+-]?\d+$/.test(t)) try {
805
+ return BigInt(t).toString();
806
+ } catch {
807
+ return;
808
+ }
809
+ }
810
+ //#endregion
811
+ //#region packages/docx/src/comments.ts
812
+ function Un(e) {
813
+ return Object.freeze({
814
+ ...e,
815
+ path: Object.freeze([...e.path])
816
+ });
817
+ }
818
+ function Wn(e) {
819
+ return Object.freeze({
820
+ source: Un(e.source),
821
+ runIndex: e.boundary,
822
+ affinity: e.boundary < e.runCount ? "following" : "preceding"
823
+ });
824
+ }
825
+ function B(e, t) {
826
+ let n = e.runs, r = 0;
827
+ for (let e = 0; e < Math.min(t, n.length); e += 1) n[e]?.type !== "unavailableDrawing" && (r += 1);
828
+ return r;
829
+ }
830
+ function Gn(e, t, n, r, i = t.boundary) {
831
+ return Object.freeze({
832
+ commentId: e,
833
+ source: Un(t.source),
834
+ startRunIndex: t.boundary,
835
+ endRunIndex: i,
836
+ reference: Wn(n),
837
+ ...r === void 0 ? {} : { geometryFallback: Object.freeze({
838
+ source: Un(r.source),
839
+ sourceRunIndex: r.boundary
840
+ }) }
841
+ });
842
+ }
843
+ function Kn(e, t) {
844
+ let n = e.flatMap(({ paragraph: e, source: n }, r) => {
845
+ let i = B(e, e.runs.length);
846
+ return [...t.get(D(n)) ?? []].sort((e, t) => e - t).map((e) => ({
847
+ paragraphIndex: r,
848
+ source: n,
849
+ boundary: e,
850
+ runCount: i
851
+ }));
852
+ });
853
+ return {
854
+ locations: n,
855
+ paragraphIndices: new Set(n.map(({ paragraphIndex: e }) => e))
856
+ };
857
+ }
858
+ function qn(e, t) {
859
+ return e.paragraphIndex - t.paragraphIndex || e.boundary - t.boundary;
860
+ }
861
+ function Jn(e, t) {
862
+ let n = 0, r = e.length;
863
+ for (; n < r;) {
864
+ let i = n + Math.floor((r - n) / 2);
865
+ qn(e[i], t) < 0 ? n = i + 1 : r = i;
866
+ }
867
+ return n;
868
+ }
869
+ function Yn(e, t) {
870
+ if (t.paragraphIndices.has(e.paragraphIndex)) return;
871
+ let n = Jn(t.locations, e), r = t.locations[n], i = n > 0 ? t.locations[n - 1] : void 0;
872
+ return Wn(e).affinity === "following" ? r ?? i : i ?? r;
873
+ }
874
+ function Xn(e, t, n) {
875
+ let r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Set();
876
+ for (let e of t) {
877
+ let t = Hn(e);
878
+ t === void 0 || i.has(t) || (r.has(t) ? (r.delete(t), i.add(t)) : r.set(t, e));
879
+ }
880
+ let a = /* @__PURE__ */ new Map();
881
+ for (let [t, { paragraph: n, source: r }] of e.entries()) for (let e of n.commentMarks ?? []) {
882
+ let i = Hn(e.id);
883
+ if (i === void 0) continue;
884
+ let o = a.get(i) ?? {
885
+ starts: [],
886
+ ends: [],
887
+ references: []
888
+ };
889
+ a.set(i, o);
890
+ let s = {
891
+ paragraphIndex: t,
892
+ source: r,
893
+ boundary: B(n, e.runIndex),
894
+ runCount: B(n, n.runs.length)
895
+ };
896
+ e.kind === "rangeStart" ? o.starts.push(s) : e.kind === "rangeEnd" ? o.ends.push(s) : e.kind === "reference" && o.references.push(s);
897
+ }
898
+ let o = [], s = Kn(e, n);
899
+ for (let [t, n] of a) {
900
+ let i = r.get(t);
901
+ if (i === void 0 || n.references.length !== 1) continue;
902
+ let a = n.references[0];
903
+ if (n.starts.length > 1 || n.ends.length > 1) continue;
904
+ let c = n.starts.length === 1 ? n.starts[0] : void 0, l = n.ends.length === 1 ? n.ends[0] : void 0;
905
+ if (c && l && (c.paragraphIndex < l.paragraphIndex || c.paragraphIndex === l.paragraphIndex && c.boundary <= l.boundary)) {
906
+ let t = Yn(c.paragraphIndex === l.paragraphIndex && c.boundary === l.boundary ? c : a, s);
907
+ for (let n = c.paragraphIndex; n <= l.paragraphIndex; n += 1) {
908
+ let r = e[n], s = n === c.paragraphIndex ? c.boundary : 0, u = n === l.paragraphIndex ? l.boundary : B(r.paragraph, r.paragraph.runs.length);
909
+ o.push(Gn(i, {
910
+ paragraphIndex: n,
911
+ source: r.source,
912
+ boundary: s,
913
+ runCount: B(r.paragraph, r.paragraph.runs.length)
914
+ }, a, t, Math.max(s, u)));
915
+ }
916
+ continue;
917
+ }
918
+ let u = c && n.ends.length === 0 ? c : l && n.starts.length === 0 ? l : void 0;
919
+ if (c && l) continue;
920
+ let d = u ?? a, f = Yn(d, s);
921
+ o.push(Gn(i, d, a, f));
922
+ }
923
+ return o;
924
+ }
925
+ function Zn(e, t, n = /* @__PURE__ */ new Map()) {
926
+ let r = new Set(e.map(({ id: e }) => e)), i = /* @__PURE__ */ new Map();
927
+ for (let e of t.blocks.sources) {
928
+ let n = t.blocks.resolve(e);
929
+ if (n.type !== "paragraph") continue;
930
+ let r = `${e.story}\u0000${e.storyInstance}`, a = i.get(r) ?? [];
931
+ i.has(r) || i.set(r, a), a.push({
932
+ paragraph: n,
933
+ source: e
934
+ });
935
+ }
936
+ return [...i.values()].flatMap((e) => Xn(e, r, n));
937
+ }
938
+ function Qn(e, t, n = /* @__PURE__ */ new Map(), r = {}) {
939
+ if ((e?.length ?? 0) === 0) return [];
940
+ let i = Zn(e ?? [], t, n), a = r.completedSourceKeys;
941
+ return a === void 0 ? i : i.filter((e) => {
942
+ let t = n.get(D(e.source)) ?? /* @__PURE__ */ new Set(), r = e.startRunIndex < e.endRunIndex ? [...t].some((t) => t >= e.startRunIndex && t < e.endRunIndex) : t.has(e.reference.affinity === "following" ? e.startRunIndex : e.startRunIndex - 1), i = n.get(D(e.reference.source))?.has(e.reference.affinity === "following" ? e.reference.runIndex : e.reference.runIndex - 1) === !0;
943
+ return r || i || a.has(D(e.source)) || a.has(D(e.reference.source));
944
+ });
945
+ }
946
+ function V(e, t) {
947
+ 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]);
948
+ }
949
+ function H(e, t) {
950
+ let n = t.filter((t) => t.sourceRunIndex !== void 0 && V(t.source, e.source)), r = n.filter((t) => t.sourceRunIndex >= e.startRunIndex && t.sourceRunIndex < e.endRunIndex);
951
+ if (r.length > 0) return r;
952
+ if (e.startRunIndex === e.endRunIndex && n.length > 0) {
953
+ let t = n.reduce((t, n) => {
954
+ let r = n.sourceRunIndex;
955
+ return r < e.startRunIndex ? t : t === void 0 || r < t ? r : t;
956
+ }, void 0), r = n.reduce((t, n) => {
957
+ let r = n.sourceRunIndex;
958
+ return r >= e.startRunIndex ? t : t === void 0 || r > t ? r : t;
959
+ }, void 0), i = t ?? r;
960
+ if (i !== void 0) return n.filter((e) => e.sourceRunIndex === i);
961
+ }
962
+ let i = t.filter((t) => t.sourceRunIndex !== void 0 && V(t.source, e.reference.source)), a = i.reduce((t, n) => {
963
+ let r = n.sourceRunIndex;
964
+ return r < e.reference.runIndex ? t : t === void 0 || r < t ? r : t;
965
+ }, void 0), o = i.reduce((t, n) => {
966
+ let r = n.sourceRunIndex;
967
+ return r >= e.reference.runIndex ? t : t === void 0 || r > t ? r : t;
968
+ }, void 0), s = e.reference.affinity === "following" ? a ?? o : o ?? a;
969
+ if (s !== void 0) return i.filter((e) => e.sourceRunIndex === s);
970
+ let c = e.geometryFallback;
971
+ return c === void 0 ? [] : t.filter((e) => e.sourceRunIndex === c.sourceRunIndex && V(e.source, c.source));
972
+ }
973
+ function $n(e, t) {
974
+ return t.some((t) => t.sourceRunIndex !== void 0 && V(t.source, e.source) && t.sourceRunIndex >= e.startRunIndex && t.sourceRunIndex < e.endRunIndex) ? "range" : t.some((t) => V(t.source, e.source) || V(t.source, e.reference.source)) ? "point" : "fallback";
975
+ }
976
+ function er(e) {
977
+ let t = e.map((e) => {
978
+ let t = e.highlightBounds;
979
+ return {
980
+ x: t?.x ?? e.x,
981
+ y: t?.y ?? e.y,
982
+ width: t?.width ?? e.w,
983
+ height: t?.height ?? e.h,
984
+ ...e.transform ? { transform: e.transform } : {}
985
+ };
986
+ }).filter(({ width: e, height: t }) => e > 0 && t > 0).sort((e, t) => e.y - t.y || e.x - t.x), n = [];
987
+ for (let e of t) {
988
+ let t = n.at(-1);
989
+ if (t && t.y === e.y && t.height === e.height && t.transform === e.transform) {
990
+ let r = Math.min(t.x, e.x), i = Math.max(t.x + t.width, e.x + e.width);
991
+ n[n.length - 1] = Object.freeze({
992
+ ...t,
993
+ x: r,
994
+ width: i - r
995
+ });
996
+ } else n.push(Object.freeze({ ...e }));
997
+ }
998
+ return Object.freeze(n);
999
+ }
1000
+ function tr(e, t, n, r = {}) {
1001
+ let i = new Map(e.map((e) => [e.id, e])), a = e.filter((e) => e.parentId === void 0), o = new Map(a.map((e) => [e.id, e])), s = /* @__PURE__ */ new Map(), c = new Map(a.map((e) => [e.id, e.id]));
1002
+ for (let t of e) {
1003
+ if (t.parentId === void 0) continue;
1004
+ let e = new Set([t.id]), n = t;
1005
+ for (; n.parentId !== void 0;) {
1006
+ let r = i.get(n.parentId);
1007
+ if (!r || e.has(r.id)) {
1008
+ n = t;
1009
+ break;
1010
+ }
1011
+ e.add(r.id), n = r;
1012
+ }
1013
+ if (!o.has(n.id) || n === t) continue;
1014
+ c.set(t.id, n.id);
1015
+ let r = s.get(n.id) ?? [];
1016
+ s.has(n.id) || s.set(n.id, r), r.push(t);
1017
+ }
1018
+ let l = /* @__PURE__ */ new Set();
1019
+ for (let e of n) e.source && l.add(D(e.source));
1020
+ let u = /* @__PURE__ */ new Map();
1021
+ for (let e of t) {
1022
+ let t = c.get(e.commentId);
1023
+ if (t === void 0 || !(l.has(D(e.source)) || l.has(D(e.reference.source)) || e.geometryFallback !== void 0 && l.has(D(e.geometryFallback.source)))) continue;
1024
+ let r = H(e, n);
1025
+ if (r.length === 0) continue;
1026
+ let i = u.get(t) ?? [];
1027
+ u.has(t) || u.set(t, i), i.push(Object.freeze({
1028
+ anchor: e,
1029
+ kind: $n(e, r),
1030
+ rects: er(r)
1031
+ }));
1032
+ }
1033
+ return Object.freeze(a.flatMap((e) => {
1034
+ if (r.includeResolved === !1 && e.resolved === !0) return [];
1035
+ let t = u.get(e.id);
1036
+ return t?.length ? [Object.freeze({
1037
+ root: e,
1038
+ replies: Object.freeze([...s.get(e.id) ?? []]),
1039
+ anchors: Object.freeze([...t])
1040
+ })] : [];
1041
+ }));
1042
+ }
1043
+ //#endregion
1044
+ //#region packages/docx/src/revisions.ts
1045
+ function nr(e) {
1046
+ let t = Hn(e.id);
1047
+ return t === void 0 ? void 0 : `${e.kind}\u0000${t}`;
1048
+ }
1049
+ function U(e) {
1050
+ return Object.freeze({
1051
+ ...e,
1052
+ path: Object.freeze([...e.path])
1053
+ });
1054
+ }
1055
+ function rr(e, t) {
1056
+ 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]);
1057
+ }
1058
+ function ir(e, t) {
1059
+ let n = 0, r = e.length;
1060
+ for (; n < r;) {
1061
+ let i = n + Math.floor((r - n) / 2);
1062
+ e[i] < t ? n = i + 1 : r = i;
1063
+ }
1064
+ return n;
1065
+ }
1066
+ function ar(e, t) {
1067
+ let n = Array(e.length), r;
1068
+ for (let i = e.length - 1; i >= 0; --i) {
1069
+ n[i] = r;
1070
+ let a = e[i], o = t.get(D(a.source))?.[0];
1071
+ o !== void 0 && (r = Object.freeze({
1072
+ source: U(a.source),
1073
+ sourceRunIndex: o
1074
+ }));
1075
+ }
1076
+ let i = Array(e.length), a;
1077
+ for (let n = 0; n < e.length; n += 1) {
1078
+ i[n] = a;
1079
+ let r = e[n], o = t.get(D(r.source))?.at(-1);
1080
+ o !== void 0 && (a = Object.freeze({
1081
+ source: U(r.source),
1082
+ sourceRunIndex: o
1083
+ }));
1084
+ }
1085
+ return {
1086
+ following: n,
1087
+ preceding: i
1088
+ };
1089
+ }
1090
+ function or(e, t, n, r, i, a) {
1091
+ let o = r[e], s = i.get(D(o.source)) ?? [], c = s[ir(s, n)], l = s[ir(s, t) - 1], u = c ?? l;
1092
+ return u === void 0 ? a.following[e] ?? a.preceding[e] : Object.freeze({
1093
+ source: U(o.source),
1094
+ sourceRunIndex: u
1095
+ });
1096
+ }
1097
+ function sr(e, t, n = /* @__PURE__ */ new Map()) {
1098
+ let r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Set();
1099
+ e.forEach((e, t) => {
1100
+ let n = nr(e);
1101
+ n === void 0 || i.has(n) || (r.has(n) ? (r.delete(n), i.add(n)) : r.set(n, t));
1102
+ });
1103
+ let a = t.blocks.sources.flatMap((e) => {
1104
+ if (e.story !== "body") return [];
1105
+ let n = t.blocks.resolve(e);
1106
+ return n.type === "paragraph" ? [{
1107
+ source: e,
1108
+ runs: n.runs
1109
+ }] : [];
1110
+ }), o = new Map([...n].map(([e, t]) => [e, Object.freeze([...t].sort((e, t) => e - t))])), s = ar(a, o), c = [];
1111
+ for (let [e, t] of a.entries()) {
1112
+ let n = 0;
1113
+ for (; n < t.runs.length;) {
1114
+ let i = t.runs[n], l = i.revision?.kind ? nr({
1115
+ kind: i.revision.kind,
1116
+ id: i.revision.id
1117
+ }) : void 0, u = l === void 0 ? void 0 : r.get(l);
1118
+ if (u === void 0) {
1119
+ n += 1;
1120
+ continue;
1121
+ }
1122
+ let d = n;
1123
+ for (n += 1; n < t.runs.length;) {
1124
+ let e = t.runs[n].revision;
1125
+ if (!e?.kind || nr({
1126
+ kind: e.kind,
1127
+ id: e.id
1128
+ }) !== l) break;
1129
+ n += 1;
1130
+ }
1131
+ let f = n, p = o.get(D(t.source)) ?? [], m = (p[ir(p, d)] ?? f) < f ? void 0 : or(e, d, f, a, o, s);
1132
+ c.push(Object.freeze({
1133
+ revisionIndex: u,
1134
+ source: U(t.source),
1135
+ startRunIndex: d,
1136
+ endRunIndex: f,
1137
+ ...m === void 0 ? {} : { geometryFallback: m }
1138
+ }));
1139
+ }
1140
+ }
1141
+ return c;
1142
+ }
1143
+ function cr(e, t, n = /* @__PURE__ */ new Map(), r = {}) {
1144
+ if ((e?.length ?? 0) === 0) return [];
1145
+ let i = sr(e ?? [], t, n), a = r.completedSourceKeys;
1146
+ return a === void 0 ? i : i.filter((e) => {
1147
+ let t = n.get(D(e.source));
1148
+ return t !== void 0 && [...t].some((t) => t >= e.startRunIndex && t < e.endRunIndex) || a.has(D(e.source));
1149
+ });
1150
+ }
1151
+ function lr(e, t) {
1152
+ let n = t.filter((t) => t.sourceRunIndex !== void 0 && rr(t.source, e.source) && t.sourceRunIndex >= e.startRunIndex && t.sourceRunIndex < e.endRunIndex);
1153
+ if (n.length > 0) return n;
1154
+ let r = e.geometryFallback;
1155
+ return r === void 0 ? [] : t.filter((e) => e.sourceRunIndex === r.sourceRunIndex && rr(e.source, r.source));
1156
+ }
1157
+ //#endregion
1158
+ //#region packages/docx/src/layout/progressive.ts
1159
+ var ur = 12;
1160
+ async function dr(e, t, n, r = {}) {
1161
+ let { onPreview: i, scheduler: a } = r;
1162
+ return Ge(ot(e, t, n, i && e.sequence.length > ur ? { onPages: (e, t) => {
1163
+ i(Object.freeze({
1164
+ layout: e,
1165
+ exact: !1,
1166
+ coveredEntries: t
1167
+ }));
1168
+ } } : void 0), a);
1169
+ }
1170
+ //#endregion
1171
+ //#region packages/docx/src/document-layout-events.ts
1172
+ var W = /* @__PURE__ */ new WeakMap();
1173
+ function G(e, t) {
1174
+ let n = Object.freeze({ ...t });
1175
+ for (let t of [...W.get(e) ?? []]) try {
1176
+ t.notify(n);
1177
+ } catch (e) {
1178
+ try {
1179
+ t.report(e);
1180
+ } catch {}
1181
+ }
1182
+ }
1183
+ function fr(e, t, n, r) {
1184
+ let i = W.get(e);
1185
+ i || (i = /* @__PURE__ */ new Set(), W.set(e, i));
1186
+ let a = Object.freeze({
1187
+ notify: n,
1188
+ report: r
1189
+ });
1190
+ i.add(a);
1191
+ try {
1192
+ n(Object.freeze({ ...t() }));
1193
+ } catch (e) {
1194
+ try {
1195
+ r(e);
1196
+ } catch {}
1197
+ }
1198
+ return () => {
1199
+ i?.delete(a), i?.size === 0 && W.delete(e);
1200
+ };
1201
+ }
1202
+ //#endregion
1203
+ //#region packages/docx/src/layout/unchanged-pages.ts
1204
+ function pr(e, t) {
1205
+ if (!e) return 0;
1206
+ let n = Math.min(e.length, t.length), r = 0;
1207
+ for (; r < n && mr(e[r], t[r]);) r += 1;
1208
+ return r;
1209
+ }
1210
+ function mr(e, t) {
1211
+ if (e === t) return !0;
1212
+ if (typeof e != "object" || typeof t != "object" || e === null || t === null) return !1;
1213
+ if (Array.isArray(e)) {
1214
+ if (!Array.isArray(t) || e.length !== t.length) return !1;
1215
+ for (let n = 0; n < e.length; n += 1) if (!mr(e[n], t[n])) return !1;
1216
+ return !0;
1217
+ }
1218
+ if (Array.isArray(t)) return !1;
1219
+ let n = Object.keys(e);
1220
+ if (n.length !== Object.keys(t).length) return !1;
1221
+ for (let r of n) if (!Object.prototype.hasOwnProperty.call(t, r) || !mr(e[r], t[r])) return !1;
1222
+ return !0;
1223
+ }
1224
+ //#endregion
1225
+ //#region packages/docx/src/document-layout-view.ts
1226
+ var K = /* @__PURE__ */ new WeakMap(), hr = /* @__PURE__ */ new WeakMap(), gr = Symbol("docxLayoutViewRequester");
1227
+ function q(e) {
1228
+ let t = O(e), n = t.activeLayoutOptions;
1229
+ return {
1230
+ showTrackedChanges: n?.showTrackedChanges === !0,
1231
+ currentDate: n?.currentDateMs ?? t.defaultCurrentDateMs
1232
+ };
1233
+ }
1234
+ async function J(e, t, n) {
1235
+ let r = O(e), i = A(t.currentDate, r.defaultCurrentDateMs, t.showTrackedChanges === !0), a = Object.freeze({
1236
+ showTrackedChanges: i.showTrackedChanges === !0,
1237
+ currentDate: i.currentDateMs
1238
+ }), o = {
1239
+ showTrackedChanges: a.showTrackedChanges,
1240
+ currentDate: a.currentDate,
1241
+ [gr]: n
1242
+ };
1243
+ await e.setLayoutView(o);
1244
+ let s = q(e);
1245
+ return s.currentDate === a.currentDate && s.showTrackedChanges === a.showTrackedChanges;
1246
+ }
1247
+ async function _r(e, t, n, r, i) {
1248
+ let a = !1, o = () => {
1249
+ a || (a = !0, e.destroy());
1250
+ };
1251
+ try {
1252
+ for (; !t.aborted;) {
1253
+ let a = n();
1254
+ if (a === void 0 || q(e).showTrackedChanges === a) break;
1255
+ t.addEventListener("abort", o, { once: !0 });
1256
+ try {
1257
+ await J(e, {
1258
+ showTrackedChanges: a,
1259
+ currentDate: r()
1260
+ }, i);
1261
+ } finally {
1262
+ t.removeEventListener("abort", o);
1263
+ }
1264
+ }
1265
+ } catch (e) {
1266
+ throw o(), e;
1267
+ }
1268
+ }
1269
+ function vr(e, t) {
1270
+ let n = Object.freeze({ ...q(e) }), r = (hr.get(e) ?? 0) + 1;
1271
+ hr.set(e, r);
1272
+ let i = Object.freeze({
1273
+ view: n,
1274
+ generation: r,
1275
+ requester: t
1276
+ });
1277
+ for (let t of [...K.get(e) ?? []]) try {
1278
+ t.notify(i);
1279
+ } catch (e) {
1280
+ try {
1281
+ t.report(e);
1282
+ } catch {}
1283
+ }
1284
+ }
1285
+ function yr(e, t, n) {
1286
+ let r = K.get(e);
1287
+ r || (r = /* @__PURE__ */ new Set(), K.set(e, r));
1288
+ let i = Object.freeze({
1289
+ notify: t,
1290
+ report: n
1291
+ });
1292
+ return r.add(i), () => {
1293
+ r?.delete(i), r?.size === 0 && K.delete(e);
1294
+ };
1295
+ }
1296
+ //#endregion
1297
+ //#region packages/docx/src/document.ts
1298
+ var br = Symbol("docxViewerLoadSignal");
1299
+ function xr(e, t) {
1300
+ return e !== null && e.currentDateMs === t.currentDateMs && e.showTrackedChanges === !0 == (t.showTrackedChanges === !0);
1301
+ }
1302
+ var Sr = Object.freeze([]), Cr = Object.freeze([]), wr = Object.freeze({
1303
+ comments: Object.freeze([]),
1304
+ revisions: Object.freeze([])
1305
+ });
1306
+ function Y(e, t) {
1307
+ return Ie({
1308
+ comments: e,
1309
+ revisions: t
1310
+ }, "DOCX review metadata");
1311
+ }
1312
+ var X = class e {
1313
+ get diagnostics() {
1314
+ return Ie([
1315
+ ...this._mode === "worker" ? this._meta?.diagnostics ?? [] : this._getLayout()?.diagnostics ?? [],
1316
+ ...this._meta?.resourceDiagnostics ?? [],
1317
+ ...dn(this)
1318
+ ], "DOCX diagnostics");
1319
+ }
1320
+ _metrics = null;
1321
+ _cjkFallback = "jp";
1322
+ _allowFootnoteContinuation = !1;
1323
+ _document = null;
1324
+ _source = null;
1325
+ _meta = null;
1326
+ _review = wr;
1327
+ _layoutLifecycle = new se();
1328
+ _layoutObservers = new ke();
1329
+ _layoutCompletion = null;
1330
+ _layoutAbort = null;
1331
+ _bookmarkPages = null;
1332
+ _commentAnchorRanges = null;
1333
+ _revisionAnchorRanges = null;
1334
+ _reviewProjectionIndex = null;
1335
+ _parseRequestId = null;
1336
+ _progressive = null;
1337
+ _parseWatchdog;
1338
+ _parseWatchdogMs;
1339
+ _layoutViewGeneration = 0;
1340
+ _mode = "main";
1341
+ _threeD;
1342
+ _regionMap;
1343
+ _chartEx;
1344
+ _tiff;
1345
+ _worker;
1346
+ _bridge;
1347
+ _rawParts = new ee({
1348
+ maxEntries: 64,
1349
+ maxBytes: g
1350
+ });
1351
+ _embeddedFontFaces = [];
1352
+ _officeFontFaces = [];
1353
+ _mainThreadFallbackReason = "vertical";
1354
+ _nativeRouteFaces = [];
1355
+ _nativeRouteFacesReleased = !1;
1356
+ _googleFontFaces = [];
1357
+ _fetchImage = (e, t) => this.getImage(e, t);
1358
+ constructor(e, t, n, r) {
1359
+ this._worker = e, this._mode = t, Le(this, n), this._bridge = new pt(this._worker, {
1360
+ correlate: (e) => "protocol" in e && e.protocol === "ooxml-pull-v1" ? e.requestId : "id" in e ? e.id : void 0,
1361
+ onUnsolicited: (e) => this._onWorkerLayoutPush(e),
1362
+ toError: (e) => {
1363
+ if (!("protocol" in e || e.type !== "error")) return Object.assign(l(e), {
1364
+ ...e.reason === void 0 ? {} : { reason: e.reason },
1365
+ ...e.outgoingColumnIndex === void 0 ? {} : { outgoingColumnIndex: e.outgoingColumnIndex },
1366
+ ...e.outgoingColumnCount === void 0 ? {} : { outgoingColumnCount: e.outgoingColumnCount },
1367
+ ...e.incomingColumnCount === void 0 ? {} : { incomingColumnCount: e.incomingColumnCount }
1368
+ });
1369
+ }
1370
+ });
1371
+ let i = new URL(r ?? hn, location.href).href;
1372
+ this._bridge.post({
1373
+ type: "init",
1374
+ wasmUrl: i
1375
+ });
1376
+ }
1377
+ static async load(t, n = {}) {
1378
+ let r = n[br], s = r?.signal, c = () => {
1379
+ if (s?.aborted) throw new j();
1380
+ };
1381
+ if (c(), n.legacyDoc !== void 0) {
1382
+ let { loadDocxModelSource: e } = await import("./document-model-source-BKNrXjAL.js"), i = await e(t, n, r);
1383
+ if (s?.aborted) throw i.destroy(), new j();
1384
+ return i;
1385
+ }
1386
+ let l = p(n.cjkFallback), d = i(n), h = Date.now(), g = n.mode ?? "main", _ = new o({
1387
+ enabled: !0,
1388
+ format: "docx",
1389
+ mode: g,
1390
+ policy: d.policy,
1391
+ onMetrics: d.onResourceMetrics,
1392
+ emitToConsole: d.debug
1393
+ });
1394
+ try {
1395
+ if (g === "worker" && (typeof Worker > "u" || typeof OffscreenCanvas > "u")) throw Error("mode: 'worker' requires Worker and OffscreenCanvas support");
1396
+ let i;
1397
+ if (typeof t == "string") {
1398
+ let e = await fetch(t, { signal: s });
1399
+ if (!e.ok) throw Error(`Failed to fetch: ${e.status} ${e.statusText}`);
1400
+ i = await e.arrayBuffer();
1401
+ } else i = t;
1402
+ c(), i = x(await ne(i, n.password)), c(), _.setSourceBytes(i.byteLength), _.checkpoint("container ready");
1403
+ let o = g === "worker" ? (await import("./render-worker-host-aF6aWkC0.js")).createRenderWorker() : new mn(), p = g === "worker" ? Nt(n) : void 0, ee = g === "worker" && !!n.progressiveLayout, v, y = !1, b = () => {
1404
+ y || !v || (y = !0, v.destroy());
1405
+ };
1406
+ try {
1407
+ v = new e(o, g, h, n.wasmUrl), s?.addEventListener("abort", b, { once: !0 }), c(), v._metrics = _, v._cjkFallback = l, v._allowFootnoteContinuation = n.allowFootnoteContinuation !== !1;
1408
+ let t = O(v), y = A(n.currentDate, t.defaultCurrentDateMs, n.showTrackedChanges === !0);
1409
+ t.activeLayoutOptions = y, await v._parse(i, d.policy, g === "worker" ? !!n.useGoogleFonts : !1, n.workerTimeoutMs, (e) => _.observeUsage(e), p, ee ? {
1410
+ onPartial: n.onLayoutPartial,
1411
+ onComplete: n.onLayoutComplete,
1412
+ onProgress: n.onLayoutProgress,
1413
+ layoutOptions: y,
1414
+ abort: new AbortController(),
1415
+ firstPublication: ue(),
1416
+ published: !1,
1417
+ settled: !1
1418
+ } : void 0), c(), g === "worker" && v._mode === "main" && (_.setMode("main"), console.warn(gn(v._mainThreadFallbackReason))), n.math && v._mode === "worker" && !p?.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 && v._mode === "worker" && !p?.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."), v._threeD = v._mode === "worker" ? void 0 : n.threeD, n.regionMap && v._mode === "worker" && !p?.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."), v._regionMap = v._mode === "worker" ? void 0 : n.regionMap, n.chartEx && v._mode === "worker" && !p?.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."), v._chartEx = v._mode === "worker" ? void 0 : n.chartEx, n.tiff && v._mode === "worker" && !p?.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."), v._tiff = v._mode === "worker" ? void 0 : n.tiff;
1419
+ let te, x, ne = v, re = v._mode === "main" && v._document && v._source ? Je(rt(v._source, v._document, {
1420
+ useGoogleFonts: !!n.useGoogleFonts,
1421
+ cjkFallback: l
1422
+ }), !0).then((e) => ne._nativeRouteFacesReleased ? (m(e.faces), null) : (ne._nativeRouteFaces.push(...e.faces), e), () => null) : null;
1423
+ if (v._mode === "main" && v._document?.embeddedFonts?.length) {
1424
+ let e = v, t = await Cn(v._document, (t) => e.getFontBytes(t));
1425
+ if (s?.aborted) throw w(t.faces), new j();
1426
+ F(v, t.diagnostics), v._embeddedFontFaces = t.faces, te = t.metrics, x = t.routes;
1427
+ }
1428
+ let S = v._mode === "main" && v._document ? await ln(et(v._document, {
1429
+ useGoogleFonts: n.useGoogleFonts,
1430
+ cjkFallback: l
1431
+ }).filter((e) => e.presenceOnly || !x?.some((t) => t.requestedFamily.toLowerCase() === e.family.toLowerCase() && t.weight === (e.weight ?? 400) && t.style === (e.style ?? "normal")))) : {
1432
+ faces: [],
1433
+ routes: {}
1434
+ };
1435
+ if (s?.aborted) throw m(S.faces), new j();
1436
+ v._officeFontFaces = S.faces;
1437
+ let ie = [];
1438
+ if (v._mode === "main" && n.useGoogleFonts && v._document) {
1439
+ let e = qe(v._document, l, S);
1440
+ ie = e.installedSubstituteFamilies;
1441
+ let t = await u(e.names, Ue);
1442
+ if (s?.aborted) throw f(t), new j();
1443
+ v._googleFontFaces = t;
1444
+ }
1445
+ let C;
1446
+ if (v._mode === "main" && n.math && v._document && $e(v._document) && (C = await tt(v._document, n.math)), c(), v._mode === "main" && v._document && v._source) {
1447
+ let e = v, t = O(v), i = {
1448
+ allowFootnoteContinuation: v._allowFootnoteContinuation,
1449
+ fontMetrics: te,
1450
+ useGoogleFonts: !!n.useGoogleFonts,
1451
+ cjkFallback: l,
1452
+ embeddedRoutes: x,
1453
+ officeRoutes: Object.values(S.routes),
1454
+ googleFaces: v._googleFontFaces,
1455
+ installedSubstituteFamilies: ie,
1456
+ installedFamilies: "installed" in S ? S.installed : void 0,
1457
+ mathResources: C?.records,
1458
+ mathDrawables: C?.drawables
1459
+ }, o = await re;
1460
+ c(), t.services = Xe(v._source, {
1461
+ ...i,
1462
+ nativeRouteMetrics: o && o.faces.length > 0 ? Ze(o.lines, a()) : void 0
1463
+ });
1464
+ let u = t.services, d = We(v._source, u, t.defaultCurrentDateMs), f = v._source.fatalParse === null, p = t.activeLayoutOptions;
1465
+ if (!p) throw Error("Active layout view was not recorded at load");
1466
+ let m = { onProgress: n.onLayoutProgress ? (t) => e._layoutObservers.notify("onLayoutProgress", n.onLayoutProgress, { committedUnits: t }) : void 0 };
1467
+ if (f && n.progressiveLayout) {
1468
+ let e = d.layoutVariants, t = v, r = new AbortController();
1469
+ t._layoutAbort = r;
1470
+ let i = ue(), a = null, o = !0;
1471
+ t._layoutCompletion = dr(v._source.bodyLayoutInput, u, p, {
1472
+ scheduler: {
1473
+ ...m,
1474
+ signal: r.signal
1475
+ },
1476
+ onPreview: (r) => {
1477
+ if (!o) return;
1478
+ let s = a === null, c = pr(a?.pages, r.layout.pages), l = t._replaceMainLayoutPublication(e, p, a, r.layout);
1479
+ if (l === null) {
1480
+ o = !1;
1481
+ return;
1482
+ }
1483
+ if (a = l, s) t._layoutLifecycle.begin(), G(t, {
1484
+ pageCount: r.layout.pages.length,
1485
+ exact: r.exact,
1486
+ complete: !1
1487
+ }), i.resolve();
1488
+ else {
1489
+ if (!t._isLayoutViewActive(p)) return;
1490
+ G(t, {
1491
+ pageCount: r.layout.pages.length,
1492
+ exact: r.exact,
1493
+ complete: !1,
1494
+ unchangedPages: c
1495
+ }), t._layoutObservers.notify("onLayoutPartial", n.onLayoutPartial, {
1496
+ availableUnits: r.layout.pages.length,
1497
+ exact: r.exact
1498
+ });
1499
+ }
1500
+ }
1501
+ }).then((r) => {
1502
+ let s;
1503
+ o && (s = pr(a?.pages, r.pages), t._replaceMainLayoutPublication(e, p, a, r) === null && (o = !1)), t._layoutLifecycle.succeed(), G(t, {
1504
+ pageCount: t.pageCount,
1505
+ exact: !0,
1506
+ complete: !0,
1507
+ ...o && t._isLayoutViewActive(p) && s !== void 0 ? { unchangedPages: s } : {}
1508
+ }), t._layoutObservers.notify("onLayoutComplete", n.onLayoutComplete), i.resolve();
1509
+ }).catch((e) => {
1510
+ if (a === null) {
1511
+ i.reject(e);
1512
+ return;
1513
+ }
1514
+ if (e instanceof j) {
1515
+ t._layoutLifecycle.succeed();
1516
+ return;
1517
+ }
1518
+ let r = t._layoutLifecycle.fail(e);
1519
+ G(t, {
1520
+ pageCount: t.pageCount,
1521
+ exact: !1,
1522
+ complete: !1,
1523
+ error: r
1524
+ }), t._layoutObservers.notify("onLayoutComplete", n.onLayoutComplete, r);
1525
+ }), await i.promise;
1526
+ } else if (f && (n.sliceLayout !== !1 || n.onLayoutProgress)) for (;;) {
1527
+ c();
1528
+ let e = r?.requestedView(), i = e === void 0 ? p : A(n.currentDate, t.defaultCurrentDateMs, e);
1529
+ t.activeLayoutOptions = i;
1530
+ let a = new AbortController(), o = !1, l = r?.subscribeViewChange(() => {
1531
+ let e = r.requestedView();
1532
+ o || e === void 0 || e === !0 == (i.showTrackedChanges === !0) || (o = !0, a.abort());
1533
+ });
1534
+ v._layoutAbort = a;
1535
+ try {
1536
+ let e = await it(v._source.bodyLayoutInput, u, i, {
1537
+ ...m,
1538
+ signal: a.signal
1539
+ });
1540
+ if (c(), o) continue;
1541
+ d.layoutVariants.prime(i, e);
1542
+ break;
1543
+ } catch (e) {
1544
+ if (e instanceof j && o && !s?.aborted) continue;
1545
+ throw e;
1546
+ } finally {
1547
+ l?.(), v._layoutAbort = null;
1548
+ }
1549
+ }
1550
+ else d.layoutVariants.layoutFor(p);
1551
+ }
1552
+ return c(), await v._resourceUsage(n.workerTimeoutMs ?? 1e3).then((e) => _.observeUsage(e), () => void 0), _.checkpoint("model and layout ready"), c(), _.succeed({ pages: v.pageCount }), v;
1553
+ } catch (e) {
1554
+ throw mt(o, v ? b : void 0), e;
1555
+ } finally {
1556
+ s?.removeEventListener("abort", b);
1557
+ }
1558
+ } catch (e) {
1559
+ throw _.fail(e), e;
1560
+ }
1561
+ }
1562
+ async _parse(e, t, n = !1, r, i, a, o) {
1563
+ if (o) {
1564
+ await this._parseProgressively(e, t, n, r, i, a, o);
1565
+ return;
1566
+ }
1567
+ let s = await this._bridge.request((r) => (this._parseRequestId = r, this._mode === "worker" ? {
1568
+ type: "parse",
1569
+ id: r,
1570
+ data: e,
1571
+ resourcePolicy: t,
1572
+ useGoogleFonts: n,
1573
+ allowFootnoteContinuation: this._allowFootnoteContinuation,
1574
+ cjkFallback: this._cjkFallback,
1575
+ defaultCurrentDateMs: O(this).defaultCurrentDateMs,
1576
+ ...this._parseViewFields(),
1577
+ renderers: a
1578
+ } : {
1579
+ type: "parse",
1580
+ id: r,
1581
+ data: e,
1582
+ resourcePolicy: t
1583
+ }), [e], { timeoutMs: r });
1584
+ if (this._parseRequestId = null, "protocol" in s) throw Error("DOCX parse open returned a pull-protocol response");
1585
+ if (this._mode === "worker") if ("usage" in s && s.usage && i?.(s.usage), s.type === "mainThreadVerticalFallback") {
1586
+ let e = await Qe(this._bridge.transport(nt), s, {
1587
+ timeoutMs: r,
1588
+ onUsage: i
1589
+ });
1590
+ this._source = e.source, this._document = e.document, this._meta = null, this._mode = "main", this._mainThreadFallbackReason = s.reason ?? "vertical";
1591
+ } else this._meta = s.meta;
1592
+ else {
1593
+ let e = s, t = await Qe(this._bridge.transport(nt), e, {
1594
+ timeoutMs: r,
1595
+ onUsage: i
1596
+ });
1597
+ this._source = t.source, this._document = t.document;
1598
+ }
1599
+ this._review = Y(this._meta?.comments ?? this._document?.comments ?? [], this._meta?.revisions ?? this._document?.revisions ?? []);
1600
+ }
1601
+ _onWorkerLayoutPush(e) {
1602
+ if (At((e, t) => this._worker.postMessage(e, t), e) || !("forId" in e) || e.forId !== this._parseRequestId) return;
1603
+ if (this._rearmParseWatchdog(), e.type === "measureHostFontLines") {
1604
+ an(e.routes).catch(() => []).then((t) => {
1605
+ e.forId === this._parseRequestId && this._worker.postMessage({
1606
+ type: "hostFontLinesMeasured",
1607
+ forId: e.forId,
1608
+ measurements: t
1609
+ });
1610
+ });
1611
+ return;
1612
+ }
1613
+ if (e.type === "measureNativeRouteLines") {
1614
+ Je(e.requests, !1).then((e) => e.lines, () => e.requests.map(() => null)).then((t) => {
1615
+ e.forId === this._parseRequestId && this._worker.postMessage({
1616
+ type: "nativeRouteLinesMeasured",
1617
+ forId: e.forId,
1618
+ lines: t
1619
+ });
1620
+ });
1621
+ return;
1622
+ }
1623
+ let t = this._progressive;
1624
+ if (t?.settled) return;
1625
+ if (e.type === "layoutProgress") {
1626
+ this._layoutObservers.notify("onLayoutProgress", t?.onProgress, { committedUnits: e.committedPages });
1627
+ return;
1628
+ }
1629
+ if (e.type !== "layoutPartial" || !t) return;
1630
+ let n = !t.published || this._isLayoutViewActive(t.layoutOptions);
1631
+ if (n && this._applyLayoutPartial(e.partial), t.published) {
1632
+ if (!n) return;
1633
+ G(this, {
1634
+ pageCount: e.partial.pageCount,
1635
+ exact: e.partial.exact,
1636
+ complete: !1,
1637
+ ...e.partial.unchangedPages === void 0 ? {} : { unchangedPages: e.partial.unchangedPages }
1638
+ }), this._layoutObservers.notify("onLayoutPartial", t.onPartial, {
1639
+ availableUnits: e.partial.pageCount,
1640
+ exact: e.partial.exact
1641
+ });
1642
+ return;
1643
+ }
1644
+ t.published = !0, this._layoutLifecycle.begin(), G(this, {
1645
+ pageCount: e.partial.pageCount,
1646
+ exact: e.partial.exact,
1647
+ complete: !1
1648
+ }), t.firstPublication.resolve();
1649
+ }
1650
+ _applyLayoutPartial(e) {
1651
+ let t = e.review ?? this._meta;
1652
+ this._meta = {
1653
+ pageCount: e.pageCount,
1654
+ pageSizes: e.pageSizes,
1655
+ bookmarkPages: e.bookmarkPages,
1656
+ revisions: t?.revisions ?? [],
1657
+ comments: t?.comments ?? [],
1658
+ footnotes: t?.footnotes ?? [],
1659
+ endnotes: t?.endnotes ?? [],
1660
+ diagnostics: e.diagnostics,
1661
+ resourceDiagnostics: e.review?.resourceDiagnostics ?? this._meta?.resourceDiagnostics,
1662
+ commentAnchorRanges: e.commentAnchorRanges,
1663
+ revisionAnchorRanges: e.revisionAnchorRanges
1664
+ }, e.review && (this._review = Y(e.review.comments, e.review.revisions)), this._invalidateLayoutDerivedCaches();
1665
+ }
1666
+ _onAuthoritativeMeta(e, t) {
1667
+ this._clearParseWatchdog();
1668
+ let n = this._progressive;
1669
+ if (n?.settled) return;
1670
+ let r = n !== null && this._meta !== null && this._isLayoutViewActive(n.layoutOptions);
1671
+ if (!n || this._isLayoutViewActive(n.layoutOptions) || !this._meta) this._meta = e;
1672
+ else {
1673
+ let t = this._meta;
1674
+ this._meta = {
1675
+ ...e,
1676
+ diagnostics: t.diagnostics,
1677
+ pageCount: t.pageCount,
1678
+ pageSizes: t.pageSizes,
1679
+ bookmarkPages: t.bookmarkPages,
1680
+ commentAnchorRanges: t.commentAnchorRanges,
1681
+ revisionAnchorRanges: t.revisionAnchorRanges
1682
+ };
1683
+ }
1684
+ this._invalidateLayoutDerivedCaches(), this._review = Y(e.comments, e.revisions), n && (n.settled = !0, this._layoutLifecycle.succeed(), G(this, {
1685
+ pageCount: this.pageCount,
1686
+ exact: !0,
1687
+ complete: !0,
1688
+ ...r && t !== void 0 ? { unchangedPages: t } : {}
1689
+ }), n.firstPublication.resolve(), this._layoutObservers.notify("onLayoutComplete", n.onComplete));
1690
+ }
1691
+ _invalidateLayoutDerivedCaches() {
1692
+ this._bookmarkPages = null, this._commentAnchorRanges = null, this._revisionAnchorRanges = null, this._reviewProjectionIndex = null;
1693
+ }
1694
+ _replaceMainLayoutPublication(e, t, n, r) {
1695
+ let i = e.replaceIfCurrent(t, n, r);
1696
+ return i !== null && this._isLayoutViewActive(t) && this._invalidateLayoutDerivedCaches(), i;
1697
+ }
1698
+ _isLayoutViewActive(e) {
1699
+ return xr(O(this).activeLayoutOptions, e);
1700
+ }
1701
+ _rearmParseWatchdog() {
1702
+ this._parseWatchdogMs !== void 0 && (clearTimeout(this._parseWatchdog), this._parseWatchdog = setTimeout(() => this._onParseWentSilent(), this._parseWatchdogMs));
1703
+ }
1704
+ _clearParseWatchdog() {
1705
+ clearTimeout(this._parseWatchdog), this._parseWatchdog = void 0, this._parseWatchdogMs = void 0;
1706
+ }
1707
+ _onParseWentSilent() {
1708
+ let e = this._progressive, t = this._parseWatchdogMs;
1709
+ this._clearParseWatchdog();
1710
+ let n = /* @__PURE__ */ Error(`worker layout produced no progress for ${t}ms`);
1711
+ e && this._failWorkerProgressive(e, n), this._bridge.terminate();
1712
+ }
1713
+ _failWorkerProgressive(e, t) {
1714
+ if (e.settled) return;
1715
+ if (e.settled = !0, this._clearParseWatchdog(), !e.published) {
1716
+ e.firstPublication.reject(t);
1717
+ return;
1718
+ }
1719
+ let n = this._layoutLifecycle.fail(t);
1720
+ G(this, {
1721
+ pageCount: this.pageCount,
1722
+ exact: !1,
1723
+ complete: !1,
1724
+ error: n
1725
+ }), this._layoutObservers.notify("onLayoutComplete", e.onComplete, n);
1726
+ }
1727
+ _parseViewFields() {
1728
+ let e = O(this), t = e.activeLayoutOptions;
1729
+ return t ? {
1730
+ ...t.currentDateMs === e.defaultCurrentDateMs ? {} : { currentDateMs: t.currentDateMs },
1731
+ ...t.showTrackedChanges === !0 ? { showTrackedChanges: !0 } : {}
1732
+ } : {};
1733
+ }
1734
+ async _parseProgressively(e, t, n, r, i, a, o) {
1735
+ this._progressive = o, this._layoutAbort = o.abort, this._parseWatchdogMs = r;
1736
+ let s = this._bridge.request((r) => (this._parseRequestId = r, {
1737
+ type: "parse",
1738
+ id: r,
1739
+ data: e,
1740
+ resourcePolicy: t,
1741
+ useGoogleFonts: n,
1742
+ allowFootnoteContinuation: this._allowFootnoteContinuation,
1743
+ cjkFallback: this._cjkFallback,
1744
+ defaultCurrentDateMs: O(this).defaultCurrentDateMs,
1745
+ ...this._parseViewFields(),
1746
+ renderers: a,
1747
+ progressiveLayout: !0
1748
+ }), [e], { timeoutMs: !1 });
1749
+ this._layoutCompletion = s.then(async (e) => {
1750
+ if (this._parseRequestId = null, "protocol" in e) throw Error("DOCX parse open returned a pull-protocol response");
1751
+ if ("usage" in e && e.usage && i?.(e.usage), e.type === "mainThreadVerticalFallback") {
1752
+ this._clearParseWatchdog(), o.settled = !0, this._progressive = null, this._layoutAbort = null;
1753
+ let t = await Qe(this._bridge.transport(nt), e, {
1754
+ timeoutMs: r,
1755
+ onUsage: i
1756
+ });
1757
+ this._source = t.source, this._document = t.document, this._meta = null, this._mode = "main", this._mainThreadFallbackReason = e.reason ?? "vertical", this._review = Y(t.document.comments ?? [], t.document.revisions ?? []), o.firstPublication.resolve();
1758
+ return;
1759
+ }
1760
+ let t = e;
1761
+ this._onAuthoritativeMeta(t.meta, t.unchangedPages);
1762
+ }, (e) => {
1763
+ if (this._parseRequestId = null, this._clearParseWatchdog(), !o.settled) {
1764
+ if (o.abort.signal.aborted) {
1765
+ o.settled = !0, this._layoutLifecycle.succeed(), o.firstPublication.resolve();
1766
+ return;
1767
+ }
1768
+ this._failWorkerProgressive(o, e);
1769
+ }
1770
+ }), this._rearmParseWatchdog(), await o.firstPublication.promise;
1771
+ }
1772
+ destroy() {
1773
+ 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 = wr, O(this).services = null, this._bookmarkPages = null, this._commentAnchorRanges = null, this._revisionAnchorRanges = null, this._reviewProjectionIndex = null, this._rawParts.clear(), this._embeddedFontFaces.length > 0 && (w(this._embeddedFontFaces), this._embeddedFontFaces = []), this._officeFontFaces.length > 0 && (m(this._officeFontFaces), this._officeFontFaces = []), this._nativeRouteFacesReleased = !0, this._nativeRouteFaces?.length > 0 && (m(this._nativeRouteFaces), this._nativeRouteFaces = []), this._googleFontFaces.length > 0 && (f(this._googleFontFaces), this._googleFontFaces = []), _(this._fetchImage), b(this._fetchImage);
1774
+ }
1775
+ async getImage(e, t) {
1776
+ return this._rawParts.get(e, t, () => this._bridge.request((t) => ({
1777
+ type: "extractImage",
1778
+ id: t,
1779
+ path: e
1780
+ })).then((e) => {
1781
+ let n = e.bytes;
1782
+ return new Blob([n], { type: t });
1783
+ }));
1784
+ }
1785
+ async getFontBytes(e) {
1786
+ let t = (await this._bridge.request((t) => ({
1787
+ type: "extractImage",
1788
+ id: t,
1789
+ path: e
1790
+ }))).bytes;
1791
+ return new Uint8Array(t);
1792
+ }
1793
+ async _resourceUsage(e) {
1794
+ return (await this._bridge.request((e) => ({
1795
+ type: "resourceUsage",
1796
+ id: e
1797
+ }), void 0, { timeoutMs: e })).usage;
1798
+ }
1799
+ async getResourceMetrics() {
1800
+ let e = this._metrics;
1801
+ if (!e) throw Error("Document not loaded");
1802
+ return s(e, (e) => this._resourceUsage(e));
1803
+ }
1804
+ async toMarkdown() {
1805
+ return (await this._bridge.request((e) => ({
1806
+ type: "toMarkdown",
1807
+ id: e
1808
+ }))).markdown;
1809
+ }
1810
+ get pageCount() {
1811
+ return this._meta ? this._meta.pageCount : this._document ? this._getLayout()?.pages.length ?? 0 : 0;
1812
+ }
1813
+ get layoutComplete() {
1814
+ return this._layoutLifecycle.complete;
1815
+ }
1816
+ async waitUntilLayoutComplete() {
1817
+ this._layoutCompletion && await this._layoutCompletion, this._layoutLifecycle.throwIfFailed();
1818
+ }
1819
+ get mode() {
1820
+ return this._mode;
1821
+ }
1822
+ get document() {
1823
+ 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");
1824
+ if (!this._document) throw Error("Document not loaded");
1825
+ return this._document;
1826
+ }
1827
+ get comments() {
1828
+ return this._reviewSnapshot().comments;
1829
+ }
1830
+ get revisions() {
1831
+ return this._reviewSnapshot().revisions;
1832
+ }
1833
+ commentAnchorRanges() {
1834
+ if (this._meta) return this._meta.commentAnchorRanges ?? Sr;
1835
+ if (!this._document || !this._source) return [];
1836
+ let e = this._reviewSnapshot().comments;
1837
+ if (e.length === 0) return Sr;
1838
+ let t = O(this), n = t.services;
1839
+ if (!n) throw Error("Document layout services are not initialized");
1840
+ let r = ze(n);
1841
+ if (!r) throw Error("Document layout variant store is not initialized");
1842
+ let i = t.activeLayoutOptions, a = i ? r.layoutFor(i) : r.defaultLayout;
1843
+ this._reviewProjectionIndex ??= He(a);
1844
+ let o = this._layoutLifecycle?.complete ?? !0 ? void 0 : { completedSourceKeys: this._reviewProjectionIndex.completedSourceKeys };
1845
+ return this._commentAnchorRanges ??= Qn(e, this._source, this._reviewProjectionIndex.renderedRunIndex, o), this._commentAnchorRanges;
1846
+ }
1847
+ revisionAnchorRanges() {
1848
+ if (this._meta) return this._meta.revisionAnchorRanges ?? Cr;
1849
+ if (!this._document || !this._source) return [];
1850
+ let e = this._reviewSnapshot().revisions;
1851
+ if (e.length === 0) return Cr;
1852
+ let t = O(this), n = t.services;
1853
+ if (!n) throw Error("Document layout services are not initialized");
1854
+ let r = ze(n);
1855
+ if (!r) throw Error("Document layout variant store is not initialized");
1856
+ let i = t.activeLayoutOptions, a = i ? r.layoutFor(i) : r.defaultLayout;
1857
+ this._reviewProjectionIndex ??= He(a);
1858
+ let o = this._layoutLifecycle?.complete ?? !0 ? void 0 : { completedSourceKeys: this._reviewProjectionIndex.completedSourceKeys };
1859
+ return this._revisionAnchorRanges ??= cr(e, this._source, this._reviewProjectionIndex.renderedRunIndex, o), this._revisionAnchorRanges;
1860
+ }
1861
+ _reviewSnapshot() {
1862
+ return this._review ||= Y(this._meta?.comments ?? this._document?.comments ?? [], this._meta?.revisions ?? this._document?.revisions ?? []), this._review;
1863
+ }
1864
+ get footnotes() {
1865
+ return this._meta?.footnotes ?? this._document?.footnotes ?? [];
1866
+ }
1867
+ get endnotes() {
1868
+ return this._meta?.endnotes ?? this._document?.endnotes ?? [];
1869
+ }
1870
+ _getLayout() {
1871
+ if (!this._document) return null;
1872
+ let e = O(this), t = e.services;
1873
+ if (!t) throw Error("Document layout services are not initialized");
1874
+ let n = ze(t);
1875
+ if (!n) throw Error("Document layout variant store is not initialized");
1876
+ let r = e.activeLayoutOptions;
1877
+ return r ? n.layoutFor(r) : n.defaultLayout;
1878
+ }
1879
+ async setLayoutView(e = {}) {
1880
+ let t = e[gr], n = O(this), r = A(e.currentDate, n.defaultCurrentDateMs, e.showTrackedChanges === !0), i = ++this._layoutViewGeneration, a = n.activeLayoutOptions;
1881
+ if (!xr(a, r)) {
1882
+ if (this._mode === "worker" && this._meta) {
1883
+ let e = await this._bridge.request((e) => ({
1884
+ type: "selectLayoutView",
1885
+ id: e,
1886
+ currentDateMs: r.currentDateMs,
1887
+ showTrackedChanges: r.showTrackedChanges === !0
1888
+ }));
1889
+ if (i !== this._layoutViewGeneration) return;
1890
+ let a = e;
1891
+ n.activeLayoutOptions = r, this._meta = {
1892
+ ...this._meta,
1893
+ ...a.meta
1894
+ }, this._invalidateLayoutDerivedCaches(), vr(this, t);
1895
+ return;
1896
+ }
1897
+ n.activeLayoutOptions = r, this._invalidateLayoutDerivedCaches(), vr(this, t);
1898
+ }
1899
+ }
1900
+ _getBookmarkPages() {
1901
+ if (this._bookmarkPages) return this._bookmarkPages;
1902
+ if (this._meta) return this._bookmarkPages = new Map(this._meta.bookmarkPages), this._bookmarkPages;
1903
+ let e = this._getLayout();
1904
+ return e ? (this._bookmarkPages = _n(e), this._bookmarkPages) : null;
1905
+ }
1906
+ getBookmarkPage(e) {
1907
+ return this._getBookmarkPages()?.get(e);
1908
+ }
1909
+ pageSize(e) {
1910
+ if (this._meta) {
1911
+ let t = this._meta.pageSizes, n = t[Math.max(0, Math.min(e, t.length - 1))];
1912
+ return n ? {
1913
+ widthPt: n.widthPt,
1914
+ heightPt: n.heightPt
1915
+ } : {
1916
+ widthPt: 0,
1917
+ heightPt: 0
1918
+ };
1919
+ }
1920
+ if (!this._document) return {
1921
+ widthPt: 0,
1922
+ heightPt: 0
1923
+ };
1924
+ let t = this._getLayout();
1925
+ if (!t || t.pages.length === 0) return {
1926
+ widthPt: 0,
1927
+ heightPt: 0
1928
+ };
1929
+ let n = Math.max(0, Math.min(e, t.pages.length - 1)), r = t.pages[n].geometry;
1930
+ return {
1931
+ widthPt: r.widthPt,
1932
+ heightPt: r.heightPt
1933
+ };
1934
+ }
1935
+ _withActiveView(e) {
1936
+ let t = O(this).activeLayoutOptions;
1937
+ if (!t) return e;
1938
+ let n = { ...e };
1939
+ return e.currentDate === void 0 && (n.currentDate = t.currentDateMs), e.showTrackedChanges === void 0 && t.showTrackedChanges === !0 && (n.showTrackedChanges = !0), n;
1940
+ }
1941
+ renderPage(e, t, n = {}) {
1942
+ return this._renderPageWithTargetOwnership(e, t, n, !0);
1943
+ }
1944
+ _renderPageWithTargetOwnership(e, t, n, r) {
1945
+ if (this._mode === "worker") throw Error("renderPage(canvas) is unavailable in mode: 'worker'; use renderPageToBitmap() and paint it via an ImageBitmapRenderingContext");
1946
+ if (!this._source) throw Error("Document not loaded");
1947
+ return Ke(this._source, e, t, {
1948
+ ...this._withActiveView(n),
1949
+ onDiagnostic: (e) => F(this, [e]),
1950
+ callerOwnedCanvasTarget: r,
1951
+ fetchImage: this._fetchImage,
1952
+ layoutServices: O(this).services ?? void 0,
1953
+ defaultCurrentDateMs: O(this).defaultCurrentDateMs,
1954
+ threeD: this._threeD,
1955
+ regionMap: this._regionMap,
1956
+ chartEx: this._chartEx,
1957
+ tiff: this._tiff
1958
+ });
1959
+ }
1960
+ async renderPageToBitmap(e, t = {}) {
1961
+ let { onTextRun: n, ...r } = t, i = {
1962
+ ...this._withActiveView(r),
1963
+ dpr: r.dpr ?? c()
1964
+ };
1965
+ if (this._mode === "worker") {
1966
+ let t = new OffscreenCanvas(1, 1), r = await this._bridge.request((n) => ({
1967
+ type: "renderPage",
1968
+ id: n,
1969
+ pageIndex: e,
1970
+ opts: i,
1971
+ canvas: t
1972
+ }), [t]);
1973
+ try {
1974
+ if (F(this, r.diagnostics), n) for (let e of r.runs) n(e);
1975
+ } catch (e) {
1976
+ throw te(r.bitmap), e;
1977
+ }
1978
+ return r.bitmap;
1979
+ }
1980
+ let a = new OffscreenCanvas(1, 1);
1981
+ return await this._renderPageWithTargetOwnership(a, e, {
1982
+ ...i,
1983
+ onTextRun: n
1984
+ }, !1), a.transferToImageBitmap();
1985
+ }
1986
+ async collectPageRuns(e, t = {}) {
1987
+ let n = { ...this._withActiveView(t) };
1988
+ if (this._mode === "worker") return (await this._bridge.request((t) => ({
1989
+ type: "collectRuns",
1990
+ id: t,
1991
+ pageIndex: e,
1992
+ opts: n
1993
+ }))).runs;
1994
+ let r = O(this), i = r.services;
1995
+ if (!i) throw Error("Document layout services are not initialized");
1996
+ return Ne(i, e, {
1997
+ currentDate: n.currentDate,
1998
+ defaultCurrentDateMs: r.defaultCurrentDateMs,
1999
+ width: n.width,
2000
+ showTrackedChanges: n.showTrackedChanges
2001
+ });
2002
+ }
2003
+ async getCommentThreads(e, t = {}) {
2004
+ let { includeResolved: n, ...r } = t, i = await this.collectPageRuns(e, r);
2005
+ return tr(this.comments, this.commentAnchorRanges(), i, { includeResolved: n });
2006
+ }
2007
+ async getElementContextAt(e, t, n = {}) {
2008
+ let r = this._withActiveView(n);
2009
+ if (this._mode === "worker") return (await this._bridge.request((n) => ({
2010
+ type: "hitTestElement",
2011
+ id: n,
2012
+ pageIndex: e,
2013
+ point: t,
2014
+ opts: r
2015
+ }))).context;
2016
+ let i = O(this), a = i.services;
2017
+ if (!a) throw Error("Document layout services are not initialized");
2018
+ return Bn(a, e, t, {
2019
+ ...r,
2020
+ defaultCurrentDateMs: i.defaultCurrentDateMs
2021
+ });
2022
+ }
2023
+ };
2024
+ //#endregion
2025
+ //#region packages/docx/src/tate-chu-yoko-overlay.ts
2026
+ function Tr(e, t) {
2027
+ if (!e.eastAsianVert) return 1;
2028
+ let n = t(e.text);
2029
+ return !(n > 0) || e.w >= n ? 1 : e.w / n;
2030
+ }
2031
+ //#endregion
2032
+ //#region packages/docx/src/text-layer.ts
2033
+ function Z(e, t, n, r, i, a, o) {
2034
+ e.innerHTML = "", T(e, "ooxmlSelectionSurface", "docx"), T(e, "pageIndex", o === void 0 ? void 0 : String(o));
2035
+ let s = e.ownerDocument ?? document;
2036
+ for (let [o, c] of t.entries()) {
2037
+ let t = s.createElement("span");
2038
+ T(t, "ooxmlSelectionRun", "docx"), T(t, "runIndex", String(o)), c.paragraphId !== void 0 && T(t, "paragraphId", c.paragraphId), c.source !== void 0 && (T(t, "sourceStory", c.source.story), T(t, "sourceStoryInstance", c.source.storyInstance), T(t, "sourcePath", JSON.stringify(c.source.path))), t.textContent = c.text;
2039
+ let l = c.transform ?? "";
2040
+ if (a && c.eastAsianVert) {
2041
+ let e = Tr(c, a(c.font));
2042
+ e !== 1 && (l = `${l ? `${l} ` : ""}scaleX(${e})`);
2043
+ }
2044
+ 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`, m = c.trailingSpaceCompressionPx === void 0 ? "" : `width:${C(c.w, n)};overflow:hidden;`;
2045
+ t.style.cssText = `position:absolute;left:${C(c.x, n)};top:${C(c.y, r)};font:${c.font};line-height:${c.h}px;letter-spacing:${p};` + m + 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) => {
2046
+ e.preventDefault(), i(d);
2047
+ })), e.appendChild(t);
2048
+ }
2049
+ }
2050
+ function Er(e, t, n, r, i, a, o = {}) {
2051
+ e.innerHTML = "";
2052
+ let s = o.match ?? "rgba(255, 214, 0, 0.42)", c = o.active ?? "rgba(255, 140, 0, 0.55)";
2053
+ for (let o of n) {
2054
+ let n = o.active ? c : s;
2055
+ for (let s of o.slices) {
2056
+ let o = t[s.runIndex];
2057
+ if (!o) continue;
2058
+ let c = a(o.font), l = ie(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 = Ye(o.text.slice(d, f)).pitchBearing, m = Ye(o.text.slice(0, d)).pitchBearing, h = l.x + m * u, g = l.width + Math.max(0, p - 1) * u, _ = Tr(o, c), ee = h * _, v = g * _;
2059
+ if (v <= 0) continue;
2060
+ let y = document.createElement("div"), b = o.transform ? `transform:${o.transform};transform-origin:top left;` : "";
2061
+ y.style.cssText = `position:absolute;left:${C(o.x + ee, r)};top:${C(o.y, i)};width:${C(v, r)};height:${C(o.h, i)};` + b + `background:${n};pointer-events:none;`, e.appendChild(y);
2062
+ }
2063
+ }
2064
+ }
2065
+ //#endregion
2066
+ //#region packages/docx/src/find.ts
2067
+ var Dr = class extends S {
2068
+ constructor(e, t) {
2069
+ super(e, t, (e) => ({ page: e }));
2070
+ }
2071
+ pageRuns(e) {
2072
+ return this.unitRuns(e);
2073
+ }
2074
+ setPageRuns(e, t) {
2075
+ this.setUnitRuns(e, t);
2076
+ }
2077
+ pageHighlights(e) {
2078
+ return this.unitHighlights(e);
2079
+ }
2080
+ activePage() {
2081
+ return this.activeUnit();
2082
+ }
2083
+ };
2084
+ //#endregion
2085
+ //#region packages/docx/src/selection-context.ts
2086
+ function Or(e, t, n, r, i = {}) {
2087
+ let a = e.find((e) => e.id === n && e.parentId === void 0);
2088
+ if (!a) return null;
2089
+ let o = new Map(e.map((e) => [e.id, e])), s = e.filter((e) => {
2090
+ if (e.parentId === void 0) return !1;
2091
+ let t = e, n = /* @__PURE__ */ new Set();
2092
+ for (; t.parentId !== void 0 && !n.has(t.id);) {
2093
+ n.add(t.id);
2094
+ let e = o.get(t.parentId);
2095
+ if (!e) return !1;
2096
+ if (e.id === a.id) return !0;
2097
+ t = e;
2098
+ }
2099
+ return !1;
2100
+ }), c = Ae({
2101
+ id: a.id,
2102
+ author: a.author,
2103
+ date: a.date,
2104
+ text: a.paragraphs?.join("\n") ?? a.text,
2105
+ status: a.resolved ? "resolved" : "active"
2106
+ }, s.map((e) => ({
2107
+ id: e.id,
2108
+ author: e.author,
2109
+ date: e.date,
2110
+ text: e.paragraphs?.join("\n") ?? e.text,
2111
+ status: e.resolved ? "resolved" : "active"
2112
+ })), i.maxTextCharacters), l = t.find((e) => e.commentId === n)?.source;
2113
+ return Object.freeze({
2114
+ format: "docx",
2115
+ kind: "comment",
2116
+ pageIndex: r,
2117
+ commentId: n,
2118
+ ...l ? { source: Object.freeze({
2119
+ ...l,
2120
+ path: Object.freeze([...l.path])
2121
+ }) } : {},
2122
+ thread: c.thread,
2123
+ truncated: c.truncated,
2124
+ truncationReasons: c.truncated ? ["text"] : [],
2125
+ textCharacters: c.textCharacters,
2126
+ maxTextCharacters: c.maxTextCharacters
2127
+ });
2128
+ }
2129
+ function kr(e) {
2130
+ for (let t = e; t; t = t.parentElement) {
2131
+ let e = Oe(t.dataset.pageIndex);
2132
+ if (e !== null) return e;
2133
+ }
2134
+ return null;
2135
+ }
2136
+ var Ar = new Set([
2137
+ "body",
2138
+ "header",
2139
+ "footer",
2140
+ "footnote",
2141
+ "endnote",
2142
+ "textbox"
2143
+ ]);
2144
+ function jr(e) {
2145
+ let t = e.dataset.sourceStory, n = e.dataset.sourceStoryInstance, r = e.dataset.sourcePath;
2146
+ if (!t || !Ar.has(t) || !n || !r) return null;
2147
+ try {
2148
+ let e = JSON.parse(r);
2149
+ return !Array.isArray(e) || e.length === 0 || e.length > 32 || !e.every((e) => Number.isSafeInteger(e) && e >= 0) ? null : {
2150
+ story: t,
2151
+ storyInstance: n,
2152
+ path: [...e]
2153
+ };
2154
+ } catch {
2155
+ return null;
2156
+ }
2157
+ }
2158
+ function Q(e, t, n = {}) {
2159
+ let r = _t(e, t, (e) => {
2160
+ let t = kr(e), n = Oe(e.dataset.runIndex);
2161
+ return t === null || n === null ? null : {
2162
+ pageIndex: t,
2163
+ runIndex: n,
2164
+ ...e.dataset.paragraphId === void 0 ? {} : { paragraphId: e.dataset.paragraphId },
2165
+ ...jr(e) === null ? {} : { source: jr(e) }
2166
+ };
2167
+ }, {
2168
+ maxChars: n.maxTextCharacters,
2169
+ maxLocators: n.maxRunLocators
2170
+ });
2171
+ if (!r) return null;
2172
+ let i = [...r.locators].sort((e, t) => e.pageIndex - t.pageIndex || e.runIndex - t.runIndex);
2173
+ return {
2174
+ format: "docx",
2175
+ kind: "text",
2176
+ text: r.text,
2177
+ pageIndexes: [...new Set(i.map((e) => e.pageIndex))],
2178
+ paragraphIds: [...new Set(i.flatMap((e) => e.paragraphId ? [e.paragraphId] : []))],
2179
+ runs: i,
2180
+ truncated: r.truncated,
2181
+ truncationReasons: r.truncationReasons,
2182
+ textCharacters: r.textCharacters,
2183
+ maxTextCharacters: r.maxTextCharacters,
2184
+ maxRunLocators: r.maxLocators
2185
+ };
2186
+ }
2187
+ //#endregion
2188
+ //#region packages/docx/src/focused-view-runtime.ts
2189
+ function $(e, t, n, r, i) {
2190
+ return r === "worker" ? e.renderPageToBitmap(n, i) : e.renderPage(t, n, i);
2191
+ }
2192
+ //#endregion
2193
+ //#region packages/docx/src/viewer.ts
2194
+ var Mr = Symbol("DocxViewer.borrowedDocument"), Nr = class e {
2195
+ _pendingLoadAbort = null;
2196
+ _pendingRequestedView;
2197
+ _pendingViewChanged = null;
2198
+ _documentOwner;
2199
+ get _doc() {
2200
+ return this._documentOwner.current;
2201
+ }
2202
+ _borrowed;
2203
+ _hostWindow;
2204
+ _currentPage = 0;
2205
+ _scale = null;
2206
+ _canvas;
2207
+ _wrapper;
2208
+ _canvasMount;
2209
+ _textLayer = null;
2210
+ _highlightLayer = null;
2211
+ _elementLayer = null;
2212
+ _find;
2213
+ _findRequestGeneration = 0;
2214
+ _measureCtx = null;
2215
+ _opts;
2216
+ _showTrackedChangesExplicit = !1;
2217
+ _mode;
2218
+ _renderDispatcher;
2219
+ _errorRouter;
2220
+ _destroyed = !1;
2221
+ _selectionChangeListener = null;
2222
+ _selectionContextKey = "null";
2223
+ _elementContext = null;
2224
+ _elementHitGeneration = 0;
2225
+ _layoutViewGeneration = 0;
2226
+ _layoutViewPublicationGeneration = 0;
2227
+ _navigationGeneration = 0;
2228
+ _layoutUnsubscribe = null;
2229
+ _internalHyperlinkGeneration = 0;
2230
+ _layoutWaiters = /* @__PURE__ */ new Set();
2231
+ _layoutFailed = !1;
2232
+ _loadingIndicator;
2233
+ _elementClickListener = null;
2234
+ _contextMenuListener = null;
2235
+ static fromDocument(t, n, r = {}) {
2236
+ let i = q(n);
2237
+ return new e(t, {
2238
+ ...r,
2239
+ currentDate: i.currentDate,
2240
+ showTrackedChanges: i.showTrackedChanges,
2241
+ [Mr]: n
2242
+ });
2243
+ }
2244
+ constructor(e, t = {}) {
2245
+ this._canvas = e, this._opts = t, this._showTrackedChangesExplicit = t.showTrackedChanges !== void 0;
2246
+ let n = t[Mr];
2247
+ this._borrowed = n !== void 0, this._mode = Ot("DocxViewer", t.mode, n), this._documentOwner = new Ct("DocxViewer", n ?? null, !1);
2248
+ let r = e.ownerDocument?.defaultView ?? (typeof window < "u" ? window : null);
2249
+ if (!r) throw Error("DocxViewer requires a canvas with an active Window");
2250
+ this._hostWindow = r, this._canvasMount = new Dt(e, {
2251
+ wrapperCssText: "position:relative;display:inline-block;vertical-align:top;",
2252
+ forceDisplayBlock: !0
2253
+ }), this._wrapper = this._canvasMount.wrapper, this._renderDispatcher = new ht(e, this._mode === "worker"), this._errorRouter = new bt("DocxViewer", t.onError);
2254
+ let i = new Tt(this._wrapper, t.enableTextSelection === !0, t.enableElementSelection === !0);
2255
+ this._textLayer = i.textLayer, this._highlightLayer = i.highlightLayer, this._elementLayer = i.elementLayer, this._loadingIndicator = new St(this._wrapper, "Loading page");
2256
+ let a = this._wrapper.ownerDocument.createElement("progress");
2257
+ a.setAttribute("aria-hidden", "true"), this._loadingIndicator.layer.appendChild(a), this._wrapper.insertBefore(this._loadingIndicator.layer, this._elementLayer), this._textLayer && (t.onSelectionContextChange || t.enableElementSelection) && (this._selectionChangeListener = () => this._emitSelectionContextChange(), this._wrapper.ownerDocument.addEventListener("selectionchange", this._selectionChangeListener)), t.enableElementSelection && (this._elementClickListener = (e) => {
2258
+ this._onElementClick(e).catch((e) => this._reportRenderError(e));
2259
+ }, this._wrapper.addEventListener("click", this._elementClickListener)), t.onContextMenu && (this._contextMenuListener = (e) => this._onContextMenu(e), this._wrapper.addEventListener("contextmenu", this._contextMenuListener)), this._find = new Dr(() => this.pageCount, (e) => this._collectPageRuns(e)), n && this._bindLayoutDocument(n);
2260
+ }
2261
+ async load(e) {
2262
+ if (this._destroyed) throw Error("DocxViewer is destroyed");
2263
+ if (this._borrowed) throw Error("DocxViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
2264
+ let t = !1, n = this._pendingRequestedView;
2265
+ this._pendingLoadAbort?.abort();
2266
+ let r = new AbortController();
2267
+ this._pendingLoadAbort = r, this._pendingRequestedView = n;
2268
+ try {
2269
+ let i = await this._documentOwner.replace(async () => {
2270
+ let t = await X.load(e, {
2271
+ password: this._opts.password,
2272
+ useGoogleFonts: this._opts.useGoogleFonts,
2273
+ allowFootnoteContinuation: this._opts.allowFootnoteContinuation,
2274
+ cjkFallback: this._opts.cjkFallback,
2275
+ maxZipEntryBytes: this._opts.maxZipEntryBytes,
2276
+ resourceLimits: this._opts.resourceLimits,
2277
+ debug: this._opts.debug,
2278
+ onResourceMetrics: this._opts.onResourceMetrics,
2279
+ workerTimeoutMs: this._opts.workerTimeoutMs,
2280
+ wasmUrl: this._opts.wasmUrl,
2281
+ math: this._opts.math,
2282
+ threeD: this._opts.threeD,
2283
+ regionMap: this._opts.regionMap,
2284
+ chartEx: this._opts.chartEx,
2285
+ tiff: this._opts.tiff,
2286
+ mode: this._mode,
2287
+ ...this._opts.progressiveLayout ? { progressiveLayout: !0 } : {},
2288
+ ...this._opts.sliceLayout === void 0 ? {} : { sliceLayout: this._opts.sliceLayout },
2289
+ [br]: {
2290
+ signal: r.signal,
2291
+ requestedView: () => this._pendingRequestedView,
2292
+ subscribeViewChange: (e) => (this._pendingViewChanged = e, () => {
2293
+ this._pendingViewChanged === e && (this._pendingViewChanged = null);
2294
+ })
2295
+ },
2296
+ onLayoutProgress: this._opts.onLayoutProgress,
2297
+ onLayoutPartial: this._opts.onLayoutPartial,
2298
+ onLayoutComplete: this._opts.onLayoutComplete,
2299
+ ...n === void 0 ? this._opts.legacyDoc === void 0 ? this._opts.showTrackedChanges === !0 ? { showTrackedChanges: !0 } : {} : this._showTrackedChangesExplicit ? { showTrackedChanges: this._opts.showTrackedChanges } : void 0 : { showTrackedChanges: n },
2300
+ ...this._opts.legacyDoc === void 0 ? void 0 : { legacyDoc: this._opts.legacyDoc },
2301
+ ...this._opts.currentDate === void 0 ? {} : { currentDate: this._opts.currentDate }
2302
+ });
2303
+ return await _r(t, r.signal, () => this._pendingRequestedView, () => this._opts.currentDate, this), t;
2304
+ }, () => {
2305
+ this._invalidateElementContext(!1), t = !0, this._renderDispatcher.begin(), this._findRequestGeneration++, this._find.invalidate(), this._unbindLayoutDocument();
2306
+ });
2307
+ if (!i) return;
2308
+ if (this._destroyed) throw Error("DocxViewer is destroyed");
2309
+ if (this._pendingLoadAbort !== r || (this._pendingRequestedView !== void 0 && (this._showTrackedChangesExplicit = !0, this._opts = {
2310
+ ...this._opts,
2311
+ showTrackedChanges: this._pendingRequestedView
2312
+ }), this._currentPage = 0, this._bindLayoutDocument(i), this._find.invalidate(), await this._render(), this._pendingLoadAbort !== r)) return;
2313
+ } catch (e) {
2314
+ if (this._destroyed) throw Error("DocxViewer is destroyed");
2315
+ if (this._pendingLoadAbort !== r) return;
2316
+ throw e instanceof Error ? e : Error(String(e));
2317
+ } finally {
2318
+ this._pendingLoadAbort === r && (this._pendingLoadAbort = null, this._pendingRequestedView = void 0, this._pendingViewChanged = null);
2319
+ }
2320
+ t && !this._destroyed && this._emitSelectionContextChange();
2321
+ }
2322
+ get pageCount() {
2323
+ return this._doc?.pageCount ?? 0;
2324
+ }
2325
+ get currentPage() {
2326
+ return this._currentPage;
2327
+ }
2328
+ get layoutComplete() {
2329
+ return this._doc?.layoutComplete ?? !0;
2330
+ }
2331
+ async waitUntilLayoutComplete() {
2332
+ await this._errorRouter.ownBackgroundLifecycle(async () => {
2333
+ await this._doc?.waitUntilLayoutComplete?.();
2334
+ });
2335
+ }
2336
+ get canvasElement() {
2337
+ return this._canvas;
2338
+ }
2339
+ async goToPage(e) {
2340
+ let t = this._doc;
2341
+ if (!t) return;
2342
+ let n = this._cancelPendingNavigation(), r = Math.max(0, Number.isNaN(e) ? 0 : Math.trunc(e));
2343
+ if (r >= this.pageCount && !this.layoutComplete) {
2344
+ this._setLoading(!0);
2345
+ try {
2346
+ await this._waitForPage(t, r, n);
2347
+ } finally {
2348
+ n === this._navigationGeneration && this._setLoading(!1);
2349
+ }
2350
+ }
2351
+ if (this._destroyed || n !== this._navigationGeneration || t !== this._doc) return;
2352
+ let i = Math.max(0, Math.min(r, this.pageCount - 1)), a = i !== this._currentPage;
2353
+ a && this._invalidateElementContext(!1), this._currentPage = i, await this._render(), a && !this._destroyed && this._emitSelectionContextChange();
2354
+ }
2355
+ async nextPage() {
2356
+ await this.goToPage(this._currentPage + 1);
2357
+ }
2358
+ async prevPage() {
2359
+ await this.goToPage(this._currentPage - 1);
2360
+ }
2361
+ _naturalWidthPx() {
2362
+ return !this._doc || this._doc.pageCount === 0 ? 0 : this._doc.pageSize(this._currentPage).widthPt * n;
2363
+ }
2364
+ _renderWidth() {
2365
+ if (this._scale === null) return this._opts.width;
2366
+ let e = this._naturalWidthPx();
2367
+ return e <= 0 ? this._opts.width : Math.round(e * this._scale);
2368
+ }
2369
+ getScale() {
2370
+ if (this._scale !== null) return this._scale;
2371
+ let e = this._naturalWidthPx();
2372
+ return e <= 0 ? 1 : this._opts.width && this._opts.width > 0 ? this._opts.width / e : 1;
2373
+ }
2374
+ _zoomMin() {
2375
+ return this._opts.zoomMin ?? .1;
2376
+ }
2377
+ _zoomMax() {
2378
+ return this._opts.zoomMax ?? 4;
2379
+ }
2380
+ async setScale(e) {
2381
+ let t = kt(e, this._zoomMin(), this._zoomMax()), n = t !== this.getScale();
2382
+ this._scale = t, await this._render(), n && this._opts.onScaleChange?.(t);
2383
+ }
2384
+ async zoomIn() {
2385
+ await this.setScale(gt(this.getScale()));
2386
+ }
2387
+ async zoomOut() {
2388
+ await this.setScale(jt(this.getScale()));
2389
+ }
2390
+ async fitWidth() {
2391
+ await this._fit("width");
2392
+ }
2393
+ async fitPage() {
2394
+ await this._fit("page");
2395
+ }
2396
+ async _fit(e) {
2397
+ if (!this._doc || this._doc.pageCount === 0) return;
2398
+ let t = this._doc.pageSize(this._currentPage), r = this._fitContainer();
2399
+ if (!r) return;
2400
+ let i = Mt({
2401
+ contentWidth: t.widthPt * n,
2402
+ contentHeight: t.heightPt * n,
2403
+ containerWidth: r.clientWidth,
2404
+ containerHeight: r.clientHeight
2405
+ }, e);
2406
+ i <= 0 || await this.setScale(i);
2407
+ }
2408
+ _fitContainer() {
2409
+ return this._opts.container ?? this._wrapper.parentElement ?? null;
2410
+ }
2411
+ async findText(e, t = {}) {
2412
+ let n = this._doc;
2413
+ if (!n) return [];
2414
+ let r = ++this._findRequestGeneration;
2415
+ if (e.length > 0 && !n.layoutComplete && (await this._errorRouter.ownBackgroundLifecycle(() => n.waitUntilLayoutComplete()), this._destroyed || this._doc !== n || r !== this._findRequestGeneration)) return [];
2416
+ let i = await this._errorRouter.ownAwaitable(() => this._find.find(e, t));
2417
+ return this._redrawHighlights(), i;
2418
+ }
2419
+ async findNext() {
2420
+ return this._activateMatch(this._find.next());
2421
+ }
2422
+ async findPrev() {
2423
+ return this._activateMatch(this._find.prev());
2424
+ }
2425
+ clearFind() {
2426
+ this._findRequestGeneration++, this._find.invalidate(), this._redrawHighlights();
2427
+ }
2428
+ async _activateMatch(e) {
2429
+ return e ? (e.location.page === this._currentPage ? this._redrawHighlights() : await this.goToPage(e.location.page), e) : (this._redrawHighlights(), null);
2430
+ }
2431
+ _redrawHighlights() {
2432
+ let e = this._find.pageRuns(this._currentPage) ?? [];
2433
+ this._buildHighlightLayer(e);
2434
+ }
2435
+ async getResourceMetrics() {
2436
+ if (!this._doc) throw Error("Document not loaded");
2437
+ return await this._doc.getResourceMetrics();
2438
+ }
2439
+ getSelectionContext(e = {}) {
2440
+ if (this._destroyed) throw Error("DocxViewer is destroyed");
2441
+ return (this._textLayer ? Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null, e) : null) ?? (this._elementContext ? Vn(this._elementContext, e.maxTextCharacters) : null);
2442
+ }
2443
+ _emitSelectionContextChange() {
2444
+ let e = this.getSelectionContext();
2445
+ e?.kind === "text" && (this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutline());
2446
+ let t = JSON.stringify(e);
2447
+ t !== this._selectionContextKey && (this._selectionContextKey = t, this._opts.onSelectionContextChange?.(e ? structuredClone(e) : null));
2448
+ }
2449
+ _setElementContext(e) {
2450
+ this._elementContext = e ? structuredClone(e) : null, this._redrawElementOutline(), this._emitSelectionContextChange();
2451
+ }
2452
+ _invalidateElementContext(e = !0) {
2453
+ this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutline(), e && this._emitSelectionContextChange();
2454
+ }
2455
+ _redrawElementOutline() {
2456
+ let e = this._elementContext, t = this._doc;
2457
+ if (!e || !t || e.pageIndex !== this._currentPage) {
2458
+ xt(this._elementLayer, null);
2459
+ return;
2460
+ }
2461
+ let n = t.pageSize(e.pageIndex);
2462
+ xt(this._elementLayer, {
2463
+ x: e.bounds.xPt / n.widthPt,
2464
+ y: e.bounds.yPt / n.heightPt,
2465
+ width: e.bounds.widthPt / n.widthPt,
2466
+ height: e.bounds.heightPt / n.heightPt
2467
+ });
2468
+ }
2469
+ async _onElementClick(e) {
2470
+ this._destroyed || e.defaultPrevented || e.button !== 0 || await this._resolveContextAt(e);
2471
+ }
2472
+ _onContextMenu(e) {
2473
+ let t;
2474
+ this._opts.onContextMenu?.({
2475
+ originalEvent: e,
2476
+ getContext: () => t ??= this._resolveContextAt(e)
2477
+ });
2478
+ }
2479
+ async _resolveContextAt(e) {
2480
+ let t = this._doc;
2481
+ if (this._destroyed || !t) return null;
2482
+ if (this._textLayer && Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null)) return this._emitSelectionContextChange(), this._destroyed ? null : this.getSelectionContext();
2483
+ if (!this._opts.enableElementSelection) return this.getSelectionContext();
2484
+ let n = this._canvas.getBoundingClientRect();
2485
+ if (n.width <= 0 || n.height <= 0) return this._invalidateElementContext(), null;
2486
+ let r = e.clientX - n.left, i = e.clientY - n.top;
2487
+ if (r < 0 || i < 0 || r > n.width || i > n.height) return this._invalidateElementContext(), null;
2488
+ let a = ++this._elementHitGeneration, o = this._currentPage, s = t.pageSize(o), c;
2489
+ try {
2490
+ c = await t.getElementContextAt(o, {
2491
+ xPt: r / n.width * s.widthPt,
2492
+ yPt: i / n.height * s.heightPt
2493
+ }, {
2494
+ currentDate: this._opts.currentDate,
2495
+ showTrackedChanges: this._opts.showTrackedChanges,
2496
+ maxTextCharacters: En
2497
+ });
2498
+ } catch (e) {
2499
+ if (this._destroyed || a !== this._elementHitGeneration || o !== this._currentPage || t !== this._doc) return null;
2500
+ throw e;
2501
+ }
2502
+ return this._destroyed || a !== this._elementHitGeneration || o !== this._currentPage || t !== this._doc ? null : (this._setElementContext(c), this._destroyed ? null : this.getSelectionContext());
2503
+ }
2504
+ destroy() {
2505
+ this._destroyed || (this._destroyed = !0, this._pendingLoadAbort?.abort(), this._pendingLoadAbort = null, this._pendingViewChanged = null, this._findRequestGeneration++, this._layoutViewGeneration++, this._unbindLayoutDocument(), this._errorRouter.close(), this._renderDispatcher.destroy(), Ve(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());
2506
+ }
2507
+ async _render() {
2508
+ let e = this._renderDispatcher.begin();
2509
+ try {
2510
+ await this._renderPage(e);
2511
+ } catch (t) {
2512
+ if (!this._renderDispatcher.isCurrent(e)) return;
2513
+ throw t;
2514
+ }
2515
+ }
2516
+ _reportRenderError(e) {
2517
+ this._errorRouter.report(e);
2518
+ }
2519
+ async _renderPage(e) {
2520
+ if (!this._doc) return;
2521
+ 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), l = this._opts.dpr ?? c(), u = {
2522
+ width: n,
2523
+ dpr: this._opts.dpr,
2524
+ imageResources: this._opts.imageResources,
2525
+ defaultTextColor: this._opts.defaultTextColor,
2526
+ currentDate: this._opts.currentDate,
2527
+ showTrackedChanges: this._opts.showTrackedChanges,
2528
+ onTextRun: s
2529
+ };
2530
+ if (t) {
2531
+ let t = await $(this._doc, this._canvas, this._currentPage, "worker", u);
2532
+ if (!this._renderDispatcher.commitBitmap(e, t, {
2533
+ cssWidth: i > 0 ? i : Math.round(t.width / l),
2534
+ cssHeight: a > 0 ? a : Math.round(t.height / l)
2535
+ })) return;
2536
+ } else if (await $(this._doc, this._canvas, this._currentPage, "main", u), !this._renderDispatcher.isCurrent(e)) return;
2537
+ 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);
2538
+ }
2539
+ _clearPresentedPage() {
2540
+ this._renderDispatcher.begin(), Ve(this._canvas), this._canvas.width = 0, this._canvas.height = 0, this._textLayer?.replaceChildren(), this._find.invalidate();
2541
+ }
2542
+ _bindLayoutDocument(e) {
2543
+ this._unbindLayoutDocument(), this._layoutFailed = !1, this._layoutViewPublicationGeneration = 0;
2544
+ let t = yr(e, (t) => this._onLayoutViewPublication(e, t), (e) => this._reportRenderError(e)), n = !0, r = fr(e, () => ({
2545
+ pageCount: e.pageCount,
2546
+ exact: e.layoutComplete,
2547
+ complete: e.layoutComplete
2548
+ }), (t) => {
2549
+ if (n) {
2550
+ n = !1;
2551
+ return;
2552
+ }
2553
+ this._onLayoutPublication(e, t);
2554
+ }, (e) => this._reportRenderError(e));
2555
+ this._layoutUnsubscribe = () => {
2556
+ r(), t();
2557
+ };
2558
+ }
2559
+ _unbindLayoutDocument() {
2560
+ this._layoutUnsubscribe?.(), this._layoutUnsubscribe = null, this._layoutFailed = !1, this._cancelPendingNavigation();
2561
+ }
2562
+ _onLayoutPublication(e, t) {
2563
+ if (!(this._destroyed || e !== this._doc)) {
2564
+ if (this._wakeLayoutWaiters(), t.error !== void 0) {
2565
+ t.pageCount === 0 && this._clearPresentedPage(), this._layoutFailed = !0, this._errorRouter.reportBackground(t.error, this._opts.onLayoutComplete !== void 0);
2566
+ return;
2567
+ }
2568
+ this._find.invalidate(), this._currentPage = Math.max(0, Math.min(this._currentPage, t.pageCount - 1)), this._render().catch((e) => this._reportRenderError(e));
2569
+ }
2570
+ }
2571
+ _onLayoutViewPublication(e, t) {
2572
+ this._destroyed || e !== this._doc || t.generation <= this._layoutViewPublicationGeneration || (this._layoutViewPublicationGeneration = t.generation, t.requester !== this && (this._layoutViewGeneration++, this._opts = {
2573
+ ...this._opts,
2574
+ currentDate: t.view.currentDate,
2575
+ showTrackedChanges: t.view.showTrackedChanges
2576
+ }, this._find.invalidate(), this._currentPage = Math.max(0, Math.min(this._currentPage, e.pageCount - 1)), this._render().catch((e) => this._reportRenderError(e))));
2577
+ }
2578
+ async _waitForPage(e, t, n) {
2579
+ await this._errorRouter.ownBackgroundLifecycle(async () => {
2580
+ for (; !this._destroyed && n === this._navigationGeneration && e === this._doc && t >= e.pageCount && !e.layoutComplete && !this._layoutFailed;) await new Promise((e) => {
2581
+ this._layoutWaiters.add(e);
2582
+ });
2583
+ e === this._doc && (e.layoutComplete || this._layoutFailed) && await e.waitUntilLayoutComplete();
2584
+ });
2585
+ }
2586
+ _wakeLayoutWaiters() {
2587
+ for (let e of this._layoutWaiters) e();
2588
+ this._layoutWaiters.clear();
2589
+ }
2590
+ _cancelPendingNavigation() {
2591
+ let e = ++this._navigationGeneration;
2592
+ return this._wakeLayoutWaiters(), this._setLoading(!1), e;
2593
+ }
2594
+ _setLoading(e) {
2595
+ this._loadingIndicator.setLoading(e);
2596
+ }
2597
+ async setShowTrackedChanges(e) {
2598
+ let t = ++this._layoutViewGeneration;
2599
+ if (this._pendingLoadAbort) {
2600
+ let t = this._pendingRequestedView !== e;
2601
+ this._pendingRequestedView = e, t && this._pendingViewChanged?.();
2602
+ }
2603
+ let n = this._doc, r = this._opts.legacyDoc === void 0 ? this._opts.showTrackedChanges === !0 : n ? q(n).showTrackedChanges : this._opts.showTrackedChanges === !0;
2604
+ if ((!n || r === e) && (this._showTrackedChangesExplicit = !0, this._opts = {
2605
+ ...this._opts,
2606
+ showTrackedChanges: e
2607
+ }), r === e) {
2608
+ n && await J(n, {
2609
+ showTrackedChanges: e,
2610
+ currentDate: this._opts.currentDate
2611
+ }, this);
2612
+ return;
2613
+ }
2614
+ let i = {
2615
+ ...this._opts,
2616
+ showTrackedChanges: e
2617
+ };
2618
+ (!n || await J(n, {
2619
+ showTrackedChanges: e,
2620
+ currentDate: i.currentDate
2621
+ }, this)) && (this._destroyed || t !== this._layoutViewGeneration || n !== this._doc || (this._showTrackedChangesExplicit = !0, this._opts = i, this._find.invalidate(), this._currentPage = Math.max(0, Math.min(this._currentPage, this.pageCount - 1)), await this._render()));
2622
+ }
2623
+ _buildHighlightLayer(e) {
2624
+ let t = this._highlightLayer;
2625
+ if (!t) return;
2626
+ let { width: n, height: r } = this._canvasCssPx();
2627
+ Er(t, e, this._find.pageHighlights(this._currentPage), n, r, (e) => this._measureForFont(e), this._opts.findHighlightColors);
2628
+ }
2629
+ _canvasCssPx() {
2630
+ return {
2631
+ width: parseFloat(this._canvas.style.width) || this._canvas.width,
2632
+ height: parseFloat(this._canvas.style.height) || this._canvas.height
2633
+ };
2634
+ }
2635
+ _measureForFont(e) {
2636
+ if (!this._measureCtx) {
2637
+ let e = document.createElement("canvas");
2638
+ this._measureCtx = e.getContext("2d");
2639
+ }
2640
+ let t = this._measureCtx;
2641
+ return t ? (t.font = e, (e) => t.measureText(e).width) : (e) => e.length;
2642
+ }
2643
+ async _collectPageRuns(e) {
2644
+ return this._doc ? this._doc.collectPageRuns(e, {
2645
+ width: this._renderWidth(),
2646
+ currentDate: this._opts.currentDate,
2647
+ showTrackedChanges: this._opts.showTrackedChanges
2648
+ }) : [];
2649
+ }
2650
+ _buildTextLayer(e, t) {
2651
+ let { width: n, height: r } = this._canvasCssPx();
2652
+ Z(e, t, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), this._currentPage);
2653
+ }
2654
+ _hyperlinkHandler() {
2655
+ return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
2656
+ if (e.kind === "external") {
2657
+ v(e.url, void 0, this._hostWindow);
2658
+ return;
2659
+ }
2660
+ let t = this._doc;
2661
+ if (!t) return;
2662
+ let n = ++this._internalHyperlinkGeneration;
2663
+ this._navigateInternalHyperlink(t, e.ref, n).catch((e) => this._reportRenderError(e));
2664
+ });
2665
+ }
2666
+ async _navigateInternalHyperlink(e, t, n) {
2667
+ if (e.layoutComplete || await e.waitUntilLayoutComplete(), this._destroyed || this._doc !== e || n !== this._internalHyperlinkGeneration) return;
2668
+ let r = e.getBookmarkPage(t);
2669
+ r !== void 0 && await this.goToPage(r);
2670
+ }
2671
+ }, Pr = class {
2672
+ hooks;
2673
+ pageById = /* @__PURE__ */ new Map();
2674
+ runsByPage = /* @__PURE__ */ new Map();
2675
+ indexedPages = /* @__PURE__ */ new Set();
2676
+ frontier = 0;
2677
+ generation = 0;
2678
+ constructor(e) {
2679
+ this.hooks = e;
2680
+ }
2681
+ reset() {
2682
+ this.generation++, this.pageById.clear(), this.runsByPage.clear(), this.indexedPages.clear(), this.frontier = 0;
2683
+ }
2684
+ commitRuns(e, t) {
2685
+ this.runsByPage.set(e, {
2686
+ scale: this.hooks.scale(),
2687
+ runs: Promise.resolve(t)
2688
+ });
2689
+ let n = this.hooks.document();
2690
+ n && e === this.frontier && this.indexPage(e, t, n.commentAnchorRanges());
2691
+ }
2692
+ indexPage(e, t, n) {
2693
+ if (!this.indexedPages.has(e)) {
2694
+ for (let r of n) !this.pageById.has(r.commentId) && H(r, t).length > 0 && this.pageById.set(r.commentId, e);
2695
+ for (this.indexedPages.add(e); this.indexedPages.has(this.frontier);) this.frontier++;
2696
+ }
2697
+ }
2698
+ async runsForPage(e, t) {
2699
+ for (; !this.hooks.destroyed() && this.hooks.document() === t;) {
2700
+ let n = this.hooks.scale(), r = this.runsByPage.get(e);
2701
+ (!r || r.scale !== n) && (r = {
2702
+ scale: n,
2703
+ runs: t.collectPageRuns(e, {
2704
+ width: this.hooks.pageWidth(e),
2705
+ currentDate: this.hooks.currentDate(),
2706
+ ...this.hooks.showTrackedChanges() ? { showTrackedChanges: !0 } : {}
2707
+ })
2708
+ }, this.runsByPage.set(e, r));
2709
+ try {
2710
+ let e = await r.runs;
2711
+ if (this.hooks.destroyed() || this.hooks.document() !== t) return null;
2712
+ if (this.hooks.scale() !== n) continue;
2713
+ return e;
2714
+ } catch (t) {
2715
+ throw this.runsByPage.get(e) === r && this.runsByPage.delete(e), t;
2716
+ }
2717
+ }
2718
+ return null;
2719
+ }
2720
+ async goToComment(e, t) {
2721
+ if (this.hooks.destroyed()) throw Error("DocxScrollViewer is destroyed");
2722
+ let n = this.hooks.document();
2723
+ if (!n || !n.comments.some((t) => t.id === e && t.parentId === void 0)) return !1;
2724
+ let r = ++this.generation, i = !n.layoutComplete, a = n.commentAnchorRanges().filter((t) => t.commentId === e), o = t?.pageIndex;
2725
+ if (o !== void 0 && (!Number.isInteger(o) || o < 0)) return !1;
2726
+ let s = o ?? this.pageById.get(e), c = async () => {
2727
+ let t = n.commentAnchorRanges();
2728
+ for (; s === void 0 && this.frontier < n.pageCount;) {
2729
+ let i = this.frontier, a = await this.runsForPage(i, n);
2730
+ if (this.hooks.destroyed()) throw Error("DocxScrollViewer is destroyed");
2731
+ if (this.hooks.document() !== n || r !== this.generation || !a) return;
2732
+ this.indexPage(i, a, t), s = this.pageById.get(e);
2733
+ }
2734
+ };
2735
+ if (o === void 0 && s === void 0 && a.length > 0 && await c(), i && (o !== void 0 && o >= n.pageCount || o === void 0 && s === void 0)) {
2736
+ if (await this.hooks.waitForLayout(n), this.hooks.destroyed()) throw Error("DocxScrollViewer is destroyed");
2737
+ if (this.hooks.document() !== n || r !== this.generation) return !1;
2738
+ a = n.commentAnchorRanges().filter((t) => t.commentId === e), this.pageById.clear(), this.runsByPage.clear(), this.indexedPages.clear(), this.frontier = 0, s = o, o === void 0 && a.length > 0 && await c();
2739
+ }
2740
+ if (a.length === 0 || s === void 0 || o !== void 0 && o >= n.pageCount) return !1;
2741
+ let l = await this.runsForPage(s, n);
2742
+ if (this.hooks.destroyed()) throw Error("DocxScrollViewer is destroyed");
2743
+ if (this.hooks.document() !== n || r !== this.generation || !l) return !1;
2744
+ let u = a.flatMap((e) => H(e, l))[0];
2745
+ return u ? (this.hooks.select(e, s, u, t), !0) : !1;
2746
+ }
2747
+ destroy() {
2748
+ this.reset();
2749
+ }
2750
+ }, Fr = class {
2751
+ hooks;
2752
+ unsubscribe = null;
2753
+ viewGeneration = 0;
2754
+ prefix = 0;
2755
+ constructor(e) {
2756
+ this.hooks = e;
2757
+ }
2758
+ get presentedPageCount() {
2759
+ return this.prefix;
2760
+ }
2761
+ set presentedPageCount(e) {
2762
+ this.prefix = e;
2763
+ }
2764
+ bind(e) {
2765
+ this.unbind(), this.viewGeneration = 0, this.prefix = e.pageCount;
2766
+ let t = yr(e, (t) => this.onViewPublication(e, t), this.hooks.report), n = !0, r = fr(e, () => ({
2767
+ pageCount: e.pageCount,
2768
+ exact: e.layoutComplete,
2769
+ complete: e.layoutComplete
2770
+ }), (t) => {
2771
+ if (n) {
2772
+ n = !1;
2773
+ return;
2774
+ }
2775
+ this.onPublication(e, t);
2776
+ }, this.hooks.report);
2777
+ this.unsubscribe = () => {
2778
+ r(), t();
2779
+ };
2780
+ }
2781
+ unbind() {
2782
+ this.unsubscribe?.(), this.unsubscribe = null, this.prefix = 0;
2783
+ }
2784
+ onPublication(e, t) {
2785
+ if (!(this.hooks.destroyed() || e !== this.hooks.current())) {
2786
+ if (t.error !== void 0) {
2787
+ t.pageCount === 0 && (this.prefix = 0), this.hooks.reportBackground(t.error);
2788
+ return;
2789
+ }
2790
+ this.hooks.invalidateFind(), this.hooks.refreshComments(), this.apply(t);
2791
+ }
2792
+ }
2793
+ onViewPublication(e, t) {
2794
+ this.hooks.destroyed() || e !== this.hooks.current() || t.generation <= this.viewGeneration || (this.viewGeneration = t.generation, this.hooks.adoptView(t));
2795
+ }
2796
+ apply(e) {
2797
+ let t = [...this.hooks.mounted()], n = this.prefix;
2798
+ if (this.prefix = e.pageCount, (e.unchangedPages ?? 0) >= Math.min(n, e.pageCount)) {
2799
+ this.hooks.relayout();
2800
+ return;
2801
+ }
2802
+ this.hooks.invalidateRender(), this.hooks.relayout();
2803
+ for (let [e, n] of t) e >= this.prefix || !this.hooks.stillMounted(e, n) || this.hooks.refreshSlot(e, n);
2804
+ }
2805
+ destroy() {
2806
+ this.unbind();
2807
+ }
2808
+ }, Ir = 12, Lr = 13, Rr = Symbol("DocxScrollViewer.borrowedDocument"), zr;
2809
+ function Br() {
2810
+ return zr ??= import("./comment-ui-runtime-D_sb2K6s.js");
2811
+ }
2812
+ var Vr = class e {
2813
+ _pendingLoadAbort = null;
2814
+ _pendingRequestedView;
2815
+ _pendingViewChanged = null;
2816
+ _documentOwner;
2817
+ get _doc() {
2818
+ return this._documentOwner.current;
2819
+ }
2820
+ _borrowed;
2821
+ _opts;
2822
+ _errorRouter;
2823
+ _container;
2824
+ _shell;
2825
+ get _wrapper() {
2826
+ return this._shell.wrapper;
2827
+ }
2828
+ get _scrollHost() {
2829
+ return this._shell.scrollHost;
2830
+ }
2831
+ get _spacer() {
2832
+ return this._shell.spacer;
2833
+ }
2834
+ _mode;
2835
+ _viewport = new de({
2836
+ options: () => this._opts,
2837
+ container: () => this._container,
2838
+ scrollHost: () => this._scrollHost
2839
+ });
2840
+ _zoom = new we({
2841
+ scrollHost: () => this._scrollHost,
2842
+ spacer: () => this._spacer,
2843
+ count: () => this._doc?.pageCount ?? 0,
2844
+ zoomMin: () => this._opts.zoomMin ?? .1,
2845
+ zoomMax: () => this._opts.zoomMax ?? 4,
2846
+ baseScale: () => this._baseScale(),
2847
+ fitWidthPx: () => this._viewport.fitWidth(),
2848
+ fitContentSize: (e) => {
2849
+ if (!this._doc) return null;
2850
+ let t = this._doc.pageSize(0);
2851
+ return {
2852
+ width: (e === "width" ? this._widestPageWidthPt() : t.widthPt) * n,
2853
+ height: t.heightPt * n
2854
+ };
2855
+ },
2856
+ indexAt: (e) => this._pageIndexAtOffset(this._range(), e),
2857
+ offset: (e) => this._scrollGeometry.offsets[e] ?? 0,
2858
+ height: (e) => this._heights[e] || 0,
2859
+ totalHeight: () => this._scrollGeometry.totalHeight,
2860
+ recomputeHeights: () => this._recomputeHeights(),
2861
+ syncSpacerWidth: () => this._syncSpacerWidth(),
2862
+ padLeft: () => this._viewport.horizontalPadding().left,
2863
+ invalidateRender: () => {
2864
+ this._renderEpoch++;
2865
+ },
2866
+ preview: () => this._previewVisible(),
2867
+ scheduleSettle: () => this._scheduleSettle(),
2868
+ onScaleChange: (e) => this._opts.onScaleChange?.(e),
2869
+ relayout: () => this.relayout(),
2870
+ mountVisible: () => this._mountVisible(),
2871
+ refitOnResize: () => this._opts.refitOnResize !== !1
2872
+ });
2873
+ get _scale() {
2874
+ return this._zoom.scale;
2875
+ }
2876
+ get _scaleEstablished() {
2877
+ return this._zoom.established;
2878
+ }
2879
+ _scroller = new fe({
2880
+ spacer: () => this._spacer,
2881
+ count: () => this._doc?.pageCount ?? 0,
2882
+ range: () => this._range(),
2883
+ createSlot: () => this._createSlot(),
2884
+ attachSlot: (e) => this._scrollHost.appendChild(e.wrapper),
2885
+ resetSlot: (e, t) => this._resetSlot(e, t),
2886
+ positionSlot: (e, t, n) => this._positionSlot(t, e, n),
2887
+ renderSlot: (e, t, n) => this._renderSlot(e, t, n),
2888
+ previewSlot: (e, t, n) => this._previewSlot(t, e, n),
2889
+ settleSlot: (e, t) => this._refreshSlotAtomically(e, t),
2890
+ renderedScale: (e) => e.renderedScale,
2891
+ scale: () => this._scale,
2892
+ syncSpacerWidth: () => this._syncSpacerWidth(),
2893
+ onRange: (e) => this._emitVisiblePageChange(e),
2894
+ onExistingSlot: (e, t, n) => this._renderSlot(e, t, n)
2895
+ });
2896
+ _slots = this._scroller.slots;
2897
+ _layout = new Fr({
2898
+ current: () => this._doc,
2899
+ destroyed: () => this._destroyed,
2900
+ report: (e) => this._reportRenderError(e),
2901
+ reportBackground: (e) => this._errorRouter.reportBackground(e, this._opts.onLayoutComplete !== void 0),
2902
+ invalidateFind: () => this._find.invalidate(),
2903
+ refreshComments: () => this._refreshCommentSurface(),
2904
+ adoptView: (e) => {
2905
+ e.requester !== this && (this._layoutViewGeneration++, this._showTrackedChanges = e.view.showTrackedChanges, this._currentDate = e.view.currentDate, this._find.invalidate(), this._layout.apply({
2906
+ pageCount: this._doc.pageCount,
2907
+ exact: !0,
2908
+ complete: this._doc.layoutComplete
2909
+ }));
2910
+ },
2911
+ relayout: () => this.relayout(),
2912
+ invalidateRender: () => {
2913
+ this._renderEpoch++;
2914
+ },
2915
+ mounted: () => this._slots,
2916
+ stillMounted: (e, t) => this._slots.get(e) === t,
2917
+ refreshSlot: (e, t) => this._refreshSlotAtomically(e, t)
2918
+ });
2919
+ _renderHooks = {
2920
+ slots: () => this._slots,
2921
+ epoch: () => this._renderEpoch,
2922
+ scale: () => this._scale,
2923
+ slotIndex: (e) => e.renderedPage,
2924
+ token: () => 0,
2925
+ nextToken: () => 0,
2926
+ wantRuns: (e) => !!(this._opts.enableTextSelection && e.textLayer) || this._findActive || !!e.commentTintLayer,
2927
+ reportError: (e) => this._reportRenderError(e)
2928
+ };
2929
+ _bitmap = new me({
2930
+ ...this._renderHooks,
2931
+ inFlight: () => this._scroller.inFlight,
2932
+ destroyed: () => this._destroyed,
2933
+ width: (e) => this._pageWidthPx(e),
2934
+ dpr: () => this._viewport.dpr(),
2935
+ canRetry: () => !0,
2936
+ render: (e, t, n, r, i) => $(this._doc, t, e, "worker", {
2937
+ width: n,
2938
+ dpr: r,
2939
+ imageResources: this._opts.imageResources,
2940
+ defaultTextColor: this._opts.defaultTextColor,
2941
+ currentDate: this._currentDate,
2942
+ ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2943
+ onTextRun: i
2944
+ }),
2945
+ commitBitmap: (e, t, n, r, i, a) => n.commitBitmap(r, i, {
2946
+ cssWidth: a,
2947
+ cssHeight: this._pageHeightPx(e)
2948
+ }),
2949
+ commitRuns: (e, t, n, r, i) => this._commitRenderedRuns(e, t, n, t.canvas, i, !0)
2950
+ });
2951
+ _main = new he({
2952
+ ...this._renderHooks,
2953
+ render: (e, t, n, r, i) => $(this._doc, t, e, "main", {
2954
+ width: n,
2955
+ dpr: r,
2956
+ imageResources: this._opts.imageResources,
2957
+ defaultTextColor: this._opts.defaultTextColor,
2958
+ currentDate: this._currentDate,
2959
+ ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2960
+ onTextRun: i
2961
+ }),
2962
+ commitRuns: (e, t, n, r, i, a, o) => this._commitRenderedRuns(e, t, n, r, a, o),
2963
+ shadow: () => this._pageShadow
2964
+ });
2965
+ _navigation = new ye({
2966
+ host: () => this._scrollHost,
2967
+ spacer: () => this._spacer,
2968
+ count: () => this.pageCount,
2969
+ established: () => this._scaleEstablished,
2970
+ offset: (e) => this._scrollGeometry.offsets[e] ?? 0,
2971
+ height: (e) => this._heights[e] || 0,
2972
+ indexAt: (e) => this._pageIndexAtOffset(this._range(), e),
2973
+ totalHeight: () => this._scrollGeometry.totalHeight,
2974
+ width: (e) => this._pageWidthPx(e),
2975
+ padLeft: () => this._viewport.horizontalPadding().left,
2976
+ marginOrigin: () => this._commentMargin.originPx,
2977
+ mount: () => this._mountVisible()
2978
+ });
2979
+ _selection = new xe({
2980
+ wrapper: () => this._wrapper,
2981
+ scrollHost: () => this._scrollHost,
2982
+ slots: () => this._slots,
2983
+ resource: () => this._doc,
2984
+ destroyed: () => this._destroyed,
2985
+ textSelectionEnabled: () => this._opts.enableTextSelection === !0,
2986
+ elementSelectionEnabled: () => this._opts.enableElementSelection === !0,
2987
+ textSelected: () => Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null) !== null,
2988
+ getContext: () => this.getSelectionContext(),
2989
+ hitTest: (e, t, n, r) => {
2990
+ let i = e.pageSize(t);
2991
+ return e.getElementContextAt(t, {
2992
+ xPt: n * i.widthPt,
2993
+ yPt: r * i.heightPt
2994
+ }, {
2995
+ currentDate: this._currentDate,
2996
+ ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2997
+ maxTextCharacters: En
2998
+ });
2999
+ },
3000
+ outline: (e, t, n) => {
3001
+ if (n.pageIndex !== t) return null;
3002
+ let r = e.pageSize(t);
3003
+ return {
3004
+ x: n.bounds.xPt / r.widthPt,
3005
+ y: n.bounds.yPt / r.heightPt,
3006
+ width: n.bounds.widthPt / r.widthPt,
3007
+ height: n.bounds.heightPt / r.heightPt
3008
+ };
3009
+ },
3010
+ onChange: (e) => this._opts.onSelectionContextChange?.(e),
3011
+ onContextMenu: (e, t) => this._opts.onContextMenu?.({
3012
+ originalEvent: e,
3013
+ getContext: t
3014
+ }),
3015
+ reportError: (e) => this._reportRenderError(e)
3016
+ });
3017
+ _heights = [];
3018
+ _scrollGeometry = {
3019
+ offsets: [],
3020
+ totalHeight: 0
3021
+ };
3022
+ _visibleEvents = new Se((e, t, n) => this._opts.onVisiblePageChange?.(e, t, n));
3023
+ _loader = new le({
3024
+ name: () => "DocxScrollViewer",
3025
+ borrowed: () => this._borrowed,
3026
+ borrowedMessage: () => "DocxScrollViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.",
3027
+ destroyed: () => this._destroyed,
3028
+ owner: () => this._documentOwner,
3029
+ beginLoad: () => {
3030
+ let e = this._pendingRequestedView;
3031
+ this._pendingLoadAbort?.abort();
3032
+ let t = new AbortController();
3033
+ return this._pendingLoadAbort = t, this._pendingRequestedView = e, t;
3034
+ },
3035
+ isCurrentLoad: (e) => this._pendingLoadAbort === e,
3036
+ finishLoad: (e) => {
3037
+ this._pendingLoadAbort === e && (this._pendingLoadAbort = null, this._pendingRequestedView = void 0, this._pendingViewChanged = null);
3038
+ },
3039
+ acquire: async (e, t) => {
3040
+ let n = this._pendingRequestedView, r = await X.load(e, {
3041
+ password: this._opts.password,
3042
+ useGoogleFonts: this._opts.useGoogleFonts,
3043
+ allowFootnoteContinuation: this._opts.allowFootnoteContinuation,
3044
+ cjkFallback: this._opts.cjkFallback,
3045
+ maxZipEntryBytes: this._opts.maxZipEntryBytes,
3046
+ resourceLimits: this._opts.resourceLimits,
3047
+ debug: this._opts.debug,
3048
+ onResourceMetrics: this._opts.onResourceMetrics,
3049
+ workerTimeoutMs: this._opts.workerTimeoutMs,
3050
+ wasmUrl: this._opts.wasmUrl,
3051
+ math: this._opts.math,
3052
+ threeD: this._opts.threeD,
3053
+ regionMap: this._opts.regionMap,
3054
+ chartEx: this._opts.chartEx,
3055
+ tiff: this._opts.tiff,
3056
+ mode: this._mode,
3057
+ ...n === void 0 ? this._opts.legacyDoc === void 0 ? this._showTrackedChanges ? { showTrackedChanges: !0 } : {} : this._requestedShowTrackedChanges === void 0 ? void 0 : { showTrackedChanges: this._requestedShowTrackedChanges } : { showTrackedChanges: n },
3058
+ ...this._currentDate === void 0 ? {} : { currentDate: this._currentDate },
3059
+ ...this._opts.legacyDoc === void 0 ? void 0 : { legacyDoc: this._opts.legacyDoc },
3060
+ ...this._opts.progressiveLayout ? { progressiveLayout: !0 } : {},
3061
+ ...this._opts.sliceLayout === void 0 ? {} : { sliceLayout: this._opts.sliceLayout },
3062
+ [br]: {
3063
+ signal: t.signal,
3064
+ requestedView: () => this._pendingRequestedView,
3065
+ subscribeViewChange: (e) => (this._pendingViewChanged = e, () => {
3066
+ this._pendingViewChanged === e && (this._pendingViewChanged = null);
3067
+ })
3068
+ },
3069
+ onLayoutProgress: this._opts.onLayoutProgress,
3070
+ onLayoutPartial: this._opts.onLayoutPartial,
3071
+ onLayoutComplete: this._opts.onLayoutComplete
3072
+ });
3073
+ return await _r(r, t.signal, () => this._pendingRequestedView, () => this._currentDate, this), r;
3074
+ },
3075
+ beforeReplace: (e) => {
3076
+ if (this._selection.invalidateElementContext(!1), this._findRequestGeneration++, this._find.invalidate(), this._findActive = !1, this._activeCommentId = null, this._activeCommentPage = null, this._commentNavigation.reset(), this._layout.unbind(), e) {
3077
+ for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
3078
+ this._visibleEvents.reset();
3079
+ }
3080
+ },
3081
+ afterReplace: (e) => {
3082
+ this._pendingRequestedView !== void 0 && (this._showTrackedChanges = this._pendingRequestedView, this._requestedShowTrackedChanges = this._pendingRequestedView), this._opts.legacyDoc !== void 0 && (this._showTrackedChanges = q(e).showTrackedChanges), this._layout.bind(e), this._find.invalidate(), this._findActive = !1, this._activeCommentId = null, this._activeCommentPage = null, this._commentNavigation.reset();
3083
+ },
3084
+ mountOpeningWindow: async () => {
3085
+ let e = [];
3086
+ this._relayout(e), await Promise.all(e);
3087
+ },
3088
+ selectionChanged: () => this._selection.emitChange()
3089
+ });
3090
+ _activeCommentId = null;
3091
+ _activeCommentPage = null;
3092
+ _commentUi = null;
3093
+ _internalHyperlinkGeneration = 0;
3094
+ _commentAnchorRangesForMargin = null;
3095
+ _commentAnchorIds = /* @__PURE__ */ new Set();
3096
+ _commentMargin = new ge({
3097
+ container: () => this._container,
3098
+ scrollHost: () => this._scrollHost,
3099
+ spacer: () => this._spacer,
3100
+ enabled: () => this._commentsEnabled(),
3101
+ cards: () => this._commentsOptions()?.cards !== !1,
3102
+ hasDisplayableComments: () => this._hasDisplayableComments(),
3103
+ requestedSide: () => this._commentsOptions()?.side,
3104
+ zoom: () => this._scaleEstablished ? this._scale : 1,
3105
+ gapPx: Ir,
3106
+ widthPx: 280,
3107
+ fontSizePx: Lr
3108
+ });
3109
+ _layers = new Ee({
3110
+ markerLayer: (e) => e.commentTintLayer,
3111
+ syncMargin: (e) => this._commentMargin.syncMargin(e),
3112
+ marginSide: () => this._commentMargin.side(),
3113
+ marginExtent: () => this._commentMargin.extent(),
3114
+ commentsEnabled: () => this._commentsEnabled(),
3115
+ previewMargin: (e, t) => this._commentUi?.previewReadOnlyCommentMargin(e, t),
3116
+ disposeMargin: (e) => {
3117
+ this._commentUi?.disposeReadOnlyCommentMargin(e), this._commentUi || e.replaceChildren();
3118
+ },
3119
+ disposeDecoration: (e) => {
3120
+ this._commentUi?.disposeReadOnlyCommentDecoration(e), this._commentUi || e.replaceChildren();
3121
+ },
3122
+ redrawOutline: (e, t) => this._selection.redrawOutlineForSlot(e, t),
3123
+ markerRatio: (e) => e,
3124
+ resetMarkerTransform: () => !0,
3125
+ resetDecorationVisibility: () => !1
3126
+ });
3127
+ _commentNavigation = new Pr({
3128
+ document: () => this._doc,
3129
+ destroyed: () => this._destroyed,
3130
+ scale: () => this._scale,
3131
+ pageWidth: (e) => this._pageWidthPx(e),
3132
+ currentDate: () => this._currentDate,
3133
+ showTrackedChanges: () => this._showTrackedChanges,
3134
+ waitForLayout: (e) => this._errorRouter.ownBackgroundLifecycle(() => e.waitUntilLayoutComplete()),
3135
+ select: (e, t, n, r) => {
3136
+ this._activeCommentId = e, this._activeCommentPage = t, this._selection.clearElementContext(), this._scrollToPageTarget(t, n, r);
3137
+ for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
3138
+ this._selection.emitChange();
3139
+ }
3140
+ });
3141
+ _commentOverlay = new Te({
3142
+ slots: () => this._slots,
3143
+ scale: () => this._scale,
3144
+ destroyed: () => this._destroyed,
3145
+ ownerWindow: () => this._wrapper.ownerDocument.defaultView,
3146
+ width: (e) => this._pageWidthPx(e),
3147
+ height: (e) => this._pageHeightPx(e),
3148
+ side: () => this._commentMargin.side(),
3149
+ marginExtent: () => this._commentMargin.extent(),
3150
+ connectorOptions: () => this._commentsOptions()?.connectors,
3151
+ runtime: () => this._commentUi,
3152
+ redrawComments: (e, t) => this._redrawSlotComments(e, t)
3153
+ });
3154
+ _destroyed = !1;
3155
+ get _renderEpoch() {
3156
+ return this._scroller.renderEpoch;
3157
+ }
3158
+ set _renderEpoch(e) {
3159
+ this._scroller.renderEpoch = e;
3160
+ }
3161
+ get _prevBase() {
3162
+ return this._zoom.prevBase;
3163
+ }
3164
+ set _prevBase(e) {
3165
+ this._zoom.prevBase = e;
3166
+ }
3167
+ _pageShadow;
3168
+ _find = new Dr(() => this.pageCount, (e) => this._collectPageRuns(e));
3169
+ _findActive = !1;
3170
+ _highlights = new ce({
3171
+ slots: () => this._slots,
3172
+ active: () => this._findActive,
3173
+ runs: (e) => this._find.pageRuns(e),
3174
+ setRuns: (e, t) => this._find.setPageRuns(e, t),
3175
+ paint: (e, t, n, r) => Er(t.highlightLayer, n, this._find.pageHighlights(e), this._pageWidthPx(e), this._pageHeightPx(e), r, this._opts.findHighlightColors),
3176
+ reveal: (e) => this.scrollToPage(e),
3177
+ unitOf: (e) => e.page
3178
+ });
3179
+ _findRequestGeneration = 0;
3180
+ _showTrackedChanges;
3181
+ _currentDate;
3182
+ _layoutViewGeneration = 0;
3183
+ static fromDocument(t, n, r = {}) {
3184
+ let i = q(n);
3185
+ return new e(t, {
3186
+ ...r,
3187
+ currentDate: i.currentDate,
3188
+ showTrackedChanges: i.showTrackedChanges,
3189
+ [Rr]: n
3190
+ });
3191
+ }
3192
+ constructor(e, t = {}) {
3193
+ 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.");
3194
+ this._container = e, this._opts = t, this._errorRouter = new bt("DocxScrollViewer", t.onError), this._showTrackedChanges = t.showTrackedChanges === !0, t.legacyDoc !== void 0 && (this._requestedShowTrackedChanges = t.showTrackedChanges), this._currentDate = t.currentDate, this._pageShadow = t.pageShadow ?? "0 1px 3px rgba(0,0,0,0.2)";
3195
+ let n = t[Rr];
3196
+ this._borrowed = n !== void 0, n ? (this._documentOwner = new Ct("DocxScrollViewer", n, !1), this._mode = Ot("DocxScrollViewer", t.mode, n)) : (this._documentOwner = new Ct("DocxScrollViewer"), this._mode = Ot("DocxScrollViewer", t.mode, void 0)), this._shell = new De(e, {
3197
+ background: t.background,
3198
+ comments: !!t.comments,
3199
+ onScroll: () => this._onScroll(),
3200
+ onOutsideComment: () => {
3201
+ if (this._activeCommentId !== null) {
3202
+ this._activeCommentId = null, this._activeCommentPage = null;
3203
+ for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
3204
+ this._selection.emitChange();
3205
+ }
3206
+ }
3207
+ }), this._commentsEnabled() && Br().then((e) => {
3208
+ if (!this._destroyed) {
3209
+ this._commentUi = e;
3210
+ for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
3211
+ }
3212
+ }).catch((e) => this._reportRenderError(e)), this._selection.bind(!!t.onSelectionContextChange, !!t.onContextMenu), this._zoom.bind(this._container, this._scrollHost, this._opts.enableZoom !== !1), this._borrowed && (this._layout.bind(n), this.relayout());
3213
+ }
3214
+ async load(e) {
3215
+ await this._loader.load(e);
3216
+ }
3217
+ get pageCount() {
3218
+ return this._doc?.pageCount ?? 0;
3219
+ }
3220
+ get layoutComplete() {
3221
+ return this._doc?.layoutComplete ?? !0;
3222
+ }
3223
+ async waitUntilLayoutComplete() {
3224
+ await this._errorRouter.ownBackgroundLifecycle(async () => {
3225
+ await this._doc?.waitUntilLayoutComplete?.();
3226
+ });
3227
+ }
3228
+ _refreshCommentSurface() {
3229
+ if (!(!this._commentsEnabled() || this._slots.size === 0)) {
3230
+ this._syncSpacerWidth();
3231
+ for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
3232
+ }
3233
+ }
3234
+ _pageWidthPx(e) {
3235
+ return this._doc.pageSize(e).widthPt * n * this._scale;
3236
+ }
3237
+ _pageHeightPx(e) {
3238
+ return this._doc.pageSize(e).heightPt * n * this._scale;
3239
+ }
3240
+ _hasDisplayableComments() {
3241
+ if (!this._commentsEnabled()) return !1;
3242
+ let e = this._doc;
3243
+ if (!e) return !1;
3244
+ let t = e.commentAnchorRanges();
3245
+ if (this._commentAnchorRangesForMargin !== t && (this._commentAnchorRangesForMargin = t, this._commentAnchorIds = new Set(t.map((e) => e.commentId))), this._commentAnchorIds.size === 0) return !1;
3246
+ let n = this._commentsOptions()?.includeResolved === !0;
3247
+ return e.comments.some((e) => this._commentAnchorIds.has(e.id) && e.parentId === void 0 && (n || e.resolved !== !0));
3248
+ }
3249
+ _commentsEnabled() {
3250
+ return this._opts.comments === !0 || typeof this._opts.comments == "object";
3251
+ }
3252
+ _commentsOptions() {
3253
+ return typeof this._opts.comments == "object" ? this._opts.comments : void 0;
3254
+ }
3255
+ _widestPageWidthPt() {
3256
+ if (!this._doc) return 0;
3257
+ let e = 0, t = this._layout.presentedPageCount || this._doc.pageCount;
3258
+ for (let n = 0; n < t; n++) {
3259
+ let t = this._doc.pageSize(n).widthPt;
3260
+ t > e && (e = t);
3261
+ }
3262
+ return e;
3263
+ }
3264
+ _baseScale() {
3265
+ if (!this._doc || this._doc.pageCount === 0) return 0;
3266
+ let e = this._viewport.fitWidth();
3267
+ if (e <= 0) return 0;
3268
+ let t = this._widestPageWidthPt();
3269
+ return t <= 0 ? 0 : e / (t * n);
3270
+ }
3271
+ relayout() {
3272
+ this._relayout();
3273
+ }
3274
+ _relayout(e) {
3275
+ if (this._doc) {
3276
+ if (this._doc.layoutComplete !== !1 && (this._layout.presentedPageCount = this._doc.pageCount), this._scaleEstablished) {
3277
+ let e = this._baseScale();
3278
+ if (e > 0 && e !== this._prevBase) {
3279
+ let t = this._prevBase > 0 ? this._scale / this._prevBase : 1;
3280
+ this._prevBase = e, this.setScale(e * t);
3281
+ }
3282
+ } else if (!this._zoom.establishBase()) return;
3283
+ this._recomputeHeights(), this._syncSpacer(), this._mountVisible(e);
3284
+ for (let [e, t] of this._slots) t.renderedPage === e && t.renderedScale >= 0 && this._redrawSlotComments(e, t);
3285
+ }
3286
+ }
3287
+ _recomputeHeights() {
3288
+ let e = Math.min(this._layout.presentedPageCount, this._doc.pageCount), t = Array(e);
3289
+ for (let n = 0; n < e; n++) t[n] = this._pageHeightPx(n);
3290
+ this._heights = t, this._scrollGeometry = re(t, this._viewport.gap(), this._viewport.verticalPadding());
3291
+ }
3292
+ _pageIndexAtOffset(e, t) {
3293
+ let { offsets: n } = e, r = 0, i = n.length - 1, a = 0;
3294
+ for (; r <= i;) {
3295
+ let e = r + i >> 1;
3296
+ n[e] <= t ? (a = e, r = e + 1) : i = e - 1;
3297
+ }
3298
+ return a;
3299
+ }
3300
+ _range() {
3301
+ return ve(this._scrollGeometry, this._scrollHost.scrollTop, this._scrollHost.clientHeight, this._viewport.overscan());
3302
+ }
3303
+ _syncSpacer() {
3304
+ this._scroller.syncSpacer();
3305
+ }
3306
+ _syncSpacerWidth() {
3307
+ let { left: e, right: t } = this._viewport.horizontalPadding(), n = 0;
3308
+ for (let e = 0; e < this._heights.length; e++) {
3309
+ let t = this._pageWidthPx(e);
3310
+ t > n && (n = t);
3311
+ }
3312
+ this._commentMargin.syncSpacerWidth(n, e, t);
3313
+ }
3314
+ _onScroll() {
3315
+ !this._doc || !this._scaleEstablished || this._mountVisible(void 0, !1);
3316
+ }
3317
+ _mountVisible(e, t = !0) {
3318
+ this._scroller.mount(e, t);
3319
+ }
3320
+ _emitVisiblePageChange(e) {
3321
+ this._doc && this._visibleEvents.publish(e, this._doc.pageCount, this.layoutComplete);
3322
+ }
3323
+ _createSlot() {
3324
+ let { wrapper: e, canvas: t, textLayer: n, highlightLayer: r } = be(this._scrollHost, this._opts.enableTextSelection === !0, this._pageShadow), { markerLayer: i, margin: a, decorationLayer: o } = Ce(e, this._commentsEnabled(), this._commentsOptions()?.cards !== !1, this._commentsOptions()?.connectors !== void 0, (e) => this._commentMargin.syncMargin(e)), s = Et(e, this._opts.enableElementSelection === !0);
3325
+ return this._scrollHost.appendChild(e), {
3326
+ wrapper: e,
3327
+ canvas: t,
3328
+ textLayer: n,
3329
+ highlightLayer: r,
3330
+ elementLayer: s,
3331
+ commentTintLayer: i,
3332
+ commentMargin: a,
3333
+ commentDecorationLayer: o,
3334
+ commentRuns: Object.freeze([]),
3335
+ commentGeometry: null,
3336
+ renderedPage: -1,
3337
+ renderedScale: -1,
3338
+ dispatcher: new ht(t, this._mode === "worker")
3339
+ };
3340
+ }
3341
+ _recycleSlot(e, t) {
3342
+ this._scroller.recycleSlot(e, t);
3343
+ }
3344
+ _resetSlot(e, t) {
3345
+ t.dispatcher.destroy(), this._destroyed || (t.dispatcher = new ht(t.canvas, this._mode === "worker")), this._layers.reset(t), t.commentRuns = Object.freeze([]), t.commentGeometry = null, t.renderedPage = -1, t.renderedScale = -1, t.wrapper.remove();
3346
+ }
3347
+ _positionSlot(e, t, n) {
3348
+ this._layers.position(t, e, n.offsets[t], this._pageWidthPx(t), this._pageHeightPx(t), this._scrollHost.clientWidth, this._viewport.horizontalPadding().left);
3349
+ }
3350
+ _renderSlot(e, t, n = !0) {
3351
+ if (!this._doc || t.renderedPage === e) return null;
3352
+ t.renderedPage = e;
3353
+ let r = this._viewport.dpr(), i = this._pageWidthPx(e), a = this._scale, o = t.dispatcher, s = o.begin();
3354
+ return this._mode === "worker" ? this._renderSlotBitmap(e, t, i, r, a, o, s, n) : this._main.render(e, t, i, r, 0, o, s, n);
3355
+ }
3356
+ _hyperlinkHandler() {
3357
+ return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
3358
+ if (e.kind === "external") {
3359
+ v(e.url);
3360
+ return;
3361
+ }
3362
+ let t = this._doc;
3363
+ if (!t) return;
3364
+ let n = ++this._internalHyperlinkGeneration;
3365
+ this._navigateInternalHyperlink(t, e.ref, n).catch((e) => this._reportRenderError(e));
3366
+ });
3367
+ }
3368
+ async _navigateInternalHyperlink(e, t, n) {
3369
+ if (e.layoutComplete || await e.waitUntilLayoutComplete(), this._destroyed || this._doc !== e || n !== this._internalHyperlinkGeneration) return;
3370
+ let r = e.getBookmarkPage(t);
3371
+ r !== void 0 && this.scrollToPage(r);
3372
+ }
3373
+ _canvasCssPx(e) {
3374
+ return {
3375
+ width: parseFloat(e.style.width) || e.width,
3376
+ height: parseFloat(e.style.height) || e.height
3377
+ };
3378
+ }
3379
+ _commitRenderedRuns(e, t, n, r, i, a) {
3380
+ if (t.textLayer && (a && this._clearTextLayerPreview(t.textLayer), this._opts.enableTextSelection)) {
3381
+ let { width: i, height: a } = this._canvasCssPx(r);
3382
+ Z(t.textLayer, n, i, a, this._hyperlinkHandler(), (e) => this._highlights.measure(e), e);
3383
+ }
3384
+ i && this._highlights.refreshRuns(e, n), this._commitCommentRuns(e, t, n), this._highlights.redrawSlot(e, t);
3385
+ }
3386
+ _reportRenderError(e) {
3387
+ this._errorRouter.report(e);
3388
+ }
3389
+ _renderSlotBitmap(e, t, n, r, i, a = t.dispatcher, o = a.begin(), s = !0) {
3390
+ return this._bitmap.render(e, t, n, r, i, 0, a, o, s);
3391
+ }
3392
+ setScale(e) {
3393
+ this._zoom.setScale(e);
3394
+ }
3395
+ getScale() {
3396
+ return this._zoom.getScale();
3397
+ }
3398
+ zoomIn() {
3399
+ this._zoom.zoomIn();
3400
+ }
3401
+ zoomOut() {
3402
+ this._zoom.zoomOut();
3403
+ }
3404
+ fitWidth() {
3405
+ this._zoom.fit("width");
3406
+ }
3407
+ fitPage() {
3408
+ this._zoom.fit("page");
3409
+ }
3410
+ _previewVisible() {
3411
+ this._scroller.preview();
3412
+ }
3413
+ _previewSlot(e, t, n) {
3414
+ this._positionSlot(e, t, n), this._layers.preview(e, this._pageWidthPx(t), this._pageHeightPx(t), this._scale);
3415
+ }
3416
+ _clearTextLayerPreview(e) {
3417
+ pe(e);
3418
+ }
3419
+ _scheduleSettle() {
3420
+ this._scroller.scheduleSettle(150);
3421
+ }
3422
+ _refreshSlotAtomically(e, t) {
3423
+ if (!this._doc) return;
3424
+ let n = this._viewport.dpr(), r = this._pageWidthPx(e), i = this._scale;
3425
+ if (this._mode === "worker") {
3426
+ this._renderSlotBitmap(e, t, r, n, i);
3427
+ return;
3428
+ }
3429
+ this._main.settle(e, t, r, n);
3430
+ }
3431
+ async setShowTrackedChanges(e) {
3432
+ let t = ++this._layoutViewGeneration;
3433
+ if (this._pendingLoadAbort) {
3434
+ let t = this._pendingRequestedView !== e;
3435
+ this._pendingRequestedView = e, t && this._pendingViewChanged?.();
3436
+ }
3437
+ let n = this._doc;
3438
+ if (this._opts.legacyDoc !== void 0 && (this._requestedShowTrackedChanges = e), this._showTrackedChanges === e) {
3439
+ n && await J(n, {
3440
+ showTrackedChanges: e,
3441
+ currentDate: this._currentDate
3442
+ }, this);
3443
+ return;
3444
+ }
3445
+ (!n || await J(n, {
3446
+ showTrackedChanges: e,
3447
+ currentDate: this._currentDate
3448
+ }, this)) && (this._destroyed || t !== this._layoutViewGeneration || n !== this._doc || (this._showTrackedChanges = e, this._opts.legacyDoc !== void 0 && (this._requestedShowTrackedChanges = e), this._find.invalidate(), this._layout.apply({
3449
+ pageCount: n?.pageCount ?? 0,
3450
+ exact: !0,
3451
+ complete: n?.layoutComplete !== !1
3452
+ })));
3453
+ }
3454
+ scrollToPage(e, t) {
3455
+ this._navigation.scrollToUnit(e, t);
3456
+ }
3457
+ _scrollToPageTarget(e, t, n) {
3458
+ this._navigation.scrollToPoint(e, t.x + t.w / 2, t.y + t.h / 2, n);
3459
+ }
3460
+ async goToComment(e, t) {
3461
+ return this._commentNavigation.goToComment(e, t);
3462
+ }
3463
+ async findText(e, t = {}) {
3464
+ if (!this._doc) return [];
3465
+ let n = ++this._findRequestGeneration;
3466
+ if (this._doc.layoutComplete === !1) {
3467
+ let e = this._doc;
3468
+ if (await this._errorRouter.ownBackgroundLifecycle(() => e.waitUntilLayoutComplete()), this._destroyed || this._doc !== e || n !== this._findRequestGeneration) return [];
3469
+ }
3470
+ this._findActive = e.length > 0;
3471
+ let r = await this._errorRouter.ownAwaitable(() => this._find.find(e, t));
3472
+ return this._highlights.redrawAll(), r;
3473
+ }
3474
+ async findNext() {
3475
+ return this._highlights.activate(this._find.next());
3476
+ }
3477
+ async findPrev() {
3478
+ return this._highlights.activate(this._find.prev());
3479
+ }
3480
+ clearFind() {
3481
+ this._findRequestGeneration++, this._findActive = !1, this._find.invalidate(), this._highlights.redrawAll();
3482
+ }
3483
+ async _collectPageRuns(e) {
3484
+ return this._doc ? this._doc.collectPageRuns(e, {
3485
+ width: this._pageWidthPx(e),
3486
+ currentDate: this._currentDate,
3487
+ ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {}
3488
+ }) : [];
3489
+ }
3490
+ _commitCommentRuns(e, t, n) {
3491
+ t.commentTintLayer && (t.commentRuns = Object.freeze([...n]), this._commentNavigation.commitRuns(e, t.commentRuns), 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 = ""));
3492
+ }
3493
+ _redrawSlotComments(e, t) {
3494
+ if (!this._doc || !t.commentTintLayer) return;
3495
+ this._commentMargin.syncMargin(t.commentMargin);
3496
+ let n = this._commentUi;
3497
+ if (!n) {
3498
+ t.commentTintLayer.replaceChildren(), t.commentMargin?.replaceChildren(), t.commentDecorationLayer?.replaceChildren(), t.commentGeometry = null;
3499
+ return;
3500
+ }
3501
+ t.commentGeometry = n.buildDocxCommentMargin(t.commentTintLayer, t.commentMargin, t.commentRuns, {
3502
+ comments: this._doc.comments,
3503
+ anchors: this._doc.commentAnchorRanges()
3504
+ }, this._pageWidthPx(e), this._pageHeightPx(e), this._activeCommentId, (t, n) => {
3505
+ let r = n ? t : this._activeCommentId === t ? null : this._activeCommentId;
3506
+ if (r !== this._activeCommentId) {
3507
+ this._activeCommentId = r, this._activeCommentPage = r ? e : null, this._selection.clearElementContext();
3508
+ for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
3509
+ this._selection.emitChange();
3510
+ }
3511
+ }, this._commentMargin.zoom(), 280, this._commentsOptions()?.markers !== !1, this._commentsOptions()?.includeResolved === !0, t.commentDecorationLayer ? () => this._commentOverlay.schedule(e, t, !1) : void 0, t.commentDecorationLayer ? () => this._commentOverlay.schedule(e, t, !0) : void 0), this._commentOverlay.drawConnectors(e, t);
3512
+ }
3513
+ get topVisiblePage() {
3514
+ return this._scroller.lastRange?.topIndex ?? 0;
3515
+ }
3516
+ async getResourceMetrics() {
3517
+ if (!this._doc) throw Error("Document not loaded");
3518
+ return await this._doc.getResourceMetrics();
3519
+ }
3520
+ getSelectionContext(e = {}) {
3521
+ if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
3522
+ return (this._doc && this._activeCommentId !== null && this._activeCommentPage !== null ? Or(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._selection.elementContext ? Vn(this._selection.elementContext, e.maxTextCharacters) : null));
3523
+ }
3524
+ destroy() {
3525
+ this._destroyed || (this._destroyed = !0, this._pendingLoadAbort?.abort(), this._pendingLoadAbort = null, this._pendingViewChanged = null, this._findRequestGeneration++, this._errorRouter.close(), this._layout.unbind(), this._layoutViewGeneration++, this._commentNavigation.reset(), this._find.invalidate(), this._findActive = !1, this._selection.destroy(), this._highlights.destroy(), this._commentOverlay.destroy(), this._selection.clearElementContext(), this._scroller.destroy(), this._zoom.destroy(), this._commentMargin.destroy(), this._documentOwner.close(), this._shell.destroy());
3526
+ }
3527
+ };
3528
+ //#endregion
3529
+ //#region packages/docx/src/types.ts
3530
+ function Hr(e) {
3531
+ let t = [];
3532
+ for (let n of e.content) {
3533
+ if (n.type !== "paragraph") continue;
3534
+ let e = "";
3535
+ for (let t of n.runs) t.type === "text" && !t.noteRef && (e += t.text);
3536
+ e = e.trim(), e && t.push(e);
3537
+ }
3538
+ return t.join(" ");
3539
+ }
3540
+ //#endregion
3541
+ //#region src/docx.ts
3542
+ var Ur = /* @__PURE__ */ e({
3543
+ DocxDocument: () => X,
3544
+ DocxScrollViewer: () => Vr,
3545
+ DocxViewer: () => Nr,
3546
+ OoxmlDecodedImageLimitError: () => lt,
3547
+ OoxmlError: () => t,
3548
+ OoxmlResourceLimitError: () => r,
3549
+ TiffDecodeError: () => dt,
3550
+ autoResize: () => ft,
3551
+ buildDocxHighlightLayer: () => Er,
3552
+ buildDocxTextLayer: () => Z,
3553
+ isOoxmlDecodedImageLimitError: () => ct,
3554
+ isTiffDecodeError: () => ut,
3555
+ noteText: () => Hr,
3556
+ openExternalHyperlink: () => v,
3557
+ readDocxTextSelectionContext: () => Q,
3558
+ resolveCommentAnchorRuns: () => H,
3559
+ resolveDocxCommentThreads: () => tr,
3560
+ resolveRevisionAnchorRuns: () => lr
3561
+ });
3562
+ //#endregion
3563
+ export { ln as _, Q as a, X as c, lr as d, H as f, F as g, gn as h, Nr as i, G as l, Cn as m, Hr as n, Er as o, tr as p, Vr as r, Z as s, Ur as t, dr as u };