@deepseek-ai/libreoffice-kit 0.0.1 → 0.0.2-rc5

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 (94) hide show
  1. package/NOTICE +240 -0
  2. package/README.md +43 -47
  3. package/README.zh.md +35 -50
  4. package/assets/font-subset.json +70 -0
  5. package/assets/font-subset.wasm +0 -0
  6. package/lib/browser/assets.json +10 -0
  7. package/lib/browser/index.js +442 -0
  8. package/lib/browser/types/connection.d.ts +20 -0
  9. package/lib/browser/types/engine-rendering.d.ts +3 -0
  10. package/lib/browser/types/engine-types.d.ts +17 -0
  11. package/lib/browser/types/font-channel.d.ts +20 -0
  12. package/lib/browser/types/index.d.ts +13 -0
  13. package/lib/browser/types/office-engine.d.ts +46 -0
  14. package/lib/browser/types/office-types.d.ts +107 -0
  15. package/lib/browser/types/office.d.ts +4 -0
  16. package/lib/browser/types/protocol.d.ts +109 -0
  17. package/lib/browser/types/rendering.d.ts +4 -0
  18. package/lib/browser/types/types.d.ts +92 -0
  19. package/lib/browser/types/worker.d.ts +2 -0
  20. package/lib/browser/worker.js +3498 -0
  21. package/lib/browser-assets.js +119 -0
  22. package/lib/cli.js +1336 -0
  23. package/lib/document.js +178 -0
  24. package/lib/engine-rendering.js +120 -0
  25. package/lib/font-config.js +46 -0
  26. package/lib/font-source.js +377 -0
  27. package/lib/font-worker.js +1383 -0
  28. package/lib/index.js +408 -165
  29. package/lib/rendering.js +99 -0
  30. package/lib/sheet-geometry.js +111 -0
  31. package/lib/types/browser-assets.d.ts +15 -0
  32. package/lib/types/cli.d.ts +3 -0
  33. package/lib/types/default-fonts.d.ts +3 -0
  34. package/lib/types/document.d.ts +1 -1
  35. package/lib/types/engine-rendering.d.ts +15 -0
  36. package/lib/types/engine.d.ts +5 -5
  37. package/lib/types/font-config.d.ts +24 -0
  38. package/lib/types/font-full.d.ts +13 -0
  39. package/lib/types/font-loader.d.ts +1 -7
  40. package/lib/types/font-preferences-data.d.ts +16 -0
  41. package/lib/types/font-preferences.d.ts +29 -0
  42. package/lib/types/font-request.d.ts +12 -0
  43. package/lib/types/font-source-types.d.ts +84 -0
  44. package/lib/types/font-source.d.ts +10 -0
  45. package/lib/types/font-subsets.d.ts +35 -0
  46. package/lib/types/font-worker.d.ts +2 -0
  47. package/lib/types/fonts.d.ts +20 -37
  48. package/lib/types/harfbuzz-subset.d.ts +11 -0
  49. package/lib/types/image-operations.d.ts +58 -0
  50. package/lib/types/image-renderer.d.ts +6 -0
  51. package/lib/types/index.d.ts +25 -2
  52. package/lib/types/native.d.ts +4 -2
  53. package/lib/types/operations.d.ts +41 -0
  54. package/lib/types/options.d.ts +1 -1
  55. package/lib/types/png.d.ts +2 -0
  56. package/lib/types/profile.d.ts +8 -0
  57. package/lib/types/rendering.d.ts +41 -0
  58. package/lib/types/runtime.d.ts +14 -0
  59. package/lib/types/sheet-geometry.d.ts +38 -0
  60. package/lib/types/unicode-scripts.d.ts +18 -0
  61. package/lib/types/wasm.d.ts +76 -1
  62. package/lib/types/worker.d.ts +3 -0
  63. package/lib/worker.js +1716 -271
  64. package/licenses/font-subset/harfbuzz-COPYING +42 -0
  65. package/licenses/font-subset/harfbuzzjs-LICENSE +19 -0
  66. package/licenses/javascript/fflate-LICENSE +21 -0
  67. package/licenses/javascript/saxes-LICENSE +64 -0
  68. package/licenses/javascript/xmlchars-LICENSE +18 -0
  69. package/package.json +59 -12
  70. package/sources/browser/packages/browser/package.json +22 -0
  71. package/sources/browser/packages/browser/src/connection.ts +166 -0
  72. package/sources/browser/packages/browser/src/engine-rendering.ts +2 -0
  73. package/sources/browser/packages/browser/src/engine-types.ts +14 -0
  74. package/sources/browser/packages/browser/src/font-channel.ts +99 -0
  75. package/sources/browser/packages/browser/src/index.ts +39 -0
  76. package/sources/browser/packages/browser/src/office-engine.ts +299 -0
  77. package/sources/browser/packages/browser/src/office-types.ts +77 -0
  78. package/sources/browser/packages/browser/src/office.ts +62 -0
  79. package/sources/browser/packages/browser/src/protocol.ts +39 -0
  80. package/sources/browser/packages/browser/src/rendering.ts +3 -0
  81. package/sources/browser/packages/browser/src/types.ts +94 -0
  82. package/sources/browser/packages/browser/src/worker.ts +166 -0
  83. package/sources/browser/packages/browser/tsconfig.json +5 -0
  84. package/sources/browser/packages/browser/tsdown.config.ts +7 -0
  85. package/sources/browser/scripts/build-browser.mjs +82 -0
  86. package/sources/font-subset/engine/font-subset/README.md +23 -0
  87. package/sources/font-subset/engine/font-subset/README.zh.md +23 -0
  88. package/sources/font-subset/engine/font-subset/source.json +16 -0
  89. package/sources/font-subset/harfbuzzjs/config-override-subset.h +7 -0
  90. package/sources/font-subset/harfbuzzjs/harfbuzz-subset.symbols +34 -0
  91. package/sources/font-subset/scripts/build-font-subset.mjs +64 -0
  92. package/sources/font-subset/scripts/pack-utils.mjs +69 -0
  93. package/sources/font-subset/scripts/platform-matrix.mjs +100 -0
  94. package/sources/font-subset/scripts/verify-artifacts.mjs +260 -0
@@ -0,0 +1,3498 @@
1
+ (function() {
2
+ //#region \0rolldown/runtime.js
3
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
4
+ //#endregion
5
+ //#region ../../node_modules/.pnpm/fflate@0.8.2/node_modules/fflate/esm/browser.js
6
+ var u8 = Uint8Array;
7
+ var u16 = Uint16Array;
8
+ var i32 = Int32Array;
9
+ var fleb = new u8([
10
+ 0,
11
+ 0,
12
+ 0,
13
+ 0,
14
+ 0,
15
+ 0,
16
+ 0,
17
+ 0,
18
+ 1,
19
+ 1,
20
+ 1,
21
+ 1,
22
+ 2,
23
+ 2,
24
+ 2,
25
+ 2,
26
+ 3,
27
+ 3,
28
+ 3,
29
+ 3,
30
+ 4,
31
+ 4,
32
+ 4,
33
+ 4,
34
+ 5,
35
+ 5,
36
+ 5,
37
+ 5,
38
+ 0,
39
+ 0,
40
+ 0,
41
+ 0
42
+ ]);
43
+ var fdeb = new u8([
44
+ 0,
45
+ 0,
46
+ 0,
47
+ 0,
48
+ 1,
49
+ 1,
50
+ 2,
51
+ 2,
52
+ 3,
53
+ 3,
54
+ 4,
55
+ 4,
56
+ 5,
57
+ 5,
58
+ 6,
59
+ 6,
60
+ 7,
61
+ 7,
62
+ 8,
63
+ 8,
64
+ 9,
65
+ 9,
66
+ 10,
67
+ 10,
68
+ 11,
69
+ 11,
70
+ 12,
71
+ 12,
72
+ 13,
73
+ 13,
74
+ 0,
75
+ 0
76
+ ]);
77
+ var clim = new u8([
78
+ 16,
79
+ 17,
80
+ 18,
81
+ 0,
82
+ 8,
83
+ 7,
84
+ 9,
85
+ 6,
86
+ 10,
87
+ 5,
88
+ 11,
89
+ 4,
90
+ 12,
91
+ 3,
92
+ 13,
93
+ 2,
94
+ 14,
95
+ 1,
96
+ 15
97
+ ]);
98
+ var freb = function(eb, start) {
99
+ var b = new u16(31);
100
+ for (var i = 0; i < 31; ++i) b[i] = start += 1 << eb[i - 1];
101
+ var r = new i32(b[30]);
102
+ for (var i = 1; i < 30; ++i) for (var j = b[i]; j < b[i + 1]; ++j) r[j] = j - b[i] << 5 | i;
103
+ return {
104
+ b,
105
+ r
106
+ };
107
+ };
108
+ var _a = freb(fleb, 2);
109
+ var fl = _a.b;
110
+ var revfl = _a.r;
111
+ fl[28] = 258, revfl[258] = 28;
112
+ var _b = freb(fdeb, 0);
113
+ var fd = _b.b;
114
+ _b.r;
115
+ var rev = new u16(32768);
116
+ for (var i = 0; i < 32768; ++i) {
117
+ var x = (i & 43690) >> 1 | (i & 21845) << 1;
118
+ x = (x & 52428) >> 2 | (x & 13107) << 2;
119
+ x = (x & 61680) >> 4 | (x & 3855) << 4;
120
+ rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
121
+ }
122
+ var hMap = (function(cd, mb, r) {
123
+ var s = cd.length;
124
+ var i = 0;
125
+ var l = new u16(mb);
126
+ for (; i < s; ++i) if (cd[i]) ++l[cd[i] - 1];
127
+ var le = new u16(mb);
128
+ for (i = 1; i < mb; ++i) le[i] = le[i - 1] + l[i - 1] << 1;
129
+ var co;
130
+ if (r) {
131
+ co = new u16(1 << mb);
132
+ var rvb = 15 - mb;
133
+ for (i = 0; i < s; ++i) if (cd[i]) {
134
+ var sv = i << 4 | cd[i];
135
+ var r_1 = mb - cd[i];
136
+ var v = le[cd[i] - 1]++ << r_1;
137
+ for (var m = v | (1 << r_1) - 1; v <= m; ++v) co[rev[v] >> rvb] = sv;
138
+ }
139
+ } else {
140
+ co = new u16(s);
141
+ for (i = 0; i < s; ++i) if (cd[i]) co[i] = rev[le[cd[i] - 1]++] >> 15 - cd[i];
142
+ }
143
+ return co;
144
+ });
145
+ var flt = new u8(288);
146
+ for (var i = 0; i < 144; ++i) flt[i] = 8;
147
+ for (var i = 144; i < 256; ++i) flt[i] = 9;
148
+ for (var i = 256; i < 280; ++i) flt[i] = 7;
149
+ for (var i = 280; i < 288; ++i) flt[i] = 8;
150
+ var fdt = new u8(32);
151
+ for (var i = 0; i < 32; ++i) fdt[i] = 5;
152
+ var flrm = /*#__PURE__*/ hMap(flt, 9, 1);
153
+ var fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
154
+ var max = function(a) {
155
+ var m = a[0];
156
+ for (var i = 1; i < a.length; ++i) if (a[i] > m) m = a[i];
157
+ return m;
158
+ };
159
+ var bits = function(d, p, m) {
160
+ var o = p / 8 | 0;
161
+ return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
162
+ };
163
+ var bits16 = function(d, p) {
164
+ var o = p / 8 | 0;
165
+ return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
166
+ };
167
+ var shft = function(p) {
168
+ return (p + 7) / 8 | 0;
169
+ };
170
+ var slc = function(v, s, e) {
171
+ if (s == null || s < 0) s = 0;
172
+ if (e == null || e > v.length) e = v.length;
173
+ return new u8(v.subarray(s, e));
174
+ };
175
+ var ec = [
176
+ "unexpected EOF",
177
+ "invalid block type",
178
+ "invalid length/literal",
179
+ "invalid distance",
180
+ "stream finished",
181
+ "no stream handler",
182
+ ,
183
+ "no callback",
184
+ "invalid UTF-8 data",
185
+ "extra field too long",
186
+ "date not in range 1980-2099",
187
+ "filename too long",
188
+ "stream finishing",
189
+ "invalid zip data"
190
+ ];
191
+ var err = function(ind, msg, nt) {
192
+ var e = new Error(msg || ec[ind]);
193
+ e.code = ind;
194
+ if (Error.captureStackTrace) Error.captureStackTrace(e, err);
195
+ if (!nt) throw e;
196
+ return e;
197
+ };
198
+ var inflt = function(dat, st, buf, dict) {
199
+ var sl = dat.length, dl = dict ? dict.length : 0;
200
+ if (!sl || st.f && !st.l) return buf || new u8(0);
201
+ var noBuf = !buf;
202
+ var resize = noBuf || st.i != 2;
203
+ var noSt = st.i;
204
+ if (noBuf) buf = new u8(sl * 3);
205
+ var cbuf = function(l) {
206
+ var bl = buf.length;
207
+ if (l > bl) {
208
+ var nbuf = new u8(Math.max(bl * 2, l));
209
+ nbuf.set(buf);
210
+ buf = nbuf;
211
+ }
212
+ };
213
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
214
+ var tbts = sl * 8;
215
+ do {
216
+ if (!lm) {
217
+ final = bits(dat, pos, 1);
218
+ var type = bits(dat, pos + 1, 3);
219
+ pos += 3;
220
+ if (!type) {
221
+ var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
222
+ if (t > sl) {
223
+ if (noSt) err(0);
224
+ break;
225
+ }
226
+ if (resize) cbuf(bt + l);
227
+ buf.set(dat.subarray(s, t), bt);
228
+ st.b = bt += l, st.p = pos = t * 8, st.f = final;
229
+ continue;
230
+ } else if (type == 1) lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
231
+ else if (type == 2) {
232
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
233
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
234
+ pos += 14;
235
+ var ldt = new u8(tl);
236
+ var clt = new u8(19);
237
+ for (var i = 0; i < hcLen; ++i) clt[clim[i]] = bits(dat, pos + i * 3, 7);
238
+ pos += hcLen * 3;
239
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
240
+ var clm = hMap(clt, clb, 1);
241
+ for (var i = 0; i < tl;) {
242
+ var r = clm[bits(dat, pos, clbmsk)];
243
+ pos += r & 15;
244
+ var s = r >> 4;
245
+ if (s < 16) ldt[i++] = s;
246
+ else {
247
+ var c = 0, n = 0;
248
+ if (s == 16) n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
249
+ else if (s == 17) n = 3 + bits(dat, pos, 7), pos += 3;
250
+ else if (s == 18) n = 11 + bits(dat, pos, 127), pos += 7;
251
+ while (n--) ldt[i++] = c;
252
+ }
253
+ }
254
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
255
+ lbt = max(lt);
256
+ dbt = max(dt);
257
+ lm = hMap(lt, lbt, 1);
258
+ dm = hMap(dt, dbt, 1);
259
+ } else err(1);
260
+ if (pos > tbts) {
261
+ if (noSt) err(0);
262
+ break;
263
+ }
264
+ }
265
+ if (resize) cbuf(bt + 131072);
266
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
267
+ var lpos = pos;
268
+ for (;; lpos = pos) {
269
+ var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
270
+ pos += c & 15;
271
+ if (pos > tbts) {
272
+ if (noSt) err(0);
273
+ break;
274
+ }
275
+ if (!c) err(2);
276
+ if (sym < 256) buf[bt++] = sym;
277
+ else if (sym == 256) {
278
+ lpos = pos, lm = null;
279
+ break;
280
+ } else {
281
+ var add = sym - 254;
282
+ if (sym > 264) {
283
+ var i = sym - 257, b = fleb[i];
284
+ add = bits(dat, pos, (1 << b) - 1) + fl[i];
285
+ pos += b;
286
+ }
287
+ var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
288
+ if (!d) err(3);
289
+ pos += d & 15;
290
+ var dt = fd[dsym];
291
+ if (dsym > 3) {
292
+ var b = fdeb[dsym];
293
+ dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
294
+ }
295
+ if (pos > tbts) {
296
+ if (noSt) err(0);
297
+ break;
298
+ }
299
+ if (resize) cbuf(bt + 131072);
300
+ var end = bt + add;
301
+ if (bt < dt) {
302
+ var shift = dl - dt, dend = Math.min(dt, end);
303
+ if (shift + bt < 0) err(3);
304
+ for (; bt < dend; ++bt) buf[bt] = dict[shift + bt];
305
+ }
306
+ for (; bt < end; ++bt) buf[bt] = buf[bt - dt];
307
+ }
308
+ }
309
+ st.l = lm, st.p = lpos, st.b = bt, st.f = final;
310
+ if (lm) final = 1, st.m = lbt, st.d = dm, st.n = dbt;
311
+ } while (!final);
312
+ return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
313
+ };
314
+ var et = /*#__PURE__*/ new u8(0);
315
+ var b2 = function(d, b) {
316
+ return d[b] | d[b + 1] << 8;
317
+ };
318
+ var b4 = function(d, b) {
319
+ return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0;
320
+ };
321
+ var b8 = function(d, b) {
322
+ return b4(d, b) + b4(d, b + 4) * 4294967296;
323
+ };
324
+ /**
325
+ * Expands DEFLATE data with no wrapper
326
+ * @param data The data to decompress
327
+ * @param opts The decompression options
328
+ * @returns The decompressed version of the data
329
+ */
330
+ function inflateSync(data, opts) {
331
+ return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
332
+ }
333
+ var td = typeof TextDecoder != "undefined" && /*#__PURE__*/ new TextDecoder();
334
+ try {
335
+ td.decode(et, { stream: true });
336
+ } catch (e) {}
337
+ var dutf8 = function(d) {
338
+ for (var r = "", i = 0;;) {
339
+ var c = d[i++];
340
+ var eb = (c > 127) + (c > 223) + (c > 239);
341
+ if (i + eb > d.length) return {
342
+ s: r,
343
+ r: slc(d, i - 1)
344
+ };
345
+ if (!eb) r += String.fromCharCode(c);
346
+ else if (eb == 3) c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | d[i++] & 63) - 65536, r += String.fromCharCode(55296 | c >> 10, 56320 | c & 1023);
347
+ else if (eb & 1) r += String.fromCharCode((c & 31) << 6 | d[i++] & 63);
348
+ else r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | d[i++] & 63);
349
+ }
350
+ };
351
+ /**
352
+ * Converts a Uint8Array to a string
353
+ * @param dat The data to decode to string
354
+ * @param latin1 Whether or not to interpret the data as Latin-1. This should
355
+ * not need to be true unless encoding to binary string.
356
+ * @returns The original UTF-8/Latin-1 string
357
+ */
358
+ function strFromU8(dat, latin1) {
359
+ if (latin1) {
360
+ var r = "";
361
+ for (var i = 0; i < dat.length; i += 16384) r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));
362
+ return r;
363
+ } else if (td) return td.decode(dat);
364
+ else {
365
+ var _a = dutf8(dat), s = _a.s, r = _a.r;
366
+ if (r.length) err(8);
367
+ return s;
368
+ }
369
+ }
370
+ var slzh = function(d, b) {
371
+ return b + 30 + b2(d, b + 26) + b2(d, b + 28);
372
+ };
373
+ var zh = function(d, b, z) {
374
+ var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);
375
+ var _a = z && bs == 4294967295 ? z64e(d, es) : [
376
+ bs,
377
+ b4(d, b + 24),
378
+ b4(d, b + 42)
379
+ ], sc = _a[0], su = _a[1], off = _a[2];
380
+ return [
381
+ b2(d, b + 10),
382
+ sc,
383
+ su,
384
+ fn,
385
+ es + b2(d, b + 30) + b2(d, b + 32),
386
+ off
387
+ ];
388
+ };
389
+ var z64e = function(d, b) {
390
+ for (; b2(d, b) != 1; b += 4 + b2(d, b + 2));
391
+ return [
392
+ b8(d, b + 12),
393
+ b8(d, b + 4),
394
+ b8(d, b + 20)
395
+ ];
396
+ };
397
+ /**
398
+ * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better
399
+ * performance with more than one file.
400
+ * @param data The raw compressed ZIP file
401
+ * @param opts The ZIP extraction options
402
+ * @returns The decompressed files
403
+ */
404
+ function unzipSync(data, opts) {
405
+ var files = {};
406
+ var e = data.length - 22;
407
+ for (; b4(data, e) != 101010256; --e) if (!e || data.length - e > 65558) err(13);
408
+ var c = b2(data, e + 8);
409
+ if (!c) return {};
410
+ var o = b4(data, e + 16);
411
+ var z = o == 4294967295 || c == 65535;
412
+ if (z) {
413
+ var ze = b4(data, e - 12);
414
+ z = b4(data, ze) == 101075792;
415
+ if (z) {
416
+ c = b4(data, ze + 32);
417
+ o = b4(data, ze + 48);
418
+ }
419
+ }
420
+ var fltr = opts && opts.filter;
421
+ for (var i = 0; i < c; ++i) {
422
+ var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
423
+ o = no;
424
+ if (!fltr || fltr({
425
+ name: fn,
426
+ size: sc,
427
+ originalSize: su,
428
+ compression: c_2
429
+ })) {
430
+ if (!c_2) files[fn] = slc(data, b, b + sc);
431
+ else if (c_2 == 8) files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });
432
+ else err(14, "unknown compression type " + c_2);
433
+ }
434
+ }
435
+ return files;
436
+ }
437
+ //#endregion
438
+ //#region ../../node_modules/.pnpm/xmlchars@2.2.0/node_modules/xmlchars/xml/1.0/ed5.js
439
+ var require_ed5 = /* @__PURE__ */ __commonJSMin(((exports) => {
440
+ /**
441
+ * Character classes and associated utilities for the 5th edition of XML 1.0.
442
+ *
443
+ * @author Louis-Dominique Dubeau
444
+ * @license MIT
445
+ * @copyright Louis-Dominique Dubeau
446
+ */
447
+ Object.defineProperty(exports, "__esModule", { value: true });
448
+ exports.CHAR = " \n\r -퟿-�𐀀-􏿿";
449
+ exports.S = " \r\n";
450
+ exports.NAME_START_CHAR = ":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿";
451
+ exports.NAME_CHAR = "-" + exports.NAME_START_CHAR + ".0-9·̀-ͯ‿-⁀";
452
+ exports.CHAR_RE = new RegExp("^[" + exports.CHAR + "]$", "u");
453
+ exports.S_RE = new RegExp("^[" + exports.S + "]+$", "u");
454
+ exports.NAME_START_CHAR_RE = new RegExp("^[" + exports.NAME_START_CHAR + "]$", "u");
455
+ exports.NAME_CHAR_RE = new RegExp("^[" + exports.NAME_CHAR + "]$", "u");
456
+ exports.NAME_RE = new RegExp("^[" + exports.NAME_START_CHAR + "][" + exports.NAME_CHAR + "]*$", "u");
457
+ exports.NMTOKEN_RE = new RegExp("^[" + exports.NAME_CHAR + "]+$", "u");
458
+ var TAB = 9;
459
+ var NL = 10;
460
+ var CR = 13;
461
+ var SPACE = 32;
462
+ /** All characters in the ``S`` production. */
463
+ exports.S_LIST = [
464
+ SPACE,
465
+ NL,
466
+ CR,
467
+ TAB
468
+ ];
469
+ /**
470
+ * Determines whether a codepoint matches the ``CHAR`` production.
471
+ *
472
+ * @param c The code point.
473
+ *
474
+ * @returns ``true`` if the codepoint matches ``CHAR``.
475
+ */
476
+ function isChar(c) {
477
+ return c >= SPACE && c <= 55295 || c === NL || c === CR || c === TAB || c >= 57344 && c <= 65533 || c >= 65536 && c <= 1114111;
478
+ }
479
+ exports.isChar = isChar;
480
+ /**
481
+ * Determines whether a codepoint matches the ``S`` (space) production.
482
+ *
483
+ * @param c The code point.
484
+ *
485
+ * @returns ``true`` if the codepoint matches ``S``.
486
+ */
487
+ function isS(c) {
488
+ return c === SPACE || c === NL || c === CR || c === TAB;
489
+ }
490
+ exports.isS = isS;
491
+ /**
492
+ * Determines whether a codepoint matches the ``NAME_START_CHAR`` production.
493
+ *
494
+ * @param c The code point.
495
+ *
496
+ * @returns ``true`` if the codepoint matches ``NAME_START_CHAR``.
497
+ */
498
+ function isNameStartChar(c) {
499
+ return c >= 65 && c <= 90 || c >= 97 && c <= 122 || c === 58 || c === 95 || c === 8204 || c === 8205 || c >= 192 && c <= 214 || c >= 216 && c <= 246 || c >= 248 && c <= 767 || c >= 880 && c <= 893 || c >= 895 && c <= 8191 || c >= 8304 && c <= 8591 || c >= 11264 && c <= 12271 || c >= 12289 && c <= 55295 || c >= 63744 && c <= 64975 || c >= 65008 && c <= 65533 || c >= 65536 && c <= 983039;
500
+ }
501
+ exports.isNameStartChar = isNameStartChar;
502
+ /**
503
+ * Determines whether a codepoint matches the ``NAME_CHAR`` production.
504
+ *
505
+ * @param c The code point.
506
+ *
507
+ * @returns ``true`` if the codepoint matches ``NAME_CHAR``.
508
+ */
509
+ function isNameChar(c) {
510
+ return isNameStartChar(c) || c >= 48 && c <= 57 || c === 45 || c === 46 || c === 183 || c >= 768 && c <= 879 || c >= 8255 && c <= 8256;
511
+ }
512
+ exports.isNameChar = isNameChar;
513
+ }));
514
+ //#endregion
515
+ //#region ../../node_modules/.pnpm/xmlchars@2.2.0/node_modules/xmlchars/xml/1.1/ed2.js
516
+ var require_ed2 = /* @__PURE__ */ __commonJSMin(((exports) => {
517
+ /**
518
+ * Character classes and associated utilities for the 2nd edition of XML 1.1.
519
+ *
520
+ * @author Louis-Dominique Dubeau
521
+ * @license MIT
522
+ * @copyright Louis-Dominique Dubeau
523
+ */
524
+ Object.defineProperty(exports, "__esModule", { value: true });
525
+ exports.CHAR = "-퟿-�𐀀-􏿿";
526
+ exports.RESTRICTED_CHAR = "-\b\v\f--„†-Ÿ";
527
+ exports.S = " \r\n";
528
+ exports.NAME_START_CHAR = ":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿";
529
+ exports.NAME_CHAR = "-" + exports.NAME_START_CHAR + ".0-9·̀-ͯ‿-⁀";
530
+ exports.CHAR_RE = new RegExp("^[" + exports.CHAR + "]$", "u");
531
+ exports.RESTRICTED_CHAR_RE = new RegExp("^[" + exports.RESTRICTED_CHAR + "]$", "u");
532
+ exports.S_RE = new RegExp("^[" + exports.S + "]+$", "u");
533
+ exports.NAME_START_CHAR_RE = new RegExp("^[" + exports.NAME_START_CHAR + "]$", "u");
534
+ exports.NAME_CHAR_RE = new RegExp("^[" + exports.NAME_CHAR + "]$", "u");
535
+ exports.NAME_RE = new RegExp("^[" + exports.NAME_START_CHAR + "][" + exports.NAME_CHAR + "]*$", "u");
536
+ exports.NMTOKEN_RE = new RegExp("^[" + exports.NAME_CHAR + "]+$", "u");
537
+ var TAB = 9;
538
+ var NL = 10;
539
+ var CR = 13;
540
+ var SPACE = 32;
541
+ /** All characters in the ``S`` production. */
542
+ exports.S_LIST = [
543
+ SPACE,
544
+ NL,
545
+ CR,
546
+ TAB
547
+ ];
548
+ /**
549
+ * Determines whether a codepoint matches the ``CHAR`` production.
550
+ *
551
+ * @param c The code point.
552
+ *
553
+ * @returns ``true`` if the codepoint matches ``CHAR``.
554
+ */
555
+ function isChar(c) {
556
+ return c >= 1 && c <= 55295 || c >= 57344 && c <= 65533 || c >= 65536 && c <= 1114111;
557
+ }
558
+ exports.isChar = isChar;
559
+ /**
560
+ * Determines whether a codepoint matches the ``RESTRICTED_CHAR`` production.
561
+ *
562
+ * @param c The code point.
563
+ *
564
+ * @returns ``true`` if the codepoint matches ``RESTRICTED_CHAR``.
565
+ */
566
+ function isRestrictedChar(c) {
567
+ return c >= 1 && c <= 8 || c === 11 || c === 12 || c >= 14 && c <= 31 || c >= 127 && c <= 132 || c >= 134 && c <= 159;
568
+ }
569
+ exports.isRestrictedChar = isRestrictedChar;
570
+ /**
571
+ * Determines whether a codepoint matches the ``CHAR`` production and does not
572
+ * match the ``RESTRICTED_CHAR`` production. ``isCharAndNotRestricted(x)`` is
573
+ * equivalent to ``isChar(x) && !isRestrictedChar(x)``. This function is faster
574
+ * than running the two-call equivalent.
575
+ *
576
+ * @param c The code point.
577
+ *
578
+ * @returns ``true`` if the codepoint matches ``CHAR`` and does not match
579
+ * ``RESTRICTED_CHAR``.
580
+ */
581
+ function isCharAndNotRestricted(c) {
582
+ return c === 9 || c === 10 || c === 13 || c > 31 && c < 127 || c === 133 || c > 159 && c <= 55295 || c >= 57344 && c <= 65533 || c >= 65536 && c <= 1114111;
583
+ }
584
+ exports.isCharAndNotRestricted = isCharAndNotRestricted;
585
+ /**
586
+ * Determines whether a codepoint matches the ``S`` (space) production.
587
+ *
588
+ * @param c The code point.
589
+ *
590
+ * @returns ``true`` if the codepoint matches ``S``.
591
+ */
592
+ function isS(c) {
593
+ return c === SPACE || c === NL || c === CR || c === TAB;
594
+ }
595
+ exports.isS = isS;
596
+ /**
597
+ * Determines whether a codepoint matches the ``NAME_START_CHAR`` production.
598
+ *
599
+ * @param c The code point.
600
+ *
601
+ * @returns ``true`` if the codepoint matches ``NAME_START_CHAR``.
602
+ */
603
+ function isNameStartChar(c) {
604
+ return c >= 65 && c <= 90 || c >= 97 && c <= 122 || c === 58 || c === 95 || c === 8204 || c === 8205 || c >= 192 && c <= 214 || c >= 216 && c <= 246 || c >= 248 && c <= 767 || c >= 880 && c <= 893 || c >= 895 && c <= 8191 || c >= 8304 && c <= 8591 || c >= 11264 && c <= 12271 || c >= 12289 && c <= 55295 || c >= 63744 && c <= 64975 || c >= 65008 && c <= 65533 || c >= 65536 && c <= 983039;
605
+ }
606
+ exports.isNameStartChar = isNameStartChar;
607
+ /**
608
+ * Determines whether a codepoint matches the ``NAME_CHAR`` production.
609
+ *
610
+ * @param c The code point.
611
+ *
612
+ * @returns ``true`` if the codepoint matches ``NAME_CHAR``.
613
+ */
614
+ function isNameChar(c) {
615
+ return isNameStartChar(c) || c >= 48 && c <= 57 || c === 45 || c === 46 || c === 183 || c >= 768 && c <= 879 || c >= 8255 && c <= 8256;
616
+ }
617
+ exports.isNameChar = isNameChar;
618
+ }));
619
+ //#endregion
620
+ //#region ../../node_modules/.pnpm/xmlchars@2.2.0/node_modules/xmlchars/xmlns/1.0/ed3.js
621
+ var require_ed3 = /* @__PURE__ */ __commonJSMin(((exports) => {
622
+ /**
623
+ * Character class utilities for XML NS 1.0 edition 3.
624
+ *
625
+ * @author Louis-Dominique Dubeau
626
+ * @license MIT
627
+ * @copyright Louis-Dominique Dubeau
628
+ */
629
+ Object.defineProperty(exports, "__esModule", { value: true });
630
+ exports.NC_NAME_START_CHAR = "A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿";
631
+ exports.NC_NAME_CHAR = "-" + exports.NC_NAME_START_CHAR + ".0-9·̀-ͯ‿-⁀";
632
+ exports.NC_NAME_START_CHAR_RE = new RegExp("^[" + exports.NC_NAME_START_CHAR + "]$", "u");
633
+ exports.NC_NAME_CHAR_RE = new RegExp("^[" + exports.NC_NAME_CHAR + "]$", "u");
634
+ exports.NC_NAME_RE = new RegExp("^[" + exports.NC_NAME_START_CHAR + "][" + exports.NC_NAME_CHAR + "]*$", "u");
635
+ /**
636
+ * Determines whether a codepoint matches [[NC_NAME_START_CHAR]].
637
+ *
638
+ * @param c The code point.
639
+ *
640
+ * @returns ``true`` if the codepoint matches.
641
+ */
642
+ function isNCNameStartChar(c) {
643
+ return c >= 65 && c <= 90 || c === 95 || c >= 97 && c <= 122 || c >= 192 && c <= 214 || c >= 216 && c <= 246 || c >= 248 && c <= 767 || c >= 880 && c <= 893 || c >= 895 && c <= 8191 || c >= 8204 && c <= 8205 || c >= 8304 && c <= 8591 || c >= 11264 && c <= 12271 || c >= 12289 && c <= 55295 || c >= 63744 && c <= 64975 || c >= 65008 && c <= 65533 || c >= 65536 && c <= 983039;
644
+ }
645
+ exports.isNCNameStartChar = isNCNameStartChar;
646
+ /**
647
+ * Determines whether a codepoint matches [[NC_NAME_CHAR]].
648
+ *
649
+ * @param c The code point.
650
+ *
651
+ * @returns ``true`` if the codepoint matches.
652
+ */
653
+ function isNCNameChar(c) {
654
+ return isNCNameStartChar(c) || c === 45 || c === 46 || c >= 48 && c <= 57 || c === 183 || c >= 768 && c <= 879 || c >= 8255 && c <= 8256;
655
+ }
656
+ exports.isNCNameChar = isNCNameChar;
657
+ }));
658
+ //#endregion
659
+ //#region ../entry/lib/document.js
660
+ var import_saxes = (/* @__PURE__ */ __commonJSMin(((exports) => {
661
+ Object.defineProperty(exports, "__esModule", { value: true });
662
+ exports.SaxesParser = exports.EVENTS = void 0;
663
+ const ed5 = require_ed5();
664
+ const ed2 = require_ed2();
665
+ const NSed3 = require_ed3();
666
+ var isS = ed5.isS;
667
+ var isChar10 = ed5.isChar;
668
+ var isNameStartChar = ed5.isNameStartChar;
669
+ var isNameChar = ed5.isNameChar;
670
+ var S_LIST = ed5.S_LIST;
671
+ var NAME_RE = ed5.NAME_RE;
672
+ var isChar11 = ed2.isChar;
673
+ var isNCNameStartChar = NSed3.isNCNameStartChar;
674
+ var isNCNameChar = NSed3.isNCNameChar;
675
+ var NC_NAME_RE = NSed3.NC_NAME_RE;
676
+ const XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace";
677
+ const XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/";
678
+ const rootNS = {
679
+ __proto__: null,
680
+ xml: XML_NAMESPACE,
681
+ xmlns: XMLNS_NAMESPACE
682
+ };
683
+ const XML_ENTITIES = {
684
+ __proto__: null,
685
+ amp: "&",
686
+ gt: ">",
687
+ lt: "<",
688
+ quot: "\"",
689
+ apos: "'"
690
+ };
691
+ const EOC = -1;
692
+ const NL_LIKE = -2;
693
+ const S_BEGIN = 0;
694
+ const S_BEGIN_WHITESPACE = 1;
695
+ const S_DOCTYPE = 2;
696
+ const S_DOCTYPE_QUOTE = 3;
697
+ const S_DTD = 4;
698
+ const S_DTD_QUOTED = 5;
699
+ const S_DTD_OPEN_WAKA = 6;
700
+ const S_DTD_OPEN_WAKA_BANG = 7;
701
+ const S_DTD_COMMENT = 8;
702
+ const S_DTD_COMMENT_ENDING = 9;
703
+ const S_DTD_COMMENT_ENDED = 10;
704
+ const S_DTD_PI = 11;
705
+ const S_DTD_PI_ENDING = 12;
706
+ const S_TEXT = 13;
707
+ const S_ENTITY = 14;
708
+ const S_OPEN_WAKA = 15;
709
+ const S_OPEN_WAKA_BANG = 16;
710
+ const S_COMMENT = 17;
711
+ const S_COMMENT_ENDING = 18;
712
+ const S_COMMENT_ENDED = 19;
713
+ const S_CDATA = 20;
714
+ const S_CDATA_ENDING = 21;
715
+ const S_CDATA_ENDING_2 = 22;
716
+ const S_PI_FIRST_CHAR = 23;
717
+ const S_PI_REST = 24;
718
+ const S_PI_BODY = 25;
719
+ const S_PI_ENDING = 26;
720
+ const S_XML_DECL_NAME_START = 27;
721
+ const S_XML_DECL_NAME = 28;
722
+ const S_XML_DECL_EQ = 29;
723
+ const S_XML_DECL_VALUE_START = 30;
724
+ const S_XML_DECL_VALUE = 31;
725
+ const S_XML_DECL_SEPARATOR = 32;
726
+ const S_XML_DECL_ENDING = 33;
727
+ const S_OPEN_TAG = 34;
728
+ const S_OPEN_TAG_SLASH = 35;
729
+ const S_ATTRIB = 36;
730
+ const S_ATTRIB_NAME = 37;
731
+ const S_ATTRIB_NAME_SAW_WHITE = 38;
732
+ const S_ATTRIB_VALUE = 39;
733
+ const S_ATTRIB_VALUE_QUOTED = 40;
734
+ const S_ATTRIB_VALUE_CLOSED = 41;
735
+ const S_ATTRIB_VALUE_UNQUOTED = 42;
736
+ const S_CLOSE_TAG = 43;
737
+ const S_CLOSE_TAG_SAW_WHITE = 44;
738
+ const TAB = 9;
739
+ const NL = 10;
740
+ const CR = 13;
741
+ const SPACE = 32;
742
+ const BANG = 33;
743
+ const DQUOTE = 34;
744
+ const AMP = 38;
745
+ const SQUOTE = 39;
746
+ const MINUS = 45;
747
+ const FORWARD_SLASH = 47;
748
+ const SEMICOLON = 59;
749
+ const LESS = 60;
750
+ const EQUAL = 61;
751
+ const GREATER = 62;
752
+ const QUESTION = 63;
753
+ const OPEN_BRACKET = 91;
754
+ const CLOSE_BRACKET = 93;
755
+ const NEL = 133;
756
+ const LS = 8232;
757
+ const isQuote = (c) => c === DQUOTE || c === SQUOTE;
758
+ const QUOTES = [DQUOTE, SQUOTE];
759
+ const DOCTYPE_TERMINATOR = [
760
+ ...QUOTES,
761
+ OPEN_BRACKET,
762
+ GREATER
763
+ ];
764
+ const DTD_TERMINATOR = [
765
+ ...QUOTES,
766
+ LESS,
767
+ CLOSE_BRACKET
768
+ ];
769
+ const XML_DECL_NAME_TERMINATOR = [
770
+ EQUAL,
771
+ QUESTION,
772
+ ...S_LIST
773
+ ];
774
+ const ATTRIB_VALUE_UNQUOTED_TERMINATOR = [
775
+ ...S_LIST,
776
+ GREATER,
777
+ AMP,
778
+ LESS
779
+ ];
780
+ function nsPairCheck(parser, prefix, uri) {
781
+ switch (prefix) {
782
+ case "xml":
783
+ if (uri !== XML_NAMESPACE) parser.fail(`xml prefix must be bound to ${XML_NAMESPACE}.`);
784
+ break;
785
+ case "xmlns": if (uri !== XMLNS_NAMESPACE) parser.fail(`xmlns prefix must be bound to ${XMLNS_NAMESPACE}.`);
786
+ }
787
+ switch (uri) {
788
+ case XMLNS_NAMESPACE:
789
+ parser.fail(prefix === "" ? `the default namespace may not be set to ${uri}.` : `may not assign a prefix (even "xmlns") to the URI \
790
+ ${XMLNS_NAMESPACE}.`);
791
+ break;
792
+ case XML_NAMESPACE: switch (prefix) {
793
+ case "xml": break;
794
+ case "":
795
+ parser.fail(`the default namespace may not be set to ${uri}.`);
796
+ break;
797
+ default: parser.fail("may not assign the xml namespace to another prefix.");
798
+ }
799
+ }
800
+ }
801
+ function nsMappingCheck(parser, mapping) {
802
+ for (const local of Object.keys(mapping)) nsPairCheck(parser, local, mapping[local]);
803
+ }
804
+ const isNCName = (name) => NC_NAME_RE.test(name);
805
+ const isName = (name) => NAME_RE.test(name);
806
+ const FORBIDDEN_START = 0;
807
+ const FORBIDDEN_BRACKET = 1;
808
+ const FORBIDDEN_BRACKET_BRACKET = 2;
809
+ /**
810
+ * The list of supported events.
811
+ */
812
+ exports.EVENTS = [
813
+ "xmldecl",
814
+ "text",
815
+ "processinginstruction",
816
+ "doctype",
817
+ "comment",
818
+ "opentagstart",
819
+ "attribute",
820
+ "opentag",
821
+ "closetag",
822
+ "cdata",
823
+ "error",
824
+ "end",
825
+ "ready"
826
+ ];
827
+ const EVENT_NAME_TO_HANDLER_NAME = {
828
+ xmldecl: "xmldeclHandler",
829
+ text: "textHandler",
830
+ processinginstruction: "piHandler",
831
+ doctype: "doctypeHandler",
832
+ comment: "commentHandler",
833
+ opentagstart: "openTagStartHandler",
834
+ attribute: "attributeHandler",
835
+ opentag: "openTagHandler",
836
+ closetag: "closeTagHandler",
837
+ cdata: "cdataHandler",
838
+ error: "errorHandler",
839
+ end: "endHandler",
840
+ ready: "readyHandler"
841
+ };
842
+ var SaxesParser = class {
843
+ /**
844
+ * @param opt The parser options.
845
+ */
846
+ constructor(opt) {
847
+ this.opt = opt !== null && opt !== void 0 ? opt : {};
848
+ this.fragmentOpt = !!this.opt.fragment;
849
+ const xmlnsOpt = this.xmlnsOpt = !!this.opt.xmlns;
850
+ this.trackPosition = this.opt.position !== false;
851
+ this.fileName = this.opt.fileName;
852
+ if (xmlnsOpt) {
853
+ this.nameStartCheck = isNCNameStartChar;
854
+ this.nameCheck = isNCNameChar;
855
+ this.isName = isNCName;
856
+ this.processAttribs = this.processAttribsNS;
857
+ this.pushAttrib = this.pushAttribNS;
858
+ this.ns = Object.assign({ __proto__: null }, rootNS);
859
+ const additional = this.opt.additionalNamespaces;
860
+ if (additional != null) {
861
+ nsMappingCheck(this, additional);
862
+ Object.assign(this.ns, additional);
863
+ }
864
+ } else {
865
+ this.nameStartCheck = isNameStartChar;
866
+ this.nameCheck = isNameChar;
867
+ this.isName = isName;
868
+ this.processAttribs = this.processAttribsPlain;
869
+ this.pushAttrib = this.pushAttribPlain;
870
+ }
871
+ this.stateTable = [
872
+ this.sBegin,
873
+ this.sBeginWhitespace,
874
+ this.sDoctype,
875
+ this.sDoctypeQuote,
876
+ this.sDTD,
877
+ this.sDTDQuoted,
878
+ this.sDTDOpenWaka,
879
+ this.sDTDOpenWakaBang,
880
+ this.sDTDComment,
881
+ this.sDTDCommentEnding,
882
+ this.sDTDCommentEnded,
883
+ this.sDTDPI,
884
+ this.sDTDPIEnding,
885
+ this.sText,
886
+ this.sEntity,
887
+ this.sOpenWaka,
888
+ this.sOpenWakaBang,
889
+ this.sComment,
890
+ this.sCommentEnding,
891
+ this.sCommentEnded,
892
+ this.sCData,
893
+ this.sCDataEnding,
894
+ this.sCDataEnding2,
895
+ this.sPIFirstChar,
896
+ this.sPIRest,
897
+ this.sPIBody,
898
+ this.sPIEnding,
899
+ this.sXMLDeclNameStart,
900
+ this.sXMLDeclName,
901
+ this.sXMLDeclEq,
902
+ this.sXMLDeclValueStart,
903
+ this.sXMLDeclValue,
904
+ this.sXMLDeclSeparator,
905
+ this.sXMLDeclEnding,
906
+ this.sOpenTag,
907
+ this.sOpenTagSlash,
908
+ this.sAttrib,
909
+ this.sAttribName,
910
+ this.sAttribNameSawWhite,
911
+ this.sAttribValue,
912
+ this.sAttribValueQuoted,
913
+ this.sAttribValueClosed,
914
+ this.sAttribValueUnquoted,
915
+ this.sCloseTag,
916
+ this.sCloseTagSawWhite
917
+ ];
918
+ this._init();
919
+ }
920
+ /**
921
+ * Indicates whether or not the parser is closed. If ``true``, wait for
922
+ * the ``ready`` event to write again.
923
+ */
924
+ get closed() {
925
+ return this._closed;
926
+ }
927
+ _init() {
928
+ var _a;
929
+ this.openWakaBang = "";
930
+ this.text = "";
931
+ this.name = "";
932
+ this.piTarget = "";
933
+ this.entity = "";
934
+ this.q = null;
935
+ this.tags = [];
936
+ this.tag = null;
937
+ this.topNS = null;
938
+ this.chunk = "";
939
+ this.chunkPosition = 0;
940
+ this.i = 0;
941
+ this.prevI = 0;
942
+ this.carriedFromPrevious = void 0;
943
+ this.forbiddenState = FORBIDDEN_START;
944
+ this.attribList = [];
945
+ const { fragmentOpt } = this;
946
+ this.state = fragmentOpt ? S_TEXT : S_BEGIN;
947
+ this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot = this.sawRoot = fragmentOpt;
948
+ this.xmlDeclPossible = !fragmentOpt;
949
+ this.xmlDeclExpects = ["version"];
950
+ this.entityReturnState = void 0;
951
+ let { defaultXMLVersion } = this.opt;
952
+ if (defaultXMLVersion === void 0) {
953
+ if (this.opt.forceXMLVersion === true) throw new Error("forceXMLVersion set but defaultXMLVersion is not set");
954
+ defaultXMLVersion = "1.0";
955
+ }
956
+ this.setXMLVersion(defaultXMLVersion);
957
+ this.positionAtNewLine = 0;
958
+ this.doctype = false;
959
+ this._closed = false;
960
+ this.xmlDecl = {
961
+ version: void 0,
962
+ encoding: void 0,
963
+ standalone: void 0
964
+ };
965
+ this.line = 1;
966
+ this.column = 0;
967
+ this.ENTITIES = Object.create(XML_ENTITIES);
968
+ (_a = this.readyHandler) === null || _a === void 0 || _a.call(this);
969
+ }
970
+ /**
971
+ * The stream position the parser is currently looking at. This field is
972
+ * zero-based.
973
+ *
974
+ * This field is not based on counting Unicode characters but is to be
975
+ * interpreted as a plain index into a JavaScript string.
976
+ */
977
+ get position() {
978
+ return this.chunkPosition + this.i;
979
+ }
980
+ /**
981
+ * The column number of the next character to be read by the parser. *
982
+ * This field is zero-based. (The first column in a line is 0.)
983
+ *
984
+ * This field reports the index at which the next character would be in the
985
+ * line if the line were represented as a JavaScript string. Note that this
986
+ * *can* be different to a count based on the number of *Unicode characters*
987
+ * due to how JavaScript handles astral plane characters.
988
+ *
989
+ * See [[column]] for a number that corresponds to a count of Unicode
990
+ * characters.
991
+ */
992
+ get columnIndex() {
993
+ return this.position - this.positionAtNewLine;
994
+ }
995
+ /**
996
+ * Set an event listener on an event. The parser supports one handler per
997
+ * event type. If you try to set an event handler over an existing handler,
998
+ * the old handler is silently overwritten.
999
+ *
1000
+ * @param name The event to listen to.
1001
+ *
1002
+ * @param handler The handler to set.
1003
+ */
1004
+ on(name, handler) {
1005
+ this[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;
1006
+ }
1007
+ /**
1008
+ * Unset an event handler.
1009
+ *
1010
+ * @parma name The event to stop listening to.
1011
+ */
1012
+ off(name) {
1013
+ this[EVENT_NAME_TO_HANDLER_NAME[name]] = void 0;
1014
+ }
1015
+ /**
1016
+ * Make an error object. The error object will have a message that contains
1017
+ * the ``fileName`` option passed at the creation of the parser. If position
1018
+ * tracking was turned on, it will also have line and column number
1019
+ * information.
1020
+ *
1021
+ * @param message The message describing the error to report.
1022
+ *
1023
+ * @returns An error object with a properly formatted message.
1024
+ */
1025
+ makeError(message) {
1026
+ var _a;
1027
+ let msg = (_a = this.fileName) !== null && _a !== void 0 ? _a : "";
1028
+ if (this.trackPosition) {
1029
+ if (msg.length > 0) msg += ":";
1030
+ msg += `${this.line}:${this.column}`;
1031
+ }
1032
+ if (msg.length > 0) msg += ": ";
1033
+ return new Error(msg + message);
1034
+ }
1035
+ /**
1036
+ * Report a parsing error. This method is made public so that client code may
1037
+ * check for issues that are outside the scope of this project and can report
1038
+ * errors.
1039
+ *
1040
+ * @param message The error to report.
1041
+ *
1042
+ * @returns this
1043
+ */
1044
+ fail(message) {
1045
+ const err = this.makeError(message);
1046
+ const handler = this.errorHandler;
1047
+ if (handler === void 0) throw err;
1048
+ else handler(err);
1049
+ return this;
1050
+ }
1051
+ /**
1052
+ * Write a XML data to the parser.
1053
+ *
1054
+ * @param chunk The XML data to write.
1055
+ *
1056
+ * @returns this
1057
+ */
1058
+ write(chunk) {
1059
+ if (this.closed) return this.fail("cannot write after close; assign an onready handler.");
1060
+ let end = false;
1061
+ if (chunk === null) {
1062
+ end = true;
1063
+ chunk = "";
1064
+ } else if (typeof chunk === "object") chunk = chunk.toString();
1065
+ if (this.carriedFromPrevious !== void 0) {
1066
+ chunk = `${this.carriedFromPrevious}${chunk}`;
1067
+ this.carriedFromPrevious = void 0;
1068
+ }
1069
+ let limit = chunk.length;
1070
+ const lastCode = chunk.charCodeAt(limit - 1);
1071
+ if (!end && (lastCode === CR || lastCode >= 55296 && lastCode <= 56319)) {
1072
+ this.carriedFromPrevious = chunk[limit - 1];
1073
+ limit--;
1074
+ chunk = chunk.slice(0, limit);
1075
+ }
1076
+ const { stateTable } = this;
1077
+ this.chunk = chunk;
1078
+ this.i = 0;
1079
+ while (this.i < limit) stateTable[this.state].call(this);
1080
+ this.chunkPosition += limit;
1081
+ return end ? this.end() : this;
1082
+ }
1083
+ /**
1084
+ * Close the current stream. Perform final well-formedness checks and reset
1085
+ * the parser tstate.
1086
+ *
1087
+ * @returns this
1088
+ */
1089
+ close() {
1090
+ return this.write(null);
1091
+ }
1092
+ /**
1093
+ * Get a single code point out of the current chunk. This updates the current
1094
+ * position if we do position tracking.
1095
+ *
1096
+ * This is the algorithm to use for XML 1.0.
1097
+ *
1098
+ * @returns The character read.
1099
+ */
1100
+ getCode10() {
1101
+ const { chunk, i } = this;
1102
+ this.prevI = i;
1103
+ this.i = i + 1;
1104
+ if (i >= chunk.length) return EOC;
1105
+ const code = chunk.charCodeAt(i);
1106
+ this.column++;
1107
+ if (code < 55296) {
1108
+ if (code >= SPACE || code === TAB) return code;
1109
+ switch (code) {
1110
+ case NL:
1111
+ this.line++;
1112
+ this.column = 0;
1113
+ this.positionAtNewLine = this.position;
1114
+ return NL;
1115
+ case CR:
1116
+ if (chunk.charCodeAt(i + 1) === NL) this.i = i + 2;
1117
+ this.line++;
1118
+ this.column = 0;
1119
+ this.positionAtNewLine = this.position;
1120
+ return NL_LIKE;
1121
+ default:
1122
+ this.fail("disallowed character.");
1123
+ return code;
1124
+ }
1125
+ }
1126
+ if (code > 56319) {
1127
+ if (!(code >= 57344 && code <= 65533)) this.fail("disallowed character.");
1128
+ return code;
1129
+ }
1130
+ const final = 65536 + (code - 55296) * 1024 + (chunk.charCodeAt(i + 1) - 56320);
1131
+ this.i = i + 2;
1132
+ if (final > 1114111) this.fail("disallowed character.");
1133
+ return final;
1134
+ }
1135
+ /**
1136
+ * Get a single code point out of the current chunk. This updates the current
1137
+ * position if we do position tracking.
1138
+ *
1139
+ * This is the algorithm to use for XML 1.1.
1140
+ *
1141
+ * @returns {number} The character read.
1142
+ */
1143
+ getCode11() {
1144
+ const { chunk, i } = this;
1145
+ this.prevI = i;
1146
+ this.i = i + 1;
1147
+ if (i >= chunk.length) return EOC;
1148
+ const code = chunk.charCodeAt(i);
1149
+ this.column++;
1150
+ if (code < 55296) {
1151
+ if (code > 31 && code < 127 || code > 159 && code !== LS || code === TAB) return code;
1152
+ switch (code) {
1153
+ case NL:
1154
+ this.line++;
1155
+ this.column = 0;
1156
+ this.positionAtNewLine = this.position;
1157
+ return NL;
1158
+ case CR: {
1159
+ const next = chunk.charCodeAt(i + 1);
1160
+ if (next === NL || next === NEL) this.i = i + 2;
1161
+ }
1162
+ case NEL:
1163
+ case LS:
1164
+ this.line++;
1165
+ this.column = 0;
1166
+ this.positionAtNewLine = this.position;
1167
+ return NL_LIKE;
1168
+ default:
1169
+ this.fail("disallowed character.");
1170
+ return code;
1171
+ }
1172
+ }
1173
+ if (code > 56319) {
1174
+ if (!(code >= 57344 && code <= 65533)) this.fail("disallowed character.");
1175
+ return code;
1176
+ }
1177
+ const final = 65536 + (code - 55296) * 1024 + (chunk.charCodeAt(i + 1) - 56320);
1178
+ this.i = i + 2;
1179
+ if (final > 1114111) this.fail("disallowed character.");
1180
+ return final;
1181
+ }
1182
+ /**
1183
+ * Like ``getCode`` but with the return value normalized so that ``NL`` is
1184
+ * returned for ``NL_LIKE``.
1185
+ */
1186
+ getCodeNorm() {
1187
+ const c = this.getCode();
1188
+ return c === NL_LIKE ? NL : c;
1189
+ }
1190
+ unget() {
1191
+ this.i = this.prevI;
1192
+ this.column--;
1193
+ }
1194
+ /**
1195
+ * Capture characters into a buffer until encountering one of a set of
1196
+ * characters.
1197
+ *
1198
+ * @param chars An array of codepoints. Encountering a character in the array
1199
+ * ends the capture. (``chars`` may safely contain ``NL``.)
1200
+ *
1201
+ * @return The character code that made the capture end, or ``EOC`` if we hit
1202
+ * the end of the chunk. The return value cannot be NL_LIKE: NL is returned
1203
+ * instead.
1204
+ */
1205
+ captureTo(chars) {
1206
+ let { i: start } = this;
1207
+ const { chunk } = this;
1208
+ while (true) {
1209
+ const c = this.getCode();
1210
+ const isNLLike = c === NL_LIKE;
1211
+ const final = isNLLike ? NL : c;
1212
+ if (final === EOC || chars.includes(final)) {
1213
+ this.text += chunk.slice(start, this.prevI);
1214
+ return final;
1215
+ }
1216
+ if (isNLLike) {
1217
+ this.text += `${chunk.slice(start, this.prevI)}\n`;
1218
+ start = this.i;
1219
+ }
1220
+ }
1221
+ }
1222
+ /**
1223
+ * Capture characters into a buffer until encountering a character.
1224
+ *
1225
+ * @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT
1226
+ * CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.
1227
+ *
1228
+ * @return ``true`` if we ran into the character. Otherwise, we ran into the
1229
+ * end of the current chunk.
1230
+ */
1231
+ captureToChar(char) {
1232
+ let { i: start } = this;
1233
+ const { chunk } = this;
1234
+ while (true) {
1235
+ let c = this.getCode();
1236
+ switch (c) {
1237
+ case NL_LIKE:
1238
+ this.text += `${chunk.slice(start, this.prevI)}\n`;
1239
+ start = this.i;
1240
+ c = NL;
1241
+ break;
1242
+ case EOC:
1243
+ this.text += chunk.slice(start);
1244
+ return false;
1245
+ }
1246
+ if (c === char) {
1247
+ this.text += chunk.slice(start, this.prevI);
1248
+ return true;
1249
+ }
1250
+ }
1251
+ }
1252
+ /**
1253
+ * Capture characters that satisfy ``isNameChar`` into the ``name`` field of
1254
+ * this parser.
1255
+ *
1256
+ * @return The character code that made the test fail, or ``EOC`` if we hit
1257
+ * the end of the chunk. The return value cannot be NL_LIKE: NL is returned
1258
+ * instead.
1259
+ */
1260
+ captureNameChars() {
1261
+ const { chunk, i: start } = this;
1262
+ while (true) {
1263
+ const c = this.getCode();
1264
+ if (c === EOC) {
1265
+ this.name += chunk.slice(start);
1266
+ return EOC;
1267
+ }
1268
+ if (!isNameChar(c)) {
1269
+ this.name += chunk.slice(start, this.prevI);
1270
+ return c === NL_LIKE ? NL : c;
1271
+ }
1272
+ }
1273
+ }
1274
+ /**
1275
+ * Skip white spaces.
1276
+ *
1277
+ * @return The character that ended the skip, or ``EOC`` if we hit
1278
+ * the end of the chunk. The return value cannot be NL_LIKE: NL is returned
1279
+ * instead.
1280
+ */
1281
+ skipSpaces() {
1282
+ while (true) {
1283
+ const c = this.getCodeNorm();
1284
+ if (c === EOC || !isS(c)) return c;
1285
+ }
1286
+ }
1287
+ setXMLVersion(version) {
1288
+ this.currentXMLVersion = version;
1289
+ if (version === "1.0") {
1290
+ this.isChar = isChar10;
1291
+ this.getCode = this.getCode10;
1292
+ } else {
1293
+ this.isChar = isChar11;
1294
+ this.getCode = this.getCode11;
1295
+ }
1296
+ }
1297
+ sBegin() {
1298
+ if (this.chunk.charCodeAt(0) === 65279) {
1299
+ this.i++;
1300
+ this.column++;
1301
+ }
1302
+ this.state = S_BEGIN_WHITESPACE;
1303
+ }
1304
+ sBeginWhitespace() {
1305
+ const iBefore = this.i;
1306
+ const c = this.skipSpaces();
1307
+ if (this.prevI !== iBefore) this.xmlDeclPossible = false;
1308
+ switch (c) {
1309
+ case LESS:
1310
+ this.state = S_OPEN_WAKA;
1311
+ if (this.text.length !== 0) throw new Error("no-empty text at start");
1312
+ break;
1313
+ case EOC: break;
1314
+ default:
1315
+ this.unget();
1316
+ this.state = S_TEXT;
1317
+ this.xmlDeclPossible = false;
1318
+ }
1319
+ }
1320
+ sDoctype() {
1321
+ var _a;
1322
+ const c = this.captureTo(DOCTYPE_TERMINATOR);
1323
+ switch (c) {
1324
+ case GREATER:
1325
+ (_a = this.doctypeHandler) === null || _a === void 0 || _a.call(this, this.text);
1326
+ this.text = "";
1327
+ this.state = S_TEXT;
1328
+ this.doctype = true;
1329
+ break;
1330
+ case EOC: break;
1331
+ default:
1332
+ this.text += String.fromCodePoint(c);
1333
+ if (c === OPEN_BRACKET) this.state = S_DTD;
1334
+ else if (isQuote(c)) {
1335
+ this.state = S_DOCTYPE_QUOTE;
1336
+ this.q = c;
1337
+ }
1338
+ }
1339
+ }
1340
+ sDoctypeQuote() {
1341
+ const q = this.q;
1342
+ if (this.captureToChar(q)) {
1343
+ this.text += String.fromCodePoint(q);
1344
+ this.q = null;
1345
+ this.state = S_DOCTYPE;
1346
+ }
1347
+ }
1348
+ sDTD() {
1349
+ const c = this.captureTo(DTD_TERMINATOR);
1350
+ if (c === EOC) return;
1351
+ this.text += String.fromCodePoint(c);
1352
+ if (c === CLOSE_BRACKET) this.state = S_DOCTYPE;
1353
+ else if (c === LESS) this.state = S_DTD_OPEN_WAKA;
1354
+ else if (isQuote(c)) {
1355
+ this.state = S_DTD_QUOTED;
1356
+ this.q = c;
1357
+ }
1358
+ }
1359
+ sDTDQuoted() {
1360
+ const q = this.q;
1361
+ if (this.captureToChar(q)) {
1362
+ this.text += String.fromCodePoint(q);
1363
+ this.state = S_DTD;
1364
+ this.q = null;
1365
+ }
1366
+ }
1367
+ sDTDOpenWaka() {
1368
+ const c = this.getCodeNorm();
1369
+ this.text += String.fromCodePoint(c);
1370
+ switch (c) {
1371
+ case BANG:
1372
+ this.state = S_DTD_OPEN_WAKA_BANG;
1373
+ this.openWakaBang = "";
1374
+ break;
1375
+ case QUESTION:
1376
+ this.state = S_DTD_PI;
1377
+ break;
1378
+ default: this.state = S_DTD;
1379
+ }
1380
+ }
1381
+ sDTDOpenWakaBang() {
1382
+ const char = String.fromCodePoint(this.getCodeNorm());
1383
+ const owb = this.openWakaBang += char;
1384
+ this.text += char;
1385
+ if (owb !== "-") {
1386
+ this.state = owb === "--" ? S_DTD_COMMENT : S_DTD;
1387
+ this.openWakaBang = "";
1388
+ }
1389
+ }
1390
+ sDTDComment() {
1391
+ if (this.captureToChar(MINUS)) {
1392
+ this.text += "-";
1393
+ this.state = S_DTD_COMMENT_ENDING;
1394
+ }
1395
+ }
1396
+ sDTDCommentEnding() {
1397
+ const c = this.getCodeNorm();
1398
+ this.text += String.fromCodePoint(c);
1399
+ this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;
1400
+ }
1401
+ sDTDCommentEnded() {
1402
+ const c = this.getCodeNorm();
1403
+ this.text += String.fromCodePoint(c);
1404
+ if (c === GREATER) this.state = S_DTD;
1405
+ else {
1406
+ this.fail("malformed comment.");
1407
+ this.state = S_DTD_COMMENT;
1408
+ }
1409
+ }
1410
+ sDTDPI() {
1411
+ if (this.captureToChar(QUESTION)) {
1412
+ this.text += "?";
1413
+ this.state = S_DTD_PI_ENDING;
1414
+ }
1415
+ }
1416
+ sDTDPIEnding() {
1417
+ const c = this.getCodeNorm();
1418
+ this.text += String.fromCodePoint(c);
1419
+ if (c === GREATER) this.state = S_DTD;
1420
+ }
1421
+ sText() {
1422
+ if (this.tags.length !== 0) this.handleTextInRoot();
1423
+ else this.handleTextOutsideRoot();
1424
+ }
1425
+ sEntity() {
1426
+ let { i: start } = this;
1427
+ const { chunk } = this;
1428
+ loop: while (true) switch (this.getCode()) {
1429
+ case NL_LIKE:
1430
+ this.entity += `${chunk.slice(start, this.prevI)}\n`;
1431
+ start = this.i;
1432
+ break;
1433
+ case SEMICOLON: {
1434
+ const { entityReturnState } = this;
1435
+ const entity = this.entity + chunk.slice(start, this.prevI);
1436
+ this.state = entityReturnState;
1437
+ let parsed;
1438
+ if (entity === "") {
1439
+ this.fail("empty entity name.");
1440
+ parsed = "&;";
1441
+ } else {
1442
+ parsed = this.parseEntity(entity);
1443
+ this.entity = "";
1444
+ }
1445
+ if (entityReturnState !== S_TEXT || this.textHandler !== void 0) this.text += parsed;
1446
+ break loop;
1447
+ }
1448
+ case EOC:
1449
+ this.entity += chunk.slice(start);
1450
+ break loop;
1451
+ }
1452
+ }
1453
+ sOpenWaka() {
1454
+ const c = this.getCode();
1455
+ if (isNameStartChar(c)) {
1456
+ this.state = S_OPEN_TAG;
1457
+ this.unget();
1458
+ this.xmlDeclPossible = false;
1459
+ } else switch (c) {
1460
+ case FORWARD_SLASH:
1461
+ this.state = S_CLOSE_TAG;
1462
+ this.xmlDeclPossible = false;
1463
+ break;
1464
+ case BANG:
1465
+ this.state = S_OPEN_WAKA_BANG;
1466
+ this.openWakaBang = "";
1467
+ this.xmlDeclPossible = false;
1468
+ break;
1469
+ case QUESTION:
1470
+ this.state = S_PI_FIRST_CHAR;
1471
+ break;
1472
+ default:
1473
+ this.fail("disallowed character in tag name");
1474
+ this.state = S_TEXT;
1475
+ this.xmlDeclPossible = false;
1476
+ }
1477
+ }
1478
+ sOpenWakaBang() {
1479
+ this.openWakaBang += String.fromCodePoint(this.getCodeNorm());
1480
+ switch (this.openWakaBang) {
1481
+ case "[CDATA[":
1482
+ if (!this.sawRoot && !this.reportedTextBeforeRoot) {
1483
+ this.fail("text data outside of root node.");
1484
+ this.reportedTextBeforeRoot = true;
1485
+ }
1486
+ if (this.closedRoot && !this.reportedTextAfterRoot) {
1487
+ this.fail("text data outside of root node.");
1488
+ this.reportedTextAfterRoot = true;
1489
+ }
1490
+ this.state = S_CDATA;
1491
+ this.openWakaBang = "";
1492
+ break;
1493
+ case "--":
1494
+ this.state = S_COMMENT;
1495
+ this.openWakaBang = "";
1496
+ break;
1497
+ case "DOCTYPE":
1498
+ this.state = S_DOCTYPE;
1499
+ if (this.doctype || this.sawRoot) this.fail("inappropriately located doctype declaration.");
1500
+ this.openWakaBang = "";
1501
+ break;
1502
+ default: if (this.openWakaBang.length >= 7) this.fail("incorrect syntax.");
1503
+ }
1504
+ }
1505
+ sComment() {
1506
+ if (this.captureToChar(MINUS)) this.state = S_COMMENT_ENDING;
1507
+ }
1508
+ sCommentEnding() {
1509
+ var _a;
1510
+ const c = this.getCodeNorm();
1511
+ if (c === MINUS) {
1512
+ this.state = S_COMMENT_ENDED;
1513
+ (_a = this.commentHandler) === null || _a === void 0 || _a.call(this, this.text);
1514
+ this.text = "";
1515
+ } else {
1516
+ this.text += `-${String.fromCodePoint(c)}`;
1517
+ this.state = S_COMMENT;
1518
+ }
1519
+ }
1520
+ sCommentEnded() {
1521
+ const c = this.getCodeNorm();
1522
+ if (c !== GREATER) {
1523
+ this.fail("malformed comment.");
1524
+ this.text += `--${String.fromCodePoint(c)}`;
1525
+ this.state = S_COMMENT;
1526
+ } else this.state = S_TEXT;
1527
+ }
1528
+ sCData() {
1529
+ if (this.captureToChar(CLOSE_BRACKET)) this.state = S_CDATA_ENDING;
1530
+ }
1531
+ sCDataEnding() {
1532
+ const c = this.getCodeNorm();
1533
+ if (c === CLOSE_BRACKET) this.state = S_CDATA_ENDING_2;
1534
+ else {
1535
+ this.text += `]${String.fromCodePoint(c)}`;
1536
+ this.state = S_CDATA;
1537
+ }
1538
+ }
1539
+ sCDataEnding2() {
1540
+ var _a;
1541
+ const c = this.getCodeNorm();
1542
+ switch (c) {
1543
+ case GREATER:
1544
+ (_a = this.cdataHandler) === null || _a === void 0 || _a.call(this, this.text);
1545
+ this.text = "";
1546
+ this.state = S_TEXT;
1547
+ break;
1548
+ case CLOSE_BRACKET:
1549
+ this.text += "]";
1550
+ break;
1551
+ default:
1552
+ this.text += `]]${String.fromCodePoint(c)}`;
1553
+ this.state = S_CDATA;
1554
+ }
1555
+ }
1556
+ sPIFirstChar() {
1557
+ const c = this.getCodeNorm();
1558
+ if (this.nameStartCheck(c)) {
1559
+ this.piTarget += String.fromCodePoint(c);
1560
+ this.state = S_PI_REST;
1561
+ } else if (c === QUESTION || isS(c)) {
1562
+ this.fail("processing instruction without a target.");
1563
+ this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;
1564
+ } else {
1565
+ this.fail("disallowed character in processing instruction name.");
1566
+ this.piTarget += String.fromCodePoint(c);
1567
+ this.state = S_PI_REST;
1568
+ }
1569
+ }
1570
+ sPIRest() {
1571
+ const { chunk, i: start } = this;
1572
+ while (true) {
1573
+ const c = this.getCodeNorm();
1574
+ if (c === EOC) {
1575
+ this.piTarget += chunk.slice(start);
1576
+ return;
1577
+ }
1578
+ if (!this.nameCheck(c)) {
1579
+ this.piTarget += chunk.slice(start, this.prevI);
1580
+ const isQuestion = c === QUESTION;
1581
+ if (isQuestion || isS(c)) {
1582
+ if (this.piTarget === "xml") {
1583
+ if (!this.xmlDeclPossible) this.fail("an XML declaration must be at the start of the document.");
1584
+ this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;
1585
+ } else this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;
1586
+ } else {
1587
+ this.fail("disallowed character in processing instruction name.");
1588
+ this.piTarget += String.fromCodePoint(c);
1589
+ }
1590
+ break;
1591
+ }
1592
+ }
1593
+ }
1594
+ sPIBody() {
1595
+ if (this.text.length === 0) {
1596
+ const c = this.getCodeNorm();
1597
+ if (c === QUESTION) this.state = S_PI_ENDING;
1598
+ else if (!isS(c)) this.text = String.fromCodePoint(c);
1599
+ } else if (this.captureToChar(QUESTION)) this.state = S_PI_ENDING;
1600
+ }
1601
+ sPIEnding() {
1602
+ var _a;
1603
+ const c = this.getCodeNorm();
1604
+ if (c === GREATER) {
1605
+ const { piTarget } = this;
1606
+ if (piTarget.toLowerCase() === "xml") this.fail("the XML declaration must appear at the start of the document.");
1607
+ (_a = this.piHandler) === null || _a === void 0 || _a.call(this, {
1608
+ target: piTarget,
1609
+ body: this.text
1610
+ });
1611
+ this.piTarget = this.text = "";
1612
+ this.state = S_TEXT;
1613
+ } else if (c === QUESTION) this.text += "?";
1614
+ else {
1615
+ this.text += `?${String.fromCodePoint(c)}`;
1616
+ this.state = S_PI_BODY;
1617
+ }
1618
+ this.xmlDeclPossible = false;
1619
+ }
1620
+ sXMLDeclNameStart() {
1621
+ const c = this.skipSpaces();
1622
+ if (c === QUESTION) {
1623
+ this.state = S_XML_DECL_ENDING;
1624
+ return;
1625
+ }
1626
+ if (c !== EOC) {
1627
+ this.state = S_XML_DECL_NAME;
1628
+ this.name = String.fromCodePoint(c);
1629
+ }
1630
+ }
1631
+ sXMLDeclName() {
1632
+ const c = this.captureTo(XML_DECL_NAME_TERMINATOR);
1633
+ if (c === QUESTION) {
1634
+ this.state = S_XML_DECL_ENDING;
1635
+ this.name += this.text;
1636
+ this.text = "";
1637
+ this.fail("XML declaration is incomplete.");
1638
+ return;
1639
+ }
1640
+ if (!(isS(c) || c === EQUAL)) return;
1641
+ this.name += this.text;
1642
+ this.text = "";
1643
+ if (!this.xmlDeclExpects.includes(this.name)) switch (this.name.length) {
1644
+ case 0:
1645
+ this.fail("did not expect any more name/value pairs.");
1646
+ break;
1647
+ case 1:
1648
+ this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);
1649
+ break;
1650
+ default: this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`);
1651
+ }
1652
+ this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;
1653
+ }
1654
+ sXMLDeclEq() {
1655
+ const c = this.getCodeNorm();
1656
+ if (c === QUESTION) {
1657
+ this.state = S_XML_DECL_ENDING;
1658
+ this.fail("XML declaration is incomplete.");
1659
+ return;
1660
+ }
1661
+ if (isS(c)) return;
1662
+ if (c !== EQUAL) this.fail("value required.");
1663
+ this.state = S_XML_DECL_VALUE_START;
1664
+ }
1665
+ sXMLDeclValueStart() {
1666
+ const c = this.getCodeNorm();
1667
+ if (c === QUESTION) {
1668
+ this.state = S_XML_DECL_ENDING;
1669
+ this.fail("XML declaration is incomplete.");
1670
+ return;
1671
+ }
1672
+ if (isS(c)) return;
1673
+ if (!isQuote(c)) {
1674
+ this.fail("value must be quoted.");
1675
+ this.q = SPACE;
1676
+ } else this.q = c;
1677
+ this.state = S_XML_DECL_VALUE;
1678
+ }
1679
+ sXMLDeclValue() {
1680
+ const c = this.captureTo([this.q, QUESTION]);
1681
+ if (c === QUESTION) {
1682
+ this.state = S_XML_DECL_ENDING;
1683
+ this.text = "";
1684
+ this.fail("XML declaration is incomplete.");
1685
+ return;
1686
+ }
1687
+ if (c === EOC) return;
1688
+ const value = this.text;
1689
+ this.text = "";
1690
+ switch (this.name) {
1691
+ case "version": {
1692
+ this.xmlDeclExpects = ["encoding", "standalone"];
1693
+ const version = value;
1694
+ this.xmlDecl.version = version;
1695
+ if (!/^1\.[0-9]+$/.test(version)) this.fail("version number must match /^1\\.[0-9]+$/.");
1696
+ else if (!this.opt.forceXMLVersion) this.setXMLVersion(version);
1697
+ break;
1698
+ }
1699
+ case "encoding":
1700
+ if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) this.fail("encoding value must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/.");
1701
+ this.xmlDeclExpects = ["standalone"];
1702
+ this.xmlDecl.encoding = value;
1703
+ break;
1704
+ case "standalone":
1705
+ if (value !== "yes" && value !== "no") this.fail("standalone value must match \"yes\" or \"no\".");
1706
+ this.xmlDeclExpects = [];
1707
+ this.xmlDecl.standalone = value;
1708
+ }
1709
+ this.name = "";
1710
+ this.state = S_XML_DECL_SEPARATOR;
1711
+ }
1712
+ sXMLDeclSeparator() {
1713
+ const c = this.getCodeNorm();
1714
+ if (c === QUESTION) {
1715
+ this.state = S_XML_DECL_ENDING;
1716
+ return;
1717
+ }
1718
+ if (!isS(c)) {
1719
+ this.fail("whitespace required.");
1720
+ this.unget();
1721
+ }
1722
+ this.state = S_XML_DECL_NAME_START;
1723
+ }
1724
+ sXMLDeclEnding() {
1725
+ var _a;
1726
+ if (this.getCodeNorm() === GREATER) {
1727
+ if (this.piTarget !== "xml") this.fail("processing instructions are not allowed before root.");
1728
+ else if (this.name !== "version" && this.xmlDeclExpects.includes("version")) this.fail("XML declaration must contain a version.");
1729
+ (_a = this.xmldeclHandler) === null || _a === void 0 || _a.call(this, this.xmlDecl);
1730
+ this.name = "";
1731
+ this.piTarget = this.text = "";
1732
+ this.state = S_TEXT;
1733
+ } else this.fail("The character ? is disallowed anywhere in XML declarations.");
1734
+ this.xmlDeclPossible = false;
1735
+ }
1736
+ sOpenTag() {
1737
+ var _a;
1738
+ const c = this.captureNameChars();
1739
+ if (c === EOC) return;
1740
+ const tag = this.tag = {
1741
+ name: this.name,
1742
+ attributes: Object.create(null)
1743
+ };
1744
+ this.name = "";
1745
+ if (this.xmlnsOpt) this.topNS = tag.ns = Object.create(null);
1746
+ (_a = this.openTagStartHandler) === null || _a === void 0 || _a.call(this, tag);
1747
+ this.sawRoot = true;
1748
+ if (!this.fragmentOpt && this.closedRoot) this.fail("documents may contain only one root.");
1749
+ switch (c) {
1750
+ case GREATER:
1751
+ this.openTag();
1752
+ break;
1753
+ case FORWARD_SLASH:
1754
+ this.state = S_OPEN_TAG_SLASH;
1755
+ break;
1756
+ default:
1757
+ if (!isS(c)) this.fail("disallowed character in tag name.");
1758
+ this.state = S_ATTRIB;
1759
+ }
1760
+ }
1761
+ sOpenTagSlash() {
1762
+ if (this.getCode() === GREATER) this.openSelfClosingTag();
1763
+ else {
1764
+ this.fail("forward-slash in opening tag not followed by >.");
1765
+ this.state = S_ATTRIB;
1766
+ }
1767
+ }
1768
+ sAttrib() {
1769
+ const c = this.skipSpaces();
1770
+ if (c === EOC) return;
1771
+ if (isNameStartChar(c)) {
1772
+ this.unget();
1773
+ this.state = S_ATTRIB_NAME;
1774
+ } else if (c === GREATER) this.openTag();
1775
+ else if (c === FORWARD_SLASH) this.state = S_OPEN_TAG_SLASH;
1776
+ else this.fail("disallowed character in attribute name.");
1777
+ }
1778
+ sAttribName() {
1779
+ const c = this.captureNameChars();
1780
+ if (c === EQUAL) this.state = S_ATTRIB_VALUE;
1781
+ else if (isS(c)) this.state = S_ATTRIB_NAME_SAW_WHITE;
1782
+ else if (c === GREATER) {
1783
+ this.fail("attribute without value.");
1784
+ this.pushAttrib(this.name, this.name);
1785
+ this.name = this.text = "";
1786
+ this.openTag();
1787
+ } else if (c !== EOC) this.fail("disallowed character in attribute name.");
1788
+ }
1789
+ sAttribNameSawWhite() {
1790
+ const c = this.skipSpaces();
1791
+ switch (c) {
1792
+ case EOC: return;
1793
+ case EQUAL:
1794
+ this.state = S_ATTRIB_VALUE;
1795
+ break;
1796
+ default:
1797
+ this.fail("attribute without value.");
1798
+ this.text = "";
1799
+ this.name = "";
1800
+ if (c === GREATER) this.openTag();
1801
+ else if (isNameStartChar(c)) {
1802
+ this.unget();
1803
+ this.state = S_ATTRIB_NAME;
1804
+ } else {
1805
+ this.fail("disallowed character in attribute name.");
1806
+ this.state = S_ATTRIB;
1807
+ }
1808
+ }
1809
+ }
1810
+ sAttribValue() {
1811
+ const c = this.getCodeNorm();
1812
+ if (isQuote(c)) {
1813
+ this.q = c;
1814
+ this.state = S_ATTRIB_VALUE_QUOTED;
1815
+ } else if (!isS(c)) {
1816
+ this.fail("unquoted attribute value.");
1817
+ this.state = S_ATTRIB_VALUE_UNQUOTED;
1818
+ this.unget();
1819
+ }
1820
+ }
1821
+ sAttribValueQuoted() {
1822
+ const { q, chunk } = this;
1823
+ let { i: start } = this;
1824
+ while (true) switch (this.getCode()) {
1825
+ case q:
1826
+ this.pushAttrib(this.name, this.text + chunk.slice(start, this.prevI));
1827
+ this.name = this.text = "";
1828
+ this.q = null;
1829
+ this.state = S_ATTRIB_VALUE_CLOSED;
1830
+ return;
1831
+ case AMP:
1832
+ this.text += chunk.slice(start, this.prevI);
1833
+ this.state = S_ENTITY;
1834
+ this.entityReturnState = S_ATTRIB_VALUE_QUOTED;
1835
+ return;
1836
+ case NL:
1837
+ case NL_LIKE:
1838
+ case TAB:
1839
+ this.text += `${chunk.slice(start, this.prevI)} `;
1840
+ start = this.i;
1841
+ break;
1842
+ case LESS:
1843
+ this.text += chunk.slice(start, this.prevI);
1844
+ this.fail("disallowed character.");
1845
+ return;
1846
+ case EOC:
1847
+ this.text += chunk.slice(start);
1848
+ return;
1849
+ }
1850
+ }
1851
+ sAttribValueClosed() {
1852
+ const c = this.getCodeNorm();
1853
+ if (isS(c)) this.state = S_ATTRIB;
1854
+ else if (c === GREATER) this.openTag();
1855
+ else if (c === FORWARD_SLASH) this.state = S_OPEN_TAG_SLASH;
1856
+ else if (isNameStartChar(c)) {
1857
+ this.fail("no whitespace between attributes.");
1858
+ this.unget();
1859
+ this.state = S_ATTRIB_NAME;
1860
+ } else this.fail("disallowed character in attribute name.");
1861
+ }
1862
+ sAttribValueUnquoted() {
1863
+ const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);
1864
+ switch (c) {
1865
+ case AMP:
1866
+ this.state = S_ENTITY;
1867
+ this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;
1868
+ break;
1869
+ case LESS:
1870
+ this.fail("disallowed character.");
1871
+ break;
1872
+ case EOC: break;
1873
+ default:
1874
+ if (this.text.includes("]]>")) this.fail("the string \"]]>\" is disallowed in char data.");
1875
+ this.pushAttrib(this.name, this.text);
1876
+ this.name = this.text = "";
1877
+ if (c === GREATER) this.openTag();
1878
+ else this.state = S_ATTRIB;
1879
+ }
1880
+ }
1881
+ sCloseTag() {
1882
+ const c = this.captureNameChars();
1883
+ if (c === GREATER) this.closeTag();
1884
+ else if (isS(c)) this.state = S_CLOSE_TAG_SAW_WHITE;
1885
+ else if (c !== EOC) this.fail("disallowed character in closing tag.");
1886
+ }
1887
+ sCloseTagSawWhite() {
1888
+ switch (this.skipSpaces()) {
1889
+ case GREATER:
1890
+ this.closeTag();
1891
+ break;
1892
+ case EOC: break;
1893
+ default: this.fail("disallowed character in closing tag.");
1894
+ }
1895
+ }
1896
+ handleTextInRoot() {
1897
+ let { i: start, forbiddenState } = this;
1898
+ const { chunk, textHandler: handler } = this;
1899
+ scanLoop: while (true) switch (this.getCode()) {
1900
+ case LESS:
1901
+ this.state = S_OPEN_WAKA;
1902
+ if (handler !== void 0) {
1903
+ const { text } = this;
1904
+ const slice = chunk.slice(start, this.prevI);
1905
+ if (text.length !== 0) {
1906
+ handler(text + slice);
1907
+ this.text = "";
1908
+ } else if (slice.length !== 0) handler(slice);
1909
+ }
1910
+ forbiddenState = FORBIDDEN_START;
1911
+ break scanLoop;
1912
+ case AMP:
1913
+ this.state = S_ENTITY;
1914
+ this.entityReturnState = S_TEXT;
1915
+ if (handler !== void 0) this.text += chunk.slice(start, this.prevI);
1916
+ forbiddenState = FORBIDDEN_START;
1917
+ break scanLoop;
1918
+ case CLOSE_BRACKET:
1919
+ switch (forbiddenState) {
1920
+ case FORBIDDEN_START:
1921
+ forbiddenState = FORBIDDEN_BRACKET;
1922
+ break;
1923
+ case FORBIDDEN_BRACKET:
1924
+ forbiddenState = FORBIDDEN_BRACKET_BRACKET;
1925
+ break;
1926
+ case FORBIDDEN_BRACKET_BRACKET: break;
1927
+ default: throw new Error("impossible state");
1928
+ }
1929
+ break;
1930
+ case GREATER:
1931
+ if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) this.fail("the string \"]]>\" is disallowed in char data.");
1932
+ forbiddenState = FORBIDDEN_START;
1933
+ break;
1934
+ case NL_LIKE:
1935
+ if (handler !== void 0) this.text += `${chunk.slice(start, this.prevI)}\n`;
1936
+ start = this.i;
1937
+ forbiddenState = FORBIDDEN_START;
1938
+ break;
1939
+ case EOC:
1940
+ if (handler !== void 0) this.text += chunk.slice(start);
1941
+ break scanLoop;
1942
+ default: forbiddenState = FORBIDDEN_START;
1943
+ }
1944
+ this.forbiddenState = forbiddenState;
1945
+ }
1946
+ handleTextOutsideRoot() {
1947
+ let { i: start } = this;
1948
+ const { chunk, textHandler: handler } = this;
1949
+ let nonSpace = false;
1950
+ outRootLoop: while (true) {
1951
+ const code = this.getCode();
1952
+ switch (code) {
1953
+ case LESS:
1954
+ this.state = S_OPEN_WAKA;
1955
+ if (handler !== void 0) {
1956
+ const { text } = this;
1957
+ const slice = chunk.slice(start, this.prevI);
1958
+ if (text.length !== 0) {
1959
+ handler(text + slice);
1960
+ this.text = "";
1961
+ } else if (slice.length !== 0) handler(slice);
1962
+ }
1963
+ break outRootLoop;
1964
+ case AMP:
1965
+ this.state = S_ENTITY;
1966
+ this.entityReturnState = S_TEXT;
1967
+ if (handler !== void 0) this.text += chunk.slice(start, this.prevI);
1968
+ nonSpace = true;
1969
+ break outRootLoop;
1970
+ case NL_LIKE:
1971
+ if (handler !== void 0) this.text += `${chunk.slice(start, this.prevI)}\n`;
1972
+ start = this.i;
1973
+ break;
1974
+ case EOC:
1975
+ if (handler !== void 0) this.text += chunk.slice(start);
1976
+ break outRootLoop;
1977
+ default: if (!isS(code)) nonSpace = true;
1978
+ }
1979
+ }
1980
+ if (!nonSpace) return;
1981
+ if (!this.sawRoot && !this.reportedTextBeforeRoot) {
1982
+ this.fail("text data outside of root node.");
1983
+ this.reportedTextBeforeRoot = true;
1984
+ }
1985
+ if (this.closedRoot && !this.reportedTextAfterRoot) {
1986
+ this.fail("text data outside of root node.");
1987
+ this.reportedTextAfterRoot = true;
1988
+ }
1989
+ }
1990
+ pushAttribNS(name, value) {
1991
+ var _a;
1992
+ const { prefix, local } = this.qname(name);
1993
+ const attr = {
1994
+ name,
1995
+ prefix,
1996
+ local,
1997
+ value
1998
+ };
1999
+ this.attribList.push(attr);
2000
+ (_a = this.attributeHandler) === null || _a === void 0 || _a.call(this, attr);
2001
+ if (prefix === "xmlns") {
2002
+ const trimmed = value.trim();
2003
+ if (this.currentXMLVersion === "1.0" && trimmed === "") this.fail("invalid attempt to undefine prefix in XML 1.0");
2004
+ this.topNS[local] = trimmed;
2005
+ nsPairCheck(this, local, trimmed);
2006
+ } else if (name === "xmlns") {
2007
+ const trimmed = value.trim();
2008
+ this.topNS[""] = trimmed;
2009
+ nsPairCheck(this, "", trimmed);
2010
+ }
2011
+ }
2012
+ pushAttribPlain(name, value) {
2013
+ var _a;
2014
+ const attr = {
2015
+ name,
2016
+ value
2017
+ };
2018
+ this.attribList.push(attr);
2019
+ (_a = this.attributeHandler) === null || _a === void 0 || _a.call(this, attr);
2020
+ }
2021
+ /**
2022
+ * End parsing. This performs final well-formedness checks and resets the
2023
+ * parser to a clean state.
2024
+ *
2025
+ * @returns this
2026
+ */
2027
+ end() {
2028
+ var _a, _b;
2029
+ if (!this.sawRoot) this.fail("document must contain a root element.");
2030
+ const { tags } = this;
2031
+ while (tags.length > 0) {
2032
+ const tag = tags.pop();
2033
+ this.fail(`unclosed tag: ${tag.name}`);
2034
+ }
2035
+ if (this.state !== S_BEGIN && this.state !== S_TEXT) this.fail("unexpected end.");
2036
+ const { text } = this;
2037
+ if (text.length !== 0) {
2038
+ (_a = this.textHandler) === null || _a === void 0 || _a.call(this, text);
2039
+ this.text = "";
2040
+ }
2041
+ this._closed = true;
2042
+ (_b = this.endHandler) === null || _b === void 0 || _b.call(this);
2043
+ this._init();
2044
+ return this;
2045
+ }
2046
+ /**
2047
+ * Resolve a namespace prefix.
2048
+ *
2049
+ * @param prefix The prefix to resolve.
2050
+ *
2051
+ * @returns The namespace URI or ``undefined`` if the prefix is not defined.
2052
+ */
2053
+ resolve(prefix) {
2054
+ var _a, _b;
2055
+ let uri = this.topNS[prefix];
2056
+ if (uri !== void 0) return uri;
2057
+ const { tags } = this;
2058
+ for (let index = tags.length - 1; index >= 0; index--) {
2059
+ uri = tags[index].ns[prefix];
2060
+ if (uri !== void 0) return uri;
2061
+ }
2062
+ uri = this.ns[prefix];
2063
+ if (uri !== void 0) return uri;
2064
+ return (_b = (_a = this.opt).resolvePrefix) === null || _b === void 0 ? void 0 : _b.call(_a, prefix);
2065
+ }
2066
+ /**
2067
+ * Parse a qname into its prefix and local name parts.
2068
+ *
2069
+ * @param name The name to parse
2070
+ *
2071
+ * @returns
2072
+ */
2073
+ qname(name) {
2074
+ const colon = name.indexOf(":");
2075
+ if (colon === -1) return {
2076
+ prefix: "",
2077
+ local: name
2078
+ };
2079
+ const local = name.slice(colon + 1);
2080
+ const prefix = name.slice(0, colon);
2081
+ if (prefix === "" || local === "" || local.includes(":")) this.fail(`malformed name: ${name}.`);
2082
+ return {
2083
+ prefix,
2084
+ local
2085
+ };
2086
+ }
2087
+ processAttribsNS() {
2088
+ var _a;
2089
+ const { attribList } = this;
2090
+ const tag = this.tag;
2091
+ {
2092
+ const { prefix, local } = this.qname(tag.name);
2093
+ tag.prefix = prefix;
2094
+ tag.local = local;
2095
+ const uri = tag.uri = (_a = this.resolve(prefix)) !== null && _a !== void 0 ? _a : "";
2096
+ if (prefix !== "") {
2097
+ if (prefix === "xmlns") this.fail("tags may not have \"xmlns\" as prefix.");
2098
+ if (uri === "") {
2099
+ this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
2100
+ tag.uri = prefix;
2101
+ }
2102
+ }
2103
+ }
2104
+ if (attribList.length === 0) return;
2105
+ const { attributes } = tag;
2106
+ const seen = /* @__PURE__ */ new Set();
2107
+ for (const attr of attribList) {
2108
+ const { name, prefix, local } = attr;
2109
+ let uri;
2110
+ let eqname;
2111
+ if (prefix === "") {
2112
+ uri = name === "xmlns" ? XMLNS_NAMESPACE : "";
2113
+ eqname = name;
2114
+ } else {
2115
+ uri = this.resolve(prefix);
2116
+ if (uri === void 0) {
2117
+ this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);
2118
+ uri = prefix;
2119
+ }
2120
+ eqname = `{${uri}}${local}`;
2121
+ }
2122
+ if (seen.has(eqname)) this.fail(`duplicate attribute: ${eqname}.`);
2123
+ seen.add(eqname);
2124
+ attr.uri = uri;
2125
+ attributes[name] = attr;
2126
+ }
2127
+ this.attribList = [];
2128
+ }
2129
+ processAttribsPlain() {
2130
+ const { attribList } = this;
2131
+ const attributes = this.tag.attributes;
2132
+ for (const { name, value } of attribList) {
2133
+ if (attributes[name] !== void 0) this.fail(`duplicate attribute: ${name}.`);
2134
+ attributes[name] = value;
2135
+ }
2136
+ this.attribList = [];
2137
+ }
2138
+ /**
2139
+ * Handle a complete open tag. This parser code calls this once it has seen
2140
+ * the whole tag. This method checks for well-formeness and then emits
2141
+ * ``onopentag``.
2142
+ */
2143
+ openTag() {
2144
+ var _a;
2145
+ this.processAttribs();
2146
+ const { tags } = this;
2147
+ const tag = this.tag;
2148
+ tag.isSelfClosing = false;
2149
+ (_a = this.openTagHandler) === null || _a === void 0 || _a.call(this, tag);
2150
+ tags.push(tag);
2151
+ this.state = S_TEXT;
2152
+ this.name = "";
2153
+ }
2154
+ /**
2155
+ * Handle a complete self-closing tag. This parser code calls this once it has
2156
+ * seen the whole tag. This method checks for well-formeness and then emits
2157
+ * ``onopentag`` and ``onclosetag``.
2158
+ */
2159
+ openSelfClosingTag() {
2160
+ var _a, _b, _c;
2161
+ this.processAttribs();
2162
+ const { tags } = this;
2163
+ const tag = this.tag;
2164
+ tag.isSelfClosing = true;
2165
+ (_a = this.openTagHandler) === null || _a === void 0 || _a.call(this, tag);
2166
+ (_b = this.closeTagHandler) === null || _b === void 0 || _b.call(this, tag);
2167
+ if ((this.tag = (_c = tags[tags.length - 1]) !== null && _c !== void 0 ? _c : null) === null) this.closedRoot = true;
2168
+ this.state = S_TEXT;
2169
+ this.name = "";
2170
+ }
2171
+ /**
2172
+ * Handle a complete close tag. This parser code calls this once it has seen
2173
+ * the whole tag. This method checks for well-formeness and then emits
2174
+ * ``onclosetag``.
2175
+ */
2176
+ closeTag() {
2177
+ const { tags, name } = this;
2178
+ this.state = S_TEXT;
2179
+ this.name = "";
2180
+ if (name === "") {
2181
+ this.fail("weird empty close tag.");
2182
+ this.text += "</>";
2183
+ return;
2184
+ }
2185
+ const handler = this.closeTagHandler;
2186
+ let l = tags.length;
2187
+ while (l-- > 0) {
2188
+ const tag = this.tag = tags.pop();
2189
+ this.topNS = tag.ns;
2190
+ handler === null || handler === void 0 || handler(tag);
2191
+ if (tag.name === name) break;
2192
+ this.fail("unexpected close tag.");
2193
+ }
2194
+ if (l === 0) this.closedRoot = true;
2195
+ else if (l < 0) {
2196
+ this.fail(`unmatched closing tag: ${name}.`);
2197
+ this.text += `</${name}>`;
2198
+ }
2199
+ }
2200
+ /**
2201
+ * Resolves an entity. Makes any necessary well-formedness checks.
2202
+ *
2203
+ * @param entity The entity to resolve.
2204
+ *
2205
+ * @returns The parsed entity.
2206
+ */
2207
+ parseEntity(entity) {
2208
+ if (entity[0] !== "#") {
2209
+ const defined = this.ENTITIES[entity];
2210
+ if (defined !== void 0) return defined;
2211
+ this.fail(this.isName(entity) ? "undefined entity." : "disallowed character in entity name.");
2212
+ return `&${entity};`;
2213
+ }
2214
+ let num = NaN;
2215
+ if (entity[1] === "x" && /^#x[0-9a-f]+$/i.test(entity)) num = parseInt(entity.slice(2), 16);
2216
+ else if (/^#[0-9]+$/.test(entity)) num = parseInt(entity.slice(1), 10);
2217
+ if (!this.isChar(num)) {
2218
+ this.fail("malformed character entity.");
2219
+ return `&${entity};`;
2220
+ }
2221
+ return String.fromCodePoint(num);
2222
+ }
2223
+ };
2224
+ exports.SaxesParser = SaxesParser;
2225
+ })))();
2226
+ /** An actionable converter failure; operating-system errors and caller abort reasons remain unchanged. */
2227
+ var ConversionError = class extends Error {
2228
+ /** Published failure category carried across worker and helper transports. */
2229
+ code;
2230
+ /**
2231
+ * @param code - Published failure category.
2232
+ * @param message - Consumer-facing failure description.
2233
+ * @param options - Standard error options; a cause is preserved for diagnostics.
2234
+ */
2235
+ constructor(code, message, options) {
2236
+ super(message, options);
2237
+ this.name = "ConversionError";
2238
+ this.code = code;
2239
+ }
2240
+ };
2241
+ /** Browser-safe family ordering and Fontconfig XML shared by both WASM adapters. */
2242
+ /**
2243
+ * Case- and separator-insensitive family key used to compare names across sources.
2244
+ * @param value - Family, style, or postscript name as recorded by a document or font.
2245
+ * @returns The normalized key.
2246
+ */
2247
+ function normalize$1(value) {
2248
+ return value.normalize("NFKC").toLowerCase().replaceAll(/[\s_-]/g, "");
2249
+ }
2250
+ /** Bounded OOXML inspection and declared font diagnostics, using maintained ZIP/XML parsers. */
2251
+ const MAIN_PARTS = {
2252
+ odt: ["content.xml", "application/vnd.oasis.opendocument.text"],
2253
+ ods: ["content.xml", "application/vnd.oasis.opendocument.spreadsheet"],
2254
+ odp: ["content.xml", "application/vnd.oasis.opendocument.presentation"],
2255
+ docx: ["word/document.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"],
2256
+ xlsx: ["xl/workbook.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"],
2257
+ pptx: ["ppt/presentation.xml", "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"]
2258
+ };
2259
+ /**
2260
+ * @param character - One code point as yielded by iteration over a string.
2261
+ * @returns the Unicode scalar the character encodes; iteration never yields an empty string.
2262
+ */
2263
+ function codePointOf(character) {
2264
+ return character.codePointAt(0);
2265
+ }
2266
+ /**
2267
+ * Validate ZIP size and membership before decoding selected document XML.
2268
+ * @param bytes - Complete source document bytes.
2269
+ * @param extension - Input extension, which selects the main document part.
2270
+ * @param limits - Archive entry and declared uncompressed byte limits.
2271
+ * @returns declared font families and the scalar values readable document XML declares.
2272
+ * @throws ConversionError when the extension is unsupported or the archive violates its limits.
2273
+ */
2274
+ function inspectDocument$1(bytes, extension, limits) {
2275
+ const main = MAIN_PARTS[extension];
2276
+ if (!main) throw new ConversionError("unsupported-format", "Input extension must be docx, xlsx, or pptx.");
2277
+ const odf = [
2278
+ "odt",
2279
+ "ods",
2280
+ "odp"
2281
+ ].includes(extension);
2282
+ const names = /* @__PURE__ */ new Set();
2283
+ let total = 0;
2284
+ let files;
2285
+ try {
2286
+ files = unzipSync(bytes, { filter(entry) {
2287
+ total += entry.originalSize;
2288
+ if (names.has(entry.name) || names.size >= limits.maxArchiveEntries || !Number.isSafeInteger(total) || total > limits.maxUncompressedBytes) throw new Error("OOXML archive exceeds its limits or repeats an entry.");
2289
+ names.add(entry.name);
2290
+ if (odf) return [
2291
+ "mimetype",
2292
+ "content.xml",
2293
+ "styles.xml",
2294
+ "META-INF/manifest.xml"
2295
+ ].includes(entry.name);
2296
+ return entry.name === "[Content_Types].xml" || /^(word|xl|ppt)\/.*\.xml$/.test(entry.name) && !entry.name.endsWith("/fontTable.xml") && !entry.name.includes("/theme/");
2297
+ } });
2298
+ } catch (cause) {
2299
+ throw new ConversionError("invalid-document", "Input is not a supported, bounded OOXML archive.", { cause });
2300
+ }
2301
+ const contentTypes = files["[Content_Types].xml"];
2302
+ if (odf ? !names.has("content.xml") || !names.has("META-INF/manifest.xml") || strFromU8(files.mimetype ?? /* @__PURE__ */ new Uint8Array()) !== main[1] : !names.has("_rels/.rels") || !names.has(main[0]) || contentTypes === void 0 || !strFromU8(contentTypes).includes(main[1])) throw new ConversionError("invalid-document", `Input does not contain a ${extension} document.`);
2303
+ const families = /* @__PURE__ */ new Map();
2304
+ const codePoints = /* @__PURE__ */ new Set();
2305
+ for (const [name, data] of Object.entries(files)) {
2306
+ if (name === "[Content_Types].xml" || name === "mimetype" || name === "META-INF/manifest.xml") continue;
2307
+ const partFamilies = [];
2308
+ const partPoints = /* @__PURE__ */ new Set();
2309
+ const parser = new import_saxes.SaxesParser({ xmlns: true });
2310
+ parser.on("opentag", (tag) => {
2311
+ const word = /wordprocessingml\/(?:2006\/)?main$/.test(tag.uri) && tag.local === "rFonts";
2312
+ const drawing = /drawingml\/(?:2006\/)?main$/.test(tag.uri);
2313
+ const sheet = /spreadsheetml\/(?:2006\/)?main$/.test(tag.uri) && tag.local === "name";
2314
+ for (const attribute of Object.values(tag.attributes)) {
2315
+ if (odf && attribute.local === "font-family") partFamilies.push(attribute.value.replace(/^['"]|['"]$/g, ""));
2316
+ if (word && [
2317
+ "ascii",
2318
+ "hAnsi",
2319
+ "eastAsia",
2320
+ "cs"
2321
+ ].includes(attribute.local) || drawing && attribute.local === "typeface" || sheet && attribute.local === "val") partFamilies.push(attribute.value);
2322
+ }
2323
+ });
2324
+ parser.on("text", (text) => {
2325
+ for (const char of text) if (!/\s/u.test(char)) partPoints.add(codePointOf(char));
2326
+ });
2327
+ const encoding = data[0] === 255 && data[1] === 254 ? "utf-16le" : data[0] === 254 && data[1] === 255 ? "utf-16be" : "utf-8";
2328
+ try {
2329
+ parser.write(new TextDecoder(encoding).decode(data)).close();
2330
+ } catch {
2331
+ continue;
2332
+ }
2333
+ for (const declared of partFamilies) for (const family of declared.split(";").map((value) => value.trim()).filter((value) => value && !/^\+(?:mj|mn)-(?:lt|ea|cs)$/.test(value))) families.set(normalize$1(family), family);
2334
+ for (const point of partPoints) codePoints.add(point);
2335
+ }
2336
+ return {
2337
+ families,
2338
+ codePoints: [...codePoints]
2339
+ };
2340
+ }
2341
+ /** Select bounded OOXML inspection or a legacy Office compound-file import. */
2342
+ /** Input suffixes accepted by the public converter. */
2343
+ const DOCUMENT_EXTENSIONS = [
2344
+ "doc",
2345
+ "docx",
2346
+ "odt",
2347
+ "xls",
2348
+ "xlsx",
2349
+ "ods",
2350
+ "ppt",
2351
+ "pptx",
2352
+ "odp"
2353
+ ];
2354
+ const COMPOUND_SIGNATURE = [
2355
+ 208,
2356
+ 207,
2357
+ 17,
2358
+ 224,
2359
+ 161,
2360
+ 177,
2361
+ 26,
2362
+ 225
2363
+ ];
2364
+ /**
2365
+ * Inspect the input container before invoking LibreOffice's document importer.
2366
+ * Compound-file streams and legacy font tables are interpreted by LibreOffice;
2367
+ * they do not supply the API's OOXML font diagnostics.
2368
+ * @param bytes - Source bytes already bounded by maxInputBytes.
2369
+ * @param extension - Lowercase source suffix.
2370
+ * @param limits - Limits applied to ZIP-based document contents.
2371
+ * @returns OOXML font metadata, or empty diagnostics for a binary document.
2372
+ */
2373
+ function inspectDocument(bytes, extension, limits) {
2374
+ if (!DOCUMENT_EXTENSIONS.includes(extension)) throw new ConversionError("unsupported-format", `Input extension must be ${DOCUMENT_EXTENSIONS.join(", ")}.`);
2375
+ if ([
2376
+ "docx",
2377
+ "xlsx",
2378
+ "pptx",
2379
+ "odt",
2380
+ "ods",
2381
+ "odp"
2382
+ ].includes(extension)) return inspectDocument$1(bytes, extension, limits);
2383
+ if (bytes.length < 512 || !COMPOUND_SIGNATURE.every((value, index) => bytes[index] === value)) throw new ConversionError("invalid-document", "Legacy Office input must contain an OLE compound document.");
2384
+ const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2385
+ const version = header.getUint16(26, true);
2386
+ const sectorShift = header.getUint16(30, true);
2387
+ if (header.getUint16(28, true) !== 65534 || header.getUint16(32, true) !== 6 || !(version === 3 && sectorShift === 9 || version === 4 && sectorShift === 12) || bytes.length < 2 ** sectorShift * 2 || bytes.length % 2 ** sectorShift !== 0) throw new ConversionError("invalid-document", "Legacy Office input has an invalid or truncated compound-file header.");
2388
+ return {
2389
+ families: /* @__PURE__ */ new Map(),
2390
+ codePoints: []
2391
+ };
2392
+ }
2393
+ //#endregion
2394
+ //#region ../entry/lib/font-config.js
2395
+ /** Browser-safe family ordering and Fontconfig XML shared by both WASM adapters. */
2396
+ /**
2397
+ * Case- and separator-insensitive family key used to compare names across sources.
2398
+ * @param value - Family, style, or postscript name as recorded by a document or font.
2399
+ * @returns The normalized key.
2400
+ */
2401
+ function normalize(value) {
2402
+ return value.normalize("NFKC").toLowerCase().replaceAll(/[\s_-]/g, "");
2403
+ }
2404
+ /**
2405
+ * Order named substitutions and their generic text family without excluding unlisted fonts.
2406
+ * @param requested - Original family names, in document order.
2407
+ * @param groups - Ordered family groups shared with Fontconfig aliases.
2408
+ * @param pitch - VCL pitch; one requests a monospaced fallback.
2409
+ * @param symbols - Whether symbol alternatives precede the generic fallback.
2410
+ * @returns distinct family names, with original requests first.
2411
+ */
2412
+ function fontFamilyPriority(requested, groups, pitch = 0, symbols = false) {
2413
+ const original = requested.map(normalize);
2414
+ const matched = groups.filter((group) => group.some((family) => original.includes(normalize(family))));
2415
+ const generic = original.includes("monospace") || pitch === 1 ? "monospace" : original.includes("serif") ? "serif" : matched.flat().map(normalize).find((family) => family === "serif" || family === "sansserif" || family === "monospace") ?? "sansserif";
2416
+ const families = [...requested, ...matched.flat()];
2417
+ for (const kind of symbols ? ["symbol", generic] : [generic]) for (const group of groups) if (group.some((family) => normalize(family) === kind)) families.push(...group);
2418
+ const priority = /* @__PURE__ */ new Map();
2419
+ for (const family of families) {
2420
+ const name = normalize(family);
2421
+ if (!priority.has(name)) priority.set(name, family);
2422
+ }
2423
+ return [...priority.values()];
2424
+ }
2425
+ /**
2426
+ * Fontconfig XML restricts WASM discovery to imported originals in MEMFS.
2427
+ * @param families - Ordered family groups; the first name of each group is its canonical spelling.
2428
+ * @param requested - Additional family names the document declared.
2429
+ * @returns the fontconfig document written into the module's memory filesystem.
2430
+ */
2431
+ function memoryFontConfig(families, requested = []) {
2432
+ const escape = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
2433
+ return `<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "fonts.dtd"><fontconfig><dir>/dsh-fonts</dir><cachedir>/dsh/font-cache</cachedir>${[...new Map([...families.flatMap((group) => group.slice(0, 1)), ...requested].map((name) => [normalize(name), name])).values()].map((name) => {
2434
+ const alternatives = fontFamilyPriority([name], families).filter((family) => normalize(family) !== normalize(name));
2435
+ return `<alias><family>${escape(name)}</family><accept>${alternatives.map((family) => `<family>${escape(family)}</family>`).join("")}</accept></alias>`;
2436
+ }).join("")}</fontconfig>`;
2437
+ }
2438
+ //#endregion
2439
+ //#region lib/types/types.js
2440
+ /** Browser-facing document rendering and host font interfaces. */
2441
+ /** A rendering failure with a stable machine-readable category. */
2442
+ var BrowserRenderError = class extends Error {
2443
+ code;
2444
+ constructor(code, message) {
2445
+ super(message);
2446
+ this.code = code;
2447
+ this.name = "BrowserRenderError";
2448
+ }
2449
+ };
2450
+ //#endregion
2451
+ //#region lib/types/font-channel.js
2452
+ /** Bounded frames bridge asynchronous Host font reads and synchronous VCL callbacks. */
2453
+ /** Views shared by the owner and engine; only the engine uses Atomics.wait. */
2454
+ function fontViews(channel) {
2455
+ return {
2456
+ control: new Int32Array(channel, 0, 2),
2457
+ bytes: new Uint8Array(channel, 8)
2458
+ };
2459
+ }
2460
+ /** The synchronous reader installs immutable subsets before returning their MEMFS paths and aliases. */
2461
+ function createFontReader(channel, timeoutMs, maxLoadedFontBytes, declaredFamilies, request, next, install, missing) {
2462
+ const { control, bytes } = fontViews(channel);
2463
+ const installed = /* @__PURE__ */ new Map();
2464
+ const aliases = /* @__PURE__ */ new Map();
2465
+ const requests = /* @__PURE__ */ new Map();
2466
+ const families = /* @__PURE__ */ new Set();
2467
+ let loadedBytes = 0;
2468
+ function read() {
2469
+ const started = performance.now();
2470
+ while (Atomics.load(control, 0) === 0) {
2471
+ const remaining = timeoutMs - (performance.now() - started);
2472
+ if (remaining <= 0 || Atomics.wait(control, 0, 0, remaining) === "timed-out") throw new BrowserRenderError("timeout", "Font loading timed out.");
2473
+ }
2474
+ const state = Atomics.load(control, 0);
2475
+ if (state === 5) throw new DOMException("Document closed.", "AbortError");
2476
+ const length = Atomics.load(control, 1);
2477
+ if (length < 0 || length > bytes.length) throw new BrowserRenderError("font-unavailable", "Invalid font transfer length.");
2478
+ const data = bytes.slice(0, length);
2479
+ if (Atomics.compareExchange(control, 0, state, 0) === 5) throw new DOMException("Document closed.", "AbortError");
2480
+ next();
2481
+ if (state === 4) throw new BrowserRenderError("font-unavailable", new TextDecoder().decode(data));
2482
+ return {
2483
+ state,
2484
+ data
2485
+ };
2486
+ }
2487
+ return (attributes) => {
2488
+ const canonical = aliases.get(normalize(attributes.family))?.family;
2489
+ const original = {
2490
+ ...attributes,
2491
+ ...canonical === void 0 ? {} : { family: canonical }
2492
+ };
2493
+ const key = JSON.stringify(original);
2494
+ const cached = requests.get(key);
2495
+ if (cached) return cached;
2496
+ request(original);
2497
+ const first = read();
2498
+ if (first.state !== 1) throw new BrowserRenderError("font-unavailable", "Expected font transfer metadata.");
2499
+ let header;
2500
+ try {
2501
+ header = JSON.parse(new TextDecoder().decode(first.data));
2502
+ } catch (cause) {
2503
+ throw new BrowserRenderError("font-unavailable", "Invalid font transfer metadata.");
2504
+ }
2505
+ if (header === null || typeof header !== "object" || !Array.isArray(header.fonts) || header.fonts.length === 0) throw new BrowserRenderError("font-unavailable", "Host has no usable fonts.");
2506
+ const faces = [];
2507
+ for (const font of header.fonts) {
2508
+ if (typeof font.id !== "string" || typeof font.family !== "string" || font.family.length === 0 || typeof font.alias !== "string" || font.alias.length === 0 || /[\x00\t\r\n]/.test(font.alias) || !Number.isSafeInteger(font.bytes) || font.bytes <= 0) throw new BrowserRenderError("font-unavailable", "Invalid font file descriptor.");
2509
+ if (font.format !== void 0 && ![
2510
+ "ttf",
2511
+ "otf",
2512
+ "ttc"
2513
+ ].includes(font.format)) throw new BrowserRenderError("font-unavailable", "Invalid full font format.");
2514
+ const prior = installed.get(font.id);
2515
+ if (prior && (prior.format !== font.format || font.format === void 0 && prior.face.family !== font.alias)) throw new BrowserRenderError("font-unavailable", "Font identity has conflicting aliases or formats.");
2516
+ const alias = normalize(font.alias);
2517
+ const previousAlias = aliases.get(alias);
2518
+ if (previousAlias && (previousAlias.family !== font.family || font.format === void 0 && previousAlias.id !== font.id)) throw new BrowserRenderError("font-unavailable", "Font alias identifies conflicting subsets.");
2519
+ if (!prior && loadedBytes + font.bytes > maxLoadedFontBytes) throw new BrowserRenderError("font-limit", "Imported fonts exceed maxLoadedFontBytes.");
2520
+ const buffer = prior ? void 0 : new Uint8Array(font.bytes);
2521
+ let received = 0;
2522
+ while (received < font.bytes) {
2523
+ const frame = read();
2524
+ if (frame.state !== 2 || frame.data.length === 0 || received + frame.data.length > font.bytes) throw new BrowserRenderError("font-unavailable", "Incomplete font file transfer.");
2525
+ buffer?.set(frame.data, received);
2526
+ received += frame.data.length;
2527
+ }
2528
+ const face = {
2529
+ path: prior?.face.path ?? (font.format === void 0 ? `/dsh-fonts/${installed.size}.font` : `/usr/share/fonts/dsh-pdfium/${installed.size}.${font.format}`),
2530
+ family: font.alias
2531
+ };
2532
+ if (buffer) {
2533
+ install(face.path, buffer);
2534
+ installed.set(font.id, {
2535
+ face,
2536
+ format: font.format
2537
+ });
2538
+ loadedBytes += buffer.length;
2539
+ }
2540
+ aliases.set(alias, {
2541
+ id: font.id,
2542
+ family: font.family
2543
+ });
2544
+ faces.push(face);
2545
+ }
2546
+ if (read().state !== 3) throw new BrowserRenderError("font-unavailable", "Unexpected font transfer trailer.");
2547
+ const absentFamily = header.missingFamily === void 0 ? void 0 : declaredFamilies.get(normalize(header.missingFamily));
2548
+ if (absentFamily !== void 0 && !families.has(absentFamily)) {
2549
+ families.add(absentFamily);
2550
+ missing([...families]);
2551
+ }
2552
+ requests.set(key, faces);
2553
+ return faces;
2554
+ };
2555
+ }
2556
+ //#endregion
2557
+ //#region ../entry/lib/sheet-geometry.js
2558
+ const MAX_COLUMN = 16383;
2559
+ const MAX_ROW = 1048575;
2560
+ function parseCellRange(value) {
2561
+ const match = /^\$?([A-Z]{1,3})\$?([1-9]\d{0,6})(?::\$?([A-Z]{1,3})\$?([1-9]\d{0,6}))?$/i.exec(value);
2562
+ if (!match) throw new TypeError("range must be an A1 cell or rectangle without a sheet prefix.");
2563
+ const col = (name) => [...name.toUpperCase()].reduce((sum, c) => sum * 26 + c.charCodeAt(0) - 64, 0) - 1;
2564
+ const firstColumn = col(match[1]);
2565
+ const firstRow = Number(match[2]) - 1;
2566
+ const lastColumn = col(match[3] ?? match[1]);
2567
+ const lastRow = Number(match[4] ?? match[2]) - 1;
2568
+ if (lastColumn < firstColumn || lastRow < firstRow || lastColumn > MAX_COLUMN || lastRow > MAX_ROW) throw new TypeError("range exceeds Calc worksheet bounds or has reversed endpoints.");
2569
+ return {
2570
+ firstColumn,
2571
+ firstRow,
2572
+ lastColumn,
2573
+ lastRow
2574
+ };
2575
+ }
2576
+ //#endregion
2577
+ //#region ../entry/lib/engine-rendering.js
2578
+ /** Validate coordinates before allocation or wasm32 integer conversion. */
2579
+ function tileDimensions(request, pages) {
2580
+ const page = pages[request.pageIndex];
2581
+ if (!Number.isSafeInteger(request.pageIndex) || !page || ![
2582
+ request.x,
2583
+ request.y,
2584
+ request.width,
2585
+ request.height,
2586
+ request.scale
2587
+ ].every(Number.isFinite) || request.x < 0 || request.y < 0 || request.width <= 0 || request.height <= 0 || request.scale <= 0 || request.x + request.width > page.width + .001 || request.y + request.height > page.height + .001) throw new Error("Tile rectangle lies outside its page.");
2588
+ const width = Math.ceil(request.width * request.scale - 1e-9);
2589
+ const height = Math.ceil(request.height * request.scale - 1e-9);
2590
+ if (width <= 0 || height <= 0 || !Number.isSafeInteger(width * height) || width * height > 16777216) throw new Error("Tile exceeds the 16 megapixel allocation limit.");
2591
+ const twips = [
2592
+ page.x + Math.round(request.x * 15),
2593
+ page.y + Math.round(request.y * 15),
2594
+ Math.round(request.width * 15),
2595
+ Math.round(request.height * 15)
2596
+ ];
2597
+ if (twips.some((value) => !Number.isSafeInteger(value) || value < 0 || value > 2147483647) || twips[0] + twips[2] > 2147483647 || twips[1] + twips[3] > 2147483647) throw new Error("Tile coordinates exceed the wasm32 range.");
2598
+ return {
2599
+ page,
2600
+ width,
2601
+ height
2602
+ };
2603
+ }
2604
+ /** Cairo/LO channels are premultiplied; PNG and ImageData require straight RGBA. */
2605
+ function rgbaPixels(source, tileMode) {
2606
+ if (tileMode !== 0 && tileMode !== 1 || source.length % 4 !== 0) throw new Error("LibreOffice returned an unsupported tile pixel format.");
2607
+ const result = new Uint8ClampedArray(source.length);
2608
+ for (let index = 0; index < source.length; index += 4) {
2609
+ const alpha = source[index + 3];
2610
+ const multiplier = alpha === 0 ? 0 : 255 / alpha;
2611
+ result[index] = source[index + (tileMode === 1 ? 2 : 0)] * multiplier;
2612
+ result[index + 1] = source[index + 1] * multiplier;
2613
+ result[index + 2] = source[index + (tileMode === 1 ? 0 : 2)] * multiplier;
2614
+ result[index + 3] = alpha;
2615
+ }
2616
+ return result;
2617
+ }
2618
+ /** Shared bounded raster allocations for browser and Node engine owners. */
2619
+ function numericCall(module, name, args) {
2620
+ return module.ccall(name, "number", args.map(() => "number"), args);
2621
+ }
2622
+ /** Paint into a temporary allocation; copy pixels before free or another engine call. */
2623
+ function renderRegion(module, document, request, pages, failure, pdf = false) {
2624
+ const call = (name, args) => numericCall(module, name, args);
2625
+ const { page, width, height } = tileDimensions(request, pages);
2626
+ const size = width * height * 4;
2627
+ const pointer = call("malloc", [size]);
2628
+ if (!pointer) throw failure();
2629
+ try {
2630
+ new Uint8Array(module.HEAPU32.buffer, pointer, size).fill(0);
2631
+ const position = [
2632
+ page.x + Math.round(request.x * 15),
2633
+ page.y + Math.round(request.y * 15),
2634
+ Math.max(1, Math.round(request.width * 15)),
2635
+ Math.max(1, Math.round(request.height * 15))
2636
+ ];
2637
+ if (!call(pdf ? "dsh_pdf_paint" : "dsh_lok_document_paint", [
2638
+ document,
2639
+ pointer,
2640
+ page.part,
2641
+ width,
2642
+ height,
2643
+ ...position
2644
+ ])) throw failure();
2645
+ const source = new Uint8Array(module.HEAPU32.buffer, pointer, size);
2646
+ return {
2647
+ width,
2648
+ height,
2649
+ rgba: pdf ? new Uint8ClampedArray(source) : rgbaPixels(source, call("dsh_lok_document_tile_mode", [document]))
2650
+ };
2651
+ } finally {
2652
+ call("free", [pointer]);
2653
+ }
2654
+ }
2655
+ /** PDF page dimensions use the same twips ABI, with an immutable PDF page index as part. */
2656
+ function pdfPages(module, pdf, failure) {
2657
+ const count = numericCall(module, "dsh_pdf_page_count", [pdf]);
2658
+ if (!Number.isSafeInteger(count) || count < 1 || count > 1e5) throw failure();
2659
+ const pointer = numericCall(module, "malloc", [8]);
2660
+ if (!pointer) throw failure();
2661
+ try {
2662
+ return Array.from({ length: count }, (_, part) => {
2663
+ if (!numericCall(module, "dsh_pdf_page_size", [
2664
+ pdf,
2665
+ part,
2666
+ pointer,
2667
+ pointer + 4
2668
+ ])) throw failure();
2669
+ const width = module.HEAPU32[pointer / 4];
2670
+ const height = module.HEAPU32[pointer / 4 + 1];
2671
+ if (width < 1 || height < 1 || width > 2147483647 || height > 2147483647) throw failure();
2672
+ return {
2673
+ part,
2674
+ x: 0,
2675
+ y: 0,
2676
+ width: width / 15,
2677
+ height: height / 15
2678
+ };
2679
+ });
2680
+ } finally {
2681
+ numericCall(module, "free", [pointer]);
2682
+ }
2683
+ }
2684
+ //#endregion
2685
+ //#region ../entry/lib/rendering.js
2686
+ /** Writer's zero-area parity placeholders have no visible page. Offsets stay in twips. */
2687
+ function writerPages(rectangles) {
2688
+ const pages = rectangles.split(";").filter((value) => value.trim()).flatMap((rectangle) => {
2689
+ const fields = rectangle.split(",").map((value) => Number(value.trim()));
2690
+ const [x, y, width, height] = fields;
2691
+ if (fields.length !== 4 || x === void 0 || y === void 0 || width === void 0 || height === void 0 || fields.some((value) => !Number.isSafeInteger(value) || value < 0 || value > 2147483647) || width === 0 !== (height === 0) || x + width > 2147483647 || y + height > 2147483647) throw new Error("LibreOffice returned invalid page rectangles.");
2692
+ return width === 0 ? [] : [{
2693
+ x,
2694
+ y,
2695
+ width: width / 15,
2696
+ height: height / 15,
2697
+ part: -1
2698
+ }];
2699
+ });
2700
+ if (pages.length === 0) throw new Error("LibreOffice returned no document pages.");
2701
+ return pages;
2702
+ }
2703
+ //#endregion
2704
+ //#region lib/types/office-engine.js
2705
+ /** Worker-owned reading, bounded VCL event slices and immutable notifications. */
2706
+ function rectangle(payload) {
2707
+ if (payload.startsWith("{")) {
2708
+ const value = JSON.parse(payload);
2709
+ if (typeof value !== "object" || value === null || !("rectangle" in value) || typeof value.rectangle !== "string") return null;
2710
+ payload = value.rectangle;
2711
+ }
2712
+ if (!payload || payload.startsWith("EMPTY") || payload === "INPLACE") return null;
2713
+ const values = payload.split(",").slice(0, 4).map(Number);
2714
+ if (values.length !== 4 || values.some((value) => !Number.isFinite(value))) return null;
2715
+ const [x, y, width, height] = values.map((value) => value / 15);
2716
+ return width >= 0 && height >= 0 ? {
2717
+ x,
2718
+ y,
2719
+ width,
2720
+ height
2721
+ } : null;
2722
+ }
2723
+ function integer(value, max = 2147483647) {
2724
+ if (!Number.isSafeInteger(value) || value < 0 || value > max) throw new BrowserRenderError("render-failed", "Office input contains an invalid integer.");
2725
+ return value;
2726
+ }
2727
+ function twips(value) {
2728
+ if (!Number.isFinite(value) || Math.abs(value * 15) > 2147483647) throw new BrowserRenderError("render-failed", "Office input lies outside document coordinates.");
2729
+ return Math.round(value * 15);
2730
+ }
2731
+ const navigationKeys = {
2732
+ down: 1024,
2733
+ up: 1025,
2734
+ left: 1026,
2735
+ right: 1027,
2736
+ home: 1028,
2737
+ end: 1029,
2738
+ pageUp: 1030,
2739
+ pageDown: 1031
2740
+ };
2741
+ /** One read-only document, driven exclusively by its Worker's messages and timer. */
2742
+ var OfficeEngine = class {
2743
+ module;
2744
+ document;
2745
+ emit;
2746
+ failure;
2747
+ state;
2748
+ timer;
2749
+ callbacks = [];
2750
+ geometryDirty = false;
2751
+ stopped = false;
2752
+ layoutWidth = 0;
2753
+ viewport = "";
2754
+ commandResult;
2755
+ constructor(module, document, format, emit, failure) {
2756
+ this.module = module;
2757
+ this.document = document;
2758
+ this.emit = emit;
2759
+ this.failure = failure;
2760
+ this.state = {
2761
+ documentType: format === "docx" || format === "doc" ? "text" : format === "xlsx" || format === "xls" ? "spreadsheet" : "presentation",
2762
+ renderGeneration: 0,
2763
+ layoutGeneration: 0,
2764
+ layout: "paginated",
2765
+ part: 0,
2766
+ parts: [],
2767
+ pages: [],
2768
+ cursor: null,
2769
+ selection: [],
2770
+ graphicSelection: null,
2771
+ cellAddress: "",
2772
+ cellFormula: ""
2773
+ };
2774
+ }
2775
+ call(name, args = []) {
2776
+ return this.module.ccall(name, "number", args.map((value) => typeof value), args);
2777
+ }
2778
+ text(name, args) {
2779
+ const pointer = this.call(name, args);
2780
+ if (!pointer) return "";
2781
+ try {
2782
+ return this.module.UTF8ToString(pointer);
2783
+ } finally {
2784
+ this.call("free", [pointer]);
2785
+ }
2786
+ }
2787
+ invoke(name, args = []) {
2788
+ if (!this.call(`dsh_lok_document_${name}`, [this.document, ...args])) throw new BrowserRenderError("render-failed", `LibreOffice could not complete ${name}.`);
2789
+ }
2790
+ requireOpen() {
2791
+ if (this.stopped) throw new BrowserRenderError("disposed", "Office document is closed.");
2792
+ }
2793
+ /** Collect callbacks without reentering LibreOffice inside its callback. */
2794
+ callback(type, payload) {
2795
+ if (!this.stopped) this.callbacks.push({
2796
+ type,
2797
+ payload
2798
+ });
2799
+ }
2800
+ /** Enforce the native read-only view before accepting any input. */
2801
+ async start() {
2802
+ this.requireOpen();
2803
+ this.configure({ mode: "paginated" });
2804
+ this.invoke("listen");
2805
+ this.refreshGeometry();
2806
+ this.pump();
2807
+ this.schedule();
2808
+ await this.command(".uno:ReportWhenIdle", { idleID: {
2809
+ type: "string",
2810
+ value: "office-open"
2811
+ } });
2812
+ }
2813
+ schedule() {
2814
+ this.timer = setTimeout(() => {
2815
+ if (this.stopped) return;
2816
+ try {
2817
+ this.pump();
2818
+ this.schedule();
2819
+ } catch (error) {
2820
+ this.stop();
2821
+ this.failure(error);
2822
+ }
2823
+ }, 16);
2824
+ }
2825
+ /** Stop event processing before destroying the document. */
2826
+ stop() {
2827
+ this.stopped = true;
2828
+ clearTimeout(this.timer);
2829
+ this.callbacks.length = 0;
2830
+ this.commandResult?.reject(new BrowserRenderError("disposed", "Office document is closed."));
2831
+ this.commandResult = void 0;
2832
+ }
2833
+ /** Return the part whose cached coordinates changed, or -1 when part identities changed. */
2834
+ refreshGeometry() {
2835
+ const count = this.state.documentType === "text" ? 1 : this.call("dsh_lok_document_parts", [this.document]);
2836
+ if (!Number.isSafeInteger(count) || count <= 0) throw new BrowserRenderError("invalid-document", "Office document has no parts.");
2837
+ const pointer = this.call("malloc", [8]);
2838
+ if (!pointer) throw new BrowserRenderError("render-failed", "Office geometry allocation failed.");
2839
+ try {
2840
+ const part = Math.min(this.state.part, count - 1);
2841
+ this.invoke("size", [
2842
+ part,
2843
+ pointer,
2844
+ pointer + 4
2845
+ ]);
2846
+ const width = this.module.HEAPU32[pointer / 4] / 15;
2847
+ const height = this.module.HEAPU32[pointer / 4 + 1] / 15;
2848
+ if (!(width > 0 && height > 0)) throw new BrowserRenderError("invalid-document", "Office returned empty document dimensions.");
2849
+ const parts = Array.from({ length: count }, (_, index) => ({
2850
+ name: this.state.documentType === "text" ? "" : this.text("dsh_lok_document_part_name", [this.document, index]),
2851
+ width: index === part ? width : this.state.parts[index]?.width ?? width,
2852
+ height: index === part ? height : this.state.parts[index]?.height ?? height
2853
+ }));
2854
+ const pages = this.state.documentType !== "text" ? [] : this.state.layout === "continuous" ? [{
2855
+ x: 0,
2856
+ y: 0,
2857
+ width,
2858
+ height
2859
+ }] : writerPages(this.text("dsh_lok_document_page_rectangles", [this.document])).map((page) => ({
2860
+ x: page.x / 15,
2861
+ y: page.y / 15,
2862
+ width: page.width,
2863
+ height: page.height
2864
+ }));
2865
+ const previous = this.state;
2866
+ const identitiesChanged = previous.parts.length > 0 && (previous.parts.length !== parts.length || parts.some((value, index) => value.name !== previous.parts[index].name));
2867
+ const measured = previous.parts[part];
2868
+ const geometryChanged = measured !== void 0 && (measured.width !== width || measured.height !== height || JSON.stringify(previous.pages) !== JSON.stringify(pages));
2869
+ this.state = {
2870
+ ...previous,
2871
+ part,
2872
+ parts,
2873
+ pages
2874
+ };
2875
+ this.geometryDirty = false;
2876
+ return identitiesChanged ? -1 : geometryChanged ? part : void 0;
2877
+ } finally {
2878
+ this.call("free", [pointer]);
2879
+ }
2880
+ }
2881
+ pump() {
2882
+ const deadline = performance.now() + 8;
2883
+ for (let pass = 0; pass < 8; pass++) {
2884
+ const result = this.call("dsh_lok_pump");
2885
+ if (result < 0) throw new BrowserRenderError("render-failed", "LibreOffice event processing failed.");
2886
+ if (!result || performance.now() >= deadline) break;
2887
+ }
2888
+ this.flush();
2889
+ }
2890
+ flush() {
2891
+ if (this.callbacks.length === 0) return;
2892
+ let changed = false;
2893
+ const invalidations = [];
2894
+ for (const { type, payload } of this.callbacks.splice(0)) switch (type) {
2895
+ case 0: {
2896
+ const fields = payload.split(",");
2897
+ const index = fields[0]?.trim() === "EMPTY" ? fields[1] : fields[4];
2898
+ const part = index !== void 0 && /^\s*-?\d+\s*$/.test(index) ? Number(index) : this.state.part;
2899
+ invalidations.push({
2900
+ part,
2901
+ rectangle: rectangle(payload)
2902
+ });
2903
+ break;
2904
+ }
2905
+ case 1:
2906
+ case 17:
2907
+ this.state = {
2908
+ ...this.state,
2909
+ cursor: rectangle(payload)
2910
+ };
2911
+ changed = true;
2912
+ break;
2913
+ case 2:
2914
+ this.state = {
2915
+ ...this.state,
2916
+ selection: payload.split(";").map(rectangle).filter((value) => value !== null)
2917
+ };
2918
+ changed = true;
2919
+ break;
2920
+ case 6:
2921
+ this.state = {
2922
+ ...this.state,
2923
+ graphicSelection: rectangle(payload)
2924
+ };
2925
+ changed = true;
2926
+ break;
2927
+ case 13:
2928
+ this.geometryDirty = true;
2929
+ break;
2930
+ case 14: {
2931
+ const part = Number(payload);
2932
+ if (Number.isSafeInteger(part) && part >= 0 && part < this.state.parts.length) {
2933
+ this.state = {
2934
+ ...this.state,
2935
+ part
2936
+ };
2937
+ this.viewport = "";
2938
+ this.geometryDirty = true;
2939
+ changed = true;
2940
+ }
2941
+ break;
2942
+ }
2943
+ case 16: {
2944
+ const result = JSON.parse(payload);
2945
+ if (typeof result === "object" && result !== null && "commandName" in result && result.commandName === this.commandResult?.name) this.commandResult?.resolve();
2946
+ break;
2947
+ }
2948
+ case 19:
2949
+ this.state = {
2950
+ ...this.state,
2951
+ cellFormula: payload
2952
+ };
2953
+ changed = true;
2954
+ break;
2955
+ case 34:
2956
+ this.state = {
2957
+ ...this.state,
2958
+ cellAddress: payload
2959
+ };
2960
+ changed = true;
2961
+ }
2962
+ const geometry = this.geometryDirty ? this.refreshGeometry() : void 0;
2963
+ if (geometry !== void 0) {
2964
+ this.state = {
2965
+ ...this.state,
2966
+ layoutGeneration: this.state.layoutGeneration + 1
2967
+ };
2968
+ if (!invalidations.some((value) => value.rectangle === null && (value.part === -1 || value.part === geometry))) {
2969
+ for (let index = invalidations.length - 1; index >= 0; index--) if (geometry === -1 || invalidations[index].part === geometry) invalidations.splice(index, 1);
2970
+ invalidations.push({
2971
+ part: geometry,
2972
+ rectangle: null
2973
+ });
2974
+ }
2975
+ }
2976
+ if (invalidations.length > 0) {
2977
+ this.state = {
2978
+ ...this.state,
2979
+ renderGeneration: this.state.renderGeneration + 1
2980
+ };
2981
+ changed = true;
2982
+ }
2983
+ if (changed) this.emit({
2984
+ type: "state",
2985
+ state: this.state
2986
+ });
2987
+ for (const invalidation of invalidations) this.emit({
2988
+ type: "invalidate",
2989
+ ...invalidation,
2990
+ generation: this.state.renderGeneration
2991
+ });
2992
+ }
2993
+ /** The Worker permits only these typed reading operations, including at runtime. */
2994
+ async operation(operation) {
2995
+ this.requireOpen();
2996
+ if (!operation || typeof operation !== "object") throw new BrowserRenderError("render-failed", "Invalid Office reading operation.");
2997
+ switch (operation.type) {
2998
+ case "pointer": {
2999
+ const event = operation.event;
3000
+ if (!event || ![
3001
+ "down",
3002
+ "up",
3003
+ "move"
3004
+ ].includes(event.action) || ![0, 1].includes(event.buttons) || ![
3005
+ 0,
3006
+ 4096,
3007
+ 8192,
3008
+ 12288
3009
+ ].includes(event.modifiers)) throw new BrowserRenderError("render-failed", "Invalid Office selection pointer.");
3010
+ this.invoke("mouse", [
3011
+ event.action === "down" ? 0 : event.action === "up" ? 1 : 2,
3012
+ twips(event.x),
3013
+ twips(event.y),
3014
+ integer(event.clicks, 3),
3015
+ event.buttons,
3016
+ event.modifiers
3017
+ ]);
3018
+ break;
3019
+ }
3020
+ case "navigate": {
3021
+ const event = operation.event;
3022
+ if (!event || !Object.hasOwn(navigationKeys, event.key) || event.extend !== void 0 && typeof event.extend !== "boolean" || event.word !== void 0 && typeof event.word !== "boolean") throw new BrowserRenderError("render-failed", "Invalid Office navigation key.");
3023
+ const key = navigationKeys[event.key] | (event.extend ? 4096 : 0) | (event.word ? 8192 : 0);
3024
+ this.invoke("key", [
3025
+ 0,
3026
+ 0,
3027
+ key
3028
+ ]);
3029
+ this.invoke("key", [
3030
+ 1,
3031
+ 0,
3032
+ key
3033
+ ]);
3034
+ break;
3035
+ }
3036
+ case "select-all":
3037
+ await this.command(".uno:SelectAll", {});
3038
+ break;
3039
+ case "cell":
3040
+ if (this.state.documentType !== "spreadsheet" || typeof operation.address !== "string") throw new BrowserRenderError("render-failed", "Cell navigation requires a spreadsheet address.");
3041
+ try {
3042
+ parseCellRange(operation.address);
3043
+ } catch {
3044
+ throw new BrowserRenderError("render-failed", "Cell navigation requires a bounded A1 cell or range.");
3045
+ }
3046
+ await this.command(".uno:GoToCell", { ToPoint: {
3047
+ type: "string",
3048
+ value: operation.address
3049
+ } });
3050
+ break;
3051
+ case "copy":
3052
+ this.pump();
3053
+ return { text: this.text("dsh_lok_document_selection", [this.document]) };
3054
+ case "part": {
3055
+ const part = integer(operation.part, this.state.parts.length - 1);
3056
+ if (part === this.state.part) break;
3057
+ this.invoke("part", [part]);
3058
+ this.viewport = "";
3059
+ this.state = {
3060
+ ...this.state,
3061
+ part,
3062
+ cursor: null,
3063
+ selection: [],
3064
+ graphicSelection: null,
3065
+ cellAddress: "",
3066
+ cellFormula: ""
3067
+ };
3068
+ const geometry = this.refreshGeometry();
3069
+ if (geometry !== void 0) this.state = {
3070
+ ...this.state,
3071
+ layoutGeneration: this.state.layoutGeneration + 1,
3072
+ renderGeneration: this.state.renderGeneration + 1
3073
+ };
3074
+ this.emit({
3075
+ type: "state",
3076
+ state: this.state
3077
+ });
3078
+ if (geometry !== void 0) this.emit({
3079
+ type: "invalidate",
3080
+ part: geometry,
3081
+ rectangle: null,
3082
+ generation: this.state.renderGeneration
3083
+ });
3084
+ break;
3085
+ }
3086
+ case "viewport": {
3087
+ const { x, y, width, height } = operation.rectangle;
3088
+ if (!(operation.scale > 0 && operation.scale <= 16 && width > 0 && height > 0)) throw new BrowserRenderError("render-failed", "Office viewport is invalid.");
3089
+ const args = [
3090
+ Math.max(1, Math.round(256 * operation.scale)),
3091
+ 3840,
3092
+ twips(x),
3093
+ twips(y),
3094
+ twips(width),
3095
+ twips(height)
3096
+ ];
3097
+ const key = args.join(",");
3098
+ if (key !== this.viewport) {
3099
+ this.invoke("viewport", args);
3100
+ this.viewport = key;
3101
+ }
3102
+ break;
3103
+ }
3104
+ case "layout": {
3105
+ const request = operation.request;
3106
+ if (!request || !["paginated", "continuous"].includes(request.mode) || request.mode === "continuous" && this.state.documentType !== "text") throw new BrowserRenderError("render-failed", "Continuous layout is only available for Writer documents.");
3107
+ const width = request.mode === "continuous" ? twips(request.width) : 0;
3108
+ if (request.mode === "continuous" && width <= 0) throw new BrowserRenderError("render-failed", "Continuous layout requires a positive width.");
3109
+ if (request.anchor && (twips(request.anchor.x) < 0 || twips(request.anchor.y) < 0)) throw new BrowserRenderError("render-failed", "Reading anchors must lie within positive document coordinates.");
3110
+ if (request.mode === this.state.layout && width === this.layoutWidth) return { layout: { changed: false } };
3111
+ const result = this.configure(request);
3112
+ this.layoutWidth = width;
3113
+ this.viewport = "";
3114
+ this.state = {
3115
+ ...this.state,
3116
+ layout: request.mode,
3117
+ layoutGeneration: this.state.layoutGeneration + 1,
3118
+ renderGeneration: this.state.renderGeneration + 1
3119
+ };
3120
+ this.refreshGeometry();
3121
+ await this.command(".uno:ReportWhenIdle", { idleID: {
3122
+ type: "string",
3123
+ value: "office-layout"
3124
+ } });
3125
+ this.refreshGeometry();
3126
+ this.emit({
3127
+ type: "state",
3128
+ state: this.state
3129
+ });
3130
+ this.emit({
3131
+ type: "invalidate",
3132
+ part: -1,
3133
+ rectangle: null,
3134
+ generation: this.state.renderGeneration
3135
+ });
3136
+ return { layout: result };
3137
+ }
3138
+ default: throw new BrowserRenderError("render-failed", "Unsupported Office reading operation.");
3139
+ }
3140
+ this.pump();
3141
+ return {};
3142
+ }
3143
+ configure(request) {
3144
+ const raw = this.text("dsh_lok_document_configure_view", [
3145
+ this.document,
3146
+ 1,
3147
+ request.mode === "continuous" ? 1 : 0,
3148
+ request.mode === "continuous" ? twips(request.width) : 0,
3149
+ request.anchor ? twips(request.anchor.x) : -1,
3150
+ request.anchor ? twips(request.anchor.y) : -1
3151
+ ]);
3152
+ if (!raw) throw new BrowserRenderError("render-failed", "LibreOffice could not configure its read-only view.");
3153
+ const result = JSON.parse(raw);
3154
+ if (typeof result.changed !== "boolean" || !(result.width > 0 && result.height > 0)) throw new BrowserRenderError("render-failed", "LibreOffice returned an invalid reading layout.");
3155
+ if (result.anchor === void 0) return { changed: result.changed };
3156
+ const { x, y, width, height } = result.anchor;
3157
+ if (![
3158
+ x,
3159
+ y,
3160
+ width,
3161
+ height
3162
+ ].every((value) => Number.isFinite(value) && value >= 0)) throw new BrowserRenderError("render-failed", "LibreOffice returned an invalid reading anchor.");
3163
+ return {
3164
+ changed: result.changed,
3165
+ anchor: {
3166
+ x: x / 15,
3167
+ y: y / 15,
3168
+ width: width / 15,
3169
+ height: height / 15
3170
+ }
3171
+ };
3172
+ }
3173
+ /** Internal whitelist commands only; no arbitrary command crosses the public API. */
3174
+ async command(name, args) {
3175
+ const result = Promise.withResolvers();
3176
+ this.commandResult = {
3177
+ name,
3178
+ resolve: () => result.resolve(),
3179
+ reject: result.reject
3180
+ };
3181
+ try {
3182
+ this.invoke("command", [name, JSON.stringify(args)]);
3183
+ this.pump();
3184
+ await result.promise;
3185
+ } finally {
3186
+ this.commandResult = void 0;
3187
+ }
3188
+ }
3189
+ /** Direct tiles preserve the active view, navigation state and selection. */
3190
+ render(request) {
3191
+ this.requireOpen();
3192
+ this.flush();
3193
+ const part = this.state.parts[integer(request.part, this.state.parts.length - 1)];
3194
+ if (request.part !== this.state.part) throw new BrowserRenderError("stale-part", "The Office tile belongs to an inactive worksheet or slide.");
3195
+ try {
3196
+ return renderRegion(this.module, this.document, {
3197
+ ...request,
3198
+ pageIndex: 0
3199
+ }, [{
3200
+ ...part,
3201
+ x: 0,
3202
+ y: 0,
3203
+ part: this.state.documentType === "text" ? -1 : request.part
3204
+ }], () => new BrowserRenderError("render-failed", "Office tile rendering failed."));
3205
+ } finally {
3206
+ this.flush();
3207
+ }
3208
+ }
3209
+ };
3210
+ //#endregion
3211
+ //#region lib/types/worker.js
3212
+ /** Classic Worker entry: serializes one LibreOffice instance and owns its pthreads. */
3213
+ const scope = globalThis;
3214
+ let module;
3215
+ let office = 0;
3216
+ let document = 0;
3217
+ let pdf = 0;
3218
+ let pages = [];
3219
+ let reader;
3220
+ let fatal = false;
3221
+ let fontFailure;
3222
+ let serial = Promise.resolve();
3223
+ const lifetime = new AbortController();
3224
+ function send(message, transfer = []) {
3225
+ scope.postMessage(message, transfer);
3226
+ }
3227
+ function call(name, args) {
3228
+ return module.ccall(name, "number", args.map(() => "number"), args);
3229
+ }
3230
+ function error(code) {
3231
+ if (fontFailure instanceof BrowserRenderError) return fontFailure;
3232
+ if (!module) return new BrowserRenderError(code, "LibreOffice could not initialize.");
3233
+ const pointer = call("dsh_lok_error", [office]);
3234
+ if (!pointer) return new BrowserRenderError(code, "LibreOffice could not render the document.");
3235
+ try {
3236
+ return new BrowserRenderError(code, module.UTF8ToString(pointer));
3237
+ } finally {
3238
+ call("free", [pointer]);
3239
+ }
3240
+ }
3241
+ async function open(options, channel, reading = false) {
3242
+ const { assets } = options;
3243
+ let metadata;
3244
+ try {
3245
+ metadata = options.extension === "pdf" ? {
3246
+ families: /* @__PURE__ */ new Map(),
3247
+ codePoints: []
3248
+ } : inspectDocument(options.data, options.extension, options);
3249
+ } catch (failure) {
3250
+ throw new BrowserRenderError("invalid-document", failure instanceof Error ? failure.message : String(failure));
3251
+ }
3252
+ const response = await fetch(assets.dataUrl, {
3253
+ credentials: "same-origin",
3254
+ signal: lifetime.signal
3255
+ });
3256
+ if (!response.ok) throw new BrowserRenderError("unavailable", `LibreOffice data request failed: ${response.status}`);
3257
+ const data = await response.arrayBuffer();
3258
+ scope.importScripts(assets.loaderUrl);
3259
+ let resolveFonts;
3260
+ module = await scope.createLibreOfficeModule({
3261
+ noInitialRun: true,
3262
+ dshOnCallback(type, payload) {
3263
+ reader?.callback(type, payload);
3264
+ },
3265
+ mainScriptUrlOrBlob: assets.loaderUrl,
3266
+ locateFile(name) {
3267
+ const basename = name.slice(name.lastIndexOf("/") + 1);
3268
+ switch (basename) {
3269
+ case "soffice.js":
3270
+ case "soffice.cjs": return assets.loaderUrl;
3271
+ case "soffice.wasm": return assets.wasmUrl;
3272
+ case "soffice.data": return assets.dataUrl;
3273
+ case "soffice.data.js.metadata": return assets.metadataUrl;
3274
+ default: throw new BrowserRenderError("unavailable", `LibreOffice requested an undeclared resource: ${basename}`);
3275
+ }
3276
+ },
3277
+ getPreloadedPackage: () => data,
3278
+ dshResolveSystemFontFaces(request) {
3279
+ if (!resolveFonts) throw new BrowserRenderError("font-unavailable", "LibreOffice requested fonts before MEMFS initialization.");
3280
+ try {
3281
+ return resolveFonts(request);
3282
+ } catch (failure) {
3283
+ fontFailure = failure;
3284
+ throw failure;
3285
+ }
3286
+ },
3287
+ preRun: [(loaded) => {
3288
+ for (const path of [
3289
+ "/dsh/profile",
3290
+ "/dsh/font-cache",
3291
+ "/dsh-fonts",
3292
+ "/usr/share/fonts/dsh-pdfium"
3293
+ ]) loaded.FS.mkdirTree(path);
3294
+ loaded.FS.writeFile("/dsh/fonts.conf", new TextEncoder().encode(memoryFontConfig(options.fontFallbacks, metadata.families.values())));
3295
+ Object.assign(loaded.ENV, {
3296
+ HOME: "/dsh/profile",
3297
+ TMPDIR: "/tmp",
3298
+ FONTCONFIG_FILE: "/dsh/fonts.conf",
3299
+ LOK_HOST_ALLOWLIST: "^$"
3300
+ });
3301
+ resolveFonts = createFontReader(channel, options.timeoutMs, options.maxLoadedFontBytes, metadata.families, (request) => send({
3302
+ type: "font",
3303
+ request
3304
+ }), () => send({ type: "font-next" }), (path, bytes) => loaded.FS.writeFile(path, bytes), (families) => send({
3305
+ type: "missing-fonts",
3306
+ families
3307
+ }));
3308
+ const initialFamilies = options.extension === "pdf" ? new Set(options.fontFallbacks.flat()) : /* @__PURE__ */ new Set(["sans-serif"]);
3309
+ for (const family of initialFamilies) resolveFonts({
3310
+ family,
3311
+ style: "",
3312
+ weight: 5,
3313
+ italic: 0,
3314
+ width: 5,
3315
+ pitch: 0,
3316
+ language: "",
3317
+ codePoints: [],
3318
+ ...options.extension === "pdf" ? { mode: "full" } : {}
3319
+ });
3320
+ }],
3321
+ onAbort() {
3322
+ fatal = true;
3323
+ },
3324
+ print() {},
3325
+ printErr() {}
3326
+ });
3327
+ if (options.extension === "pdf") {
3328
+ const pointer = call("malloc", [options.data.byteLength]);
3329
+ if (!pointer) throw error("invalid-document");
3330
+ try {
3331
+ new Uint8Array(module.HEAPU32.buffer, pointer, options.data.byteLength).set(options.data);
3332
+ pdf = module.ccall("dsh_pdf_open", "number", [
3333
+ "number",
3334
+ "number",
3335
+ "string"
3336
+ ], [
3337
+ pointer,
3338
+ options.data.byteLength,
3339
+ ""
3340
+ ]);
3341
+ } finally {
3342
+ call("free", [pointer]);
3343
+ }
3344
+ if (!pdf) throw error("invalid-document");
3345
+ pages = pdfPages(module, pdf, () => error("invalid-document"));
3346
+ return;
3347
+ }
3348
+ const input = `/dsh/document.${options.extension}`;
3349
+ module.FS.writeFile(input, options.data);
3350
+ office = module.ccall("dsh_lok_initialize", "number", ["string", "string"], [assets.programDirectory, "file:///dsh/profile"]);
3351
+ if (!office) throw error("invalid-document");
3352
+ document = module.ccall("dsh_lok_document_load", "number", [
3353
+ "number",
3354
+ "string",
3355
+ "string"
3356
+ ], [
3357
+ office,
3358
+ `file://${input}`,
3359
+ "ReadOnly=true,EnableMacrosExecution=false"
3360
+ ]);
3361
+ if (!document || !call("dsh_lok_document_initialize_rendering", [document])) throw error("invalid-document");
3362
+ const type = call("dsh_lok_document_type", [document]);
3363
+ if (type !== (options.extension === "docx" || options.extension === "doc" ? 0 : options.extension === "xlsx" || options.extension === "xls" ? 1 : 2)) throw new BrowserRenderError("invalid-document", "The document type does not match its extension.");
3364
+ if (reading) {
3365
+ reader = new OfficeEngine(module, document, options.extension, (event) => send({
3366
+ type: "office-event",
3367
+ event
3368
+ }), (failure) => {
3369
+ fatal ||= failure instanceof WebAssembly.RuntimeError;
3370
+ send({
3371
+ type: "office-event",
3372
+ event: {
3373
+ type: "error",
3374
+ code: "render-failed",
3375
+ message: failure instanceof Error ? failure.message : String(failure)
3376
+ }
3377
+ });
3378
+ });
3379
+ await reader.start();
3380
+ pages = reader.state.parts.map((part, index) => ({
3381
+ ...part,
3382
+ x: 0,
3383
+ y: 0,
3384
+ part: type === 0 ? -1 : index
3385
+ }));
3386
+ return;
3387
+ }
3388
+ throw new BrowserRenderError("invalid-document", "Office documents require a retained session.");
3389
+ }
3390
+ function render(request) {
3391
+ if (fatal) throw new BrowserRenderError("render-failed", "LibreOffice Worker has aborted.");
3392
+ if (!pdf || !module) throw new BrowserRenderError("disposed", "The document is closed.");
3393
+ return renderRegion(module, pdf, request, pages, () => error("render-failed"), true);
3394
+ }
3395
+ function dispose() {
3396
+ reader?.stop();
3397
+ reader = void 0;
3398
+ try {
3399
+ if (module && !fatal) {
3400
+ if (pdf) {
3401
+ const value = pdf;
3402
+ pdf = 0;
3403
+ if (!call("dsh_pdf_destroy", [value])) throw error("render-failed");
3404
+ }
3405
+ if (document) {
3406
+ const value = document;
3407
+ document = 0;
3408
+ if (!call("dsh_lok_document_destroy", [value])) throw error("render-failed");
3409
+ }
3410
+ if (office) {
3411
+ const value = office;
3412
+ office = 0;
3413
+ if (!call("dsh_lok_destroy", [value])) throw error("render-failed");
3414
+ }
3415
+ }
3416
+ } finally {
3417
+ module?.PThread.terminateAllThreads();
3418
+ module = void 0;
3419
+ document = 0;
3420
+ pdf = 0;
3421
+ office = 0;
3422
+ pages = [];
3423
+ }
3424
+ }
3425
+ scope.onmessage = (event) => {
3426
+ const message = event.data;
3427
+ if (message.type === "dispose") {
3428
+ lifetime.abort();
3429
+ reader?.stop();
3430
+ }
3431
+ serial = serial.then(async () => {
3432
+ try {
3433
+ switch (message.type) {
3434
+ case "open":
3435
+ await open(message.options, message.channel, message.office);
3436
+ send({
3437
+ type: "opened",
3438
+ id: message.id,
3439
+ pages: pages.map(({ width, height }) => ({
3440
+ width,
3441
+ height
3442
+ })),
3443
+ ...reader ? { office: reader.state } : {}
3444
+ });
3445
+ break;
3446
+ case "tile": {
3447
+ const tile = render(message.request);
3448
+ send({
3449
+ type: "tile",
3450
+ id: message.id,
3451
+ tile
3452
+ }, [tile.rgba.buffer]);
3453
+ break;
3454
+ }
3455
+ case "office-tile": {
3456
+ if (!reader) throw new BrowserRenderError("disposed", "Office reader is closed.");
3457
+ const tile = reader.render(message.request);
3458
+ send({
3459
+ type: "tile",
3460
+ id: message.id,
3461
+ tile
3462
+ }, [tile.rgba.buffer]);
3463
+ break;
3464
+ }
3465
+ case "office-operation": {
3466
+ if (!reader) throw new BrowserRenderError("disposed", "Office reader is closed.");
3467
+ const result = await reader.operation(message.operation);
3468
+ send({
3469
+ type: "office-result",
3470
+ id: message.id,
3471
+ ...result
3472
+ });
3473
+ break;
3474
+ }
3475
+ case "dispose":
3476
+ dispose();
3477
+ send({
3478
+ type: "disposed",
3479
+ id: message.id
3480
+ });
3481
+ scope.close();
3482
+ break;
3483
+ default: throw new BrowserRenderError("render-failed", "Unsupported Office Worker request.");
3484
+ }
3485
+ } catch (failure) {
3486
+ fatal ||= failure instanceof WebAssembly.RuntimeError;
3487
+ send({
3488
+ type: "error",
3489
+ id: message.id,
3490
+ code: failure instanceof BrowserRenderError ? failure.code : "render-failed",
3491
+ message: failure instanceof Error ? failure.message : String(failure),
3492
+ fatal
3493
+ });
3494
+ }
3495
+ });
3496
+ };
3497
+ //#endregion
3498
+ })();