@silurus/ooxml 0.76.2 → 0.77.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +144 -32
  2. package/dist/{canvas-viewer-mechanics-CwVSOYke.js → canvas-viewer-mechanics-D5zXbOrS.js} +319 -153
  3. package/dist/{document-pull-client-B-3_7_YS.js → document-pull-client-CC8pPuzi.js} +2361 -2253
  4. package/dist/{docx-C6B98B4-.js → docx-Dg9N9OX4.js} +623 -202
  5. package/dist/docx.mjs +4 -4
  6. package/dist/docx_parser_bg.wasm +0 -0
  7. package/dist/index.mjs +3 -3
  8. package/dist/{line-distribute-C1r2zvji.js → line-distribute-BtfPlM2A.js} +133 -72
  9. package/dist/{line-metrics-BdCACYlq.js → line-metrics-B66x33iy.js} +1446 -1340
  10. package/dist/node.mjs +7 -7
  11. package/dist/pptx-BFP7Isgf.js +2123 -0
  12. package/dist/pptx.mjs +5 -5
  13. package/dist/pptx_parser_bg.wasm +0 -0
  14. package/dist/{render-CLcpSi0m.js → render-D-cOpMLV.js} +1 -1
  15. package/dist/render-worker-host-BzpMoFRr.js +27 -0
  16. package/dist/render-worker-host-CdZ5hW2X.js +27 -0
  17. package/dist/render-worker-host-quqYq02i.js +27 -0
  18. package/dist/{resource-measurement-E_S_iau4.js → resource-measurement-CVfVTQrt.js} +1 -1
  19. package/dist/{session-B4Y54cbT.js → session-DxAVpIP-.js} +2 -2
  20. package/dist/{slide-pull-client-WCuYCjio.js → slide-pull-client-Lag44QA8.js} +1173 -876
  21. package/dist/types/docx.d.ts +172 -28
  22. package/dist/types/index.d.ts +498 -88
  23. package/dist/types/node.d.ts +133 -22
  24. package/dist/types/pptx.d.ts +166 -10
  25. package/dist/types/xlsx.d.ts +248 -54
  26. package/dist/{worksheet-pull-client-YzjJMOns.js → worksheet-pull-client-D74b_23i.js} +2 -2
  27. package/dist/{xlsx-EykJ9tPV.js → xlsx-Bik59Raj.js} +2090 -1224
  28. package/dist/xlsx.mjs +5 -5
  29. package/dist/xlsx_parser_bg.wasm +0 -0
  30. package/package.json +1 -1
  31. package/dist/pptx-CKAk5e-J.js +0 -1735
  32. package/dist/render-worker-host-Bkf1jUcW.js +0 -27
  33. package/dist/render-worker-host-CKOmXdyr.js +0 -27
  34. package/dist/render-worker-host-Dpv-nKHY.js +0 -27
@@ -1,1735 +0,0 @@
1
- import { t as e } from "./chunk-DmhlhrBa.js";
2
- import { a as t, c as n, i as r, l as i, n as a, o, r as s, s as c, t as l } from "./slide-pull-client-WCuYCjio.js";
3
- import { B as u, Et as d, G as f, It as p, Lt as m, R as h, a as g, at as _, gt as v, hn as y, ht as b, in as x, it as S, kt as C, mn as w, q as T, z as ee } from "./line-metrics-BdCACYlq.js";
4
- import { _ as te, a as E, b as ne, c as re, d as ie, f as D, g as ae, h as oe, i as O, l as se, m as ce, n as le, o as k, p as A, r as ue, s as de, t as fe, u as pe, v as me, x as he, y as ge } from "./canvas-viewer-mechanics-CwVSOYke.js";
5
- import { a as _e, i as ve, n as ye, t as be } from "./bounded-raw-part-cache-C6ro6Ezf.js";
6
- import { n as xe } from "./resource-measurement-E_S_iau4.js";
7
- import { n as Se, r as j, t as Ce } from "./visible-index-CgyJLAS_.js";
8
- import { n as we, r as M, t as N } from "./highlight-rect-CAkCWJ37.js";
9
- //#region packages/core/src/nav/internal-target.ts
10
- function Te(e, t) {
11
- let n = t.startsWith("/") ? [] : e.split("/").filter((e) => e !== "");
12
- for (let e of t.split("/")) if (e === "..") n.pop();
13
- else if (e === "." || e === "") continue;
14
- else n.push(e);
15
- return n.join("/");
16
- }
17
- function Ee(e) {
18
- let t = /[?&]jump=([a-zA-Z]+)/.exec(e);
19
- if (!t) return null;
20
- let n = t[1].toLowerCase();
21
- return n === "firstslide" || n === "lastslide" || n === "nextslide" || n === "previousslide" ? n : null;
22
- }
23
- function De(e, t, n) {
24
- if (!(n <= 0)) switch (e) {
25
- case "firstslide": return 0;
26
- case "lastslide": return n - 1;
27
- case "nextslide": return Math.min(t + 1, n - 1);
28
- case "previousslide": return Math.max(t - 1, 0);
29
- }
30
- }
31
- //#endregion
32
- //#region packages/pptx/src/text-layer.ts
33
- function P(e, t, n, r, i) {
34
- e.innerHTML = "";
35
- let a = /* @__PURE__ */ new Map();
36
- for (let o of t) {
37
- let t = o.rotation + (o.textBodyRotation ?? 0), s = `${o.shapeX},${o.shapeY},${o.shapeW},${o.shapeH},${t}`;
38
- if (!a.has(s)) {
39
- let i = document.createElement("div");
40
- i.style.cssText = `position:absolute;left:${N(o.shapeX, n)};top:${N(o.shapeY, r)};width:${N(o.shapeW, n)};height:${N(o.shapeH, r)};pointer-events:all;overflow:hidden;`, t !== 0 && (i.style.transformOrigin = "center center", i.style.transform = `rotate(${t}deg)`), a.set(s, {
41
- div: i,
42
- x: o.shapeX,
43
- y: o.shapeY,
44
- w: o.shapeW,
45
- h: o.shapeH,
46
- rot: t
47
- }), e.appendChild(i);
48
- }
49
- let c = a.get(s), l = document.createElement("span");
50
- l.textContent = o.text;
51
- let u = i ? o.hyperlink : void 0;
52
- l.style.cssText = `position:absolute;left:${N(o.inShapeX, c.w)};top:${N(o.inShapeY, c.h)};font:${o.font};line-height:${o.h}px;letter-spacing:0;white-space:pre;color:transparent;cursor:${u ? "pointer" : "text"};`, u && i && (l.title = u.kind === "external" ? u.url : u.ref, l.addEventListener("click", (e) => {
53
- e.preventDefault(), i(u);
54
- })), c.div.appendChild(l);
55
- }
56
- }
57
- function F(e, t, n, r, i, a, o = {}) {
58
- e.innerHTML = "";
59
- let s = o.match ?? "rgba(255, 214, 0, 0.42)", c = o.active ?? "rgba(255, 140, 0, 0.55)", l = /* @__PURE__ */ new Map(), u = (t) => {
60
- let n = t.rotation + (t.textBodyRotation ?? 0), a = `${t.shapeX},${t.shapeY},${t.shapeW},${t.shapeH},${n}`, o = l.get(a);
61
- if (!o) {
62
- let s = document.createElement("div");
63
- s.style.cssText = `position:absolute;left:${N(t.shapeX, r)};top:${N(t.shapeY, i)};width:${N(t.shapeW, r)};height:${N(t.shapeH, i)};pointer-events:none;overflow:hidden;`, n !== 0 && (s.style.transformOrigin = "center center", s.style.transform = `rotate(${n}deg)`), o = {
64
- div: s,
65
- w: t.shapeW,
66
- h: t.shapeH
67
- }, l.set(a, o), e.appendChild(s);
68
- }
69
- return o;
70
- };
71
- for (let e of n) {
72
- let n = e.active ? c : s;
73
- for (let r of e.slices) {
74
- let e = t[r.runIndex];
75
- if (!e) continue;
76
- let i = a(e.font), { x: o, width: s } = we(e.text, r.start, r.end, i);
77
- if (s <= 0) continue;
78
- let c = u(e), l = document.createElement("div");
79
- l.style.cssText = `position:absolute;left:${N(e.inShapeX + o, c.w)};top:${N(e.inShapeY, c.h)};width:${N(s, c.w)};height:${N(e.h, c.h)};background:${n};pointer-events:none;`, c.div.appendChild(l);
80
- }
81
- }
82
- }
83
- //#endregion
84
- //#region packages/pptx/src/find.ts
85
- var I = class {
86
- _slideRuns = /* @__PURE__ */ new Map();
87
- _matches = [];
88
- _active = -1;
89
- _generation = 0;
90
- _runsRevision = 0;
91
- constructor(e, t) {
92
- this._slideCount = e, this._collectSlideRuns = t;
93
- }
94
- invalidate() {
95
- this._generation++, this._runsRevision++, this._slideRuns.clear(), this._matches = [], this._active = -1;
96
- }
97
- slideRuns(e) {
98
- return this._slideRuns.get(e);
99
- }
100
- setSlideRuns(e, t) {
101
- this._runsRevision++, this._slideRuns.set(e, t);
102
- }
103
- slideHighlights(e) {
104
- let t = [];
105
- for (let n = 0; n < this._matches.length; n++) {
106
- let r = this._matches[n];
107
- r.slide === e && t.push({
108
- slices: r.slices,
109
- active: n === this._active
110
- });
111
- }
112
- return t;
113
- }
114
- activeSlide() {
115
- let e = this._matches[this._active];
116
- return e ? e.slide : null;
117
- }
118
- matches() {
119
- return this._matches.map((e, t) => ({
120
- matchIndex: t,
121
- text: e.text,
122
- location: { slide: e.slide }
123
- }));
124
- }
125
- async find(e, t = {}) {
126
- let n = ++this._generation;
127
- if (e.length === 0) return this._runsRevision++, this._slideRuns.clear(), this._matches = [], this._active = -1, [];
128
- let r = this._runsRevision, i = new Map(this._slideRuns), a = this._slideCount();
129
- for (let e = 0; e < a; e++) {
130
- let t = i.get(e);
131
- if (!t) {
132
- try {
133
- t = await this._collectSlideRuns(e);
134
- } catch (e) {
135
- if (n !== this._generation) return [];
136
- throw e;
137
- }
138
- if (n !== this._generation) return [];
139
- i.set(e, t);
140
- }
141
- }
142
- if (n !== this._generation) return [];
143
- let o = r === this._runsRevision ? i : new Map([...i, ...this._slideRuns]), s = [];
144
- for (let n = 0; n < a; n++) {
145
- let r = o.get(n) ?? [], i = se(r);
146
- for (let a of pe(i, e, t)) {
147
- let e = a.slices.map((e) => r[e.runIndex].text.slice(e.start, e.end)).join("");
148
- s.push({
149
- slide: n,
150
- text: e,
151
- slices: a.slices
152
- });
153
- }
154
- }
155
- return this._runsRevision++, this._slideRuns = o, this._matches = s, this._active = -1, this.matches();
156
- }
157
- next() {
158
- return this._active = de(this._active, this._matches.length), this._activePublic();
159
- }
160
- prev() {
161
- return this._active = re(this._active, this._matches.length), this._activePublic();
162
- }
163
- _activePublic() {
164
- let e = this._matches[this._active];
165
- return e ? {
166
- matchIndex: this._active,
167
- text: e.text,
168
- location: { slide: e.slide }
169
- } : null;
170
- }
171
- }, L = (e) => e >= "0" && e <= "9";
172
- function Oe(e) {
173
- let t = 0;
174
- for (let n = 0; n < 10; n++) t = Math.max(t, e.measureText(String(n)).width);
175
- return t;
176
- }
177
- function ke(e, t, n) {
178
- let r = 0;
179
- for (let i of t) r += L(i) ? n : e.measureText(i).width;
180
- return r;
181
- }
182
- function Ae(e, t, n, r, i) {
183
- let a = e.textAlign;
184
- e.textAlign = "left";
185
- let o = n;
186
- for (let n of t) if (L(n)) {
187
- let t = e.measureText(n).width;
188
- e.fillText(n, o + (i - t) / 2, r), o += i;
189
- } else e.fillText(n, o, r), o += e.measureText(n).width;
190
- e.textAlign = a;
191
- }
192
- //#endregion
193
- //#region packages/pptx/src/presentation-handle.ts
194
- var R = (e, t) => e / x * t;
195
- async function je(e, t, n) {
196
- let r = e.getContext("2d");
197
- if (!r) throw Error("2D context not available");
198
- let a = n.width / (n.slideWidthEmu / x);
199
- await n.drawBase();
200
- let o = document.createElement("canvas");
201
- o.width = e.width, o.height = e.height;
202
- let s = o.getContext("2d");
203
- if (!s) throw Error("base 2D context not available");
204
- s.drawImage(e, 0, 0);
205
- let c = [], l = [], u = !1, d = (e) => {
206
- u || (n.onError ? n.onError(e) : console.error("[ooxml] PPTX embedded media failed:", e));
207
- };
208
- for (let e of t) {
209
- let t;
210
- try {
211
- t = await n.fetchMedia(e.mediaPath);
212
- } catch (t) {
213
- d(Me(e, t)), l.push(z(e, a));
214
- continue;
215
- }
216
- let r = e.mimeType || t.type, i = t.type === r ? t : new Blob([t], { type: r }), o = URL.createObjectURL(i), s = e.mediaKind === "video" ? document.createElement("video") : document.createElement("audio");
217
- s.src = o, s.preload = "metadata", e.mediaKind === "video" && (s.playsInline = !0);
218
- let f = z(e, a), p = {
219
- el: e,
220
- rect: e.mediaKind === "audio" ? {
221
- x: f.x + f.w / 2 - Math.max(f.w, 260) / 2,
222
- y: f.y,
223
- w: Math.max(f.w, 260),
224
- h: f.h + 36
225
- } : f,
226
- posterRect: f,
227
- media: s,
228
- objectUrl: o,
229
- loadState: "loading",
230
- detachListeners: () => {}
231
- }, m = () => {
232
- u || (p.loadState = "metadata");
233
- }, h = () => {
234
- u || (p.loadState = "ready");
235
- }, g = () => {
236
- u || (p.loadState = "error", d(V(e, s, "decode")));
237
- };
238
- s.addEventListener("loadedmetadata", m), s.addEventListener("canplay", h), s.addEventListener("error", g), p.detachListeners = () => {
239
- s.removeEventListener("loadedmetadata", m), s.removeEventListener("canplay", h), s.removeEventListener("error", g);
240
- }, c.push(p);
241
- try {
242
- s.load();
243
- } catch (t) {
244
- p.loadState = "error", d(V(e, s, "load", t));
245
- }
246
- }
247
- let f = null, p = null, m = () => {
248
- r.setTransform(n.dpr, 0, 0, n.dpr, 0, 0);
249
- let t = e.width / n.dpr, a = e.height / n.dpr;
250
- r.drawImage(o, 0, 0, e.width, e.height, 0, 0, t, a);
251
- for (let e of l) B(r, e, "Media unavailable");
252
- for (let e of c) {
253
- let t = e.media;
254
- if (e.loadState !== "loading") {
255
- if (e.loadState === "error") {
256
- B(r, e.posterRect, "Media unavailable");
257
- continue;
258
- }
259
- if (e.el.mediaKind === "video" && t.readyState >= 2) {
260
- let { x: n, y: i, w: a, h: o } = e.posterRect;
261
- r.drawImage(t, n, i, a, o);
262
- }
263
- if (e === p || v?.state === e) Fe(r, e, t);
264
- else if (t.paused) {
265
- let { x: t, y: n, w: a, h: o } = e.posterRect;
266
- i(r, t + a / 2, n + o / 2, a, o, "paused");
267
- }
268
- }
269
- }
270
- }, h = () => {
271
- u || (m(), f = requestAnimationFrame(h));
272
- }, g = (t, r) => {
273
- let i = e.getBoundingClientRect(), a = e.width / n.dpr, o = e.height / n.dpr;
274
- return {
275
- x: (t - i.left) / i.width * a,
276
- y: (r - i.top) / i.height * o
277
- };
278
- }, _ = (e, t) => {
279
- for (let n of c) {
280
- let { x: r, y: i, w: a, h: o } = n.rect;
281
- if (e < r || e > r + a || t < i || t > i + o) continue;
282
- let s = Y(n), c = s.y - 12, l = s.y + s.h + 8;
283
- return (Number.isFinite(n.media.duration) ? n.media.duration : 0) > 0 && e >= s.x && e <= s.x + s.w && t >= c && t <= l ? {
284
- kind: "seek",
285
- state: n,
286
- fraction: Math.max(0, Math.min(1, (e - s.x) / s.w))
287
- } : {
288
- kind: "toggle",
289
- state: n
290
- };
291
- }
292
- return null;
293
- }, v = null, y = (e, t) => {
294
- let n = Number.isFinite(e.media.duration) ? e.media.duration : 0;
295
- n <= 0 || (e.media.currentTime = n * t);
296
- }, b = (e) => {
297
- try {
298
- e.media.play().catch((t) => {
299
- d(V(e.el, e.media, "play", t));
300
- });
301
- } catch (t) {
302
- d(V(e.el, e.media, "play", t));
303
- }
304
- }, S = (t) => {
305
- let { x: n, y: r } = g(t.clientX, t.clientY), i = _(n, r);
306
- i && (i.kind === "seek" ? (v = {
307
- state: i.state,
308
- wasPlaying: !i.state.media.paused
309
- }, i.state.media.pause(), y(i.state, i.fraction), e.setPointerCapture(t.pointerId), t.preventDefault()) : i.state.media.paused ? b(i.state) : i.state.media.pause());
310
- }, C = (e) => {
311
- let { x: t, y: n } = g(e.clientX, e.clientY);
312
- p = null;
313
- for (let e of c) {
314
- let { x: r, y: i, w: a, h: o } = e.rect;
315
- if (t >= r && t <= r + a && n >= i && n <= i + o) {
316
- p = e;
317
- break;
318
- }
319
- }
320
- if (v) {
321
- let e = Y(v.state), n = Math.max(0, Math.min(1, (t - e.x) / e.w));
322
- y(v.state, n);
323
- }
324
- }, w = () => {
325
- p = null;
326
- }, T = (t) => {
327
- if (!v) return;
328
- let { wasPlaying: n, state: r } = v;
329
- v = null, e.releasePointerCapture(t.pointerId), n && b(r);
330
- };
331
- return c.length > 0 ? (e.addEventListener("pointerdown", S), e.addEventListener("pointermove", C), e.addEventListener("pointerleave", w), e.addEventListener("pointerup", T), e.addEventListener("pointercancel", T), e.style.cursor = "pointer", h()) : l.length > 0 && m(), {
332
- play(e) {
333
- for (let t of c) (!e || t.el.mediaPath === e) && b(t);
334
- },
335
- pause(e) {
336
- for (let t of c) (!e || t.el.mediaPath === e) && t.media.pause();
337
- },
338
- destroy() {
339
- if (!u) {
340
- u = !0, f !== null && cancelAnimationFrame(f), e.removeEventListener("pointerdown", S), e.removeEventListener("pointermove", C), e.removeEventListener("pointerleave", w), e.removeEventListener("pointerup", T), e.removeEventListener("pointercancel", T), e.style.cursor = "";
341
- for (let e of c) e.detachListeners(), e.media.pause(), e.media.removeAttribute("src"), e.media.load(), URL.revokeObjectURL(e.objectUrl);
342
- }
343
- }
344
- };
345
- }
346
- function z(e, t) {
347
- return {
348
- x: R(e.x, t),
349
- y: R(e.y, t),
350
- w: R(e.width, t),
351
- h: R(e.height, t)
352
- };
353
- }
354
- function B(e, t, n) {
355
- let r = Math.max(10, Math.min(14, t.h * .12));
356
- e.save(), e.font = `500 ${r}px system-ui, -apple-system, sans-serif`, e.textAlign = "center", e.textBaseline = "middle";
357
- let i = r + 12, a = Math.min(t.w, Math.max(100, e.measureText(n).width + 24));
358
- X(e, t.x + (t.w - a) / 2, t.y + (t.h - i) / 2, a, i, i / 2), e.fillStyle = "rgba(20, 20, 20, 0.72)", e.fill(), e.fillStyle = "rgba(255, 255, 255, 0.95)", e.fillText(n, t.x + t.w / 2, t.y + t.h / 2), e.restore();
359
- }
360
- function Me(e, t) {
361
- return /* @__PURE__ */ Error(`Embedded ${e.mediaKind} fetch failed for "${e.mediaPath}" (mime=${e.mimeType || "unknown"}): ${H(t)}`);
362
- }
363
- function V(e, t, n, r) {
364
- let i = "";
365
- try {
366
- i = e.mimeType ? t.canPlayType(e.mimeType) : "";
367
- } catch {}
368
- let a = t.error, o = [
369
- `mime=${e.mimeType || "unknown"}`,
370
- `canPlayType=${i || "no"}`,
371
- `readyState=${t.readyState}`,
372
- `networkState=${t.networkState}`
373
- ];
374
- a && o.push(`mediaError=${a.code}${a.message ? ` ${a.message}` : ""}`);
375
- let s = r === void 0 ? "" : `: ${H(r)}`;
376
- return /* @__PURE__ */ Error(`Embedded ${e.mediaKind} ${n} failed for "${e.mediaPath}" (${o.join("; ")})${s}`);
377
- }
378
- function H(e) {
379
- return e instanceof Error ? `${e.name || "Error"}${e.message ? `: ${e.message}` : ""}` : String(e);
380
- }
381
- var U = 28, W = 14, Ne = 72, Pe = 10, G = 3;
382
- function Fe(e, t, n) {
383
- let r = Number.isFinite(n.duration) ? n.duration : 0, a = r > 0 ? Math.min(1, n.currentTime / r) : 0, o = t.posterRect;
384
- i(e, o.x + o.w / 2, o.y + o.h / 2, o.w, o.h, n.paused ? "paused" : "playing"), t.el.mediaKind === "audio" ? Le(e, t, n, r, a) : Ie(e, t, n, r, a);
385
- }
386
- function Ie(e, t, n, r, i) {
387
- let { x: a, y: o, w: s, h: c } = t.rect, l = Math.max(28, Math.min(56, c * .22)), u = o + c - l;
388
- e.save();
389
- let d = e.createLinearGradient(0, u, 0, o + c);
390
- d.addColorStop(0, "rgba(0, 0, 0, 0)"), d.addColorStop(1, "rgba(0, 0, 0, 0.55)"), e.fillStyle = d, e.fillRect(a, u, s, l), e.restore();
391
- let f = Y(t);
392
- q(e, f, i, r > 0), e.save(), e.font = "500 11px system-ui, -apple-system, sans-serif", e.textBaseline = "middle", e.shadowColor = "rgba(0, 0, 0, 0.75)", e.shadowBlur = 3, e.fillStyle = "rgba(255, 255, 255, 0.95)", K(e, n.currentTime, r, f.x, f.y - 10, "bottom"), e.restore();
393
- }
394
- function Le(e, t, n, r, i) {
395
- let a = J(t.rect);
396
- e.save(), X(e, a.x, a.y, a.w, a.h, a.h / 2), e.fillStyle = "rgba(20, 20, 20, 0.72)", e.fill(), e.font = "500 11px system-ui, -apple-system, sans-serif", e.textBaseline = "middle", e.fillStyle = "rgba(255, 255, 255, 0.95)", K(e, n.currentTime, r, a.x + W, a.y + a.h / 2, "middle"), e.restore(), q(e, Y(t), i, r > 0);
397
- }
398
- function K(e, t, n, r, i, a) {
399
- let o = Z(t), s = Z(n), c = Oe(e), l = ke(e, o, c), u = ke(e, s, c), d = e.measureText(" / ").width, f = Math.max(l, u);
400
- Ae(e, o, r + f - l, i, c);
401
- let p = e.textAlign;
402
- e.textAlign = "left", e.fillText(" / ", r + f, i), e.textAlign = p, Ae(e, s, r + f + d, i, c);
403
- }
404
- function q(e, t, n, r) {
405
- let i = t.h / 2;
406
- if (e.save(), X(e, t.x, t.y, t.w, t.h, i), e.fillStyle = "rgba(255, 255, 255, 0.35)", e.fill(), n > 0 && (X(e, t.x, t.y, t.w * n, t.h, i), e.fillStyle = "#fff", e.fill()), r) {
407
- let r = Math.max(t.x + 5, Math.min(t.x + t.w - 5, t.x + t.w * n));
408
- e.shadowColor = "rgba(0, 0, 0, 0.3)", e.shadowBlur = 3, e.fillStyle = "#fff", e.beginPath(), e.arc(r, t.y + t.h / 2, 5, 0, Math.PI * 2), e.fill();
409
- }
410
- e.restore();
411
- }
412
- function J(e) {
413
- let t = Math.max(220, e.w - 24);
414
- return {
415
- x: e.x + e.w / 2 - t / 2,
416
- y: e.y + e.h - U - 4,
417
- w: t,
418
- h: U
419
- };
420
- }
421
- function Y(e) {
422
- if (e.el.mediaKind === "audio") {
423
- let t = J(e.rect), n = t.x + W + Ne + Pe, r = Math.max(40, t.x + t.w - W - n);
424
- return {
425
- x: n,
426
- y: t.y + (t.h - G) / 2,
427
- w: r,
428
- h: G
429
- };
430
- }
431
- let t = e.rect, n = Math.max(12, t.w * .025), r = Math.max(12, Math.min(18, t.h * .05));
432
- return {
433
- x: t.x + n,
434
- y: t.y + t.h - G - r,
435
- w: t.w - n * 2,
436
- h: G
437
- };
438
- }
439
- function X(e, t, n, r, i, a) {
440
- let o = Math.min(a, i / 2, r / 2);
441
- e.beginPath(), e.moveTo(t + o, n), e.lineTo(t + r - o, n), e.quadraticCurveTo(t + r, n, t + r, n + o), e.lineTo(t + r, n + i - o), e.quadraticCurveTo(t + r, n + i, t + r - o, n + i), e.lineTo(t + o, n + i), e.quadraticCurveTo(t, n + i, t, n + i - o), e.lineTo(t, n + o), e.quadraticCurveTo(t, n, t + o, n), e.closePath();
442
- }
443
- function Z(e) {
444
- if (!Number.isFinite(e) || e < 0) return "0:00";
445
- let t = Math.floor(e);
446
- return `${Math.floor(t / 60)}:${(t % 60).toString().padStart(2, "0")}`;
447
- }
448
- //#endregion
449
- //#region packages/pptx/src/slide-nav.ts
450
- function Re(e) {
451
- let t = /* @__PURE__ */ new Map();
452
- for (let n = 0; n < e.length; n++) {
453
- let r = e[n];
454
- r !== void 0 && r !== "" && !t.has(r) && t.set(r, n);
455
- }
456
- return t;
457
- }
458
- function ze(e, t) {
459
- if (e === "") return;
460
- let n = Te("ppt/slides", e);
461
- return t.get(n);
462
- }
463
- function Be(e, t, n) {
464
- let r = Ee(e);
465
- return r === null ? ze(e, t) : De(r, n, t.size);
466
- }
467
- //#endregion
468
- //#region packages/pptx/src/slide-repository.ts
469
- var Ve = class {
470
- #e;
471
- #t;
472
- #n;
473
- #r = 0;
474
- #i = Promise.resolve();
475
- #a;
476
- #o;
477
- constructor(e) {
478
- if (!Number.isSafeInteger(e.slideCount) || e.slideCount < 0) throw TypeError("slideCount must be a non-negative safe integer");
479
- this.#e = e.slideCount, this.#t = e.loadSlide, this.#n = new ye({
480
- maxEntries: e.maxCachedSlides,
481
- maxWeight: e.maxCachedStructuralBytes,
482
- measure: (e) => xe(e).jsonBytes
483
- });
484
- }
485
- get slideCount() {
486
- return this.#e;
487
- }
488
- get usage() {
489
- return this.#n.usage;
490
- }
491
- withSlide(e, t) {
492
- this.#c(e);
493
- let n = this.#r, r = this.#i.then(async () => {
494
- if (n !== this.#r) throw this.#a ? this.#a : Error("PPTX slide repository generation is stale");
495
- if (this.#a) throw this.#a;
496
- let r = await this.#s(e, n);
497
- try {
498
- return await t(r);
499
- } catch (e) {
500
- let t = He(e);
501
- throw t ? (this.#l(t, n), this.#o === n ? this.#a ?? t : t) : e;
502
- }
503
- });
504
- return this.#i = r.then(() => void 0, () => void 0), r;
505
- }
506
- async #s(e, t) {
507
- return this.#n.getOrLoad(e, async () => {
508
- let n;
509
- try {
510
- n = await this.#t(e);
511
- } catch (e) {
512
- let n = He(e);
513
- throw n ? (this.#l(n, t), this.#o === t ? this.#a ?? n : n) : e;
514
- }
515
- if (this.#o === t && this.#a) throw this.#a;
516
- return n;
517
- });
518
- }
519
- clear() {
520
- this.#r += 1, this.#a = void 0, this.#o = void 0, this.#n.clear();
521
- }
522
- #c(e) {
523
- if (!Number.isSafeInteger(e) || e < 0 || e >= this.#e) throw RangeError(`Slide index ${e} out of range (count: ${this.#e})`);
524
- }
525
- #l(e, t) {
526
- t !== this.#r || this.#a || (this.#a = e, this.#o = t, this.#r += 1, this.#n.clear());
527
- }
528
- };
529
- function He(e) {
530
- return e instanceof y ? e : _(e);
531
- }
532
- //#endregion
533
- //#region packages/pptx/src/worker.ts?worker&inline
534
- var Ue = "var e=class e extends Error{code;constructor(t,n){super(n),this.name=`OoxmlError`,this.code=t,Object.setPrototypeOf(this,e.prototype)}},t=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)}};const n=`https://fonts.googleapis.com/css2?family=Noto+Naskh+Arabic:wght@400;700&display=swap`,r=`https://fonts.googleapis.com/css2?family=Noto+Sans+Arabic:wght@400;700&display=swap`,i={calibri:{url:`https://fonts.googleapis.com/css2?family=Carlito:ital,wght@0,400;0,700;1,400;1,700&display=swap`,loadFamily:`Carlito`},\"calibri light\":{url:`https://fonts.googleapis.com/css2?family=Carlito:ital,wght@0,400;0,700;1,400;1,700&display=swap`,loadFamily:`Carlito`},cambria:{url:`https://fonts.googleapis.com/css2?family=Caladea:ital,wght@0,400;0,700;1,400;1,700&display=swap`,loadFamily:`Caladea`},\"cambria math\":{url:`https://fonts.googleapis.com/css2?family=Caladea:ital,wght@0,400;0,700;1,400;1,700&display=swap`,loadFamily:`Caladea`},\"nunito sans\":{url:`https://fonts.googleapis.com/css2?family=Nunito+Sans:ital,wght@0,400;0,700;1,400;1,700&display=swap`},nunito:{url:`https://fonts.googleapis.com/css2?family=Nunito:ital,wght@0,400;0,700;1,400;1,700&display=swap`},\"open sans\":{url:`https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,400;0,700;1,400;1,700&display=swap`},roboto:{url:`https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,400;0,700;1,400;1,700&display=swap`},lato:{url:`https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,400;0,700;1,400;1,700&display=swap`},montserrat:{url:`https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,700;1,400;1,700&display=swap`},poppins:{url:`https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,400;0,700;1,400;1,700&display=swap`},raleway:{url:`https://fonts.googleapis.com/css2?family=Raleway:ital,wght@0,400;0,700;1,400;1,700&display=swap`},\"playfair display\":{url:`https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,700;1,400;1,700&display=swap`},ubuntu:{url:`https://fonts.googleapis.com/css2?family=Ubuntu:ital,wght@0,400;0,700;1,400;1,700&display=swap`},\"sakkal majalla\":{url:n,loadFamily:`Noto Naskh Arabic`},\"traditional arabic\":{url:n,loadFamily:`Noto Naskh Arabic`},\"simplified arabic\":{url:n,loadFamily:`Noto Naskh Arabic`},\"arabic typesetting\":{url:n,loadFamily:`Noto Naskh Arabic`},\"univers next arabic\":{url:r,loadFamily:`Noto Sans Arabic`},\"noto naskh arabic\":{url:n,loadFamily:`Noto Naskh Arabic`},\"noto sans arabic\":{url:r,loadFamily:`Noto Sans Arabic`}};function a(e){if(!e)return null;let t=e.toLowerCase();return/[ᄀ-ᇿ㄰-㆏가-힯]/.test(e)?`kr`:/[぀-ヿ]/.test(e)?`jp`:/jhenghei|微軟正黑|新細明|細明|pmingliu|mingliu|dfkai|標楷|華康|cns11643|kaiti tc|ming\\s*liu/.test(t)||/新細明體|細明體|標楷體|微軟正黑體|華康/.test(e)?`tc`:/simsun|nsimsun|simhei|simkai|simfang|yahei|dengxian|fangsong|kaiti|youyuan|lisu|stsong|stkaiti|stfangsong|stheiti|stxihei|stzhongsong|songti sc|heiti sc|微软雅黑/.test(t)||/宋体|黑体|楷体|仿宋|等线|微软雅黑|隶书|幼圆/.test(e)?`sc`:/malgun|batang|gulim|dotum|gungsuh|nanum|new gulim|hancom|hy(gothic|graphic|namu)?/.test(t)?`kr`:/\\bmeiryo\\b|\\byu\\s*(gothic|mincho)\\b|yugothic|yumincho|hiragino|\\bms\\s*(gothic|mincho|pgothic|pmincho|ui\\s*gothic)\\b|\\bms[pg]?(gothic|mincho)\\b|ipa(ex)?(gothic|mincho)|noto\\s+(sans|serif)\\s+jp|游ゴシック|游明朝|MS|メイリオ|ヒラギノ/.test(t)||/游ゴシック|游明朝|MS ゴシック|MS 明朝|MS Pゴシック|メイリオ|ヒラギノ/.test(e)?`jp`:null}const o=e=>`https://fonts.googleapis.com/css2?family=${e}:wght@400;700&display=swap`,s={\"noto sans kr\":{url:o(`Noto+Sans+KR`)},\"noto sans sc\":{url:o(`Noto+Sans+SC`)},\"noto sans tc\":{url:o(`Noto+Sans+TC`)},\"noto sans jp\":{url:o(`Noto+Sans+JP`)},\"noto serif kr\":{url:o(`Noto+Serif+KR`)},\"noto serif sc\":{url:o(`Noto+Serif+SC`)},\"noto serif tc\":{url:o(`Noto+Serif+TC`)},\"noto serif jp\":{url:o(`Noto+Serif+JP`)},\"noto sans\":{url:o(`Noto+Sans`)},\"noto serif\":{url:o(`Noto+Serif`)},\"noto sans devanagari\":{url:o(`Noto+Sans+Devanagari`)},\"noto sans thai\":{url:o(`Noto+Sans+Thai`)},\"noto sans hebrew\":{url:o(`Noto+Sans+Hebrew`)},\"noto serif hebrew\":{url:o(`Noto+Serif+Hebrew`)}};var ee=class e{hasHan=!1;hasHangul=!1;hasKana=!1;hasArabic=!1;hasThai=!1;hasHebrew=!1;hasDevanagari=!1;hasCyrGreek=!1;constructor(e){this.cjkLang=e}clone(){let t=new e(this.cjkLang);return t.hasHan=this.hasHan,t.hasHangul=this.hasHangul,t.hasKana=this.hasKana,t.hasArabic=this.hasArabic,t.hasThai=this.hasThai,t.hasHebrew=this.hasHebrew,t.hasDevanagari=this.hasDevanagari,t.hasCyrGreek=this.hasCyrGreek,t}addText(e){let t=()=>this.hasHan&&this.hasHangul&&this.hasKana&&this.hasArabic&&this.hasThai&&this.hasHebrew&&this.hasDevanagari&&this.hasCyrGreek;outer:for(let n of e)if(n)for(let e of n){let n=e.codePointAt(0);if(n!==void 0&&!(n<=591)&&(n>=4352&&n<=4607||n>=12592&&n<=12687||n>=44032&&n<=55215?this.hasHangul=!0:n>=12352&&n<=12543?this.hasKana=!0:n>=13312&&n<=19903||n>=19968&&n<=40959||n>=63744&&n<=64255||n>=131072&&n<=195103?this.hasHan=!0:n>=1536&&n<=1791||n>=1872&&n<=1919||n>=2208&&n<=2303||n>=64336&&n<=65023||n>=65136&&n<=65279?this.hasArabic=!0:n>=3584&&n<=3711?this.hasThai=!0:n>=1424&&n<=1535||n>=64285&&n<=64335?this.hasHebrew=!0:n>=2304&&n<=2431?this.hasDevanagari=!0:(n>=1024&&n<=1279||n>=880&&n<=1023)&&(this.hasCyrGreek=!0),t()))break outer}}names(){let e=[],t=new Set;this.hasHangul&&t.add(`kr`),this.hasKana&&t.add(`jp`),this.hasHan&&t.size===0&&t.add(this.cjkLang??`jp`);for(let n of[`kr`,`sc`,`tc`,`jp`])if(t.has(n)){let t={kr:`KR`,sc:`SC`,tc:`TC`,jp:`JP`}[n];e.push(`Noto Sans ${t}`,`Noto Serif ${t}`)}return this.hasCyrGreek&&e.push(`Noto Sans`,`Noto Serif`),this.hasArabic&&e.push(`Noto Naskh Arabic`,`Noto Sans Arabic`),this.hasThai&&e.push(`Noto Sans Thai`),this.hasHebrew&&e.push(`Noto Sans Hebrew`,`Noto Serif Hebrew`),this.hasDevanagari&&e.push(`Noto Sans Devanagari`),e}},c=class e extends RangeError{code=`ooxml-decoded-image-limit`;constructor(t,n,r){super(`OOXML decoded image limit exceeded: ${t} ${r} > ${n}`),this.metric=t,this.limit=n,this.observed=r,this.name=`OoxmlDecodedImageLimitError`,Object.setPrototypeOf(this,e.prototype)}};function te(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 l=class{state=`uninitialized`;generationValue=0;readiness;poisonListeners=new Set;constructor(e,t,n){this.initialize=e,this.reinitialize=t,this.normalizeFailure=n}get generation(){return this.generationValue}get poisoned(){return this.state===`poisoned`}onPoison(e){return this.poisonListeners.add(e),()=>this.poisonListeners.delete(e)}async ensureReady(){if(this.state!==`ready`){if(!this.readiness){let e=this.state===`uninitialized`?this.initialize:this.reinitialize;this.readiness=Promise.resolve().then(e).then(()=>{this.generationValue+=1,this.state=`ready`,this.readiness=void 0},e=>{throw this.readiness=void 0,e})}await this.readiness}}run(e){try{return e()}catch(e){let t=this.normalizeFailure(e);throw t?(this.poison(t),t):e}}tryRunReady(e){if(this.state!==`ready`)return{current:!1};let t=this.generationValue,n=this.run(e);return this.state!==`ready`||t!==this.generationValue?{current:!1}:{current:!0,generation:t,value:n}}poison(e){this.state=`poisoned`,this.readiness=void 0;for(let t of this.poisonListeners)t(e)}assertCurrent(e){if(this.state!==`ready`||e!==this.generationValue)throw Error(`WASM archive session belongs to a discarded runtime generation`)}},u=class e extends Error{code=`parser-crashed`;constructor(t){super(t),this.name=`WasmTrapError`,Object.setPrototypeOf(this,e.prototype)}};function ne(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 re(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 ie(e,t){return e({module_or_path:t})}var ae=class{runtime;wasmInput=null;currentArchive=null;constructor(e,t={}){this.init=e,this.options=t,this.runtime=new l(()=>this.invokeConfigured(this.init),()=>this.invokeConfigured(this.options.reinit??this.init),oe),this.runtime.onPoison(()=>this.dropPoisonedArchive())}setWasmInput(e){this.wasmInput=e,this.runtime.ensureReady().catch(()=>void 0)}setWasmUrl(e){this.setWasmInput(e)}get archive(){return this.currentArchive}setArchive(e){this.freeArchive(),this.currentArchive=e}disposeArchive(){this.freeArchive()}get poisoned(){return this.runtime.poisoned}async ensureReady(){await this.runtime.ensureReady()}run(e){return this.runtime.run(e)}poison(){this.runtime.poison(new u(`WASM parser was recycled`))}invokeConfigured(e){return this.wasmInput===null?Promise.reject(Error(`WasmParserHost: setWasmInput was never called`)):ie(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,re(e)}};function oe(e){return ne(e)?new u(`WASM parser trapped and was recycled: ${e instanceof Error?e.message:String(e)}`):null}function d(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function f(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return d(t.requiredBytes)&&d(t.offeredBytes)&&t.requiredBytes>t.offeredBytes}var p=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 se(e){if(e instanceof p)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`||!f(r)))return new p(r)}function ce(e,t,n){let r=se(e);if(!(!r||r.offeredBytes!==t||r.requiredBytes>n))return r}const le=`OOXML_RESOURCE_LIMIT:`;function m(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function ue(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return m(t.archiveEntryCount)&&m(t.declaredInflatedBytes)&&(t.largestInflatedEntryBytes===void 0||m(t.largestInflatedEntryBytes))&&m(t.distinctInflatedBytes)&&m(t.operationInflatedBytes)}function de(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw TypeError(`OOXML resource usage checkpoint is not valid JSON`)}if(!ue(t))throw TypeError(`OOXML resource usage checkpoint is invalid`);return t}function fe(e){return e===`docx`||e===`xlsx`||e===`pptx`}function pe(e){return e===`container`||e===`decompression`||e===`parsing`||e===`serialization`||e===`layout`||e===`rendering`||e===`worker`}function h(e,t){return typeof e==`string`&&e.length>0&&e.length<=t&&!/[\\u0000-\\u001f\\u007f]/u.test(e)}function g(e){return h(e,128)&&/^[a-z0-9][a-z0-9-]*$/u.test(e)}function me(e){return!h(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 _=new Map([[`archive-entry:declared-inflated-bytes`,{stage:`container`,part:`required`}],[`archive-entry:actual-inflated-bytes`,{stage:`decompression`,part:`required`}],[`archive:entry-count`,{stage:`container`,part:`forbidden`}],[`archive:central-directory-bytes`,{stage:`container`,part:`forbidden`,configurable:!1}],[`archive:distinct-inflated-bytes`,{stage:`decompression`,part:`required`}],[`xml-event:bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`xml-context:bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`xml-tree:depth`,{stage:`parsing`,part:`optional`,configurable:!1}],[`worksheet-row:projected-bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`worksheet-shell:projected-bytes`,{stage:`parsing`,part:`optional`,configurable:!1}]]),he=new Set([..._.keys()].map(e=>e.slice(0,e.indexOf(`:`)))),ge=new Set([..._.keys()].map(e=>e.slice(e.indexOf(`:`)+1)));function _e(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return!fe(t.format)||!h(t.operation,256)||!g(t.resource)||!g(t.metric)||!m(t.limit)||!m(t.observed)||typeof t.configurable!=`boolean`||!ue(t.usage)?!1:!(`part`in t)||me(t.part)}function v(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;if(!pe(t.stage)||!_e(t.violation))return!1;let n=t.violation,r=_.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:!(he.has(n.resource)&&ge.has(n.metric))}function ve(e){return{archiveEntryCount:e.archiveEntryCount,declaredInflatedBytes:e.declaredInflatedBytes,...e.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:e.largestInflatedEntryBytes},distinctInflatedBytes:e.distinctInflatedBytes,operationInflatedBytes:e.operationInflatedBytes}}function ye(e){if(!v(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:ve(t.usage)}};return v(n)?n:void 0}function be(e){let t=e.violation;return`OOXML resource limit exceeded${t.part?` for ${t.part}`:``}: ${t.metric} ${t.observed} > ${t.limit}`}function y(e){let n=e instanceof Error?e.message:String(e);if(!n.startsWith(le))return;let r;try{r=JSON.parse(n.slice(21))}catch{return}if(!r||typeof r!=`object`)return;let i=r;if(!(i.code!==`ooxml-resource-limit`||!v(i.details)))return new t(be(i.details),i.details)}function xe(n){if(n instanceof c)return{message:n.message,errorName:n.name,code:n.code,decodedImage:{metric:n.metric,limit:n.limit,observed:n.observed}};let r=se(n);if(r)return{message:r.message,errorName:r.name,code:r.code,insufficientCredit:{requiredBytes:r.requiredBytes,offeredBytes:r.offeredBytes}};let i=n instanceof e||n instanceof t?n:y(n);if(i instanceof t){let e=ye(i.details);return e?{message:typeof i.message==`string`?i.message:be(e),errorName:`OoxmlResourceLimitError`,code:`ooxml-resource-limit`,resourceLimit:e}:{message:`Invalid OOXML resource-limit error payload`,errorName:`Error`}}if(i instanceof e)return{message:typeof i.message==`string`?i.message:String(i.message),errorName:h(i.name,128)?i.name:`OoxmlError`,...g(i.code)?{code:i.code}:{}};let a=n instanceof Error?n.message:String(n);if(typeof a==`string`&&a.startsWith(le))return{message:`Invalid OOXML resource-limit payload`,errorName:`Error`};let o=n instanceof Error?n:Error(a),s=o;return{message:typeof o.message==`string`?o.message:String(o.message),errorName:h(o.name,128)?o.name:`Error`,...typeof s.code==`string`?{code:s.code}:{}}}function b(e){try{return xe(e)}catch{return{message:`Worker operation failed with an unreadable error`,errorName:`Error`}}}const Se=new Set([`encrypted`,`invalid-password`,`unsupported-encryption`,`legacy-binary-format`,`not-ooxml`]);function Ce(n){if(n.code===`ooxml-decoded-image-limit`&&n.decodedImage&&(n.decodedImage.metric===`image-pixels`||n.decodedImage.metric===`active-decoded-bytes`)&&m(n.decodedImage.limit)&&m(n.decodedImage.observed)&&n.decodedImage.observed>n.decodedImage.limit)return new c(n.decodedImage.metric,n.decodedImage.limit,n.decodedImage.observed);if(n.code===`ooxml-insufficient-credit`&&f(n.insufficientCredit))return new p(n.insufficientCredit);if(n.code===`ooxml-resource-limit`&&v(n.resourceLimit))return new t(n.message,n.resourceLimit);if(n.code&&Se.has(n.code))return new e(n.code,n.message);let r=n.errorName===`TypeError`?TypeError(n.message):n.errorName===`RangeError`?RangeError(n.message):Error(n.message);return n.errorName&&(r.name=n.errorName),n.code!==void 0&&Object.assign(r,{code:n.code}),r}function we(e){return e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&e.buffer instanceof ArrayBuffer?e.buffer:e.slice().buffer}const x=67108864;Object.freeze({maxArchiveEntryBytes:134217728,maxTotalInflatedBytes:268435456,maxArchiveEntries:4096});function Te(e){return[e.maxArchiveEntryBytes===null?0n:BigInt(e.maxArchiveEntryBytes),e.maxTotalInflatedBytes===null?0n:BigInt(e.maxTotalInflatedBytes),e.maxArchiveEntries===null?0n:BigInt(e.maxArchiveEntries)]}const S=`ooxml-pull-v1`;function C(e,t){if(!Number.isSafeInteger(e)||e<=0)throw RangeError(`${t} must be a positive safe integer`)}function Ee(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 w=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,C(this.maxRetainedBytes,`max retained lease bytes`),C(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}},De=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){Ee(e.sessionId),C(e.operationId,`operation id`),C(e.generation,`generation`),C(e.maxByteCredit,`max byte credit`),e.wireLeaseIdStart!==void 0&&C(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=b(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(C(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:S,...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){C(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(C(e,`byte credit`),e>this.options.maxByteCredit)throw RangeError(`byte credit exceeds host maximum`)}accepted(e,t,n=!1){return{kind:`accepted`,protocol:S,...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:S,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:t,usage:this.errorResourceUsage()}}async forceFatalCleanup(){this.cancelRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;for(let t of[...this.leases.keys()])try{await this.release(t)}catch(t){e??=t}if(!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch(t){e??=t}if(e)throw e;this.unregisterCleanup()}allocateWireLeaseId(){if(!Number.isSafeInteger(this.nextWireLeaseId)||this.nextWireLeaseId<=0)throw RangeError(`wire lease id space exhausted`);return this.nextWireLeaseId++}arrayBufferTransferBytes(e){let t=0;for(let n of e??[])if(n instanceof ArrayBuffer&&(t+=n.byteLength,!Number.isSafeInteger(t)))throw RangeError(`ArrayBuffer transfer bytes overflow`);return t}maybeUnregisterCompleted(){this.completed&&this.leases.size===0&&this.unregisterCleanup()}resourceUsage(){return this.options.driver.resourceUsage?.()}errorResourceUsage(){try{return this.resourceUsage()}catch{return}}};function T(e,t){if(!Number.isSafeInteger(e)||e<0)throw Error(`${t} must be a non-negative safe integer`)}function E(e,t,n){return T(e,`resource measurement`),T(t,`resource measurement`),T(n,`resource measurement limit`),e>n||t>n||t>n-e?n===2**53-1?n:n+1:e+t}function Oe(e,t=2**53-1){T(t,`resource measurement limit`);let n=0;for(let r=0;r<e.length;r+=1){let i=e.charCodeAt(r),a;if(i<=127)a=1;else if(i<=2047)a=2;else if(i>=55296&&i<=56319&&r+1<e.length){let t=e.charCodeAt(r+1);t>=56320&&t<=57343?(a=4,r+=1):a=3}else a=3;if(n=E(n,a,t),n>t)return n}return n}function D(e,t=2**53-1){T(t,`resource measurement limit`);let n=E(0,2,t);if(n>t)return n;for(let r=0;r<e.length;r+=1){let i=e.charCodeAt(r),a;if(i===34||i===92||i===8||i===9||i===10||i===12||i===13)a=2;else if(i<=31)a=6;else if(i<=127)a=1;else if(i<=2047)a=2;else if(i>=55296&&i<=56319&&r+1<e.length){let t=e.charCodeAt(r+1);t>=56320&&t<=57343?(a=4,r+=1):a=6}else a=i>=55296&&i<=57343?6:3;if(n=E(n,a,t),n>t)return n}return n}function O(e,t){return E(0,e,t)}function k(e,t=2**53-1,n=!1){if(T(t,`resource measurement limit`),e===null)return{jsonBytes:O(4,t),stringValueUtf8Bytes:0};if(typeof e==`string`)return{jsonBytes:D(e,t),stringValueUtf8Bytes:Oe(e,t)};if(typeof e==`boolean`)return{jsonBytes:O(e?4:5,t),stringValueUtf8Bytes:0};if(typeof e==`number`)return{jsonBytes:O((Number.isFinite(e)?String(Object.is(e,-0)?0:e):`null`).length,t),stringValueUtf8Bytes:0};if(typeof e==`bigint`)throw TypeError(`BigInt values cannot be serialized to JSON`);if(Array.isArray(e)){let n=O(2,t),r=0;for(let i=0;i<e.length;i+=1){i!==0&&(n=E(n,1,t));let a=k(e[i],t,!0);n=E(n,a.jsonBytes,t),r=E(r,a.stringValueUtf8Bytes,t)}return{jsonBytes:n,stringValueUtf8Bytes:r}}if(typeof e==`object`){let n=O(2,t),r=0,i=0;for(let[a,o]of Object.entries(e)){if(o===void 0||typeof o==`function`||typeof o==`symbol`)continue;i++!==0&&(n=E(n,1,t)),n=E(n,D(a,t),t),n=E(n,1,t);let e=k(o,t);n=E(n,e.jsonBytes,t),r=E(r,e.stringValueUtf8Bytes,t)}return{jsonBytes:n,stringValueUtf8Bytes:r}}return{jsonBytes:n?O(4,t):0,stringValueUtf8Bytes:0}}({...i,...s});function*A(e){for(let t of e?.paragraphs??[])for(let e of t.runs)e.type===`text`&&(yield e.text)}function*ke(e){for(let t of e.elements)if(t.type===`shape`)yield*A(t.textBody);else if(t.type===`table`)for(let e of t.rows)for(let t of e.cells)yield*A(t.textBody);else if(t.type===`chart`){t.chart.title&&(yield t.chart.title);for(let e of t.chart.categories)yield e;for(let e of t.chart.series)e.name&&(yield e.name)}}var Ae=class e{scripts;constructor(e,t,n){this.majorFont=e,this.minorFont=t;let r=a(e)??a(t)??null;this.scripts=n??new ee(r)}addSlide(e){this.scripts.addText(ke(e))}names(){return[this.majorFont,this.minorFont,...this.scripts.names()]}withSlide(t){let n=new e(this.majorFont,this.minorFont,this.scripts.clone());return n.addSlide(t),n}};const j=Object.freeze({archiveEntryCount:0,declaredInflatedBytes:0,distinctInflatedBytes:0,operationInflatedBytes:0}),M=67108864;function N(e,t){if(e!==null&&typeof e!=`string`)throw Error(`invalid PPTX presentation bootstrap ${t}`)}function je(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`invalid PPTX presentation bootstrap slide at ${t}`);let n=e;if(n.index!==t)throw Error(`invalid PPTX presentation bootstrap slide index ${n.index}`);if(n.partName!==void 0&&typeof n.partName!=`string`)throw Error(`invalid PPTX presentation bootstrap slide partName at ${t}`);return Object.freeze({index:n.index,...n.partName===void 0?{}:{partName:n.partName}})}function Me(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`invalid PPTX presentation bootstrap payload`);let t=e;if(!Number.isSafeInteger(t.slideCount)||(t.slideCount??-1)<0||!Number.isSafeInteger(t.slideWidth)||(t.slideWidth??0)<=0||!Number.isSafeInteger(t.slideHeight)||(t.slideHeight??0)<=0||!Array.isArray(t.slides)||t.slides.length!==t.slideCount)throw Error(`invalid PPTX presentation bootstrap dimensions or slide count`);return N(t.defaultTextColor,`defaultTextColor`),N(t.majorFont,`majorFont`),N(t.minorFont,`minorFont`),N(t.hlinkColor,`hlinkColor`),N(t.folHlinkColor,`folHlinkColor`),Object.freeze({slideCount:t.slideCount,slideWidth:t.slideWidth,slideHeight:t.slideHeight,defaultTextColor:t.defaultTextColor,majorFont:t.majorFont,minorFont:t.minorFont,hlinkColor:t.hlinkColor,folHlinkColor:t.folHlinkColor,slides:Object.freeze(t.slides.map(je))})}function Ne(e){return Object.freeze({type:`media`,x:e.x,y:e.y,width:e.width,height:e.height,rotation:e.rotation,flipH:e.flipH,flipV:e.flipV,mediaKind:e.mediaKind,posterPath:e.posterPath,posterMimeType:e.posterMimeType,mediaPath:e.mediaPath,mimeType:e.mimeType})}function Pe(e,t){if(e.index!==t.index||e.partName!==t.partName)throw Error(`PPTX pulled slide identity does not match bootstrap index ${t.index}`);return Object.freeze({index:t.index,...t.partName===void 0?{}:{partName:t.partName},notes:e.notes??null,hidden:e.hidden??!1,mediaElements:Object.freeze(e.elements.filter(e=>e.type===`media`).map(Ne))})}function Fe(e,n,r){if(!(e<=n))throw new t(`PPTX presentation preflight exceeded its hard limit of ${n} projected bytes`,{stage:`parsing`,violation:{format:`pptx`,operation:`presentation-preflight`,resource:`presentation-preflight`,metric:`projected-bytes`,limit:n,observed:Math.min(e,n+1),configurable:!1,usage:r}})}var Ie=class{slideCountValue;slideWidthValue;slideHeightValue;defaultTextColorValue;majorFontValue;minorFontValue;hlinkColorValue;folHlinkColorValue;descriptors;slides=[];fonts;fontPreloadNames;fontProjectionBytes;projectionBytesValue;limit;pending=null;finished=null;constructor(e,t={}){let n=Me(e),r=t.hardLimitForTesting??M;if(!Number.isSafeInteger(r)||r<=0||r>M)throw Error(`invalid PPTX presentation preflight test limit`);this.limit=r,this.slideCountValue=n.slideCount,this.slideWidthValue=n.slideWidth,this.slideHeightValue=n.slideHeight,this.defaultTextColorValue=n.defaultTextColor,this.majorFontValue=n.majorFont,this.minorFontValue=n.minorFont,this.hlinkColorValue=n.hlinkColor,this.folHlinkColorValue=n.folHlinkColor,this.descriptors=[...n.slides],this.fonts=new Ae(this.majorFontValue,this.minorFontValue),this.fontPreloadNames=Object.freeze(this.fonts.names()),this.fontProjectionBytes=k(this.fontPreloadNames,this.limit).jsonBytes,this.projectionBytesValue=k({slideCount:this.slideCountValue,slideWidth:this.slideWidthValue,slideHeight:this.slideHeightValue,defaultTextColor:this.defaultTextColorValue,majorFont:this.majorFontValue,minorFont:this.minorFontValue,hlinkColor:this.hlinkColorValue,folHlinkColor:this.folHlinkColorValue,remainingSlides:this.descriptors,slides:[],fontPreloadNames:this.fontPreloadNames},this.limit).jsonBytes,Fe(this.projectionBytesValue,this.limit,j)}get acceptedSlideCount(){return this.finished?.slideCount??this.slides.length}get projectedBytes(){return this.projectionBytesValue}get remainingDescriptorCount(){return this.descriptors.reduce((e,t)=>e+Number(t!==void 0),0)}addSlide(e,t=j){this.prepareSlide(e,t).commit()}prepareSlide(e,t=j){if(this.finished)throw Error(`PPTX presentation preflight is already finished`);if(this.pending)throw Error(`PPTX presentation preflight already has a prepared slide`);let n=this.slides.length,r=this.descriptors[n];if(!r)throw Error(`PPTX presentation preflight received an extra slide`);let i=Pe(e,r),a=this.fonts.withSlide(e),o=Object.freeze(a.names()),s=k(o,this.limit).jsonBytes,ee=k(i,this.limit).jsonBytes,c=this.projectionBytesValue-this.fontProjectionBytes-k(r,this.limit).jsonBytes+4;c=E(c,s,this.limit),c=E(c,ee,this.limit),this.slides.length!==0&&(c=E(c,1,this.limit));let te=k({slide:i,fontPreloadNames:o},this.limit).jsonBytes,l=E(this.projectionBytesValue,te,this.limit);Fe(Math.max(l,c),this.limit,t);let u={state:`prepared`,fact:i,fonts:a,fontNames:o,fontBytes:s,committedBytes:c};return this.pending=u,{projectedBytes:l,commit:()=>{if(u.state!==`committed`){if(u.state===`rolled-back`)throw Error(`PPTX presentation preflight cannot commit a rolled-back slide`);if(this.pending!==u)throw Error(`PPTX presentation preflight prepared slide is stale`);this.descriptors[n]=void 0,this.slides.push(u.fact),this.fonts=u.fonts,this.fontPreloadNames=u.fontNames,this.fontProjectionBytes=u.fontBytes,this.projectionBytesValue=u.committedBytes,u.state=`committed`,this.pending=null}},rollback:()=>{if(u.state!==`rolled-back`){if(u.state===`committed`)throw Error(`PPTX presentation preflight cannot roll back a committed slide`);if(this.pending!==u)throw Error(`PPTX presentation preflight prepared slide is stale`);u.state=`rolled-back`,this.pending=null}}}}finish(){if(this.finished)return this.finished;if(this.pending)throw Error(`PPTX presentation preflight has an uncommitted slide`);if(this.slides.length!==this.slideCountValue)throw Error(`PPTX presentation preflight is incomplete: ${this.slides.length}/${this.slideCountValue} slides`);return this.finished=Object.freeze({slideCount:this.slideCountValue,slideWidth:this.slideWidthValue,slideHeight:this.slideHeightValue,defaultTextColor:this.defaultTextColorValue,majorFont:this.majorFontValue,minorFont:this.minorFontValue,hlinkColor:this.hlinkColorValue,folHlinkColor:this.folHlinkColorValue,slides:Object.freeze([...this.slides]),fontPreloadNames:this.fontPreloadNames}),this.descriptors=[],this.slides=[],this.projectionBytesValue=k(this.finished,this.limit).jsonBytes,this.finished}};function Le(e){try{return de(e(e=>e.slide_cursor_resource_usage()))}catch(e){if(String(e).includes(`slide cursor usage is unavailable`))return;throw e}}function Re(e,t,n,r,i){let a,o;try{if(i){if(!r)throw Error(`slide payload is missing before acknowledgement`);let t=i(n,r,Le(e));typeof t==`function`?a=t:t&&({rollback:a,commit:o}=t)}e(e=>e.acknowledge_slide(t.operationId,t.generation)),o?.()}catch(e){try{a?.()}catch{}throw e}}var ze=class{coordinatorGeneration=new w;sessions=new Map;pendingOpens=new Map;operationTail=Promise.resolve();resourceFailure;lifecycleState=`ready`;resetBarrier;resetIdentities=new Map;constructor(e,t,n=e=>e(this.requireArchive())){this.archive=e,this.acceptSlide=t,this.executeArchive=n}get coordinator(){return this.coordinatorGeneration}reserveOpen(e){if(this.assertReady(),Ve(e),this.pendingOpens.has(e.sessionId)||this.sessions.has(e.sessionId))throw Error(`slide pull session id is already reserved`);this.pendingOpens.set(e.sessionId,{identity:e,canceled:!1})}abandonOpen(e){this.pendingOpens.delete(e)}get pendingOpenCount(){return this.pendingOpens.size}async open(e,t){if(this.assertReady(),this.resourceFailure)throw this.resourceFailure;if(!Number.isSafeInteger(e)||e<0)throw RangeError(`slide index must be a non-negative safe integer`);let n=this.pendingOpens.get(t.sessionId);if(!n||!P(n.identity,t))throw Error(`slide pull session open reservation is stale or missing`);let r,i=new Promise(e=>{r=e}),a=this.operationTail.then(()=>this.coordinator.enqueue(async()=>{if(n.canceled)throw Error(`slide pull session open was canceled`);let i,a=!1,o=new De({...t,maxByteCredit:x,coordinator:this.coordinator,driver:{pull:n=>{let r;try{r=this.executeArchive(r=>r.pull_slide(e,t.operationId,t.generation,n))}catch(e){throw ce(e,n,x)||(this.latchResourceFailure(e),e)}let o=we(r);return this.acceptSlide&&(i=JSON.parse(new TextDecoder().decode(new Uint8Array(o)))),a=!0,{payload:o,byteLength:o.byteLength,done:!0,transfer:[o]}},measureChunk:({payload:e})=>e.byteLength,acknowledge:()=>{if(!a)throw Error(`slide unit is not awaiting acknowledgement`);try{Re(this.executeArchive,t,e,i,this.acceptSlide)}catch(e){throw this.latchResourceFailure(e),e}a=!1,i=void 0,this.sessions.delete(t.sessionId),r()},cancel:async()=>{try{this.archive()&&await this.executeArchive(e=>e.cancel_slide())}finally{i=void 0,a=!1,this.sessions.delete(t.sessionId),r()}},close:async()=>{try{this.archive()&&await this.executeArchive(e=>e.cancel_slide())}finally{i=void 0,a=!1,this.sessions.delete(t.sessionId),r()}},resourceUsage:()=>{try{return this.readResourceUsage()}catch(e){throw this.latchResourceFailure(e),e}}}});this.sessions.set(t.sessionId,{host:o,identity:t}),this.pendingOpens.delete(t.sessionId)}));this.operationTail=a.then(()=>i,()=>void 0);try{await a}catch(e){throw this.pendingOpens.delete(t.sessionId),r(),e}}async postOpenedSafely(e,t,n){if(this.lifecycleState!==`ready`){try{n(this.lifecycleError())}catch{}return}try{t()}catch(t){await this.closeIdentity(e);try{n(t)}catch{}}}dispatch(e,t){if(this.lifecycleState!==`ready`)return t(this.responseDuringReset(e)),Promise.resolve();let n=this.sessions.get(e.sessionId);if(n)return n.host.dispatch(e,t);let r=this.pendingOpens.get(e.sessionId);if(r&&(e.kind===`cancel`||e.kind===`close`)){let n=P(r.identity,e);return n&&(r.canceled=!0),t(n?{protocol:S,kind:`accepted`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,command:e.kind}:this.staleLifecycleResponse(e)),Promise.resolve()}return e.kind===`cancel`||e.kind===`close`?(t({protocol:S,kind:`accepted`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,command:e.kind}),Promise.resolve()):(t({protocol:S,kind:`error`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:b(Error(`slide pull session is not open`))}),Promise.resolve())}async dispatchSafely(e,t){try{await this.dispatch(e,t)}catch(n){try{t({protocol:S,kind:`error`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:b(n)})}catch{}}}run(e){if(this.lifecycleState!==`ready`)return Promise.reject(this.lifecycleError());let t=this.operationTail.then(()=>this.coordinator.enqueue(async()=>{if(this.resourceFailure)throw this.resourceFailure;return e()})).catch(e=>{throw this.latchResourceFailure(e),e});return this.operationTail=t.then(()=>void 0,()=>void 0),t}reset(){if(this.resetBarrier)return this.resetBarrier;this.lifecycleState=`resetting`,this.captureResetIdentities();let e=this.performReset().then(()=>{this.resetIdentities.clear(),this.lifecycleState=`ready`},e=>{throw this.lifecycleState=`reset-failed`,e}).finally(()=>{this.resetBarrier===e&&(this.resetBarrier=void 0)});return this.resetBarrier=e,e}async performReset(){for(let e of this.pendingOpens.values())e.canceled=!0;let e=1;for(let{host:t,identity:n}of[...this.sessions.values()]){let r;if(await t.dispatch({protocol:S,kind:`close`,...n,requestId:e++},e=>{e.kind===`error`&&(r=Ce(e.error))}),r)throw r}this.sessions.clear(),await this.operationTail,this.pendingOpens.clear(),this.archive()&&await this.executeArchive(e=>e.close_presentation_session()),this.coordinatorGeneration=new w,this.resourceFailure=void 0}assertReady(){if(this.lifecycleState!==`ready`)throw this.lifecycleError()}lifecycleError(){let e=this.lifecycleState===`reset-failed`,t=Error(e?`slide pull worker reset failed; retry reset before new work`:`slide pull worker reset is in progress`);return t.name=`PullSessionLifecycleError`,Object.assign(t,{code:e?`ooxml-pull-reset-failed`:`ooxml-pull-resetting`})}captureResetIdentities(){for(let{identity:e}of this.sessions.values())this.resetIdentities.set(e.sessionId,e);for(let{identity:e}of this.pendingOpens.values())this.resetIdentities.set(e.sessionId,e)}responseDuringReset(e){if(e.kind===`cancel`||e.kind===`close`){let t=this.resetIdentities.get(e.sessionId);return t&&!P(t,e)?this.staleLifecycleResponse(e):{protocol:S,kind:`accepted`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,command:e.kind}}return{protocol:S,kind:`error`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:b(this.lifecycleError())}}requireArchive(){let e=this.archive();if(!e)throw Error(`Presentation not loaded`);return e}async closeIdentity(e){if(this.lifecycleState!==`ready`)return;let t=this.sessions.get(e.sessionId);if(t){await t.host.dispatch({protocol:S,kind:`close`,...e,requestId:1},()=>void 0);return}let n=this.pendingOpens.get(e.sessionId);n&&P(n.identity,e)&&(n.canceled=!0)}readResourceUsage(){return Le(this.executeArchive)}latchResourceFailure(e){let n=e instanceof t?e:y(e);n&&(this.resourceFailure??=n)}staleLifecycleResponse(e){return{protocol:S,kind:`error`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:{message:`stale lifecycle targets another slide operation`,errorName:`PullSessionProtocolError`,code:`ooxml-stale-lifecycle`}}}};function Be(e){return!!e&&typeof e==`object`&&e.protocol===`ooxml-pull-v1`}function Ve(e){if(!Number.isSafeInteger(e.sessionId)||e.sessionId<=0)throw RangeError(`session id must be a positive safe integer`);if(!Number.isSafeInteger(e.operationId)||e.operationId<=0)throw RangeError(`operation id must be a positive safe integer`);if(!Number.isSafeInteger(e.generation)||e.generation<=0)throw RangeError(`generation must be a positive safe integer`)}function P(e,t){return e.sessionId===t.sessionId&&e.operationId===t.operationId&&e.generation===t.generation}var F=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,Ue.unregister(this),e}free(){let e=this.__destroy_into_raw();J.__wbg_pptxarchive_free(e,0)}acknowledge_slide(e,t){let n=J.pptxarchive_acknowledge_slide(this.__wbg_ptr,e,t);if(n[1])throw U(n[0])}assert_healthy(){let e=J.pptxarchive_assert_healthy(this.__wbg_ptr);if(e[1])throw U(e[0])}cancel_slide(){J.pptxarchive_cancel_slide(this.__wbg_ptr)}close_presentation_session(){J.pptxarchive_close_presentation_session(this.__wbg_ptr)}extract_image(e){let t=H(e,J.__wbindgen_malloc,J.__wbindgen_realloc),n=q,r=J.pptxarchive_extract_image(this.__wbg_ptr,t,n);if(r[3])throw U(r[2]);var i=I(r[0],r[1]).slice();return J.__wbindgen_free(r[0],r[1]*1,1),i}extract_media(e){let t=H(e,J.__wbindgen_malloc,J.__wbindgen_realloc),n=q,r=J.pptxarchive_extract_media(this.__wbg_ptr,t,n);if(r[3])throw U(r[2]);var i=I(r[0],r[1]).slice();return J.__wbindgen_free(r[0],r[1]*1,1),i}constructor(e,t,n,r){let i=Ge(e,J.__wbindgen_malloc),a=q,o=J.pptxarchive_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,Ue.register(this,this.__wbg_ptr,this),this}parse(){let e=J.pptxarchive_parse(this.__wbg_ptr);if(e[3])throw U(e[2]);var t=I(e[0],e[1]).slice();return J.__wbindgen_free(e[0],e[1]*1,1),t}presentation_bootstrap(){let e=J.pptxarchive_presentation_bootstrap(this.__wbg_ptr);if(e[3])throw U(e[2]);var t=I(e[0],e[1]).slice();return J.__wbindgen_free(e[0],e[1]*1,1),t}pull_slide(e,t,n,r){let i=J.pptxarchive_pull_slide(this.__wbg_ptr,e,t,n,r);if(i[3])throw U(i[2]);var a=I(i[0],i[1]).slice();return J.__wbindgen_free(i[0],i[1]*1,1),a}resource_usage(){let e=J.pptxarchive_resource_usage(this.__wbg_ptr);if(e[3])throw U(e[2]);var t=I(e[0],e[1]).slice();return J.__wbindgen_free(e[0],e[1]*1,1),t}slide_cursor_resource_usage(){let e=J.pptxarchive_slide_cursor_resource_usage(this.__wbg_ptr);if(e[3])throw U(e[2]);var t=I(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.pptxarchive_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&&(F.prototype[Symbol.dispose]=F.prototype.free);function He(){return{__proto__:null,\"./pptx_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;We().setInt32(e+4,i,!0),We().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 Ue=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>J.__wbg_pptxarchive_free(e>>>0,1));function I(e,t){return e>>>=0,B().subarray(e/1,e/1+t)}let L=null;function We(){return(L===null||L.buffer.detached===!0||L.buffer.detached===void 0&&L.buffer!==J.memory.buffer)&&(L=new DataView(J.memory.buffer)),L}function R(e,t){return e>>>=0,Ke(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 Ge(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 Ke(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 qe(e,t){return J=e.exports,L=null,z=null,J.__wbindgen_start(),J}async function Je(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 Ye(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=He();(typeof e==`string`||typeof Request==`function`&&e instanceof Request||typeof URL==`function`&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await Je(await e,t);return qe(n,r)}async function Xe(e){return J=void 0,L=null,z=null,Ye(e)}const Y=new ae(Ye,{freeArchive:e=>e.free(),reinit:Xe});let X=null,Z=`empty`;function Ze(){if(Z!==`empty`){let e=Error(`this PPTX worker already owns a presentation parse`);throw e.name=`PptxWorkerStateError`,Object.assign(e,{code:`ooxml-pptx-parse-already-started`})}Z=`opening`}const Q=new ze(()=>Y.archive,(e,t,n)=>{if(X){if(e!==X.acceptedSlideCount)throw Error(`PPTX preflight expected slide ${X.acceptedSlideCount}, received ${e}`);return X.prepareSlide(t,n)}},e=>{let t=Y.archive;if(!t)throw Error(`Presentation not loaded`);return Y.run(()=>e(t))}),$=(e,t)=>self.postMessage(e,t);self.onmessage=async e=>{let t=e.data;if(Be(t)){await Q.dispatchSafely(t,$);return}if(t.kind===`init`){Y.setWasmInput(te(t.wasmUrl)??t.wasmUrl);return}let n=t.id,r=!1;try{if(t.kind===`openSlideSession`&&Q.reserveOpen(t),t.kind===`parse`&&(Ze(),r=!0),t.kind===`openSlideSession`){await Y.ensureReady(),await Q.open(t.slideIndex,t),await Q.postOpenedSafely(t,()=>$({kind:`slideSessionOpened`,id:n,sessionId:t.sessionId,operationId:t.operationId,generation:t.generation}),e=>$({kind:`error`,id:n,...b(e)}));return}t.kind===`parse`&&await Q.reset(),await Q.run(async()=>{if(await Y.ensureReady(),t.kind!==`parse`&&Y.archive){let e=Y.archive;Y.run(()=>e.assert_healthy())}if(t.kind===`parse`){X=null;let[e,r,i]=Te(t.resourcePolicy),a=Y.run(()=>{let n=new F(new Uint8Array(t.buffer),e,r,i);return Y.setArchive(n),JSON.parse(new TextDecoder().decode(n.presentation_bootstrap()))});X=new Ie(a),$({kind:`presentationOpened`,id:n,bootstrap:a}),Z=`ready`;return}let e=Y.archive;if(!e)throw Error(`No pptx loaded`);if(t.kind===`finishPresentationPreflight`){if(!X)throw Error(`PPTX presentation preflight is not active`);let e=X.finish();X=null,$({kind:`presentationPreflightReady`,id:n,preflight:e});return}if(t.kind===`extractMedia`){let r=Y.run(()=>e.extract_media(t.path).buffer);$({kind:`mediaExtracted`,id:n,bytes:r},[r]);return}if(t.kind===`extractImage`){let r=Y.run(()=>e.extract_image(t.path).buffer);$({kind:`imageExtracted`,id:n,bytes:r},[r]);return}if(t.kind===`resourceUsage`){$({kind:`resourceUsage`,id:n,usage:de(Y.run(()=>e.resource_usage()))});return}t.kind===`toMarkdown`&&$({kind:`markdownRendered`,id:n,markdown:Y.run(()=>e.to_markdown())})})}catch(e){r&&(Z=`failed`),t.kind===`openSlideSession`&&Q.abandonOpen(t.sessionId);try{$({kind:`error`,id:n,...b(e)})}catch{}}};", We = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", Ue], { type: "text/javascript;charset=utf-8" });
535
- function Ge(e) {
536
- let t;
537
- try {
538
- if (t = We && (self.URL || self.webkitURL).createObjectURL(We), !t) throw "";
539
- let n = new Worker(t, {
540
- type: "module",
541
- name: e?.name
542
- });
543
- return n.addEventListener("error", () => {
544
- (self.URL || self.webkitURL).revokeObjectURL(t);
545
- }), n;
546
- } catch {
547
- return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(Ue), {
548
- type: "module",
549
- name: e?.name
550
- });
551
- }
552
- }
553
- //#endregion
554
- //#region packages/pptx/src/wasm/pptx_parser_bg.wasm?url
555
- var Ke = new URL("pptx_parser_bg.wasm", import.meta.url).href, Q = class e {
556
- _metrics = null;
557
- _worker;
558
- _bridge;
559
- _mode = "main";
560
- _preflight = null;
561
- _slides = null;
562
- _slidePullClient = null;
563
- _resourceFailure = null;
564
- _slidePartIndex = null;
565
- _rawParts = new be({
566
- maxEntries: 64,
567
- maxBytes: T
568
- });
569
- _googleFontFaces = [];
570
- _fetchImage = (e, t) => this.getImage(e, t);
571
- _fetchMedia = (e) => this.getMedia(e);
572
- _math;
573
- constructor(e, t, n) {
574
- this._worker = e, this._mode = t, this._bridge = new me(this._worker, {
575
- correlate: (e) => "protocol" in e && e.protocol === "ooxml-pull-v1" ? e.requestId : "id" in e ? e.id : void 0,
576
- toError: (e) => !("protocol" in e) && e.kind === "error" ? S(e) : void 0
577
- });
578
- let r = new URL(n ?? Ke, location.href).href;
579
- this._bridge.post({
580
- kind: "init",
581
- wasmUrl: r
582
- });
583
- }
584
- _assertResourceHealthy() {
585
- if (this._resourceFailure) throw this._resourceFailure;
586
- }
587
- _rethrowWithResourceFailure(e) {
588
- let t = e instanceof y ? e : _(e);
589
- throw t ? (this._resourceFailure ??= t, this._resourceFailure) : e;
590
- }
591
- static async load(t, n = {}) {
592
- let r = u(n), i = n.mode ?? "main", a = new h({
593
- enabled: !0,
594
- format: "pptx",
595
- mode: i,
596
- policy: r.policy,
597
- onMetrics: r.onResourceMetrics,
598
- emitToConsole: r.debug
599
- });
600
- try {
601
- if (i === "worker" && (typeof Worker > "u" || typeof OffscreenCanvas > "u")) throw Error("mode: 'worker' requires Worker and OffscreenCanvas support");
602
- let s;
603
- if (typeof t == "string") {
604
- let e = await fetch(t);
605
- if (!e.ok) throw Error(`Failed to fetch: ${e.status} ${e.statusText}`);
606
- s = await e.arrayBuffer();
607
- } else s = t;
608
- s = he(await ne(s, n.password)), a.setSourceBytes(s.byteLength), a.checkpoint("container ready");
609
- let c = i === "worker" ? (await import("./render-worker-host-CKOmXdyr.js")).createRenderWorker() : new Ge(), l;
610
- try {
611
- return l = new e(c, i, n.wasmUrl), l._metrics = a, n.math && i === "worker" && console.warn("[ooxml] the math engine is unavailable in mode: 'worker'; equations will be skipped. Use mode: 'main' for documents with equations."), l._math = i === "worker" ? void 0 : n.math, await l._parse(s, r.policy, i === "worker" ? !!n.useGoogleFonts : !1, n.workerTimeoutMs, (e) => a.observeUsage(e)), a.checkpoint("presentation preflight ready"), i === "main" && n.useGoogleFonts && l._preflight && (l._googleFontFaces = await ve(l._preflight.fontPreloadNames, o)), a.succeed({ slides: l.slideCount }), l;
612
- } catch (e) {
613
- let t = l;
614
- throw te(c, t ? () => t.destroy() : void 0), e;
615
- }
616
- } catch (e) {
617
- throw a.fail(e), e;
618
- }
619
- }
620
- async _parse(e, n, i = !1, o, s) {
621
- let c = await this._bridge.request((t) => this._mode === "worker" ? {
622
- kind: "parse",
623
- id: t,
624
- buffer: e,
625
- resourcePolicy: n,
626
- useGoogleFonts: i
627
- } : {
628
- kind: "parse",
629
- id: t,
630
- buffer: e,
631
- resourcePolicy: n
632
- }, [e], { timeoutMs: o });
633
- if (this._mode === "worker") {
634
- let e = c;
635
- e.usage && s?.(e.usage), this._preflight = t(c.preflight);
636
- return;
637
- }
638
- let u = r(c.bootstrap);
639
- this._slidePullClient = new l({
640
- slideCount: u.slideCount,
641
- transport: this._bridge.transport(a),
642
- open: async (e, t, n) => {
643
- await this._bridge.request((n) => ({
644
- kind: "openSlideSession",
645
- id: n,
646
- slideIndex: e,
647
- ...t
648
- }), void 0, { timeoutMs: n });
649
- },
650
- onUsage: s
651
- });
652
- for (let e = 0; e < u.slideCount; e += 1) await this._slidePullClient.load(e, !1, o);
653
- this._preflight = t((await this._bridge.request((e) => ({
654
- kind: "finishPresentationPreflight",
655
- id: e
656
- }), void 0, { timeoutMs: o })).preflight), this._slides = new Ve({
657
- slideCount: this._preflight.slideCount,
658
- maxCachedSlides: 8,
659
- maxCachedStructuralBytes: f,
660
- loadSlide: async (e) => {
661
- let t = await this._slidePullClient?.load(e, !0);
662
- if (!t) throw Error("PPTX slide pull client is unavailable");
663
- return t;
664
- }
665
- });
666
- }
667
- get slideCount() {
668
- return this._preflight?.slideCount ?? 0;
669
- }
670
- get slideWidth() {
671
- return this._preflight?.slideWidth ?? 0;
672
- }
673
- get slideHeight() {
674
- return this._preflight?.slideHeight ?? 0;
675
- }
676
- get mode() {
677
- return this._mode;
678
- }
679
- getNotes(e) {
680
- return Number.isInteger(e) ? this._preflight?.slides[e]?.notes ?? null : null;
681
- }
682
- isHidden(e) {
683
- return Number.isInteger(e) ? this._preflight?.slides[e]?.hidden ?? !1 : !1;
684
- }
685
- _partNames() {
686
- return (this._preflight?.slides ?? []).map((e) => e.partName);
687
- }
688
- _partIndex() {
689
- return this._slidePartIndex ||= Re(this._partNames()), this._slidePartIndex;
690
- }
691
- getSlideIndexByPartName(e) {
692
- return this._partIndex().get(e);
693
- }
694
- resolveInternalTarget(e, t = 0) {
695
- return Be(e, this._partIndex(), t);
696
- }
697
- async renderSlide(e, t, r = {}) {
698
- this._assertResourceHealthy();
699
- try {
700
- if (this._mode === "worker") throw Error("renderSlide(canvas) is unavailable in mode: 'worker'; use renderSlideToBitmap() and paint it via an ImageBitmapRenderingContext");
701
- let i = this._preflight, a = this._slides;
702
- if (!i || !a) throw Error("Presentation not loaded");
703
- let o = r.dpr ?? b(), s = r.width ?? ((v(e) ? e.offsetWidth : 0) || 960);
704
- await a.withSlide(t, (t) => (this._assertResourceHealthy(), n(e, t, i.slideWidth, i.slideHeight, {
705
- width: s,
706
- dpr: o,
707
- defaultTextColor: i.defaultTextColor,
708
- majorFont: i.majorFont,
709
- minorFont: i.minorFont,
710
- hlinkColor: i.hlinkColor,
711
- fetchMedia: this._fetchMedia,
712
- fetchImage: this._fetchImage,
713
- skipMediaControls: r.skipMediaControls,
714
- dim: r.dim,
715
- math: this._math
716
- }, r.onTextRun)));
717
- } catch (e) {
718
- this._rethrowWithResourceFailure(e);
719
- }
720
- }
721
- async renderSlideToBitmap(e, t = {}) {
722
- this._assertResourceHealthy();
723
- try {
724
- let n = t.width ?? 960, r = t.dpr ?? b();
725
- if (this._mode === "worker") {
726
- if (!Number.isInteger(e) || e < 0 || e >= this.slideCount) throw Error(`Slide index ${e} out of range (count: ${this.slideCount})`);
727
- let i = await this._bridge.request((i) => ({
728
- kind: "renderSlide",
729
- id: i,
730
- slideIndex: e,
731
- width: n,
732
- dpr: r,
733
- skipMediaControls: t.skipMediaControls,
734
- dim: t.dim
735
- }));
736
- if (t.onTextRun) for (let e of i.runs) t.onTextRun(e);
737
- return i.bitmap;
738
- }
739
- let i = new OffscreenCanvas(1, 1);
740
- return await this.renderSlide(i, e, {
741
- width: n,
742
- dpr: r,
743
- skipMediaControls: t.skipMediaControls,
744
- dim: t.dim,
745
- onTextRun: t.onTextRun
746
- }), i.transferToImageBitmap();
747
- } catch (e) {
748
- this._rethrowWithResourceFailure(e);
749
- }
750
- }
751
- async collectSlideRuns(e, t = 960) {
752
- this._assertResourceHealthy();
753
- try {
754
- if (this._mode === "worker") {
755
- if (!Number.isInteger(e) || e < 0 || e >= this.slideCount) throw Error(`Slide index ${e} out of range (count: ${this.slideCount})`);
756
- return (await this._bridge.request((n) => ({
757
- kind: "collectRuns",
758
- id: n,
759
- slideIndex: e,
760
- width: t
761
- }))).runs;
762
- }
763
- let n = [], r = new OffscreenCanvas(1, 1);
764
- return await this.renderSlide(r, e, {
765
- width: t,
766
- onTextRun: (e) => n.push(e)
767
- }), n;
768
- } catch (e) {
769
- this._rethrowWithResourceFailure(e);
770
- }
771
- }
772
- async getMedia(e) {
773
- this._assertResourceHealthy();
774
- try {
775
- let t = this._findMimeTypeForPath(e);
776
- return await this._rawParts.get(e, t, async () => {
777
- let n = (await this._bridge.request((t) => ({
778
- kind: "extractMedia",
779
- id: t,
780
- path: e
781
- }))).bytes;
782
- return new Blob([n], { type: t });
783
- });
784
- } catch (e) {
785
- this._rethrowWithResourceFailure(e);
786
- }
787
- }
788
- _findMimeTypeForPath(e) {
789
- return this._preflight ? s(this._preflight, e) : "";
790
- }
791
- async getImage(e, t) {
792
- this._assertResourceHealthy();
793
- try {
794
- return await this._rawParts.get(e, t, async () => {
795
- let n = (await this._bridge.request((t) => ({
796
- kind: "extractImage",
797
- id: t,
798
- path: e
799
- }))).bytes;
800
- return new Blob([n], { type: t });
801
- });
802
- } catch (e) {
803
- this._rethrowWithResourceFailure(e);
804
- }
805
- }
806
- async getResourceMetrics() {
807
- let e = this._metrics;
808
- if (!e) throw Error("Presentation not loaded");
809
- return ee(e, async (e) => (await this._bridge.request((e) => ({
810
- kind: "resourceUsage",
811
- id: e
812
- }), void 0, { timeoutMs: e })).usage);
813
- }
814
- async toMarkdown() {
815
- this._assertResourceHealthy();
816
- try {
817
- return (await this._bridge.request((e) => ({
818
- kind: "toMarkdown",
819
- id: e
820
- }))).markdown;
821
- } catch (e) {
822
- this._rethrowWithResourceFailure(e);
823
- }
824
- }
825
- async presentSlide(e, t, n = {}) {
826
- this._assertResourceHealthy();
827
- try {
828
- if (!this._preflight) throw Error("Presentation not loaded");
829
- if (!Number.isInteger(t) || t < 0 || t >= this.slideCount) throw Error(`Slide index ${t} out of range (count: ${this.slideCount})`);
830
- let r = n.dpr ?? b(), i = n.width ?? (e.offsetWidth || 960), a = this._mode === "worker" ? async () => {
831
- let a = await this.renderSlideToBitmap(t, {
832
- width: i,
833
- dpr: r,
834
- skipMediaControls: !0,
835
- dim: n.dim,
836
- onTextRun: n.onTextRun
837
- });
838
- e.width = a.width, e.height = a.height, e.style.width = `${Math.round(a.width / r)}px`, e.style.display || (e.style.display = "block");
839
- let o = e.getContext("2d");
840
- if (!o) throw Error("2D context not available");
841
- o.drawImage(a, 0, 0), a.close();
842
- } : () => this.renderSlide(e, t, {
843
- width: i,
844
- dpr: r,
845
- skipMediaControls: !0,
846
- dim: n.dim,
847
- onTextRun: n.onTextRun
848
- });
849
- return await je(e, this._preflight.slides[t]?.mediaElements ?? [], {
850
- width: i,
851
- dpr: r,
852
- slideWidthEmu: this.slideWidth,
853
- fetchMedia: this._fetchMedia,
854
- fetchImage: this._fetchImage,
855
- drawBase: a,
856
- onError: n.onError
857
- });
858
- } catch (e) {
859
- this._rethrowWithResourceFailure(e);
860
- }
861
- }
862
- destroy() {
863
- this._slidePullClient?.cancelAll(), this._bridge.terminate(), this._slides?.clear(), this._slides = null, this._slidePullClient = null, this._preflight = null, this._resourceFailure = null, this._slidePartIndex = null, this._rawParts.clear(), this._googleFontFaces.length > 0 && (_e(this._googleFontFaces), this._googleFontFaces = []), C(this._fetchImage), d(this._fetchImage);
864
- }
865
- }, qe = Symbol("PptxViewer.borrowedPresentation"), $ = {
866
- color: "#ffffff",
867
- opacity: .6
868
- }, Je = class e {
869
- canvas;
870
- wrapper;
871
- canvasMount;
872
- _scale = null;
873
- textLayer = null;
874
- highlightLayer = null;
875
- _find;
876
- _measureCtx = null;
877
- presentationOwner;
878
- get engine() {
879
- return this.presentationOwner.current;
880
- }
881
- borrowed;
882
- hostWindow;
883
- opts;
884
- currentSlide = 0;
885
- _hiddenMode;
886
- handle = null;
887
- _mode;
888
- renderDispatcher;
889
- errorRouter;
890
- destroyed = !1;
891
- static fromPresentation(t, n, r = {}) {
892
- return new e(t, {
893
- ...r,
894
- [qe]: n
895
- });
896
- }
897
- constructor(e, t = {}) {
898
- this.opts = t, this.canvas = e;
899
- let n = t[qe];
900
- this.borrowed = n !== void 0, this._mode = k("PptxViewer", t.mode, n), this.presentationOwner = new E("PptxViewer", n ?? null, !1);
901
- let r = e.ownerDocument?.defaultView ?? (typeof window < "u" ? window : null);
902
- if (!r) throw Error("PptxViewer requires a canvas with an active Window");
903
- this.hostWindow = r, this._hiddenMode = t.hiddenSlideMode ?? "show", this.canvasMount = new fe(e, {
904
- wrapperCssText: "position:relative;display:inline-block;vertical-align:top;",
905
- forceDisplayBlock: !0
906
- }), this.wrapper = this.canvasMount.wrapper, this.renderDispatcher = new O(e, this._mode === "worker" && !t.enableMediaPlayback), this.errorRouter = new ue("PptxViewer", t.onError);
907
- let i = new le(this.wrapper, t.enableTextSelection === !0);
908
- this.textLayer = i.textLayer, this.highlightLayer = i.highlightLayer, this._find = new I(() => this.slideCount, (e) => this._collectSlideRuns(e));
909
- }
910
- async load(e) {
911
- if (this.destroyed) throw Error("PptxViewer is destroyed");
912
- if (this.borrowed) throw Error("PptxViewer.load() is unsupported on a Viewer created by fromPresentation(); the borrowed presentation is already loaded.");
913
- try {
914
- if (!await this.presentationOwner.replace(() => Q.load(e, {
915
- useGoogleFonts: this.opts.useGoogleFonts,
916
- maxZipEntryBytes: this.opts.maxZipEntryBytes,
917
- resourceLimits: this.opts.resourceLimits,
918
- debug: this.opts.debug,
919
- onResourceMetrics: this.opts.onResourceMetrics,
920
- workerTimeoutMs: this.opts.workerTimeoutMs,
921
- wasmUrl: this.opts.wasmUrl,
922
- math: this.opts.math,
923
- mode: this._mode
924
- }), () => {
925
- this.renderDispatcher.begin(), this._find.invalidate(), this.handle?.destroy(), this.handle = null;
926
- })) return;
927
- if (this.destroyed) throw Error("PptxViewer is destroyed");
928
- this.currentSlide = this._initialSlide(), this._find.invalidate(), await this.renderCurrentSlide();
929
- } catch (e) {
930
- if (this.destroyed) throw Error("PptxViewer is destroyed");
931
- let t = e instanceof Error ? e : Error(String(e));
932
- if (this.opts.onError) {
933
- this.opts.onError(t);
934
- return;
935
- }
936
- throw t;
937
- }
938
- }
939
- async goToSlide(e) {
940
- !this.engine || this.slideCount === 0 || (this.currentSlide = Math.max(0, Math.min(e, this.slideCount - 1)), await this.renderCurrentSlide());
941
- }
942
- async nextSlide() {
943
- await this.goToSlide(this._step(1));
944
- }
945
- async prevSlide() {
946
- await this.goToSlide(this._step(-1));
947
- }
948
- _step(e) {
949
- return this._hiddenMode === "skip" && this.engine ? Se(this.currentSlide, e, (e) => this.engine.isHidden(e), this.slideCount) : this.currentSlide + e;
950
- }
951
- _initialSlide() {
952
- return this._hiddenMode === "skip" && this.engine ? j(0, (e) => this.engine.isHidden(e), this.slideCount) : 0;
953
- }
954
- _dim() {
955
- return {
956
- color: this.opts.hiddenSlideDim?.color ?? $.color,
957
- opacity: this.opts.hiddenSlideDim?.opacity ?? $.opacity
958
- };
959
- }
960
- async setHiddenSlideMode(e) {
961
- this._hiddenMode = e, e === "skip" && this.engine && (this.currentSlide = j(this.currentSlide, (e) => this.engine.isHidden(e), this.slideCount)), await this.renderCurrentSlide();
962
- }
963
- get hiddenSlideMode() {
964
- return this._hiddenMode;
965
- }
966
- get visibleSlideCount() {
967
- if (!this.engine) return 0;
968
- let e = this.engine;
969
- return Ce((t) => e.isHidden(t), this.slideCount);
970
- }
971
- get slideIndex() {
972
- return this.currentSlide;
973
- }
974
- get slideCount() {
975
- return this.engine?.slideCount ?? 0;
976
- }
977
- getNotes(e) {
978
- return this.engine?.getNotes(e) ?? null;
979
- }
980
- get canvasElement() {
981
- return this.canvas;
982
- }
983
- _naturalWidthPx() {
984
- let e = this.engine?.slideWidth ?? 0;
985
- return e > 0 ? e / x : 0;
986
- }
987
- _targetWidth() {
988
- if (this._scale === null) return this.opts.width ?? (this.canvas.offsetWidth || 960);
989
- let e = this._naturalWidthPx();
990
- return e <= 0 ? this.opts.width ?? (this.canvas.offsetWidth || 960) : Math.round(e * this._scale);
991
- }
992
- getScale() {
993
- if (this._scale !== null) return this._scale;
994
- let e = this._naturalWidthPx();
995
- return e <= 0 ? 1 : this._targetWidth() / e;
996
- }
997
- _zoomMin() {
998
- return this.opts.zoomMin ?? .1;
999
- }
1000
- _zoomMax() {
1001
- return this.opts.zoomMax ?? 4;
1002
- }
1003
- async setScale(e) {
1004
- let t = ie(e, this._zoomMin(), this._zoomMax()), n = t !== this.getScale();
1005
- this._scale = t, await this.renderCurrentSlide(), n && this.opts.onScaleChange?.(t);
1006
- }
1007
- async zoomIn() {
1008
- await this.setScale(A(this.getScale()));
1009
- }
1010
- async zoomOut() {
1011
- await this.setScale(ce(this.getScale()));
1012
- }
1013
- async fitWidth() {
1014
- await this._fit("width");
1015
- }
1016
- async fitPage() {
1017
- await this._fit("page");
1018
- }
1019
- async _fit(e) {
1020
- if (!this.engine) return;
1021
- let t = this.wrapper.parentElement;
1022
- if (!t) return;
1023
- let n = D({
1024
- contentWidth: this.engine.slideWidth / x,
1025
- contentHeight: this.engine.slideHeight / x,
1026
- containerWidth: t.clientWidth,
1027
- containerHeight: t.clientHeight
1028
- }, e);
1029
- n <= 0 || await this.setScale(n);
1030
- }
1031
- async renderCurrentSlide() {
1032
- if (!this.engine) return;
1033
- let e = this.renderDispatcher.begin(), t = this._hiddenMode === "dim" && this.engine.isHidden(this.currentSlide) ? this._dim() : void 0, n = this._targetWidth(), r = this.opts.dpr ?? (window.devicePixelRatio || 1), i = n / this.engine.slideWidth, a = Math.round(this.engine.slideHeight * i);
1034
- this.canvas.style.width = `${n}px`, this.canvas.style.height = `${a}px`, this.handle?.destroy(), this.handle = null;
1035
- let o = this._mode === "worker", s = [], c = (e) => s.push(e);
1036
- try {
1037
- if (this.opts.enableMediaPlayback) {
1038
- let i = await this.engine.presentSlide(this.canvas, this.currentSlide, {
1039
- width: n,
1040
- dpr: r,
1041
- dim: t,
1042
- onTextRun: c,
1043
- onError: (t) => {
1044
- this.renderDispatcher.isCurrent(e) && this._reportRenderError(t);
1045
- }
1046
- });
1047
- if (!this.renderDispatcher.isCurrent(e)) {
1048
- i.destroy();
1049
- return;
1050
- }
1051
- this.handle = i;
1052
- } else if (o) {
1053
- let i = await this.engine.renderSlideToBitmap(this.currentSlide, {
1054
- width: n,
1055
- dpr: r,
1056
- dim: t,
1057
- onTextRun: c
1058
- });
1059
- if (!this.renderDispatcher.commitBitmap(e, i)) return;
1060
- } else if (await this.engine.renderSlide(this.canvas, this.currentSlide, {
1061
- width: n,
1062
- dpr: r,
1063
- onTextRun: c,
1064
- dim: t
1065
- }), !this.renderDispatcher.isCurrent(e)) return;
1066
- this.opts.onSlideChange?.(this.currentSlide, this.slideCount);
1067
- } catch (t) {
1068
- this.renderDispatcher.isCurrent(e) && this._reportRenderError(t);
1069
- return;
1070
- }
1071
- this.textLayer && this._buildTextLayer(this.textLayer, s, n, a), this._find.setSlideRuns(this.currentSlide, s), this._buildHighlightLayer(s, n, a);
1072
- }
1073
- _buildHighlightLayer(e, t, n) {
1074
- let r = this.highlightLayer;
1075
- r && F(r, e, this._find.slideHighlights(this.currentSlide), t, n, (e) => this._measureForFont(e), this.opts.findHighlightColors);
1076
- }
1077
- _measureForFont(e) {
1078
- this._measureCtx ||= document.createElement("canvas").getContext("2d");
1079
- let t = this._measureCtx;
1080
- return t ? (t.font = e, (e) => t.measureText(e).width) : (e) => e.length;
1081
- }
1082
- async _collectSlideRuns(e) {
1083
- return this.engine ? this.engine.collectSlideRuns(e, this._targetWidth()) : [];
1084
- }
1085
- async findText(e, t = {}) {
1086
- if (!this.engine) return [];
1087
- let n = await this._find.find(e, t);
1088
- return this._redrawHighlights(), n;
1089
- }
1090
- async findNext() {
1091
- return this._activateMatch(this._find.next());
1092
- }
1093
- async findPrev() {
1094
- return this._activateMatch(this._find.prev());
1095
- }
1096
- clearFind() {
1097
- this._find.invalidate(), this._redrawHighlights();
1098
- }
1099
- async _activateMatch(e) {
1100
- return e ? (e.location.slide === this.currentSlide ? this._redrawHighlights() : await this.goToSlide(e.location.slide), e) : (this._redrawHighlights(), null);
1101
- }
1102
- _redrawHighlights() {
1103
- let e = this._find.slideRuns(this.currentSlide) ?? [], t = this._targetWidth(), n = this.engine ? Math.round(this.engine.slideHeight * (t / this.engine.slideWidth)) : 0;
1104
- this._buildHighlightLayer(e, t, n);
1105
- }
1106
- _buildTextLayer(e, t, n, r) {
1107
- P(e, t, n, r, this._hyperlinkHandler());
1108
- }
1109
- _hyperlinkHandler() {
1110
- if (this.opts.enableHyperlinks !== !1) return (e) => this._onHyperlinkClick(e);
1111
- }
1112
- _onHyperlinkClick(e) {
1113
- let t = this._resolveInternalSlideIndex(e);
1114
- if (this.opts.onHyperlinkClick) {
1115
- this.opts.onHyperlinkClick(t);
1116
- return;
1117
- }
1118
- if (t.kind === "external") {
1119
- g(t.url, void 0, this.hostWindow);
1120
- return;
1121
- }
1122
- t.slideIndex !== void 0 && this.goToSlide(t.slideIndex);
1123
- }
1124
- _resolveInternalSlideIndex(e) {
1125
- if (e.kind !== "internal" || e.slideIndex !== void 0) return e;
1126
- let t = this.engine?.resolveInternalTarget(e.ref, this.currentSlide);
1127
- return t === void 0 ? e : {
1128
- ...e,
1129
- slideIndex: t
1130
- };
1131
- }
1132
- _reportRenderError(e) {
1133
- this.errorRouter.report(e);
1134
- }
1135
- async getResourceMetrics() {
1136
- if (!this.engine) throw Error("Presentation not loaded");
1137
- return await this.engine.getResourceMetrics();
1138
- }
1139
- destroy() {
1140
- this.destroyed || (this.destroyed = !0, this.errorRouter.close(), this.renderDispatcher.destroy(), c(this.canvas), this.handle?.destroy(), this.handle = null, this.presentationOwner.close(), this._find.invalidate(), this.canvasMount.restore());
1141
- }
1142
- }, Ye = 150, Xe = "0 1px 3px rgba(0,0,0,0.2)", Ze = Symbol("PptxScrollViewer.borrowedPresentation"), Qe = class e {
1143
- _presentationOwner;
1144
- get _pres() {
1145
- return this._presentationOwner.current;
1146
- }
1147
- _borrowed;
1148
- _opts;
1149
- _container;
1150
- _wrapper;
1151
- _scrollHost;
1152
- _spacer;
1153
- _mode;
1154
- _scale = 1;
1155
- _scaleEstablished = !1;
1156
- _pendingScale = null;
1157
- _slots = /* @__PURE__ */ new Map();
1158
- _free = [];
1159
- _heights = [];
1160
- _lastRange = null;
1161
- _lastTopIndex = -1;
1162
- _scrollListener = null;
1163
- _destroyed = !1;
1164
- _slideInFlight = /* @__PURE__ */ new Set();
1165
- _renderEpoch = 0;
1166
- _settleTimer = null;
1167
- _wheelListener = null;
1168
- _pendingZoomAnchor = null;
1169
- _resizeObserver = null;
1170
- _prevBase = 0;
1171
- _lastFitWidth = 0;
1172
- _pageShadow;
1173
- _find = new I(() => this.slideCount, (e) => this._collectSlideRuns(e));
1174
- _findActive = !1;
1175
- _findMeasureCtx;
1176
- static fromPresentation(t, n, r = {}) {
1177
- return new e(t, {
1178
- ...r,
1179
- [Ze]: n
1180
- });
1181
- }
1182
- constructor(e, t = {}) {
1183
- if (e.tagName === "CANVAS") throw Error("PptxScrollViewer 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-slide canvas API use PptxViewer.");
1184
- this._container = e, this._opts = t, this._pageShadow = t.pageShadow ?? Xe;
1185
- let n = t[Ze];
1186
- this._borrowed = n !== void 0, n ? (this._presentationOwner = new E("PptxScrollViewer", n, !1), this._mode = k("PptxScrollViewer", t.mode, n)) : (this._presentationOwner = new E("PptxScrollViewer"), this._mode = k("PptxScrollViewer", t.mode, void 0)), this._wrapper = document.createElement("div"), this._wrapper.style.cssText = "position:relative;width:100%;height:100%;overflow:hidden;", this._scrollHost = document.createElement("div"), this._scrollHost.style.cssText = "position:absolute;inset:0;overflow:auto;", this._scrollHost.style.scrollbarGutter = "stable", t.background && (this._scrollHost.style.background = t.background), this._spacer = document.createElement("div"), this._spacer.style.cssText = "position:absolute;top:0;left:0;width:1px;height:0;pointer-events:none;", this._scrollHost.appendChild(this._spacer), this._wrapper.appendChild(this._scrollHost), this._container.appendChild(this._wrapper), this._scrollListener = () => this._onScroll(), this._scrollHost.addEventListener("scroll", this._scrollListener), this._opts.enableZoom !== !1 && (this._wheelListener = (e) => {
1187
- if (!(e.ctrlKey || e.metaKey) || (e.preventDefault(), e.deltaY === 0)) return;
1188
- let t = this._scrollHost.getBoundingClientRect(), n = e.clientX - t.left, r = e.clientY - t.top;
1189
- this._pendingZoomAnchor = Number.isFinite(n) && Number.isFinite(r) ? {
1190
- x: n,
1191
- y: r
1192
- } : null, this.setScale(ae(this._scale, e.deltaY));
1193
- }, this._scrollHost.addEventListener("wheel", this._wheelListener, { passive: !1 })), typeof ResizeObserver < "u" && (this._resizeObserver = new ResizeObserver(() => this._onResize()), this._resizeObserver.observe(this._container)), this._borrowed && this.relayout();
1194
- }
1195
- async load(e) {
1196
- if (this._destroyed) throw Error("PptxScrollViewer is destroyed");
1197
- if (this._borrowed) throw Error("PptxScrollViewer.load() is unsupported on a Viewer created by fromPresentation(); the borrowed presentation is already loaded.");
1198
- try {
1199
- if (!await this._presentationOwner.replace(() => Q.load(e, {
1200
- useGoogleFonts: this._opts.useGoogleFonts,
1201
- maxZipEntryBytes: this._opts.maxZipEntryBytes,
1202
- resourceLimits: this._opts.resourceLimits,
1203
- debug: this._opts.debug,
1204
- onResourceMetrics: this._opts.onResourceMetrics,
1205
- workerTimeoutMs: this._opts.workerTimeoutMs,
1206
- wasmUrl: this._opts.wasmUrl,
1207
- math: this._opts.math,
1208
- mode: this._mode
1209
- }), (e) => {
1210
- if (this._find.invalidate(), this._findActive = !1, e) {
1211
- for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
1212
- this._lastTopIndex = -1;
1213
- }
1214
- })) return;
1215
- if (this._destroyed) throw Error("PptxScrollViewer is destroyed");
1216
- this._find.invalidate(), this._findActive = !1, this.relayout();
1217
- } catch (e) {
1218
- if (this._destroyed) throw Error("PptxScrollViewer is destroyed");
1219
- let t = e instanceof Error ? e : Error(String(e));
1220
- if (this._opts.onError) {
1221
- this._opts.onError(t);
1222
- return;
1223
- }
1224
- throw t;
1225
- }
1226
- }
1227
- get slideCount() {
1228
- return this._pres?.slideCount ?? 0;
1229
- }
1230
- _slideWidthPx() {
1231
- return this._pres.slideWidth / x * this._scale;
1232
- }
1233
- _slideHeightPx() {
1234
- return this._pres.slideHeight / x * this._scale;
1235
- }
1236
- _fitWidthPx() {
1237
- if (this._opts.width && this._opts.width > 0) return this._opts.width;
1238
- let e = this._scrollHost.clientWidth || this._container.clientWidth;
1239
- if (e <= 0) return 0;
1240
- let { left: t, right: n } = this._padH(), r = e - t - n;
1241
- return r > 0 ? r : 0;
1242
- }
1243
- _baseScale() {
1244
- if (!this._pres || this._pres.slideCount === 0) return 0;
1245
- let e = this._fitWidthPx(), t = this._pres.slideWidth / x;
1246
- return e <= 0 || t <= 0 ? 0 : e / t;
1247
- }
1248
- relayout() {
1249
- if (this._pres) {
1250
- if (!this._scaleEstablished) {
1251
- let e = this._baseScale();
1252
- if (e > 0) {
1253
- if (this._scale = e, this._prevBase = e, this._lastFitWidth = this._fitWidthPx(), this._scaleEstablished = !0, this._pendingScale !== null) {
1254
- let e = this._pendingScale;
1255
- this._pendingScale = null, e !== this._scale && (this._scale = e, this._opts.onScaleChange?.(e));
1256
- }
1257
- } else return;
1258
- }
1259
- this._recomputeHeights(), this._syncSpacer(), this._mountVisible();
1260
- }
1261
- }
1262
- _recomputeHeights() {
1263
- let e = this._pres.slideCount, t = this._slideHeightPx();
1264
- this._heights = Array(e).fill(t);
1265
- }
1266
- _gap() {
1267
- return this._opts.gap ?? 16;
1268
- }
1269
- _overscan() {
1270
- return this._opts.overscan ?? 1;
1271
- }
1272
- _mediaOverscan() {
1273
- return this._opts.mediaOverscan ?? 1;
1274
- }
1275
- _pad() {
1276
- let e = this._gap();
1277
- return {
1278
- leading: this._opts.paddingTop ?? e,
1279
- trailing: this._opts.paddingBottom ?? e
1280
- };
1281
- }
1282
- _padH() {
1283
- let e = this._gap();
1284
- return {
1285
- left: this._opts.paddingLeft ?? e,
1286
- right: this._opts.paddingRight ?? e
1287
- };
1288
- }
1289
- _slideIndexAtOffset(e, t) {
1290
- let { offsets: n } = e, r = 0, i = n.length - 1, a = 0;
1291
- for (; r <= i;) {
1292
- let e = r + i >> 1;
1293
- n[e] <= t ? (a = e, r = e + 1) : i = e - 1;
1294
- }
1295
- return a;
1296
- }
1297
- _range() {
1298
- return M(this._heights, this._gap(), this._scrollHost.scrollTop, this._scrollHost.clientHeight, this._overscan(), this._pad());
1299
- }
1300
- _mediaRange() {
1301
- return M(this._heights, this._gap(), this._scrollHost.scrollTop, this._scrollHost.clientHeight, this._mediaOverscan(), this._pad());
1302
- }
1303
- _rangeContains(e, t) {
1304
- return t >= e.start && t <= e.end;
1305
- }
1306
- _syncSpacer() {
1307
- let e = this._range();
1308
- this._lastRange = e, this._spacer.style.height = `${e.totalHeight}px`, this._syncSpacerWidth();
1309
- }
1310
- _syncSpacerWidth() {
1311
- let { left: e, right: t } = this._padH();
1312
- this._spacer.style.width = `${this._slideWidthPx() + e + t}px`;
1313
- }
1314
- _onScroll() {
1315
- !this._pres || !this._scaleEstablished || this._mountVisible();
1316
- }
1317
- _mountVisible() {
1318
- if (!this._pres || this._pres.slideCount === 0) return;
1319
- let e = this._range(), t = this._opts.enableMediaPlayback ? this._mediaRange() : null;
1320
- this._lastRange = e;
1321
- for (let [t, n] of [...this._slots]) (t < e.start || t > e.end) && this._recycleSlot(t, n);
1322
- for (let n = e.start; n <= e.end; n++) if (this._slots.has(n)) this._positionSlot(this._slots.get(n), n, e);
1323
- else {
1324
- let r = this._acquireSlot();
1325
- this._positionSlot(r, n, e), this._slots.set(n, r), this._renderSlot(n, r, !!t && this._rangeContains(t, n));
1326
- }
1327
- t && this._syncMediaPlayback(t), e.topIndex !== this._lastTopIndex && (this._lastTopIndex = e.topIndex, this._opts.onVisibleSlideChange?.(e.topIndex, this._pres.slideCount));
1328
- }
1329
- _applyPageShadow(e) {
1330
- this._pageShadow !== !1 && (e.style.boxShadow = this._pageShadow);
1331
- }
1332
- _acquireSlot() {
1333
- let e = this._free.pop();
1334
- if (e) return this._scrollHost.appendChild(e.wrapper), e;
1335
- let t = document.createElement("div");
1336
- t.style.cssText = "position:absolute;";
1337
- let n = document.createElement("canvas");
1338
- n.style.cssText = "display:block;background:#fff;", this._applyPageShadow(n), t.appendChild(n);
1339
- let r = null;
1340
- this._opts.enableTextSelection && (r = document.createElement("div"), r.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;user-select:text;-webkit-user-select:text;", t.appendChild(r));
1341
- let i = document.createElement("div");
1342
- return i.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;", t.appendChild(i), this._scrollHost.appendChild(t), {
1343
- wrapper: t,
1344
- canvas: n,
1345
- textLayer: r,
1346
- highlightLayer: i,
1347
- renderedSlide: -1,
1348
- renderedScale: -1,
1349
- dispatcher: new O(n, this._mode === "worker"),
1350
- presentationHandle: null,
1351
- mediaInteractive: !1,
1352
- renderGeneration: 0,
1353
- presentationGeneration: 0
1354
- };
1355
- }
1356
- _recycleSlot(e, t) {
1357
- this._slots.delete(e), t.renderGeneration++, t.presentationGeneration++, t.presentationHandle?.destroy(), t.presentationHandle = null, t.mediaInteractive = !1, t.dispatcher.destroy(), this._destroyed || (t.dispatcher = new O(t.canvas, this._mode === "worker")), t.textLayer && (t.textLayer.innerHTML = "", t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = ""), t.highlightLayer.innerHTML = "", t.highlightLayer.style.transform = "", t.highlightLayer.style.transformOrigin = "", t.canvas.style.height = "", t.renderedSlide = -1, t.renderedScale = -1, t.wrapper.remove(), this._free.push(t);
1358
- }
1359
- _positionSlot(e, t, n) {
1360
- e.wrapper.style.top = `${n.offsets[t]}px`;
1361
- let r = this._slideWidthPx();
1362
- e.wrapper.style.width = `${r}px`, e.wrapper.style.height = `${this._slideHeightPx()}px`;
1363
- let { left: i } = this._padH(), a = this._scrollHost.clientWidth;
1364
- e.wrapper.style.left = `${Math.max(i, (a - r) / 2)}px`;
1365
- }
1366
- _dpr() {
1367
- return this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1);
1368
- }
1369
- _renderSlot(e, t, n = !1) {
1370
- if (!this._pres || t.renderedSlide === e) return;
1371
- t.renderedSlide = e;
1372
- let r = ++t.renderGeneration, i = this._dpr(), a = this._slideWidthPx(), o = this._renderEpoch, s = this._scale, c = t.dispatcher, l = c.begin();
1373
- if (this._opts.enableMediaPlayback && n) {
1374
- t.mediaInteractive = !0, this._renderInteractiveSlot(e, t, a, i, s, o);
1375
- return;
1376
- }
1377
- if (t.mediaInteractive = !1, this._mode === "worker") {
1378
- this._renderSlotBitmap(e, t, a, i, s, r, c, l);
1379
- return;
1380
- }
1381
- let u = [], d = !!this._opts.enableTextSelection && !!t.textLayer, f = d || this._findActive, p = f ? (e) => u.push(e) : void 0, m = t.canvas;
1382
- this._pres.renderSlide(m, e, {
1383
- width: a,
1384
- dpr: i,
1385
- onTextRun: p
1386
- }).then(() => {
1387
- r !== t.renderGeneration || !c.isCurrent(l) || m !== t.canvas || o !== this._renderEpoch || this._slots.get(e) !== t || t.renderedSlide !== e || (t.renderedScale = s, d && t.textLayer && P(t.textLayer, u, Math.round(a), Math.round(this._slideHeightPx()), this._hyperlinkHandler()), f && this._refreshFindRuns(e, u), this._redrawSlotHighlights(e, t));
1388
- }).catch((n) => {
1389
- r === t.renderGeneration && c.isCurrent(l) && m === t.canvas && o === this._renderEpoch && this._slots.get(e) === t && t.renderedSlide === e && this._reportRenderError(n);
1390
- });
1391
- }
1392
- _renderInteractiveSlot(e, t, n, r, i, a) {
1393
- if (!this._pres) return;
1394
- let o = ++t.presentationGeneration;
1395
- t.presentationHandle?.destroy(), t.presentationHandle = null;
1396
- let s = [], c = !!this._opts.enableTextSelection && !!t.textLayer, l = c || this._findActive, u = l ? (e) => s.push(e) : void 0;
1397
- this._pres.presentSlide(t.canvas, e, {
1398
- width: n,
1399
- dpr: r,
1400
- onTextRun: u,
1401
- onError: (e) => {
1402
- o === t.presentationGeneration && this._reportRenderError(e);
1403
- }
1404
- }).then((r) => {
1405
- if (o !== t.presentationGeneration || !t.mediaInteractive || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedSlide !== e) {
1406
- r.destroy();
1407
- return;
1408
- }
1409
- t.presentationHandle = r, t.renderedScale = i, c && t.textLayer && P(t.textLayer, s, Math.round(n), Math.round(this._slideHeightPx()), this._hyperlinkHandler()), l && this._refreshFindRuns(e, s), this._redrawSlotHighlights(e, t);
1410
- }).catch((e) => {
1411
- o === t.presentationGeneration && this._reportRenderError(e);
1412
- });
1413
- }
1414
- _syncMediaPlayback(e = this._mediaRange()) {
1415
- if (this._opts.enableMediaPlayback) for (let [t, n] of this._slots) {
1416
- let r = this._rangeContains(e, t);
1417
- r !== n.mediaInteractive && (r ? (n.mediaInteractive = !0, this._settleInteractiveSlot(t, n, this._slideWidthPx(), this._dpr(), this._scale, this._renderEpoch)) : (n.mediaInteractive = !1, n.presentationGeneration++, n.presentationHandle?.destroy(), n.presentationHandle = null));
1418
- }
1419
- }
1420
- _reportRenderError(e) {
1421
- if (this._destroyed) return;
1422
- let t = e instanceof Error ? e : Error(String(e));
1423
- this._opts.onError ? this._opts.onError(t) : console.error("[ooxml] PptxScrollViewer render failed:", t);
1424
- }
1425
- async _renderSlotBitmap(e, t, n, r, i, a = ++t.renderGeneration, o = t.dispatcher, s = o.begin()) {
1426
- if (this._slideInFlight.has(e) || this._slots.get(e) !== t) return;
1427
- let c = this._renderEpoch;
1428
- this._slideInFlight.add(e);
1429
- let l = t.canvas, u = !1, d = !!this._opts.enableTextSelection && !!t.textLayer, f = d || this._findActive, p = [];
1430
- try {
1431
- let m = await this._pres.renderSlideToBitmap(e, {
1432
- width: n,
1433
- dpr: r,
1434
- onTextRun: f ? (e) => p.push(e) : void 0
1435
- });
1436
- if (a !== t.renderGeneration || !o.isCurrent(s) || l !== t.canvas || c !== this._renderEpoch || this._slots.get(e) !== t || t.renderedSlide !== e) {
1437
- m.close();
1438
- return;
1439
- }
1440
- if (!o.commitBitmap(s, m, {
1441
- cssWidth: Math.round(m.width / r),
1442
- cssHeight: Math.round(m.height / r)
1443
- })) return;
1444
- t.renderedScale = i, t.textLayer && (t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = "", d && P(t.textLayer, p, Math.round(n), Math.round(this._slideHeightPx()), this._hyperlinkHandler())), f && this._refreshFindRuns(e, p), this._redrawSlotHighlights(e, t), u = !0;
1445
- } catch (n) {
1446
- a === t.renderGeneration && o.isCurrent(s) && l === t.canvas && c === this._renderEpoch && this._slots.get(e) === t && t.renderedSlide === e && this._reportRenderError(n);
1447
- } finally {
1448
- this._slideInFlight.delete(e);
1449
- let n = this._slots.get(e);
1450
- !u && n && (n !== t || c !== this._renderEpoch || a !== n.renderGeneration || !o.isCurrent(s)) && !this._slideInFlight.has(e) && !this._destroyed && !(this._opts.enableMediaPlayback && n.mediaInteractive) && this._renderSlotBitmap(e, n, this._slideWidthPx(), this._dpr(), this._scale);
1451
- }
1452
- }
1453
- setScale(e) {
1454
- let t = this._opts.zoomMin ?? .1, n = this._opts.zoomMax ?? 4, r = Math.min(n, Math.max(t, e)), i = this._pendingZoomAnchor;
1455
- if (this._pendingZoomAnchor = null, !this._pres || this._pres.slideCount === 0 || !this._scaleEstablished) {
1456
- this._pendingScale = r;
1457
- return;
1458
- }
1459
- if (r === this._scale) return;
1460
- let a = this._scale, o = i ? i.y : 0, s = this._range(), c = this._scrollHost.scrollTop, l = c + o, u = this._slideIndexAtOffset(s, l), d = this._heights[u] || 0, f = d > 0 ? (l - s.offsets[u]) / d : 0;
1461
- f = Math.min(1, Math.max(0, f));
1462
- let p = this._padH().left, m = this._scrollHost.scrollLeft || 0;
1463
- this._renderEpoch++, this._scale = r, this._recomputeHeights();
1464
- let h = M(this._heights, this._gap(), 0, this._scrollHost.clientHeight, this._overscan(), this._pad());
1465
- this._spacer.style.height = `${h.totalHeight}px`, this._syncSpacerWidth();
1466
- let g = Math.max(0, h.totalHeight - this._scrollHost.clientHeight), _ = (h.offsets[u] ?? 0) + f * (this._heights[u] || 0), v = l < (s.offsets[0] ?? 0) ? c : _ - o;
1467
- if (this._scrollHost.scrollTop = Math.min(g, Math.max(0, v)), i) {
1468
- let e = Math.max(0, (this._spacer.offsetWidth || 0) - this._scrollHost.clientWidth);
1469
- this._scrollHost.scrollLeft = oe(m, i.x - p, a, r, { maxScroll: e });
1470
- }
1471
- this._previewVisible(), this._scheduleSettle(), this._opts.onScaleChange?.(r);
1472
- }
1473
- getScale() {
1474
- return this._scaleEstablished ? this._scale : this._pendingScale ?? 1;
1475
- }
1476
- zoomIn() {
1477
- this.setScale(A(this.getScale()));
1478
- }
1479
- zoomOut() {
1480
- this.setScale(ce(this.getScale()));
1481
- }
1482
- fitWidth() {
1483
- this._fit("width");
1484
- }
1485
- fitPage() {
1486
- this._fit("page");
1487
- }
1488
- _fit(e) {
1489
- if (!this._pres || this._pres.slideCount === 0) return;
1490
- let t = D({
1491
- contentWidth: this._pres.slideWidth / x,
1492
- contentHeight: this._pres.slideHeight / x,
1493
- containerWidth: this._fitWidthPx(),
1494
- containerHeight: this._scrollHost.clientHeight
1495
- }, e);
1496
- t <= 0 || this.setScale(t);
1497
- }
1498
- _previewVisible() {
1499
- if (!this._pres || this._pres.slideCount === 0) return;
1500
- let e = this._range(), t = this._opts.enableMediaPlayback ? this._mediaRange() : null;
1501
- this._lastRange = e;
1502
- for (let [t, n] of [...this._slots]) (t < e.start || t > e.end) && this._recycleSlot(t, n);
1503
- for (let n = e.start; n <= e.end; n++) {
1504
- let r = this._slots.get(n);
1505
- if (r) this._previewSlot(r, n, e);
1506
- else {
1507
- let r = this._acquireSlot();
1508
- this._positionSlot(r, n, e), this._slots.set(n, r), this._renderSlot(n, r, !!t && this._rangeContains(t, n));
1509
- }
1510
- }
1511
- t && this._syncMediaPlayback(t), e.topIndex !== this._lastTopIndex && (this._lastTopIndex = e.topIndex, this._opts.onVisibleSlideChange?.(e.topIndex, this._pres.slideCount));
1512
- }
1513
- _previewSlot(e, t, n) {
1514
- if (this._positionSlot(e, t, n), e.canvas.style.width = `${this._slideWidthPx()}px`, e.canvas.style.height = `${this._slideHeightPx()}px`, e.textLayer && e.renderedScale > 0) {
1515
- let t = this._scale / e.renderedScale;
1516
- e.textLayer.style.transformOrigin = "0 0", e.textLayer.style.transform = `scale(${t})`;
1517
- }
1518
- }
1519
- _scheduleSettle() {
1520
- this._settleTimer !== null && clearTimeout(this._settleTimer), this._settleTimer = setTimeout(() => {
1521
- this._settleTimer = null, this._settleRender();
1522
- }, Ye);
1523
- }
1524
- _settleRender() {
1525
- if (this._destroyed || !this._pres || this._pres.slideCount === 0) return;
1526
- let e = this._opts.enableMediaPlayback ? this._mediaRange() : null;
1527
- for (let [t, n] of [...this._slots]) e && !this._rangeContains(e, t) || n.renderedScale !== this._scale && this._settleSlot(t, n);
1528
- }
1529
- _settleSlot(e, t) {
1530
- if (!this._pres) return;
1531
- let n = this._dpr(), r = this._slideWidthPx(), i = this._scale, a = this._renderEpoch;
1532
- if (this._opts.enableMediaPlayback && t.mediaInteractive) {
1533
- this._settleInteractiveSlot(e, t, r, n, i, a);
1534
- return;
1535
- }
1536
- if (this._opts.enableMediaPlayback) return;
1537
- if (this._mode === "worker") {
1538
- this._renderSlotBitmap(e, t, r, n, i);
1539
- return;
1540
- }
1541
- let o = document.createElement("canvas"), s = ++t.renderGeneration;
1542
- o.style.cssText = "display:block;background:#fff;", this._applyPageShadow(o);
1543
- let c = new O(o, !1), l = c.begin(), u = [], d = !!this._opts.enableTextSelection && !!t.textLayer, f = d || this._findActive, p = f ? (e) => u.push(e) : void 0;
1544
- this._pres.renderSlide(o, e, {
1545
- width: r,
1546
- dpr: n,
1547
- onTextRun: p
1548
- }).then(() => {
1549
- if (s !== t.renderGeneration || !c.isCurrent(l) || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedSlide !== e) {
1550
- c.destroy();
1551
- return;
1552
- }
1553
- let n = t.canvas;
1554
- t.dispatcher.destroy(), t.wrapper.insertBefore(o, n), n.remove(), t.canvas = o, t.dispatcher = c, t.renderedScale = i, t.textLayer && (t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = "", d && P(t.textLayer, u, Math.round(r), Math.round(this._slideHeightPx()), this._hyperlinkHandler())), f && this._refreshFindRuns(e, u), this._redrawSlotHighlights(e, t);
1555
- }).catch((n) => {
1556
- s === t.renderGeneration && c.isCurrent(l) && a === this._renderEpoch && this._slots.get(e) === t && t.renderedSlide === e && this._reportRenderError(n), c.destroy();
1557
- });
1558
- }
1559
- _settleInteractiveSlot(e, t, n, r, i, a) {
1560
- if (!this._pres) return;
1561
- let o = ++t.presentationGeneration, s = document.createElement("canvas");
1562
- s.style.cssText = "display:block;background:#fff;", this._applyPageShadow(s);
1563
- let c = [], l = !!this._opts.enableTextSelection && !!t.textLayer, u = l || this._findActive, d = u ? (e) => c.push(e) : void 0;
1564
- this._pres.presentSlide(s, e, {
1565
- width: n,
1566
- dpr: r,
1567
- onTextRun: d,
1568
- onError: (e) => {
1569
- o === t.presentationGeneration && this._reportRenderError(e);
1570
- }
1571
- }).then((r) => {
1572
- if (o !== t.presentationGeneration || !t.mediaInteractive || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedSlide !== e) {
1573
- r.destroy();
1574
- return;
1575
- }
1576
- let d = t.canvas, f = t.presentationHandle;
1577
- t.dispatcher.destroy(), t.wrapper.insertBefore(s, d), d.remove(), t.canvas = s, t.dispatcher = new O(s, !1), t.presentationHandle = r, t.renderedScale = i, f?.destroy(), t.textLayer && (t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = "", l && P(t.textLayer, c, Math.round(n), Math.round(this._slideHeightPx()), this._hyperlinkHandler())), u && this._refreshFindRuns(e, c), this._redrawSlotHighlights(e, t);
1578
- }).catch((e) => {
1579
- o === t.presentationGeneration && this._reportRenderError(e);
1580
- });
1581
- }
1582
- scrollToSlide(e, t) {
1583
- if (!this._pres || this._pres.slideCount === 0 || !this._scaleEstablished) return;
1584
- let n = Math.max(0, Math.min(e, this._pres.slideCount - 1)), r = M(this._heights, this._gap(), 0, this._scrollHost.clientHeight, this._overscan(), this._pad()), i = r.offsets[n] ?? 0, a = Math.max(0, r.totalHeight - this._scrollHost.clientHeight), o = Math.min(a, Math.max(0, i)), s = this._scrollHost;
1585
- typeof s.scrollTo == "function" ? s.scrollTo({
1586
- top: o,
1587
- behavior: t?.behavior ?? "auto"
1588
- }) : this._scrollHost.scrollTop = o, this._mountVisible();
1589
- }
1590
- async findText(e, t = {}) {
1591
- if (!this._pres) return [];
1592
- this._findActive = e.length > 0;
1593
- let n = await this._find.find(e, t);
1594
- return this._redrawHighlights(), n;
1595
- }
1596
- async findNext() {
1597
- return this._activateMatch(this._find.next());
1598
- }
1599
- async findPrev() {
1600
- return this._activateMatch(this._find.prev());
1601
- }
1602
- clearFind() {
1603
- this._findActive = !1, this._find.invalidate(), this._redrawHighlights();
1604
- }
1605
- async _activateMatch(e) {
1606
- return e && this.scrollToSlide(e.location.slide), this._redrawHighlights(), e;
1607
- }
1608
- async _collectSlideRuns(e) {
1609
- return this._pres ? this._pres.collectSlideRuns(e, this._slideWidthPx()) : [];
1610
- }
1611
- _redrawHighlights() {
1612
- for (let [e, t] of this._slots) this._redrawSlotHighlights(e, t);
1613
- }
1614
- _refreshFindRuns(e, t) {
1615
- this._findActive && this._find.setSlideRuns(e, t);
1616
- }
1617
- _redrawSlotHighlights(e, t) {
1618
- if (!this._findActive) {
1619
- t.highlightLayer.innerHTML = "";
1620
- return;
1621
- }
1622
- let n = this._find.slideRuns(e);
1623
- if (!n) {
1624
- t.highlightLayer.innerHTML = "";
1625
- return;
1626
- }
1627
- F(t.highlightLayer, n, this._find.slideHighlights(e), this._slideWidthPx(), this._slideHeightPx(), (e) => this._measureForFind(e), this._opts.findHighlightColors);
1628
- }
1629
- _measureForFind(e) {
1630
- this._findMeasureCtx === void 0 && (this._findMeasureCtx = document.createElement("canvas").getContext("2d"));
1631
- let t = this._findMeasureCtx;
1632
- return !t || typeof t.measureText != "function" ? (e) => e.length : (t.font = e, (e) => t.measureText(e).width);
1633
- }
1634
- _hyperlinkHandler() {
1635
- if (this._opts.enableHyperlinks !== !1) return (e) => this._onHyperlinkClick(e);
1636
- }
1637
- _onHyperlinkClick(e) {
1638
- let t = this._resolveInternalSlideIndex(e);
1639
- if (this._opts.onHyperlinkClick) {
1640
- this._opts.onHyperlinkClick(t);
1641
- return;
1642
- }
1643
- if (t.kind === "external") {
1644
- g(t.url);
1645
- return;
1646
- }
1647
- t.slideIndex !== void 0 && this.scrollToSlide(t.slideIndex);
1648
- }
1649
- _resolveInternalSlideIndex(e) {
1650
- if (e.kind !== "internal" || e.slideIndex !== void 0) return e;
1651
- let t = this._pres?.resolveInternalTarget(e.ref, this._range().topIndex);
1652
- return t === void 0 ? e : {
1653
- ...e,
1654
- slideIndex: t
1655
- };
1656
- }
1657
- _onResize() {
1658
- if (!this._pres || this._pres.slideCount === 0) return;
1659
- if (!this._scaleEstablished) {
1660
- this.relayout();
1661
- return;
1662
- }
1663
- if (this._opts.refitOnResize === !1) {
1664
- this._lastFitWidth = this._fitWidthPx(), this._mountVisible();
1665
- return;
1666
- }
1667
- let e = this._baseScale();
1668
- if (e <= 0) return;
1669
- let t = this._fitWidthPx();
1670
- if (t === this._lastFitWidth) {
1671
- this._mountVisible();
1672
- return;
1673
- }
1674
- this._lastFitWidth = t;
1675
- let n = this._prevBase > 0 ? this._scale / this._prevBase : 1;
1676
- this._prevBase = e, this.setScale(e * n), this._mountVisible();
1677
- }
1678
- get topVisibleSlide() {
1679
- return this._lastRange?.topIndex ?? 0;
1680
- }
1681
- mountedSlideIndicesForTest() {
1682
- return [...this._slots.keys()];
1683
- }
1684
- interactiveSlideIndicesForTest() {
1685
- return [...this._slots].filter(([, e]) => e.mediaInteractive).map(([e]) => e);
1686
- }
1687
- scaleForTest() {
1688
- return this._scale;
1689
- }
1690
- baseScaleForTest() {
1691
- return this._baseScale();
1692
- }
1693
- renderEpochForTest() {
1694
- return this._renderEpoch;
1695
- }
1696
- resizeForTest() {
1697
- this._onResize();
1698
- }
1699
- contentAtViewportYForTest(e) {
1700
- let t = this._range(), n = this._scrollHost.scrollTop + e, r = this._slideIndexAtOffset(t, n), i = this._heights[r] || 0;
1701
- return {
1702
- slide: r,
1703
- frac: i > 0 ? Math.min(1, Math.max(0, (n - t.offsets[r]) / i)) : 0
1704
- };
1705
- }
1706
- viewportYOfForTest(e, t) {
1707
- return (this._range().offsets[e] ?? 0) + t * (this._heights[e] || 0) - this._scrollHost.scrollTop;
1708
- }
1709
- async getResourceMetrics() {
1710
- if (!this._pres) throw Error("Presentation not loaded");
1711
- return await this._pres.getResourceMetrics();
1712
- }
1713
- destroy() {
1714
- if (!this._destroyed) {
1715
- this._destroyed = !0, this._find.invalidate(), this._findActive = !1, this._scrollListener &&= (this._scrollHost.removeEventListener("scroll", this._scrollListener), null), this._wheelListener &&= (this._scrollHost.removeEventListener("wheel", this._wheelListener), null), this._resizeObserver?.disconnect(), this._resizeObserver = null, this._settleTimer !== null && (clearTimeout(this._settleTimer), this._settleTimer = null);
1716
- for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
1717
- this._free.length = 0, this._presentationOwner.close(), this._wrapper.remove();
1718
- }
1719
- }
1720
- }, $e = /* @__PURE__ */ e({
1721
- OoxmlDecodedImageLimitError: () => p,
1722
- OoxmlError: () => w,
1723
- OoxmlResourceLimitError: () => y,
1724
- PptxPresentation: () => Q,
1725
- PptxScrollViewer: () => Qe,
1726
- PptxViewer: () => Je,
1727
- autoResize: () => ge,
1728
- buildPptxHighlightLayer: () => F,
1729
- buildPptxTextLayer: () => P,
1730
- isOoxmlDecodedImageLimitError: () => m,
1731
- openExternalHyperlink: () => g,
1732
- renderSlide: () => n
1733
- });
1734
- //#endregion
1735
- export { F as a, Q as i, Qe as n, P as o, Je as r, $e as t };