@clazic/kordoc 2.1.6 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +67 -4
  2. package/dist/chunk-3NF22UFF.js +9617 -0
  3. package/dist/chunk-3NF22UFF.js.map +1 -0
  4. package/dist/{chunk-TFYOEQE2.js → chunk-7MXQWWUW.js} +2 -2
  5. package/dist/chunk-ZWE3DS7E.js +39 -0
  6. package/dist/cli.js +114 -11
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +2985 -179
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +36 -4
  11. package/dist/index.d.ts +36 -4
  12. package/dist/index.js +3009 -178
  13. package/dist/index.js.map +1 -1
  14. package/dist/mcp.js +100 -7
  15. package/dist/mcp.js.map +1 -1
  16. package/dist/{page-range-737B4EZW.js → page-range-ALIRXAL5.js} +2 -1
  17. package/dist/provider-XVKP5OGI.js +167 -0
  18. package/dist/provider-XVKP5OGI.js.map +1 -0
  19. package/dist/resolve-Z4DEPDUS.js +179 -0
  20. package/dist/resolve-Z4DEPDUS.js.map +1 -0
  21. package/dist/tesseract-provider-UNJOI25M.js +24 -0
  22. package/dist/tesseract-provider-UNJOI25M.js.map +1 -0
  23. package/dist/{utils-7JE5SKSL.js → utils-I4UIMOH7.js} +3 -2
  24. package/dist/utils-I4UIMOH7.js.map +1 -0
  25. package/dist/{watch-XALC6VOR.js → watch-XPLMUIZB.js} +4 -3
  26. package/dist/{watch-XALC6VOR.js.map → watch-XPLMUIZB.js.map} +1 -1
  27. package/package.json +5 -2
  28. package/dist/chunk-H7HMKSLX.js +0 -5494
  29. package/dist/chunk-H7HMKSLX.js.map +0 -1
  30. package/dist/provider-A4FHJSID.js +0 -38
  31. package/dist/provider-A4FHJSID.js.map +0 -1
  32. /package/dist/{chunk-TFYOEQE2.js.map → chunk-7MXQWWUW.js.map} +0 -0
  33. /package/dist/{page-range-737B4EZW.js.map → chunk-ZWE3DS7E.js.map} +0 -0
  34. /package/dist/{utils-7JE5SKSL.js.map → page-range-ALIRXAL5.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,12 +1,41 @@
1
+ var __create = Object.create;
1
2
  var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
3
13
  var __esm = (fn, res) => function __init() {
4
14
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
15
  };
16
+ var __commonJS = (cb, mod) => function __require2() {
17
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
+ };
6
19
  var __export = (target, all) => {
7
20
  for (var name in all)
8
21
  __defProp(target, name, { get: all[name], enumerable: true });
9
22
  };
23
+ var __copyProps = (to, from, except, desc) => {
24
+ if (from && typeof from === "object" || typeof from === "function") {
25
+ for (let key of __getOwnPropNames(from))
26
+ if (!__hasOwnProp.call(to, key) && key !== except)
27
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
28
+ }
29
+ return to;
30
+ };
31
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
32
+ // If the importer is in node compatibility mode or this is not an ESM
33
+ // file that has been converted to a CommonJS file using a Babel-
34
+ // compatible transform (i.e. "__esModule" has not been set), then set
35
+ // "default" to the CommonJS "module.exports" for node compatibility.
36
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
37
+ mod
38
+ ));
10
39
 
11
40
  // src/page-range.ts
12
41
  var page_range_exports = {};
@@ -21,27 +50,2255 @@ function parsePageRange(spec, maxPages) {
21
50
  const page = Math.round(n);
22
51
  if (page >= 1 && page <= maxPages) result.add(page);
23
52
  }
24
- return result;
53
+ return result;
54
+ }
55
+ if (typeof spec !== "string" || spec.trim() === "") return result;
56
+ const parts = spec.split(",");
57
+ for (const part of parts) {
58
+ const trimmed = part.trim();
59
+ if (!trimmed) continue;
60
+ const rangeMatch = trimmed.match(/^(\d+)\s*-\s*(\d+)$/);
61
+ if (rangeMatch) {
62
+ const start = Math.max(1, parseInt(rangeMatch[1], 10));
63
+ const end = Math.min(maxPages, parseInt(rangeMatch[2], 10));
64
+ for (let i = start; i <= end; i++) result.add(i);
65
+ } else {
66
+ const page = parseInt(trimmed, 10);
67
+ if (!isNaN(page) && page >= 1 && page <= maxPages) result.add(page);
68
+ }
69
+ }
70
+ return result;
71
+ }
72
+ var init_page_range = __esm({
73
+ "src/page-range.ts"() {
74
+ "use strict";
75
+ }
76
+ });
77
+
78
+ // node_modules/cfb/cfb.js
79
+ var require_cfb = __commonJS({
80
+ "node_modules/cfb/cfb.js"(exports, module) {
81
+ "use strict";
82
+ var Base64_map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
83
+ function Base64_encode(input) {
84
+ var o = "";
85
+ var c1 = 0, c2 = 0, c3 = 0, e1 = 0, e2 = 0, e3 = 0, e4 = 0;
86
+ for (var i = 0; i < input.length; ) {
87
+ c1 = input.charCodeAt(i++);
88
+ e1 = c1 >> 2;
89
+ c2 = input.charCodeAt(i++);
90
+ e2 = (c1 & 3) << 4 | c2 >> 4;
91
+ c3 = input.charCodeAt(i++);
92
+ e3 = (c2 & 15) << 2 | c3 >> 6;
93
+ e4 = c3 & 63;
94
+ if (isNaN(c2)) e3 = e4 = 64;
95
+ else if (isNaN(c3)) e4 = 64;
96
+ o += Base64_map.charAt(e1) + Base64_map.charAt(e2) + Base64_map.charAt(e3) + Base64_map.charAt(e4);
97
+ }
98
+ return o;
99
+ }
100
+ function Base64_decode(input) {
101
+ var o = "";
102
+ var c1 = 0, c2 = 0, c3 = 0, e1 = 0, e2 = 0, e3 = 0, e4 = 0;
103
+ input = input.replace(/[^\w\+\/\=]/g, "");
104
+ for (var i = 0; i < input.length; ) {
105
+ e1 = Base64_map.indexOf(input.charAt(i++));
106
+ e2 = Base64_map.indexOf(input.charAt(i++));
107
+ c1 = e1 << 2 | e2 >> 4;
108
+ o += String.fromCharCode(c1);
109
+ e3 = Base64_map.indexOf(input.charAt(i++));
110
+ c2 = (e2 & 15) << 4 | e3 >> 2;
111
+ if (e3 !== 64) o += String.fromCharCode(c2);
112
+ e4 = Base64_map.indexOf(input.charAt(i++));
113
+ c3 = (e3 & 3) << 6 | e4;
114
+ if (e4 !== 64) o += String.fromCharCode(c3);
115
+ }
116
+ return o;
117
+ }
118
+ var has_buf = (function() {
119
+ return typeof Buffer !== "undefined" && typeof process !== "undefined" && typeof process.versions !== "undefined" && !!process.versions.node;
120
+ })();
121
+ var Buffer_from = (function() {
122
+ if (typeof Buffer !== "undefined") {
123
+ var nbfs = !Buffer.from;
124
+ if (!nbfs) try {
125
+ Buffer.from("foo", "utf8");
126
+ } catch (e) {
127
+ nbfs = true;
128
+ }
129
+ return nbfs ? function(buf, enc) {
130
+ return enc ? new Buffer(buf, enc) : new Buffer(buf);
131
+ } : Buffer.from.bind(Buffer);
132
+ }
133
+ return function() {
134
+ };
135
+ })();
136
+ function new_raw_buf(len) {
137
+ if (has_buf) {
138
+ if (Buffer.alloc) return Buffer.alloc(len);
139
+ var b = new Buffer(len);
140
+ b.fill(0);
141
+ return b;
142
+ }
143
+ return typeof Uint8Array != "undefined" ? new Uint8Array(len) : new Array(len);
144
+ }
145
+ function new_unsafe_buf(len) {
146
+ if (has_buf) return Buffer.allocUnsafe ? Buffer.allocUnsafe(len) : new Buffer(len);
147
+ return typeof Uint8Array != "undefined" ? new Uint8Array(len) : new Array(len);
148
+ }
149
+ var s2a = function s2a2(s) {
150
+ if (has_buf) return Buffer_from(s, "binary");
151
+ return s.split("").map(function(x) {
152
+ return x.charCodeAt(0) & 255;
153
+ });
154
+ };
155
+ var chr0 = /\u0000/g;
156
+ var chr1 = /[\u0001-\u0006]/g;
157
+ var __toBuffer = function(bufs) {
158
+ var x = [];
159
+ for (var i = 0; i < bufs[0].length; ++i) {
160
+ x.push.apply(x, bufs[0][i]);
161
+ }
162
+ return x;
163
+ };
164
+ var ___toBuffer = __toBuffer;
165
+ var __utf16le = function(b, s, e) {
166
+ var ss = [];
167
+ for (var i = s; i < e; i += 2) ss.push(String.fromCharCode(__readUInt16LE(b, i)));
168
+ return ss.join("").replace(chr0, "");
169
+ };
170
+ var ___utf16le = __utf16le;
171
+ var __hexlify = function(b, s, l) {
172
+ var ss = [];
173
+ for (var i = s; i < s + l; ++i) ss.push(("0" + b[i].toString(16)).slice(-2));
174
+ return ss.join("");
175
+ };
176
+ var ___hexlify = __hexlify;
177
+ var __bconcat = function(bufs) {
178
+ if (Array.isArray(bufs[0])) return [].concat.apply([], bufs);
179
+ var maxlen = 0, i = 0;
180
+ for (i = 0; i < bufs.length; ++i) maxlen += bufs[i].length;
181
+ var o = new Uint8Array(maxlen);
182
+ for (i = 0, maxlen = 0; i < bufs.length; maxlen += bufs[i].length, ++i) o.set(bufs[i], maxlen);
183
+ return o;
184
+ };
185
+ var bconcat = __bconcat;
186
+ if (has_buf) {
187
+ __utf16le = function(b, s, e) {
188
+ if (!Buffer.isBuffer(b)) return ___utf16le(b, s, e);
189
+ return b.toString("utf16le", s, e).replace(chr0, "");
190
+ };
191
+ __hexlify = function(b, s, l) {
192
+ return Buffer.isBuffer(b) ? b.toString("hex", s, s + l) : ___hexlify(b, s, l);
193
+ };
194
+ __toBuffer = function(bufs) {
195
+ return bufs[0].length > 0 && Buffer.isBuffer(bufs[0][0]) ? Buffer.concat(bufs[0]) : ___toBuffer(bufs);
196
+ };
197
+ s2a = function(s) {
198
+ return Buffer_from(s, "binary");
199
+ };
200
+ bconcat = function(bufs) {
201
+ return Buffer.isBuffer(bufs[0]) ? Buffer.concat(bufs) : __bconcat(bufs);
202
+ };
203
+ }
204
+ var __readUInt8 = function(b, idx) {
205
+ return b[idx];
206
+ };
207
+ var __readUInt16LE = function(b, idx) {
208
+ return b[idx + 1] * (1 << 8) + b[idx];
209
+ };
210
+ var __readInt16LE = function(b, idx) {
211
+ var u = b[idx + 1] * (1 << 8) + b[idx];
212
+ return u < 32768 ? u : (65535 - u + 1) * -1;
213
+ };
214
+ var __readUInt32LE = function(b, idx) {
215
+ return b[idx + 3] * (1 << 24) + (b[idx + 2] << 16) + (b[idx + 1] << 8) + b[idx];
216
+ };
217
+ var __readInt32LE = function(b, idx) {
218
+ return (b[idx + 3] << 24) + (b[idx + 2] << 16) + (b[idx + 1] << 8) + b[idx];
219
+ };
220
+ function ReadShift(size, t) {
221
+ var oI, oS, type = 0;
222
+ switch (size) {
223
+ case 1:
224
+ oI = __readUInt8(this, this.l);
225
+ break;
226
+ case 2:
227
+ oI = (t !== "i" ? __readUInt16LE : __readInt16LE)(this, this.l);
228
+ break;
229
+ case 4:
230
+ oI = __readInt32LE(this, this.l);
231
+ break;
232
+ case 16:
233
+ type = 2;
234
+ oS = __hexlify(this, this.l, size);
235
+ }
236
+ this.l += size;
237
+ if (type === 0) return oI;
238
+ return oS;
239
+ }
240
+ var __writeUInt32LE = function(b, val, idx) {
241
+ b[idx] = val & 255;
242
+ b[idx + 1] = val >>> 8 & 255;
243
+ b[idx + 2] = val >>> 16 & 255;
244
+ b[idx + 3] = val >>> 24 & 255;
245
+ };
246
+ var __writeInt32LE = function(b, val, idx) {
247
+ b[idx] = val & 255;
248
+ b[idx + 1] = val >> 8 & 255;
249
+ b[idx + 2] = val >> 16 & 255;
250
+ b[idx + 3] = val >> 24 & 255;
251
+ };
252
+ function WriteShift(t, val, f) {
253
+ var size = 0, i = 0;
254
+ switch (f) {
255
+ case "hex":
256
+ for (; i < t; ++i) {
257
+ this[this.l++] = parseInt(val.slice(2 * i, 2 * i + 2), 16) || 0;
258
+ }
259
+ return this;
260
+ case "utf16le":
261
+ var end = this.l + t;
262
+ for (i = 0; i < Math.min(val.length, t); ++i) {
263
+ var cc = val.charCodeAt(i);
264
+ this[this.l++] = cc & 255;
265
+ this[this.l++] = cc >> 8;
266
+ }
267
+ while (this.l < end) this[this.l++] = 0;
268
+ return this;
269
+ }
270
+ switch (t) {
271
+ case 1:
272
+ size = 1;
273
+ this[this.l] = val & 255;
274
+ break;
275
+ case 2:
276
+ size = 2;
277
+ this[this.l] = val & 255;
278
+ val >>>= 8;
279
+ this[this.l + 1] = val & 255;
280
+ break;
281
+ case 4:
282
+ size = 4;
283
+ __writeUInt32LE(this, val, this.l);
284
+ break;
285
+ case -4:
286
+ size = 4;
287
+ __writeInt32LE(this, val, this.l);
288
+ break;
289
+ }
290
+ this.l += size;
291
+ return this;
292
+ }
293
+ function CheckField(hexstr, fld) {
294
+ var m = __hexlify(this, this.l, hexstr.length >> 1);
295
+ if (m !== hexstr) throw new Error(fld + "Expected " + hexstr + " saw " + m);
296
+ this.l += hexstr.length >> 1;
297
+ }
298
+ function prep_blob(blob, pos) {
299
+ blob.l = pos;
300
+ blob.read_shift = ReadShift;
301
+ blob.chk = CheckField;
302
+ blob.write_shift = WriteShift;
303
+ }
304
+ function new_buf(sz) {
305
+ var o = new_raw_buf(sz);
306
+ prep_blob(o, 0);
307
+ return o;
308
+ }
309
+ var CRC32 = (function() {
310
+ var CRC322 = {};
311
+ CRC322.version = "1.2.1";
312
+ function signed_crc_table() {
313
+ var c = 0, table = new Array(256);
314
+ for (var n = 0; n != 256; ++n) {
315
+ c = n;
316
+ c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
317
+ c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
318
+ c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
319
+ c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
320
+ c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
321
+ c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
322
+ c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
323
+ c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
324
+ table[n] = c;
325
+ }
326
+ return typeof Int32Array !== "undefined" ? new Int32Array(table) : table;
327
+ }
328
+ var T0 = signed_crc_table();
329
+ function slice_by_16_tables(T) {
330
+ var c = 0, v = 0, n = 0, table = typeof Int32Array !== "undefined" ? new Int32Array(4096) : new Array(4096);
331
+ for (n = 0; n != 256; ++n) table[n] = T[n];
332
+ for (n = 0; n != 256; ++n) {
333
+ v = T[n];
334
+ for (c = 256 + n; c < 4096; c += 256) v = table[c] = v >>> 8 ^ T[v & 255];
335
+ }
336
+ var out = [];
337
+ for (n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== "undefined" ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256);
338
+ return out;
339
+ }
340
+ var TT = slice_by_16_tables(T0);
341
+ var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4];
342
+ var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9];
343
+ var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14];
344
+ function crc32_bstr(bstr, seed) {
345
+ var C = seed ^ -1;
346
+ for (var i = 0, L = bstr.length; i < L; ) C = C >>> 8 ^ T0[(C ^ bstr.charCodeAt(i++)) & 255];
347
+ return ~C;
348
+ }
349
+ function crc32_buf(B, seed) {
350
+ var C = seed ^ -1, L = B.length - 15, i = 0;
351
+ for (; i < L; ) C = Tf[B[i++] ^ C & 255] ^ Te[B[i++] ^ C >> 8 & 255] ^ Td[B[i++] ^ C >> 16 & 255] ^ Tc[B[i++] ^ C >>> 24] ^ Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]];
352
+ L += 15;
353
+ while (i < L) C = C >>> 8 ^ T0[(C ^ B[i++]) & 255];
354
+ return ~C;
355
+ }
356
+ function crc32_str(str, seed) {
357
+ var C = seed ^ -1;
358
+ for (var i = 0, L = str.length, c = 0, d = 0; i < L; ) {
359
+ c = str.charCodeAt(i++);
360
+ if (c < 128) {
361
+ C = C >>> 8 ^ T0[(C ^ c) & 255];
362
+ } else if (c < 2048) {
363
+ C = C >>> 8 ^ T0[(C ^ (192 | c >> 6 & 31)) & 255];
364
+ C = C >>> 8 ^ T0[(C ^ (128 | c & 63)) & 255];
365
+ } else if (c >= 55296 && c < 57344) {
366
+ c = (c & 1023) + 64;
367
+ d = str.charCodeAt(i++) & 1023;
368
+ C = C >>> 8 ^ T0[(C ^ (240 | c >> 8 & 7)) & 255];
369
+ C = C >>> 8 ^ T0[(C ^ (128 | c >> 2 & 63)) & 255];
370
+ C = C >>> 8 ^ T0[(C ^ (128 | d >> 6 & 15 | (c & 3) << 4)) & 255];
371
+ C = C >>> 8 ^ T0[(C ^ (128 | d & 63)) & 255];
372
+ } else {
373
+ C = C >>> 8 ^ T0[(C ^ (224 | c >> 12 & 15)) & 255];
374
+ C = C >>> 8 ^ T0[(C ^ (128 | c >> 6 & 63)) & 255];
375
+ C = C >>> 8 ^ T0[(C ^ (128 | c & 63)) & 255];
376
+ }
377
+ }
378
+ return ~C;
379
+ }
380
+ CRC322.table = T0;
381
+ CRC322.bstr = crc32_bstr;
382
+ CRC322.buf = crc32_buf;
383
+ CRC322.str = crc32_str;
384
+ return CRC322;
385
+ })();
386
+ var CFB2 = (function _CFB() {
387
+ var exports2 = {};
388
+ exports2.version = "1.2.2";
389
+ function namecmp(l, r) {
390
+ var L = l.split("/"), R = r.split("/");
391
+ for (var i2 = 0, c = 0, Z = Math.min(L.length, R.length); i2 < Z; ++i2) {
392
+ if (c = L[i2].length - R[i2].length) return c;
393
+ if (L[i2] != R[i2]) return L[i2] < R[i2] ? -1 : 1;
394
+ }
395
+ return L.length - R.length;
396
+ }
397
+ function dirname(p) {
398
+ if (p.charAt(p.length - 1) == "/") return p.slice(0, -1).indexOf("/") === -1 ? p : dirname(p.slice(0, -1));
399
+ var c = p.lastIndexOf("/");
400
+ return c === -1 ? p : p.slice(0, c + 1);
401
+ }
402
+ function filename(p) {
403
+ if (p.charAt(p.length - 1) == "/") return filename(p.slice(0, -1));
404
+ var c = p.lastIndexOf("/");
405
+ return c === -1 ? p : p.slice(c + 1);
406
+ }
407
+ function write_dos_date(buf, date) {
408
+ if (typeof date === "string") date = new Date(date);
409
+ var hms = date.getHours();
410
+ hms = hms << 6 | date.getMinutes();
411
+ hms = hms << 5 | date.getSeconds() >>> 1;
412
+ buf.write_shift(2, hms);
413
+ var ymd = date.getFullYear() - 1980;
414
+ ymd = ymd << 4 | date.getMonth() + 1;
415
+ ymd = ymd << 5 | date.getDate();
416
+ buf.write_shift(2, ymd);
417
+ }
418
+ function parse_dos_date(buf) {
419
+ var hms = buf.read_shift(2) & 65535;
420
+ var ymd = buf.read_shift(2) & 65535;
421
+ var val = /* @__PURE__ */ new Date();
422
+ var d = ymd & 31;
423
+ ymd >>>= 5;
424
+ var m = ymd & 15;
425
+ ymd >>>= 4;
426
+ val.setMilliseconds(0);
427
+ val.setFullYear(ymd + 1980);
428
+ val.setMonth(m - 1);
429
+ val.setDate(d);
430
+ var S = hms & 31;
431
+ hms >>>= 5;
432
+ var M = hms & 63;
433
+ hms >>>= 6;
434
+ val.setHours(hms);
435
+ val.setMinutes(M);
436
+ val.setSeconds(S << 1);
437
+ return val;
438
+ }
439
+ function parse_extra_field(blob) {
440
+ prep_blob(blob, 0);
441
+ var o = {};
442
+ var flags = 0;
443
+ while (blob.l <= blob.length - 4) {
444
+ var type = blob.read_shift(2);
445
+ var sz = blob.read_shift(2), tgt = blob.l + sz;
446
+ var p = {};
447
+ switch (type) {
448
+ /* UNIX-style Timestamps */
449
+ case 21589:
450
+ {
451
+ flags = blob.read_shift(1);
452
+ if (flags & 1) p.mtime = blob.read_shift(4);
453
+ if (sz > 5) {
454
+ if (flags & 2) p.atime = blob.read_shift(4);
455
+ if (flags & 4) p.ctime = blob.read_shift(4);
456
+ }
457
+ if (p.mtime) p.mt = new Date(p.mtime * 1e3);
458
+ }
459
+ break;
460
+ }
461
+ blob.l = tgt;
462
+ o[type] = p;
463
+ }
464
+ return o;
465
+ }
466
+ var fs;
467
+ function get_fs() {
468
+ return fs || (fs = __require("fs"));
469
+ }
470
+ function parse3(file, options) {
471
+ if (file[0] == 80 && file[1] == 75) return parse_zip(file, options);
472
+ if ((file[0] | 32) == 109 && (file[1] | 32) == 105) return parse_mad(file, options);
473
+ if (file.length < 512) throw new Error("CFB file size " + file.length + " < 512");
474
+ var mver = 3;
475
+ var ssz = 512;
476
+ var nmfs = 0;
477
+ var difat_sec_cnt = 0;
478
+ var dir_start = 0;
479
+ var minifat_start = 0;
480
+ var difat_start = 0;
481
+ var fat_addrs = [];
482
+ var blob = file.slice(0, 512);
483
+ prep_blob(blob, 0);
484
+ var mv = check_get_mver(blob);
485
+ mver = mv[0];
486
+ switch (mver) {
487
+ case 3:
488
+ ssz = 512;
489
+ break;
490
+ case 4:
491
+ ssz = 4096;
492
+ break;
493
+ case 0:
494
+ if (mv[1] == 0) return parse_zip(file, options);
495
+ /* falls through */
496
+ default:
497
+ throw new Error("Major Version: Expected 3 or 4 saw " + mver);
498
+ }
499
+ if (ssz !== 512) {
500
+ blob = file.slice(0, ssz);
501
+ prep_blob(
502
+ blob,
503
+ 28
504
+ /* blob.l */
505
+ );
506
+ }
507
+ var header = file.slice(0, ssz);
508
+ check_shifts(blob, mver);
509
+ var dir_cnt = blob.read_shift(4, "i");
510
+ if (mver === 3 && dir_cnt !== 0) throw new Error("# Directory Sectors: Expected 0 saw " + dir_cnt);
511
+ blob.l += 4;
512
+ dir_start = blob.read_shift(4, "i");
513
+ blob.l += 4;
514
+ blob.chk("00100000", "Mini Stream Cutoff Size: ");
515
+ minifat_start = blob.read_shift(4, "i");
516
+ nmfs = blob.read_shift(4, "i");
517
+ difat_start = blob.read_shift(4, "i");
518
+ difat_sec_cnt = blob.read_shift(4, "i");
519
+ for (var q2 = -1, j = 0; j < 109; ++j) {
520
+ q2 = blob.read_shift(4, "i");
521
+ if (q2 < 0) break;
522
+ fat_addrs[j] = q2;
523
+ }
524
+ var sectors = sectorify(file, ssz);
525
+ sleuth_fat(difat_start, difat_sec_cnt, sectors, ssz, fat_addrs);
526
+ var sector_list = make_sector_list(sectors, dir_start, fat_addrs, ssz);
527
+ sector_list[dir_start].name = "!Directory";
528
+ if (nmfs > 0 && minifat_start !== ENDOFCHAIN) sector_list[minifat_start].name = "!MiniFAT";
529
+ sector_list[fat_addrs[0]].name = "!FAT";
530
+ sector_list.fat_addrs = fat_addrs;
531
+ sector_list.ssz = ssz;
532
+ var files = {}, Paths = [], FileIndex = [], FullPaths = [];
533
+ read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, minifat_start);
534
+ build_full_paths(FileIndex, FullPaths, Paths);
535
+ Paths.shift();
536
+ var o = {
537
+ FileIndex,
538
+ FullPaths
539
+ };
540
+ if (options && options.raw) o.raw = { header, sectors };
541
+ return o;
542
+ }
543
+ function check_get_mver(blob) {
544
+ if (blob[blob.l] == 80 && blob[blob.l + 1] == 75) return [0, 0];
545
+ blob.chk(HEADER_SIGNATURE, "Header Signature: ");
546
+ blob.l += 16;
547
+ var mver = blob.read_shift(2, "u");
548
+ return [blob.read_shift(2, "u"), mver];
549
+ }
550
+ function check_shifts(blob, mver) {
551
+ var shift = 9;
552
+ blob.l += 2;
553
+ switch (shift = blob.read_shift(2)) {
554
+ case 9:
555
+ if (mver != 3) throw new Error("Sector Shift: Expected 9 saw " + shift);
556
+ break;
557
+ case 12:
558
+ if (mver != 4) throw new Error("Sector Shift: Expected 12 saw " + shift);
559
+ break;
560
+ default:
561
+ throw new Error("Sector Shift: Expected 9 or 12 saw " + shift);
562
+ }
563
+ blob.chk("0600", "Mini Sector Shift: ");
564
+ blob.chk("000000000000", "Reserved: ");
565
+ }
566
+ function sectorify(file, ssz) {
567
+ var nsectors = Math.ceil(file.length / ssz) - 1;
568
+ var sectors = [];
569
+ for (var i2 = 1; i2 < nsectors; ++i2) sectors[i2 - 1] = file.slice(i2 * ssz, (i2 + 1) * ssz);
570
+ sectors[nsectors - 1] = file.slice(nsectors * ssz);
571
+ return sectors;
572
+ }
573
+ function build_full_paths(FI, FP, Paths) {
574
+ var i2 = 0, L = 0, R = 0, C = 0, j = 0, pl = Paths.length;
575
+ var dad = [], q2 = [];
576
+ for (; i2 < pl; ++i2) {
577
+ dad[i2] = q2[i2] = i2;
578
+ FP[i2] = Paths[i2];
579
+ }
580
+ for (; j < q2.length; ++j) {
581
+ i2 = q2[j];
582
+ L = FI[i2].L;
583
+ R = FI[i2].R;
584
+ C = FI[i2].C;
585
+ if (dad[i2] === i2) {
586
+ if (L !== -1 && dad[L] !== L) dad[i2] = dad[L];
587
+ if (R !== -1 && dad[R] !== R) dad[i2] = dad[R];
588
+ }
589
+ if (C !== -1) dad[C] = i2;
590
+ if (L !== -1 && i2 != dad[i2]) {
591
+ dad[L] = dad[i2];
592
+ if (q2.lastIndexOf(L) < j) q2.push(L);
593
+ }
594
+ if (R !== -1 && i2 != dad[i2]) {
595
+ dad[R] = dad[i2];
596
+ if (q2.lastIndexOf(R) < j) q2.push(R);
597
+ }
598
+ }
599
+ for (i2 = 1; i2 < pl; ++i2) if (dad[i2] === i2) {
600
+ if (R !== -1 && dad[R] !== R) dad[i2] = dad[R];
601
+ else if (L !== -1 && dad[L] !== L) dad[i2] = dad[L];
602
+ }
603
+ for (i2 = 1; i2 < pl; ++i2) {
604
+ if (FI[i2].type === 0) continue;
605
+ j = i2;
606
+ if (j != dad[j]) do {
607
+ j = dad[j];
608
+ FP[i2] = FP[j] + "/" + FP[i2];
609
+ } while (j !== 0 && -1 !== dad[j] && j != dad[j]);
610
+ dad[i2] = -1;
611
+ }
612
+ FP[0] += "/";
613
+ for (i2 = 1; i2 < pl; ++i2) {
614
+ if (FI[i2].type !== 2) FP[i2] += "/";
615
+ }
616
+ }
617
+ function get_mfat_entry(entry, payload, mini) {
618
+ var start = entry.start, size = entry.size;
619
+ var o = [];
620
+ var idx = start;
621
+ while (mini && size > 0 && idx >= 0) {
622
+ o.push(payload.slice(idx * MSSZ, idx * MSSZ + MSSZ));
623
+ size -= MSSZ;
624
+ idx = __readInt32LE(mini, idx * 4);
625
+ }
626
+ if (o.length === 0) return new_buf(0);
627
+ return bconcat(o).slice(0, entry.size);
628
+ }
629
+ function sleuth_fat(idx, cnt, sectors, ssz, fat_addrs) {
630
+ var q2 = ENDOFCHAIN;
631
+ if (idx === ENDOFCHAIN) {
632
+ if (cnt !== 0) throw new Error("DIFAT chain shorter than expected");
633
+ } else if (idx !== -1) {
634
+ var sector = sectors[idx], m = (ssz >>> 2) - 1;
635
+ if (!sector) return;
636
+ for (var i2 = 0; i2 < m; ++i2) {
637
+ if ((q2 = __readInt32LE(sector, i2 * 4)) === ENDOFCHAIN) break;
638
+ fat_addrs.push(q2);
639
+ }
640
+ if (cnt >= 1) sleuth_fat(__readInt32LE(sector, ssz - 4), cnt - 1, sectors, ssz, fat_addrs);
641
+ }
642
+ }
643
+ function get_sector_list(sectors, start, fat_addrs, ssz, chkd) {
644
+ var buf = [], buf_chain = [];
645
+ if (!chkd) chkd = [];
646
+ var modulus = ssz - 1, j = 0, jj = 0;
647
+ for (j = start; j >= 0; ) {
648
+ chkd[j] = true;
649
+ buf[buf.length] = j;
650
+ buf_chain.push(sectors[j]);
651
+ var addr = fat_addrs[Math.floor(j * 4 / ssz)];
652
+ jj = j * 4 & modulus;
653
+ if (ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 " + ssz);
654
+ if (!sectors[addr]) break;
655
+ j = __readInt32LE(sectors[addr], jj);
656
+ }
657
+ return { nodes: buf, data: __toBuffer([buf_chain]) };
658
+ }
659
+ function make_sector_list(sectors, dir_start, fat_addrs, ssz) {
660
+ var sl = sectors.length, sector_list = [];
661
+ var chkd = [], buf = [], buf_chain = [];
662
+ var modulus = ssz - 1, i2 = 0, j = 0, k = 0, jj = 0;
663
+ for (i2 = 0; i2 < sl; ++i2) {
664
+ buf = [];
665
+ k = i2 + dir_start;
666
+ if (k >= sl) k -= sl;
667
+ if (chkd[k]) continue;
668
+ buf_chain = [];
669
+ var seen = [];
670
+ for (j = k; j >= 0; ) {
671
+ seen[j] = true;
672
+ chkd[j] = true;
673
+ buf[buf.length] = j;
674
+ buf_chain.push(sectors[j]);
675
+ var addr = fat_addrs[Math.floor(j * 4 / ssz)];
676
+ jj = j * 4 & modulus;
677
+ if (ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 " + ssz);
678
+ if (!sectors[addr]) break;
679
+ j = __readInt32LE(sectors[addr], jj);
680
+ if (seen[j]) break;
681
+ }
682
+ sector_list[k] = { nodes: buf, data: __toBuffer([buf_chain]) };
683
+ }
684
+ return sector_list;
685
+ }
686
+ function read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, mini) {
687
+ var minifat_store = 0, pl = Paths.length ? 2 : 0;
688
+ var sector = sector_list[dir_start].data;
689
+ var i2 = 0, namelen = 0, name;
690
+ for (; i2 < sector.length; i2 += 128) {
691
+ var blob = sector.slice(i2, i2 + 128);
692
+ prep_blob(blob, 64);
693
+ namelen = blob.read_shift(2);
694
+ name = __utf16le(blob, 0, namelen - pl);
695
+ Paths.push(name);
696
+ var o = {
697
+ name,
698
+ type: blob.read_shift(1),
699
+ color: blob.read_shift(1),
700
+ L: blob.read_shift(4, "i"),
701
+ R: blob.read_shift(4, "i"),
702
+ C: blob.read_shift(4, "i"),
703
+ clsid: blob.read_shift(16),
704
+ state: blob.read_shift(4, "i"),
705
+ start: 0,
706
+ size: 0
707
+ };
708
+ var ctime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
709
+ if (ctime !== 0) o.ct = read_date(blob, blob.l - 8);
710
+ var mtime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
711
+ if (mtime !== 0) o.mt = read_date(blob, blob.l - 8);
712
+ o.start = blob.read_shift(4, "i");
713
+ o.size = blob.read_shift(4, "i");
714
+ if (o.size < 0 && o.start < 0) {
715
+ o.size = o.type = 0;
716
+ o.start = ENDOFCHAIN;
717
+ o.name = "";
718
+ }
719
+ if (o.type === 5) {
720
+ minifat_store = o.start;
721
+ if (nmfs > 0 && minifat_store !== ENDOFCHAIN) sector_list[minifat_store].name = "!StreamData";
722
+ } else if (o.size >= 4096) {
723
+ o.storage = "fat";
724
+ if (sector_list[o.start] === void 0) sector_list[o.start] = get_sector_list(sectors, o.start, sector_list.fat_addrs, sector_list.ssz);
725
+ sector_list[o.start].name = o.name;
726
+ o.content = sector_list[o.start].data.slice(0, o.size);
727
+ } else {
728
+ o.storage = "minifat";
729
+ if (o.size < 0) o.size = 0;
730
+ else if (minifat_store !== ENDOFCHAIN && o.start !== ENDOFCHAIN && sector_list[minifat_store]) {
731
+ o.content = get_mfat_entry(o, sector_list[minifat_store].data, (sector_list[mini] || {}).data);
732
+ }
733
+ }
734
+ if (o.content) prep_blob(o.content, 0);
735
+ files[name] = o;
736
+ FileIndex.push(o);
737
+ }
738
+ }
739
+ function read_date(blob, offset) {
740
+ return new Date((__readUInt32LE(blob, offset + 4) / 1e7 * Math.pow(2, 32) + __readUInt32LE(blob, offset) / 1e7 - 11644473600) * 1e3);
741
+ }
742
+ function read_file(filename2, options) {
743
+ get_fs();
744
+ return parse3(fs.readFileSync(filename2), options);
745
+ }
746
+ function read(blob, options) {
747
+ var type = options && options.type;
748
+ if (!type) {
749
+ if (has_buf && Buffer.isBuffer(blob)) type = "buffer";
750
+ }
751
+ switch (type || "base64") {
752
+ case "file":
753
+ return read_file(blob, options);
754
+ case "base64":
755
+ return parse3(s2a(Base64_decode(blob)), options);
756
+ case "binary":
757
+ return parse3(s2a(blob), options);
758
+ }
759
+ return parse3(blob, options);
760
+ }
761
+ function init_cfb(cfb, opts) {
762
+ var o = opts || {}, root = o.root || "Root Entry";
763
+ if (!cfb.FullPaths) cfb.FullPaths = [];
764
+ if (!cfb.FileIndex) cfb.FileIndex = [];
765
+ if (cfb.FullPaths.length !== cfb.FileIndex.length) throw new Error("inconsistent CFB structure");
766
+ if (cfb.FullPaths.length === 0) {
767
+ cfb.FullPaths[0] = root + "/";
768
+ cfb.FileIndex[0] = { name: root, type: 5 };
769
+ }
770
+ if (o.CLSID) cfb.FileIndex[0].clsid = o.CLSID;
771
+ seed_cfb(cfb);
772
+ }
773
+ function seed_cfb(cfb) {
774
+ var nm = "Sh33tJ5";
775
+ if (CFB2.find(cfb, "/" + nm)) return;
776
+ var p = new_buf(4);
777
+ p[0] = 55;
778
+ p[1] = p[3] = 50;
779
+ p[2] = 54;
780
+ cfb.FileIndex.push({ name: nm, type: 2, content: p, size: 4, L: 69, R: 69, C: 69 });
781
+ cfb.FullPaths.push(cfb.FullPaths[0] + nm);
782
+ rebuild_cfb(cfb);
783
+ }
784
+ function rebuild_cfb(cfb, f) {
785
+ init_cfb(cfb);
786
+ var gc = false, s = false;
787
+ for (var i2 = cfb.FullPaths.length - 1; i2 >= 0; --i2) {
788
+ var _file = cfb.FileIndex[i2];
789
+ switch (_file.type) {
790
+ case 0:
791
+ if (s) gc = true;
792
+ else {
793
+ cfb.FileIndex.pop();
794
+ cfb.FullPaths.pop();
795
+ }
796
+ break;
797
+ case 1:
798
+ case 2:
799
+ case 5:
800
+ s = true;
801
+ if (isNaN(_file.R * _file.L * _file.C)) gc = true;
802
+ if (_file.R > -1 && _file.L > -1 && _file.R == _file.L) gc = true;
803
+ break;
804
+ default:
805
+ gc = true;
806
+ break;
807
+ }
808
+ }
809
+ if (!gc && !f) return;
810
+ var now = new Date(1987, 1, 19), j = 0;
811
+ var fullPaths = Object.create ? /* @__PURE__ */ Object.create(null) : {};
812
+ var data = [];
813
+ for (i2 = 0; i2 < cfb.FullPaths.length; ++i2) {
814
+ fullPaths[cfb.FullPaths[i2]] = true;
815
+ if (cfb.FileIndex[i2].type === 0) continue;
816
+ data.push([cfb.FullPaths[i2], cfb.FileIndex[i2]]);
817
+ }
818
+ for (i2 = 0; i2 < data.length; ++i2) {
819
+ var dad = dirname(data[i2][0]);
820
+ s = fullPaths[dad];
821
+ while (!s) {
822
+ while (dirname(dad) && !fullPaths[dirname(dad)]) dad = dirname(dad);
823
+ data.push([dad, {
824
+ name: filename(dad).replace("/", ""),
825
+ type: 1,
826
+ clsid: HEADER_CLSID,
827
+ ct: now,
828
+ mt: now,
829
+ content: null
830
+ }]);
831
+ fullPaths[dad] = true;
832
+ dad = dirname(data[i2][0]);
833
+ s = fullPaths[dad];
834
+ }
835
+ }
836
+ data.sort(function(x, y) {
837
+ return namecmp(x[0], y[0]);
838
+ });
839
+ cfb.FullPaths = [];
840
+ cfb.FileIndex = [];
841
+ for (i2 = 0; i2 < data.length; ++i2) {
842
+ cfb.FullPaths[i2] = data[i2][0];
843
+ cfb.FileIndex[i2] = data[i2][1];
844
+ }
845
+ for (i2 = 0; i2 < data.length; ++i2) {
846
+ var elt = cfb.FileIndex[i2];
847
+ var nm = cfb.FullPaths[i2];
848
+ elt.name = filename(nm).replace("/", "");
849
+ elt.L = elt.R = elt.C = -(elt.color = 1);
850
+ elt.size = elt.content ? elt.content.length : 0;
851
+ elt.start = 0;
852
+ elt.clsid = elt.clsid || HEADER_CLSID;
853
+ if (i2 === 0) {
854
+ elt.C = data.length > 1 ? 1 : -1;
855
+ elt.size = 0;
856
+ elt.type = 5;
857
+ } else if (nm.slice(-1) == "/") {
858
+ for (j = i2 + 1; j < data.length; ++j) if (dirname(cfb.FullPaths[j]) == nm) break;
859
+ elt.C = j >= data.length ? -1 : j;
860
+ for (j = i2 + 1; j < data.length; ++j) if (dirname(cfb.FullPaths[j]) == dirname(nm)) break;
861
+ elt.R = j >= data.length ? -1 : j;
862
+ elt.type = 1;
863
+ } else {
864
+ if (dirname(cfb.FullPaths[i2 + 1] || "") == dirname(nm)) elt.R = i2 + 1;
865
+ elt.type = 2;
866
+ }
867
+ }
868
+ }
869
+ function _write(cfb, options) {
870
+ var _opts = options || {};
871
+ if (_opts.fileType == "mad") return write_mad(cfb, _opts);
872
+ rebuild_cfb(cfb);
873
+ switch (_opts.fileType) {
874
+ case "zip":
875
+ return write_zip(cfb, _opts);
876
+ }
877
+ var L = (function(cfb2) {
878
+ var mini_size = 0, fat_size = 0;
879
+ for (var i3 = 0; i3 < cfb2.FileIndex.length; ++i3) {
880
+ var file2 = cfb2.FileIndex[i3];
881
+ if (!file2.content) continue;
882
+ var flen2 = file2.content.length;
883
+ if (flen2 > 0) {
884
+ if (flen2 < 4096) mini_size += flen2 + 63 >> 6;
885
+ else fat_size += flen2 + 511 >> 9;
886
+ }
887
+ }
888
+ var dir_cnt = cfb2.FullPaths.length + 3 >> 2;
889
+ var mini_cnt = mini_size + 7 >> 3;
890
+ var mfat_cnt = mini_size + 127 >> 7;
891
+ var fat_base = mini_cnt + fat_size + dir_cnt + mfat_cnt;
892
+ var fat_cnt = fat_base + 127 >> 7;
893
+ var difat_cnt = fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt - 109) / 127);
894
+ while (fat_base + fat_cnt + difat_cnt + 127 >> 7 > fat_cnt) difat_cnt = ++fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt - 109) / 127);
895
+ var L2 = [1, difat_cnt, fat_cnt, mfat_cnt, dir_cnt, fat_size, mini_size, 0];
896
+ cfb2.FileIndex[0].size = mini_size << 6;
897
+ L2[7] = (cfb2.FileIndex[0].start = L2[0] + L2[1] + L2[2] + L2[3] + L2[4] + L2[5]) + (L2[6] + 7 >> 3);
898
+ return L2;
899
+ })(cfb);
900
+ var o = new_buf(L[7] << 9);
901
+ var i2 = 0, T = 0;
902
+ {
903
+ for (i2 = 0; i2 < 8; ++i2) o.write_shift(1, HEADER_SIG[i2]);
904
+ for (i2 = 0; i2 < 8; ++i2) o.write_shift(2, 0);
905
+ o.write_shift(2, 62);
906
+ o.write_shift(2, 3);
907
+ o.write_shift(2, 65534);
908
+ o.write_shift(2, 9);
909
+ o.write_shift(2, 6);
910
+ for (i2 = 0; i2 < 3; ++i2) o.write_shift(2, 0);
911
+ o.write_shift(4, 0);
912
+ o.write_shift(4, L[2]);
913
+ o.write_shift(4, L[0] + L[1] + L[2] + L[3] - 1);
914
+ o.write_shift(4, 0);
915
+ o.write_shift(4, 1 << 12);
916
+ o.write_shift(4, L[3] ? L[0] + L[1] + L[2] - 1 : ENDOFCHAIN);
917
+ o.write_shift(4, L[3]);
918
+ o.write_shift(-4, L[1] ? L[0] - 1 : ENDOFCHAIN);
919
+ o.write_shift(4, L[1]);
920
+ for (i2 = 0; i2 < 109; ++i2) o.write_shift(-4, i2 < L[2] ? L[1] + i2 : -1);
921
+ }
922
+ if (L[1]) {
923
+ for (T = 0; T < L[1]; ++T) {
924
+ for (; i2 < 236 + T * 127; ++i2) o.write_shift(-4, i2 < L[2] ? L[1] + i2 : -1);
925
+ o.write_shift(-4, T === L[1] - 1 ? ENDOFCHAIN : T + 1);
926
+ }
927
+ }
928
+ var chainit = function(w) {
929
+ for (T += w; i2 < T - 1; ++i2) o.write_shift(-4, i2 + 1);
930
+ if (w) {
931
+ ++i2;
932
+ o.write_shift(-4, ENDOFCHAIN);
933
+ }
934
+ };
935
+ T = i2 = 0;
936
+ for (T += L[1]; i2 < T; ++i2) o.write_shift(-4, consts.DIFSECT);
937
+ for (T += L[2]; i2 < T; ++i2) o.write_shift(-4, consts.FATSECT);
938
+ chainit(L[3]);
939
+ chainit(L[4]);
940
+ var j = 0, flen = 0;
941
+ var file = cfb.FileIndex[0];
942
+ for (; j < cfb.FileIndex.length; ++j) {
943
+ file = cfb.FileIndex[j];
944
+ if (!file.content) continue;
945
+ flen = file.content.length;
946
+ if (flen < 4096) continue;
947
+ file.start = T;
948
+ chainit(flen + 511 >> 9);
949
+ }
950
+ chainit(L[6] + 7 >> 3);
951
+ while (o.l & 511) o.write_shift(-4, consts.ENDOFCHAIN);
952
+ T = i2 = 0;
953
+ for (j = 0; j < cfb.FileIndex.length; ++j) {
954
+ file = cfb.FileIndex[j];
955
+ if (!file.content) continue;
956
+ flen = file.content.length;
957
+ if (!flen || flen >= 4096) continue;
958
+ file.start = T;
959
+ chainit(flen + 63 >> 6);
960
+ }
961
+ while (o.l & 511) o.write_shift(-4, consts.ENDOFCHAIN);
962
+ for (i2 = 0; i2 < L[4] << 2; ++i2) {
963
+ var nm = cfb.FullPaths[i2];
964
+ if (!nm || nm.length === 0) {
965
+ for (j = 0; j < 17; ++j) o.write_shift(4, 0);
966
+ for (j = 0; j < 3; ++j) o.write_shift(4, -1);
967
+ for (j = 0; j < 12; ++j) o.write_shift(4, 0);
968
+ continue;
969
+ }
970
+ file = cfb.FileIndex[i2];
971
+ if (i2 === 0) file.start = file.size ? file.start - 1 : ENDOFCHAIN;
972
+ var _nm = i2 === 0 && _opts.root || file.name;
973
+ if (_nm.length > 32) {
974
+ console.error("Name " + _nm + " will be truncated to " + _nm.slice(0, 32));
975
+ _nm = _nm.slice(0, 32);
976
+ }
977
+ flen = 2 * (_nm.length + 1);
978
+ o.write_shift(64, _nm, "utf16le");
979
+ o.write_shift(2, flen);
980
+ o.write_shift(1, file.type);
981
+ o.write_shift(1, file.color);
982
+ o.write_shift(-4, file.L);
983
+ o.write_shift(-4, file.R);
984
+ o.write_shift(-4, file.C);
985
+ if (!file.clsid) for (j = 0; j < 4; ++j) o.write_shift(4, 0);
986
+ else o.write_shift(16, file.clsid, "hex");
987
+ o.write_shift(4, file.state || 0);
988
+ o.write_shift(4, 0);
989
+ o.write_shift(4, 0);
990
+ o.write_shift(4, 0);
991
+ o.write_shift(4, 0);
992
+ o.write_shift(4, file.start);
993
+ o.write_shift(4, file.size);
994
+ o.write_shift(4, 0);
995
+ }
996
+ for (i2 = 1; i2 < cfb.FileIndex.length; ++i2) {
997
+ file = cfb.FileIndex[i2];
998
+ if (file.size >= 4096) {
999
+ o.l = file.start + 1 << 9;
1000
+ if (has_buf && Buffer.isBuffer(file.content)) {
1001
+ file.content.copy(o, o.l, 0, file.size);
1002
+ o.l += file.size + 511 & -512;
1003
+ } else {
1004
+ for (j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
1005
+ for (; j & 511; ++j) o.write_shift(1, 0);
1006
+ }
1007
+ }
1008
+ }
1009
+ for (i2 = 1; i2 < cfb.FileIndex.length; ++i2) {
1010
+ file = cfb.FileIndex[i2];
1011
+ if (file.size > 0 && file.size < 4096) {
1012
+ if (has_buf && Buffer.isBuffer(file.content)) {
1013
+ file.content.copy(o, o.l, 0, file.size);
1014
+ o.l += file.size + 63 & -64;
1015
+ } else {
1016
+ for (j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
1017
+ for (; j & 63; ++j) o.write_shift(1, 0);
1018
+ }
1019
+ }
1020
+ }
1021
+ if (has_buf) {
1022
+ o.l = o.length;
1023
+ } else {
1024
+ while (o.l < o.length) o.write_shift(1, 0);
1025
+ }
1026
+ return o;
1027
+ }
1028
+ function find2(cfb, path) {
1029
+ var UCFullPaths = cfb.FullPaths.map(function(x) {
1030
+ return x.toUpperCase();
1031
+ });
1032
+ var UCPaths = UCFullPaths.map(function(x) {
1033
+ var y = x.split("/");
1034
+ return y[y.length - (x.slice(-1) == "/" ? 2 : 1)];
1035
+ });
1036
+ var k = false;
1037
+ if (path.charCodeAt(0) === 47) {
1038
+ k = true;
1039
+ path = UCFullPaths[0].slice(0, -1) + path;
1040
+ } else k = path.indexOf("/") !== -1;
1041
+ var UCPath = path.toUpperCase();
1042
+ var w = k === true ? UCFullPaths.indexOf(UCPath) : UCPaths.indexOf(UCPath);
1043
+ if (w !== -1) return cfb.FileIndex[w];
1044
+ var m = !UCPath.match(chr1);
1045
+ UCPath = UCPath.replace(chr0, "");
1046
+ if (m) UCPath = UCPath.replace(chr1, "!");
1047
+ for (w = 0; w < UCFullPaths.length; ++w) {
1048
+ if ((m ? UCFullPaths[w].replace(chr1, "!") : UCFullPaths[w]).replace(chr0, "") == UCPath) return cfb.FileIndex[w];
1049
+ if ((m ? UCPaths[w].replace(chr1, "!") : UCPaths[w]).replace(chr0, "") == UCPath) return cfb.FileIndex[w];
1050
+ }
1051
+ return null;
1052
+ }
1053
+ var MSSZ = 64;
1054
+ var ENDOFCHAIN = -2;
1055
+ var HEADER_SIGNATURE = "d0cf11e0a1b11ae1";
1056
+ var HEADER_SIG = [208, 207, 17, 224, 161, 177, 26, 225];
1057
+ var HEADER_CLSID = "00000000000000000000000000000000";
1058
+ var consts = {
1059
+ /* 2.1 Compund File Sector Numbers and Types */
1060
+ MAXREGSECT: -6,
1061
+ DIFSECT: -4,
1062
+ FATSECT: -3,
1063
+ ENDOFCHAIN,
1064
+ FREESECT: -1,
1065
+ /* 2.2 Compound File Header */
1066
+ HEADER_SIGNATURE,
1067
+ HEADER_MINOR_VERSION: "3e00",
1068
+ MAXREGSID: -6,
1069
+ NOSTREAM: -1,
1070
+ HEADER_CLSID,
1071
+ /* 2.6.1 Compound File Directory Entry */
1072
+ EntryTypes: ["unknown", "storage", "stream", "lockbytes", "property", "root"]
1073
+ };
1074
+ function write_file(cfb, filename2, options) {
1075
+ get_fs();
1076
+ var o = _write(cfb, options);
1077
+ fs.writeFileSync(filename2, o);
1078
+ }
1079
+ function a2s(o) {
1080
+ var out = new Array(o.length);
1081
+ for (var i2 = 0; i2 < o.length; ++i2) out[i2] = String.fromCharCode(o[i2]);
1082
+ return out.join("");
1083
+ }
1084
+ function write(cfb, options) {
1085
+ var o = _write(cfb, options);
1086
+ switch (options && options.type || "buffer") {
1087
+ case "file":
1088
+ get_fs();
1089
+ fs.writeFileSync(options.filename, o);
1090
+ return o;
1091
+ case "binary":
1092
+ return typeof o == "string" ? o : a2s(o);
1093
+ case "base64":
1094
+ return Base64_encode(typeof o == "string" ? o : a2s(o));
1095
+ case "buffer":
1096
+ if (has_buf) return Buffer.isBuffer(o) ? o : Buffer_from(o);
1097
+ /* falls through */
1098
+ case "array":
1099
+ return typeof o == "string" ? s2a(o) : o;
1100
+ }
1101
+ return o;
1102
+ }
1103
+ var _zlib;
1104
+ function use_zlib(zlib) {
1105
+ try {
1106
+ var InflateRaw = zlib.InflateRaw;
1107
+ var InflRaw = new InflateRaw();
1108
+ InflRaw._processChunk(new Uint8Array([3, 0]), InflRaw._finishFlushFlag);
1109
+ if (InflRaw.bytesRead) _zlib = zlib;
1110
+ else throw new Error("zlib does not expose bytesRead");
1111
+ } catch (e) {
1112
+ console.error("cannot use native zlib: " + (e.message || e));
1113
+ }
1114
+ }
1115
+ function _inflateRawSync(payload, usz) {
1116
+ if (!_zlib) return _inflate(payload, usz);
1117
+ var InflateRaw = _zlib.InflateRaw;
1118
+ var InflRaw = new InflateRaw();
1119
+ var out = InflRaw._processChunk(payload.slice(payload.l), InflRaw._finishFlushFlag);
1120
+ payload.l += InflRaw.bytesRead;
1121
+ return out;
1122
+ }
1123
+ function _deflateRawSync(payload) {
1124
+ return _zlib ? _zlib.deflateRawSync(payload) : _deflate(payload);
1125
+ }
1126
+ var CLEN_ORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
1127
+ var LEN_LN = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258];
1128
+ var DST_LN = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577];
1129
+ function bit_swap_8(n) {
1130
+ var t = (n << 1 | n << 11) & 139536 | (n << 5 | n << 15) & 558144;
1131
+ return (t >> 16 | t >> 8 | t) & 255;
1132
+ }
1133
+ var use_typed_arrays = typeof Uint8Array !== "undefined";
1134
+ var bitswap8 = use_typed_arrays ? new Uint8Array(1 << 8) : [];
1135
+ for (var q = 0; q < 1 << 8; ++q) bitswap8[q] = bit_swap_8(q);
1136
+ function bit_swap_n(n, b) {
1137
+ var rev = bitswap8[n & 255];
1138
+ if (b <= 8) return rev >>> 8 - b;
1139
+ rev = rev << 8 | bitswap8[n >> 8 & 255];
1140
+ if (b <= 16) return rev >>> 16 - b;
1141
+ rev = rev << 8 | bitswap8[n >> 16 & 255];
1142
+ return rev >>> 24 - b;
1143
+ }
1144
+ function read_bits_2(buf, bl) {
1145
+ var w = bl & 7, h = bl >>> 3;
1146
+ return (buf[h] | (w <= 6 ? 0 : buf[h + 1] << 8)) >>> w & 3;
1147
+ }
1148
+ function read_bits_3(buf, bl) {
1149
+ var w = bl & 7, h = bl >>> 3;
1150
+ return (buf[h] | (w <= 5 ? 0 : buf[h + 1] << 8)) >>> w & 7;
1151
+ }
1152
+ function read_bits_4(buf, bl) {
1153
+ var w = bl & 7, h = bl >>> 3;
1154
+ return (buf[h] | (w <= 4 ? 0 : buf[h + 1] << 8)) >>> w & 15;
1155
+ }
1156
+ function read_bits_5(buf, bl) {
1157
+ var w = bl & 7, h = bl >>> 3;
1158
+ return (buf[h] | (w <= 3 ? 0 : buf[h + 1] << 8)) >>> w & 31;
1159
+ }
1160
+ function read_bits_7(buf, bl) {
1161
+ var w = bl & 7, h = bl >>> 3;
1162
+ return (buf[h] | (w <= 1 ? 0 : buf[h + 1] << 8)) >>> w & 127;
1163
+ }
1164
+ function read_bits_n(buf, bl, n) {
1165
+ var w = bl & 7, h = bl >>> 3, f = (1 << n) - 1;
1166
+ var v = buf[h] >>> w;
1167
+ if (n < 8 - w) return v & f;
1168
+ v |= buf[h + 1] << 8 - w;
1169
+ if (n < 16 - w) return v & f;
1170
+ v |= buf[h + 2] << 16 - w;
1171
+ if (n < 24 - w) return v & f;
1172
+ v |= buf[h + 3] << 24 - w;
1173
+ return v & f;
1174
+ }
1175
+ function write_bits_3(buf, bl, v) {
1176
+ var w = bl & 7, h = bl >>> 3;
1177
+ if (w <= 5) buf[h] |= (v & 7) << w;
1178
+ else {
1179
+ buf[h] |= v << w & 255;
1180
+ buf[h + 1] = (v & 7) >> 8 - w;
1181
+ }
1182
+ return bl + 3;
1183
+ }
1184
+ function write_bits_1(buf, bl, v) {
1185
+ var w = bl & 7, h = bl >>> 3;
1186
+ v = (v & 1) << w;
1187
+ buf[h] |= v;
1188
+ return bl + 1;
1189
+ }
1190
+ function write_bits_8(buf, bl, v) {
1191
+ var w = bl & 7, h = bl >>> 3;
1192
+ v <<= w;
1193
+ buf[h] |= v & 255;
1194
+ v >>>= 8;
1195
+ buf[h + 1] = v;
1196
+ return bl + 8;
1197
+ }
1198
+ function write_bits_16(buf, bl, v) {
1199
+ var w = bl & 7, h = bl >>> 3;
1200
+ v <<= w;
1201
+ buf[h] |= v & 255;
1202
+ v >>>= 8;
1203
+ buf[h + 1] = v & 255;
1204
+ buf[h + 2] = v >>> 8;
1205
+ return bl + 16;
1206
+ }
1207
+ function realloc(b, sz) {
1208
+ var L = b.length, M = 2 * L > sz ? 2 * L : sz + 5, i2 = 0;
1209
+ if (L >= sz) return b;
1210
+ if (has_buf) {
1211
+ var o = new_unsafe_buf(M);
1212
+ if (b.copy) b.copy(o);
1213
+ else for (; i2 < b.length; ++i2) o[i2] = b[i2];
1214
+ return o;
1215
+ } else if (use_typed_arrays) {
1216
+ var a = new Uint8Array(M);
1217
+ if (a.set) a.set(b);
1218
+ else for (; i2 < L; ++i2) a[i2] = b[i2];
1219
+ return a;
1220
+ }
1221
+ b.length = M;
1222
+ return b;
1223
+ }
1224
+ function zero_fill_array(n) {
1225
+ var o = new Array(n);
1226
+ for (var i2 = 0; i2 < n; ++i2) o[i2] = 0;
1227
+ return o;
1228
+ }
1229
+ function build_tree(clens, cmap, MAX) {
1230
+ var maxlen = 1, w = 0, i2 = 0, j = 0, ccode = 0, L = clens.length;
1231
+ var bl_count = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
1232
+ for (i2 = 0; i2 < 32; ++i2) bl_count[i2] = 0;
1233
+ for (i2 = L; i2 < MAX; ++i2) clens[i2] = 0;
1234
+ L = clens.length;
1235
+ var ctree = use_typed_arrays ? new Uint16Array(L) : zero_fill_array(L);
1236
+ for (i2 = 0; i2 < L; ++i2) {
1237
+ bl_count[w = clens[i2]]++;
1238
+ if (maxlen < w) maxlen = w;
1239
+ ctree[i2] = 0;
1240
+ }
1241
+ bl_count[0] = 0;
1242
+ for (i2 = 1; i2 <= maxlen; ++i2) bl_count[i2 + 16] = ccode = ccode + bl_count[i2 - 1] << 1;
1243
+ for (i2 = 0; i2 < L; ++i2) {
1244
+ ccode = clens[i2];
1245
+ if (ccode != 0) ctree[i2] = bl_count[ccode + 16]++;
1246
+ }
1247
+ var cleni = 0;
1248
+ for (i2 = 0; i2 < L; ++i2) {
1249
+ cleni = clens[i2];
1250
+ if (cleni != 0) {
1251
+ ccode = bit_swap_n(ctree[i2], maxlen) >> maxlen - cleni;
1252
+ for (j = (1 << maxlen + 4 - cleni) - 1; j >= 0; --j)
1253
+ cmap[ccode | j << cleni] = cleni & 15 | i2 << 4;
1254
+ }
1255
+ }
1256
+ return maxlen;
1257
+ }
1258
+ var fix_lmap = use_typed_arrays ? new Uint16Array(512) : zero_fill_array(512);
1259
+ var fix_dmap = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
1260
+ if (!use_typed_arrays) {
1261
+ for (var i = 0; i < 512; ++i) fix_lmap[i] = 0;
1262
+ for (i = 0; i < 32; ++i) fix_dmap[i] = 0;
1263
+ }
1264
+ (function() {
1265
+ var dlens = [];
1266
+ var i2 = 0;
1267
+ for (; i2 < 32; i2++) dlens.push(5);
1268
+ build_tree(dlens, fix_dmap, 32);
1269
+ var clens = [];
1270
+ i2 = 0;
1271
+ for (; i2 <= 143; i2++) clens.push(8);
1272
+ for (; i2 <= 255; i2++) clens.push(9);
1273
+ for (; i2 <= 279; i2++) clens.push(7);
1274
+ for (; i2 <= 287; i2++) clens.push(8);
1275
+ build_tree(clens, fix_lmap, 288);
1276
+ })();
1277
+ var _deflateRaw = (function _deflateRawIIFE() {
1278
+ var DST_LN_RE = use_typed_arrays ? new Uint8Array(32768) : [];
1279
+ var j = 0, k = 0;
1280
+ for (; j < DST_LN.length - 1; ++j) {
1281
+ for (; k < DST_LN[j + 1]; ++k) DST_LN_RE[k] = j;
1282
+ }
1283
+ for (; k < 32768; ++k) DST_LN_RE[k] = 29;
1284
+ var LEN_LN_RE = use_typed_arrays ? new Uint8Array(259) : [];
1285
+ for (j = 0, k = 0; j < LEN_LN.length - 1; ++j) {
1286
+ for (; k < LEN_LN[j + 1]; ++k) LEN_LN_RE[k] = j;
1287
+ }
1288
+ function write_stored(data, out) {
1289
+ var boff = 0;
1290
+ while (boff < data.length) {
1291
+ var L = Math.min(65535, data.length - boff);
1292
+ var h = boff + L == data.length;
1293
+ out.write_shift(1, +h);
1294
+ out.write_shift(2, L);
1295
+ out.write_shift(2, ~L & 65535);
1296
+ while (L-- > 0) out[out.l++] = data[boff++];
1297
+ }
1298
+ return out.l;
1299
+ }
1300
+ function write_huff_fixed(data, out) {
1301
+ var bl = 0;
1302
+ var boff = 0;
1303
+ var addrs = use_typed_arrays ? new Uint16Array(32768) : [];
1304
+ while (boff < data.length) {
1305
+ var L = (
1306
+ /* data.length - boff; */
1307
+ Math.min(65535, data.length - boff)
1308
+ );
1309
+ if (L < 10) {
1310
+ bl = write_bits_3(out, bl, +!!(boff + L == data.length));
1311
+ if (bl & 7) bl += 8 - (bl & 7);
1312
+ out.l = bl / 8 | 0;
1313
+ out.write_shift(2, L);
1314
+ out.write_shift(2, ~L & 65535);
1315
+ while (L-- > 0) out[out.l++] = data[boff++];
1316
+ bl = out.l * 8;
1317
+ continue;
1318
+ }
1319
+ bl = write_bits_3(out, bl, +!!(boff + L == data.length) + 2);
1320
+ var hash = 0;
1321
+ while (L-- > 0) {
1322
+ var d = data[boff];
1323
+ hash = (hash << 5 ^ d) & 32767;
1324
+ var match = -1, mlen = 0;
1325
+ if (match = addrs[hash]) {
1326
+ match |= boff & ~32767;
1327
+ if (match > boff) match -= 32768;
1328
+ if (match < boff) while (data[match + mlen] == data[boff + mlen] && mlen < 250) ++mlen;
1329
+ }
1330
+ if (mlen > 2) {
1331
+ d = LEN_LN_RE[mlen];
1332
+ if (d <= 22) bl = write_bits_8(out, bl, bitswap8[d + 1] >> 1) - 1;
1333
+ else {
1334
+ write_bits_8(out, bl, 3);
1335
+ bl += 5;
1336
+ write_bits_8(out, bl, bitswap8[d - 23] >> 5);
1337
+ bl += 3;
1338
+ }
1339
+ var len_eb = d < 8 ? 0 : d - 4 >> 2;
1340
+ if (len_eb > 0) {
1341
+ write_bits_16(out, bl, mlen - LEN_LN[d]);
1342
+ bl += len_eb;
1343
+ }
1344
+ d = DST_LN_RE[boff - match];
1345
+ bl = write_bits_8(out, bl, bitswap8[d] >> 3);
1346
+ bl -= 3;
1347
+ var dst_eb = d < 4 ? 0 : d - 2 >> 1;
1348
+ if (dst_eb > 0) {
1349
+ write_bits_16(out, bl, boff - match - DST_LN[d]);
1350
+ bl += dst_eb;
1351
+ }
1352
+ for (var q2 = 0; q2 < mlen; ++q2) {
1353
+ addrs[hash] = boff & 32767;
1354
+ hash = (hash << 5 ^ data[boff]) & 32767;
1355
+ ++boff;
1356
+ }
1357
+ L -= mlen - 1;
1358
+ } else {
1359
+ if (d <= 143) d = d + 48;
1360
+ else bl = write_bits_1(out, bl, 1);
1361
+ bl = write_bits_8(out, bl, bitswap8[d]);
1362
+ addrs[hash] = boff & 32767;
1363
+ ++boff;
1364
+ }
1365
+ }
1366
+ bl = write_bits_8(out, bl, 0) - 1;
1367
+ }
1368
+ out.l = (bl + 7) / 8 | 0;
1369
+ return out.l;
1370
+ }
1371
+ return function _deflateRaw2(data, out) {
1372
+ if (data.length < 8) return write_stored(data, out);
1373
+ return write_huff_fixed(data, out);
1374
+ };
1375
+ })();
1376
+ function _deflate(data) {
1377
+ var buf = new_buf(50 + Math.floor(data.length * 1.1));
1378
+ var off = _deflateRaw(data, buf);
1379
+ return buf.slice(0, off);
1380
+ }
1381
+ var dyn_lmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
1382
+ var dyn_dmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
1383
+ var dyn_cmap = use_typed_arrays ? new Uint16Array(128) : zero_fill_array(128);
1384
+ var dyn_len_1 = 1, dyn_len_2 = 1;
1385
+ function dyn(data, boff) {
1386
+ var _HLIT = read_bits_5(data, boff) + 257;
1387
+ boff += 5;
1388
+ var _HDIST = read_bits_5(data, boff) + 1;
1389
+ boff += 5;
1390
+ var _HCLEN = read_bits_4(data, boff) + 4;
1391
+ boff += 4;
1392
+ var w = 0;
1393
+ var clens = use_typed_arrays ? new Uint8Array(19) : zero_fill_array(19);
1394
+ var ctree = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1395
+ var maxlen = 1;
1396
+ var bl_count = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
1397
+ var next_code = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
1398
+ var L = clens.length;
1399
+ for (var i2 = 0; i2 < _HCLEN; ++i2) {
1400
+ clens[CLEN_ORDER[i2]] = w = read_bits_3(data, boff);
1401
+ if (maxlen < w) maxlen = w;
1402
+ bl_count[w]++;
1403
+ boff += 3;
1404
+ }
1405
+ var ccode = 0;
1406
+ bl_count[0] = 0;
1407
+ for (i2 = 1; i2 <= maxlen; ++i2) next_code[i2] = ccode = ccode + bl_count[i2 - 1] << 1;
1408
+ for (i2 = 0; i2 < L; ++i2) if ((ccode = clens[i2]) != 0) ctree[i2] = next_code[ccode]++;
1409
+ var cleni = 0;
1410
+ for (i2 = 0; i2 < L; ++i2) {
1411
+ cleni = clens[i2];
1412
+ if (cleni != 0) {
1413
+ ccode = bitswap8[ctree[i2]] >> 8 - cleni;
1414
+ for (var j = (1 << 7 - cleni) - 1; j >= 0; --j) dyn_cmap[ccode | j << cleni] = cleni & 7 | i2 << 3;
1415
+ }
1416
+ }
1417
+ var hcodes = [];
1418
+ maxlen = 1;
1419
+ for (; hcodes.length < _HLIT + _HDIST; ) {
1420
+ ccode = dyn_cmap[read_bits_7(data, boff)];
1421
+ boff += ccode & 7;
1422
+ switch (ccode >>>= 3) {
1423
+ case 16:
1424
+ w = 3 + read_bits_2(data, boff);
1425
+ boff += 2;
1426
+ ccode = hcodes[hcodes.length - 1];
1427
+ while (w-- > 0) hcodes.push(ccode);
1428
+ break;
1429
+ case 17:
1430
+ w = 3 + read_bits_3(data, boff);
1431
+ boff += 3;
1432
+ while (w-- > 0) hcodes.push(0);
1433
+ break;
1434
+ case 18:
1435
+ w = 11 + read_bits_7(data, boff);
1436
+ boff += 7;
1437
+ while (w-- > 0) hcodes.push(0);
1438
+ break;
1439
+ default:
1440
+ hcodes.push(ccode);
1441
+ if (maxlen < ccode) maxlen = ccode;
1442
+ break;
1443
+ }
1444
+ }
1445
+ var h1 = hcodes.slice(0, _HLIT), h2 = hcodes.slice(_HLIT);
1446
+ for (i2 = _HLIT; i2 < 286; ++i2) h1[i2] = 0;
1447
+ for (i2 = _HDIST; i2 < 30; ++i2) h2[i2] = 0;
1448
+ dyn_len_1 = build_tree(h1, dyn_lmap, 286);
1449
+ dyn_len_2 = build_tree(h2, dyn_dmap, 30);
1450
+ return boff;
1451
+ }
1452
+ function inflate(data, usz) {
1453
+ if (data[0] == 3 && !(data[1] & 3)) {
1454
+ return [new_raw_buf(usz), 2];
1455
+ }
1456
+ var boff = 0;
1457
+ var header = 0;
1458
+ var outbuf = new_unsafe_buf(usz ? usz : 1 << 18);
1459
+ var woff = 0;
1460
+ var OL = outbuf.length >>> 0;
1461
+ var max_len_1 = 0, max_len_2 = 0;
1462
+ while ((header & 1) == 0) {
1463
+ header = read_bits_3(data, boff);
1464
+ boff += 3;
1465
+ if (header >>> 1 == 0) {
1466
+ if (boff & 7) boff += 8 - (boff & 7);
1467
+ var sz = data[boff >>> 3] | data[(boff >>> 3) + 1] << 8;
1468
+ boff += 32;
1469
+ if (sz > 0) {
1470
+ if (!usz && OL < woff + sz) {
1471
+ outbuf = realloc(outbuf, woff + sz);
1472
+ OL = outbuf.length;
1473
+ }
1474
+ while (sz-- > 0) {
1475
+ outbuf[woff++] = data[boff >>> 3];
1476
+ boff += 8;
1477
+ }
1478
+ }
1479
+ continue;
1480
+ } else if (header >> 1 == 1) {
1481
+ max_len_1 = 9;
1482
+ max_len_2 = 5;
1483
+ } else {
1484
+ boff = dyn(data, boff);
1485
+ max_len_1 = dyn_len_1;
1486
+ max_len_2 = dyn_len_2;
1487
+ }
1488
+ for (; ; ) {
1489
+ if (!usz && OL < woff + 32767) {
1490
+ outbuf = realloc(outbuf, woff + 32767);
1491
+ OL = outbuf.length;
1492
+ }
1493
+ var bits = read_bits_n(data, boff, max_len_1);
1494
+ var code = header >>> 1 == 1 ? fix_lmap[bits] : dyn_lmap[bits];
1495
+ boff += code & 15;
1496
+ code >>>= 4;
1497
+ if ((code >>> 8 & 255) === 0) outbuf[woff++] = code;
1498
+ else if (code == 256) break;
1499
+ else {
1500
+ code -= 257;
1501
+ var len_eb = code < 8 ? 0 : code - 4 >> 2;
1502
+ if (len_eb > 5) len_eb = 0;
1503
+ var tgt = woff + LEN_LN[code];
1504
+ if (len_eb > 0) {
1505
+ tgt += read_bits_n(data, boff, len_eb);
1506
+ boff += len_eb;
1507
+ }
1508
+ bits = read_bits_n(data, boff, max_len_2);
1509
+ code = header >>> 1 == 1 ? fix_dmap[bits] : dyn_dmap[bits];
1510
+ boff += code & 15;
1511
+ code >>>= 4;
1512
+ var dst_eb = code < 4 ? 0 : code - 2 >> 1;
1513
+ var dst = DST_LN[code];
1514
+ if (dst_eb > 0) {
1515
+ dst += read_bits_n(data, boff, dst_eb);
1516
+ boff += dst_eb;
1517
+ }
1518
+ if (!usz && OL < tgt) {
1519
+ outbuf = realloc(outbuf, tgt + 100);
1520
+ OL = outbuf.length;
1521
+ }
1522
+ while (woff < tgt) {
1523
+ outbuf[woff] = outbuf[woff - dst];
1524
+ ++woff;
1525
+ }
1526
+ }
1527
+ }
1528
+ }
1529
+ if (usz) return [outbuf, boff + 7 >>> 3];
1530
+ return [outbuf.slice(0, woff), boff + 7 >>> 3];
1531
+ }
1532
+ function _inflate(payload, usz) {
1533
+ var data = payload.slice(payload.l || 0);
1534
+ var out = inflate(data, usz);
1535
+ payload.l += out[1];
1536
+ return out[0];
1537
+ }
1538
+ function warn_or_throw(wrn, msg) {
1539
+ if (wrn) {
1540
+ if (typeof console !== "undefined") console.error(msg);
1541
+ } else throw new Error(msg);
1542
+ }
1543
+ function parse_zip(file, options) {
1544
+ var blob = file;
1545
+ prep_blob(blob, 0);
1546
+ var FileIndex = [], FullPaths = [];
1547
+ var o = {
1548
+ FileIndex,
1549
+ FullPaths
1550
+ };
1551
+ init_cfb(o, { root: options.root });
1552
+ var i2 = blob.length - 4;
1553
+ while ((blob[i2] != 80 || blob[i2 + 1] != 75 || blob[i2 + 2] != 5 || blob[i2 + 3] != 6) && i2 >= 0) --i2;
1554
+ blob.l = i2 + 4;
1555
+ blob.l += 4;
1556
+ var fcnt = blob.read_shift(2);
1557
+ blob.l += 6;
1558
+ var start_cd = blob.read_shift(4);
1559
+ blob.l = start_cd;
1560
+ for (i2 = 0; i2 < fcnt; ++i2) {
1561
+ blob.l += 20;
1562
+ var csz = blob.read_shift(4);
1563
+ var usz = blob.read_shift(4);
1564
+ var namelen = blob.read_shift(2);
1565
+ var efsz = blob.read_shift(2);
1566
+ var fcsz = blob.read_shift(2);
1567
+ blob.l += 8;
1568
+ var offset = blob.read_shift(4);
1569
+ var EF = parse_extra_field(blob.slice(blob.l + namelen, blob.l + namelen + efsz));
1570
+ blob.l += namelen + efsz + fcsz;
1571
+ var L = blob.l;
1572
+ blob.l = offset + 4;
1573
+ parse_local_file(blob, csz, usz, o, EF);
1574
+ blob.l = L;
1575
+ }
1576
+ return o;
1577
+ }
1578
+ function parse_local_file(blob, csz, usz, o, EF) {
1579
+ blob.l += 2;
1580
+ var flags = blob.read_shift(2);
1581
+ var meth = blob.read_shift(2);
1582
+ var date = parse_dos_date(blob);
1583
+ if (flags & 8257) throw new Error("Unsupported ZIP encryption");
1584
+ var crc32 = blob.read_shift(4);
1585
+ var _csz = blob.read_shift(4);
1586
+ var _usz = blob.read_shift(4);
1587
+ var namelen = blob.read_shift(2);
1588
+ var efsz = blob.read_shift(2);
1589
+ var name = "";
1590
+ for (var i2 = 0; i2 < namelen; ++i2) name += String.fromCharCode(blob[blob.l++]);
1591
+ if (efsz) {
1592
+ var ef = parse_extra_field(blob.slice(blob.l, blob.l + efsz));
1593
+ if ((ef[21589] || {}).mt) date = ef[21589].mt;
1594
+ if (((EF || {})[21589] || {}).mt) date = EF[21589].mt;
1595
+ }
1596
+ blob.l += efsz;
1597
+ var data = blob.slice(blob.l, blob.l + _csz);
1598
+ switch (meth) {
1599
+ case 8:
1600
+ data = _inflateRawSync(blob, _usz);
1601
+ break;
1602
+ case 0:
1603
+ break;
1604
+ // TODO: scan for magic number
1605
+ default:
1606
+ throw new Error("Unsupported ZIP Compression method " + meth);
1607
+ }
1608
+ var wrn = false;
1609
+ if (flags & 8) {
1610
+ crc32 = blob.read_shift(4);
1611
+ if (crc32 == 134695760) {
1612
+ crc32 = blob.read_shift(4);
1613
+ wrn = true;
1614
+ }
1615
+ _csz = blob.read_shift(4);
1616
+ _usz = blob.read_shift(4);
1617
+ }
1618
+ if (_csz != csz) warn_or_throw(wrn, "Bad compressed size: " + csz + " != " + _csz);
1619
+ if (_usz != usz) warn_or_throw(wrn, "Bad uncompressed size: " + usz + " != " + _usz);
1620
+ var _crc32 = CRC32.buf(data, 0);
1621
+ if (crc32 >> 0 != _crc32 >> 0) warn_or_throw(wrn, "Bad CRC32 checksum: " + crc32 + " != " + _crc32);
1622
+ cfb_add(o, name, data, { unsafe: true, mt: date });
1623
+ }
1624
+ function write_zip(cfb, options) {
1625
+ var _opts = options || {};
1626
+ var out = [], cdirs = [];
1627
+ var o = new_buf(1);
1628
+ var method = _opts.compression ? 8 : 0, flags = 0;
1629
+ var desc = false;
1630
+ if (desc) flags |= 8;
1631
+ var i2 = 0, j = 0;
1632
+ var start_cd = 0, fcnt = 0;
1633
+ var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
1634
+ var crcs = [];
1635
+ var sz_cd = 0;
1636
+ for (i2 = 1; i2 < cfb.FullPaths.length; ++i2) {
1637
+ fp = cfb.FullPaths[i2].slice(root.length);
1638
+ fi = cfb.FileIndex[i2];
1639
+ if (!fi.size || !fi.content || fp == "Sh33tJ5") continue;
1640
+ var start = start_cd;
1641
+ var namebuf = new_buf(fp.length);
1642
+ for (j = 0; j < fp.length; ++j) namebuf.write_shift(1, fp.charCodeAt(j) & 127);
1643
+ namebuf = namebuf.slice(0, namebuf.l);
1644
+ crcs[fcnt] = CRC32.buf(fi.content, 0);
1645
+ var outbuf = fi.content;
1646
+ if (method == 8) outbuf = _deflateRawSync(outbuf);
1647
+ o = new_buf(30);
1648
+ o.write_shift(4, 67324752);
1649
+ o.write_shift(2, 20);
1650
+ o.write_shift(2, flags);
1651
+ o.write_shift(2, method);
1652
+ if (fi.mt) write_dos_date(o, fi.mt);
1653
+ else o.write_shift(4, 0);
1654
+ o.write_shift(-4, flags & 8 ? 0 : crcs[fcnt]);
1655
+ o.write_shift(4, flags & 8 ? 0 : outbuf.length);
1656
+ o.write_shift(4, flags & 8 ? 0 : fi.content.length);
1657
+ o.write_shift(2, namebuf.length);
1658
+ o.write_shift(2, 0);
1659
+ start_cd += o.length;
1660
+ out.push(o);
1661
+ start_cd += namebuf.length;
1662
+ out.push(namebuf);
1663
+ start_cd += outbuf.length;
1664
+ out.push(outbuf);
1665
+ if (flags & 8) {
1666
+ o = new_buf(12);
1667
+ o.write_shift(-4, crcs[fcnt]);
1668
+ o.write_shift(4, outbuf.length);
1669
+ o.write_shift(4, fi.content.length);
1670
+ start_cd += o.l;
1671
+ out.push(o);
1672
+ }
1673
+ o = new_buf(46);
1674
+ o.write_shift(4, 33639248);
1675
+ o.write_shift(2, 0);
1676
+ o.write_shift(2, 20);
1677
+ o.write_shift(2, flags);
1678
+ o.write_shift(2, method);
1679
+ o.write_shift(4, 0);
1680
+ o.write_shift(-4, crcs[fcnt]);
1681
+ o.write_shift(4, outbuf.length);
1682
+ o.write_shift(4, fi.content.length);
1683
+ o.write_shift(2, namebuf.length);
1684
+ o.write_shift(2, 0);
1685
+ o.write_shift(2, 0);
1686
+ o.write_shift(2, 0);
1687
+ o.write_shift(2, 0);
1688
+ o.write_shift(4, 0);
1689
+ o.write_shift(4, start);
1690
+ sz_cd += o.l;
1691
+ cdirs.push(o);
1692
+ sz_cd += namebuf.length;
1693
+ cdirs.push(namebuf);
1694
+ ++fcnt;
1695
+ }
1696
+ o = new_buf(22);
1697
+ o.write_shift(4, 101010256);
1698
+ o.write_shift(2, 0);
1699
+ o.write_shift(2, 0);
1700
+ o.write_shift(2, fcnt);
1701
+ o.write_shift(2, fcnt);
1702
+ o.write_shift(4, sz_cd);
1703
+ o.write_shift(4, start_cd);
1704
+ o.write_shift(2, 0);
1705
+ return bconcat([bconcat(out), bconcat(cdirs), o]);
1706
+ }
1707
+ var ContentTypeMap = {
1708
+ "htm": "text/html",
1709
+ "xml": "text/xml",
1710
+ "gif": "image/gif",
1711
+ "jpg": "image/jpeg",
1712
+ "png": "image/png",
1713
+ "mso": "application/x-mso",
1714
+ "thmx": "application/vnd.ms-officetheme",
1715
+ "sh33tj5": "application/octet-stream"
1716
+ };
1717
+ function get_content_type(fi, fp) {
1718
+ if (fi.ctype) return fi.ctype;
1719
+ var ext = fi.name || "", m = ext.match(/\.([^\.]+)$/);
1720
+ if (m && ContentTypeMap[m[1]]) return ContentTypeMap[m[1]];
1721
+ if (fp) {
1722
+ m = (ext = fp).match(/[\.\\]([^\.\\])+$/);
1723
+ if (m && ContentTypeMap[m[1]]) return ContentTypeMap[m[1]];
1724
+ }
1725
+ return "application/octet-stream";
1726
+ }
1727
+ function write_base64_76(bstr) {
1728
+ var data = Base64_encode(bstr);
1729
+ var o = [];
1730
+ for (var i2 = 0; i2 < data.length; i2 += 76) o.push(data.slice(i2, i2 + 76));
1731
+ return o.join("\r\n") + "\r\n";
1732
+ }
1733
+ function write_quoted_printable(text) {
1734
+ var encoded = text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF=]/g, function(c) {
1735
+ var w = c.charCodeAt(0).toString(16).toUpperCase();
1736
+ return "=" + (w.length == 1 ? "0" + w : w);
1737
+ });
1738
+ encoded = encoded.replace(/ $/mg, "=20").replace(/\t$/mg, "=09");
1739
+ if (encoded.charAt(0) == "\n") encoded = "=0D" + encoded.slice(1);
1740
+ encoded = encoded.replace(/\r(?!\n)/mg, "=0D").replace(/\n\n/mg, "\n=0A").replace(/([^\r\n])\n/mg, "$1=0A");
1741
+ var o = [], split = encoded.split("\r\n");
1742
+ for (var si = 0; si < split.length; ++si) {
1743
+ var str = split[si];
1744
+ if (str.length == 0) {
1745
+ o.push("");
1746
+ continue;
1747
+ }
1748
+ for (var i2 = 0; i2 < str.length; ) {
1749
+ var end = 76;
1750
+ var tmp = str.slice(i2, i2 + end);
1751
+ if (tmp.charAt(end - 1) == "=") end--;
1752
+ else if (tmp.charAt(end - 2) == "=") end -= 2;
1753
+ else if (tmp.charAt(end - 3) == "=") end -= 3;
1754
+ tmp = str.slice(i2, i2 + end);
1755
+ i2 += end;
1756
+ if (i2 < str.length) tmp += "=";
1757
+ o.push(tmp);
1758
+ }
1759
+ }
1760
+ return o.join("\r\n");
1761
+ }
1762
+ function parse_quoted_printable(data) {
1763
+ var o = [];
1764
+ for (var di = 0; di < data.length; ++di) {
1765
+ var line = data[di];
1766
+ while (di <= data.length && line.charAt(line.length - 1) == "=") line = line.slice(0, line.length - 1) + data[++di];
1767
+ o.push(line);
1768
+ }
1769
+ for (var oi = 0; oi < o.length; ++oi) o[oi] = o[oi].replace(/[=][0-9A-Fa-f]{2}/g, function($$) {
1770
+ return String.fromCharCode(parseInt($$.slice(1), 16));
1771
+ });
1772
+ return s2a(o.join("\r\n"));
1773
+ }
1774
+ function parse_mime(cfb, data, root) {
1775
+ var fname = "", cte = "", ctype = "", fdata;
1776
+ var di = 0;
1777
+ for (; di < 10; ++di) {
1778
+ var line = data[di];
1779
+ if (!line || line.match(/^\s*$/)) break;
1780
+ var m = line.match(/^(.*?):\s*([^\s].*)$/);
1781
+ if (m) switch (m[1].toLowerCase()) {
1782
+ case "content-location":
1783
+ fname = m[2].trim();
1784
+ break;
1785
+ case "content-type":
1786
+ ctype = m[2].trim();
1787
+ break;
1788
+ case "content-transfer-encoding":
1789
+ cte = m[2].trim();
1790
+ break;
1791
+ }
1792
+ }
1793
+ ++di;
1794
+ switch (cte.toLowerCase()) {
1795
+ case "base64":
1796
+ fdata = s2a(Base64_decode(data.slice(di).join("")));
1797
+ break;
1798
+ case "quoted-printable":
1799
+ fdata = parse_quoted_printable(data.slice(di));
1800
+ break;
1801
+ default:
1802
+ throw new Error("Unsupported Content-Transfer-Encoding " + cte);
1803
+ }
1804
+ var file = cfb_add(cfb, fname.slice(root.length), fdata, { unsafe: true });
1805
+ if (ctype) file.ctype = ctype;
1806
+ }
1807
+ function parse_mad(file, options) {
1808
+ if (a2s(file.slice(0, 13)).toLowerCase() != "mime-version:") throw new Error("Unsupported MAD header");
1809
+ var root = options && options.root || "";
1810
+ var data = (has_buf && Buffer.isBuffer(file) ? file.toString("binary") : a2s(file)).split("\r\n");
1811
+ var di = 0, row = "";
1812
+ for (di = 0; di < data.length; ++di) {
1813
+ row = data[di];
1814
+ if (!/^Content-Location:/i.test(row)) continue;
1815
+ row = row.slice(row.indexOf("file"));
1816
+ if (!root) root = row.slice(0, row.lastIndexOf("/") + 1);
1817
+ if (row.slice(0, root.length) == root) continue;
1818
+ while (root.length > 0) {
1819
+ root = root.slice(0, root.length - 1);
1820
+ root = root.slice(0, root.lastIndexOf("/") + 1);
1821
+ if (row.slice(0, root.length) == root) break;
1822
+ }
1823
+ }
1824
+ var mboundary = (data[1] || "").match(/boundary="(.*?)"/);
1825
+ if (!mboundary) throw new Error("MAD cannot find boundary");
1826
+ var boundary = "--" + (mboundary[1] || "");
1827
+ var FileIndex = [], FullPaths = [];
1828
+ var o = {
1829
+ FileIndex,
1830
+ FullPaths
1831
+ };
1832
+ init_cfb(o);
1833
+ var start_di, fcnt = 0;
1834
+ for (di = 0; di < data.length; ++di) {
1835
+ var line = data[di];
1836
+ if (line !== boundary && line !== boundary + "--") continue;
1837
+ if (fcnt++) parse_mime(o, data.slice(start_di, di), root);
1838
+ start_di = di;
1839
+ }
1840
+ return o;
1841
+ }
1842
+ function write_mad(cfb, options) {
1843
+ var opts = options || {};
1844
+ var boundary = opts.boundary || "SheetJS";
1845
+ boundary = "------=" + boundary;
1846
+ var out = [
1847
+ "MIME-Version: 1.0",
1848
+ 'Content-Type: multipart/related; boundary="' + boundary.slice(2) + '"',
1849
+ "",
1850
+ "",
1851
+ ""
1852
+ ];
1853
+ var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
1854
+ for (var i2 = 1; i2 < cfb.FullPaths.length; ++i2) {
1855
+ fp = cfb.FullPaths[i2].slice(root.length);
1856
+ fi = cfb.FileIndex[i2];
1857
+ if (!fi.size || !fi.content || fp == "Sh33tJ5") continue;
1858
+ fp = fp.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF]/g, function(c) {
1859
+ return "_x" + c.charCodeAt(0).toString(16) + "_";
1860
+ }).replace(/[\u0080-\uFFFF]/g, function(u) {
1861
+ return "_u" + u.charCodeAt(0).toString(16) + "_";
1862
+ });
1863
+ var ca = fi.content;
1864
+ var cstr = has_buf && Buffer.isBuffer(ca) ? ca.toString("binary") : a2s(ca);
1865
+ var dispcnt = 0, L = Math.min(1024, cstr.length), cc = 0;
1866
+ for (var csl = 0; csl <= L; ++csl) if ((cc = cstr.charCodeAt(csl)) >= 32 && cc < 128) ++dispcnt;
1867
+ var qp = dispcnt >= L * 4 / 5;
1868
+ out.push(boundary);
1869
+ out.push("Content-Location: " + (opts.root || "file:///C:/SheetJS/") + fp);
1870
+ out.push("Content-Transfer-Encoding: " + (qp ? "quoted-printable" : "base64"));
1871
+ out.push("Content-Type: " + get_content_type(fi, fp));
1872
+ out.push("");
1873
+ out.push(qp ? write_quoted_printable(cstr) : write_base64_76(cstr));
1874
+ }
1875
+ out.push(boundary + "--\r\n");
1876
+ return out.join("\r\n");
1877
+ }
1878
+ function cfb_new(opts) {
1879
+ var o = {};
1880
+ init_cfb(o, opts);
1881
+ return o;
1882
+ }
1883
+ function cfb_add(cfb, name, content, opts) {
1884
+ var unsafe = opts && opts.unsafe;
1885
+ if (!unsafe) init_cfb(cfb);
1886
+ var file = !unsafe && CFB2.find(cfb, name);
1887
+ if (!file) {
1888
+ var fpath = cfb.FullPaths[0];
1889
+ if (name.slice(0, fpath.length) == fpath) fpath = name;
1890
+ else {
1891
+ if (fpath.slice(-1) != "/") fpath += "/";
1892
+ fpath = (fpath + name).replace("//", "/");
1893
+ }
1894
+ file = { name: filename(name), type: 2 };
1895
+ cfb.FileIndex.push(file);
1896
+ cfb.FullPaths.push(fpath);
1897
+ if (!unsafe) CFB2.utils.cfb_gc(cfb);
1898
+ }
1899
+ file.content = content;
1900
+ file.size = content ? content.length : 0;
1901
+ if (opts) {
1902
+ if (opts.CLSID) file.clsid = opts.CLSID;
1903
+ if (opts.mt) file.mt = opts.mt;
1904
+ if (opts.ct) file.ct = opts.ct;
1905
+ }
1906
+ return file;
1907
+ }
1908
+ function cfb_del(cfb, name) {
1909
+ init_cfb(cfb);
1910
+ var file = CFB2.find(cfb, name);
1911
+ if (file) {
1912
+ for (var j = 0; j < cfb.FileIndex.length; ++j) if (cfb.FileIndex[j] == file) {
1913
+ cfb.FileIndex.splice(j, 1);
1914
+ cfb.FullPaths.splice(j, 1);
1915
+ return true;
1916
+ }
1917
+ }
1918
+ return false;
1919
+ }
1920
+ function cfb_mov(cfb, old_name, new_name) {
1921
+ init_cfb(cfb);
1922
+ var file = CFB2.find(cfb, old_name);
1923
+ if (file) {
1924
+ for (var j = 0; j < cfb.FileIndex.length; ++j) if (cfb.FileIndex[j] == file) {
1925
+ cfb.FileIndex[j].name = filename(new_name);
1926
+ cfb.FullPaths[j] = new_name;
1927
+ return true;
1928
+ }
1929
+ }
1930
+ return false;
1931
+ }
1932
+ function cfb_gc(cfb) {
1933
+ rebuild_cfb(cfb, true);
1934
+ }
1935
+ exports2.find = find2;
1936
+ exports2.read = read;
1937
+ exports2.parse = parse3;
1938
+ exports2.write = write;
1939
+ exports2.writeFile = write_file;
1940
+ exports2.utils = {
1941
+ cfb_new,
1942
+ cfb_add,
1943
+ cfb_del,
1944
+ cfb_mov,
1945
+ cfb_gc,
1946
+ ReadShift,
1947
+ CheckField,
1948
+ prep_blob,
1949
+ bconcat,
1950
+ use_zlib,
1951
+ _deflateRaw: _deflate,
1952
+ _inflateRaw: _inflate,
1953
+ consts
1954
+ };
1955
+ return exports2;
1956
+ })();
1957
+ if (typeof __require !== "undefined" && typeof module !== "undefined" && typeof DO_NOT_EXPORT_CFB === "undefined") {
1958
+ module.exports = CFB2;
1959
+ }
1960
+ }
1961
+ });
1962
+
1963
+ // src/ocr/auto-detect.ts
1964
+ import { execSync } from "child_process";
1965
+ function detectAvailableOcr() {
1966
+ for (const cli of CLI_PRIORITY) {
1967
+ if (isCliInstalled(cli)) return cli;
1968
+ }
1969
+ return "tesseract";
1970
+ }
1971
+ function isCliInstalled(name) {
1972
+ try {
1973
+ const cmd = process.platform === "win32" ? "where" : "which";
1974
+ execSync(`${cmd} ${name}`, { stdio: "ignore", timeout: 3e3 });
1975
+ return true;
1976
+ } catch {
1977
+ return false;
1978
+ }
1979
+ }
1980
+ function validateOcrMode(mode) {
1981
+ if (mode === "auto" || mode === "off" || mode === "tesseract") return;
1982
+ if (!isCliInstalled(mode)) {
1983
+ throw new Error(`'${mode}' CLI\uAC00 \uC124\uCE58\uB418\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.
1984
+ ${getInstallGuide(mode)}`);
1985
+ }
1986
+ }
1987
+ function getInstallGuide(mode) {
1988
+ const guides = {
1989
+ gemini: "\uC124\uCE58: https://ai.google.dev/gemini-api/docs/cli",
1990
+ claude: "\uC124\uCE58: npm install -g @anthropic-ai/claude-code \uB610\uB294 https://claude.ai/code",
1991
+ codex: "\uC124\uCE58: npm install -g @openai/codex \uB610\uB294 https://github.com/openai/codex",
1992
+ ollama: "\uC124\uCE58: brew install ollama \uB610\uB294 https://ollama.com/download"
1993
+ };
1994
+ return guides[mode] || `'${mode}'\uC744(\uB97C) \uC124\uCE58\uD574\uC8FC\uC138\uC694.`;
1995
+ }
1996
+ function getTesseractFallbackMessage() {
1997
+ return [
1998
+ "\uC124\uCE58\uB41C AI CLI\uAC00 \uC5C6\uC5B4 \uB0B4\uC7A5 tesseract.js\uB85C OCR\uC744 \uC218\uD589\uD569\uB2C8\uB2E4.",
1999
+ "\uB354 \uB098\uC740 \uD488\uC9C8(\uD14C\uC774\uBE14/\uD5E4\uB529 \uAD6C\uC870 \uBCF4\uC874)\uC744 \uC704\uD574 AI CLI \uC124\uCE58\uB97C \uAD8C\uC7A5\uD569\uB2C8\uB2E4:",
2000
+ "",
2001
+ " [\uAD8C\uC7A5] Gemini CLI: https://ai.google.dev/gemini-api/docs/cli",
2002
+ " Claude CLI: npm install -g @anthropic-ai/claude-code",
2003
+ " Codex CLI: npm install -g @openai/codex",
2004
+ " Ollama: brew install ollama (+ ollama pull gemma4:27b)"
2005
+ ].join("\n");
2006
+ }
2007
+ var CLI_PRIORITY;
2008
+ var init_auto_detect = __esm({
2009
+ "src/ocr/auto-detect.ts"() {
2010
+ "use strict";
2011
+ CLI_PRIORITY = ["gemini", "claude", "codex", "ollama"];
2012
+ }
2013
+ });
2014
+
2015
+ // src/ocr/cli-provider.ts
2016
+ import { spawnSync } from "child_process";
2017
+ import { writeFileSync, unlinkSync, mkdtempSync } from "fs";
2018
+ import { join } from "path";
2019
+ import { tmpdir } from "os";
2020
+ function getTempDir() {
2021
+ if (!_tempDir) _tempDir = mkdtempSync(join(tmpdir(), "kordoc-ocr-"));
2022
+ return _tempDir;
2023
+ }
2024
+ function createCliOcrProvider(mode) {
2025
+ return async (pageImage, pageNumber) => {
2026
+ const tempPath = join(getTempDir(), `page-${pageNumber}.png`);
2027
+ try {
2028
+ writeFileSync(tempPath, pageImage);
2029
+ let output;
2030
+ if (mode === "ollama") {
2031
+ output = await callOllamaApi(tempPath);
2032
+ } else {
2033
+ output = callCli(mode, tempPath);
2034
+ }
2035
+ return { markdown: stripCodeFence(output.trim()) };
2036
+ } finally {
2037
+ try {
2038
+ unlinkSync(tempPath);
2039
+ } catch {
2040
+ }
2041
+ }
2042
+ };
2043
+ }
2044
+ function callCli(mode, imagePath) {
2045
+ const args = buildCliArgs(mode, imagePath);
2046
+ const result = spawnSync(mode === "codex" ? "codex" : mode, args, {
2047
+ encoding: "utf-8",
2048
+ timeout: 6e4,
2049
+ maxBuffer: 10 * 1024 * 1024
2050
+ });
2051
+ if (result.error) {
2052
+ throw new Error(`${mode} CLI \uC2E4\uD589 \uC2E4\uD328: ${result.error.message}`);
2053
+ }
2054
+ if (result.status !== 0) {
2055
+ const errMsg = result.stderr?.trim() || `exit code ${result.status}`;
2056
+ throw new Error(`${mode} OCR \uC2E4\uD328: ${errMsg}`);
2057
+ }
2058
+ return result.stdout || "";
2059
+ }
2060
+ function buildCliArgs(mode, imagePath) {
2061
+ const promptWithImage = `${OCR_PROMPT}
2062
+
2063
+ \uC774\uBBF8\uC9C0: @${imagePath}`;
2064
+ const promptOnly = OCR_PROMPT;
2065
+ switch (mode) {
2066
+ case "gemini":
2067
+ return ["--prompt", promptWithImage, "--yolo"];
2068
+ case "claude":
2069
+ return ["--print", promptWithImage];
2070
+ case "codex":
2071
+ return ["exec", "--image", imagePath, promptOnly];
2072
+ default:
2073
+ throw new Error(`\uC9C0\uC6D0\uD558\uC9C0 \uC54A\uB294 CLI: ${mode}`);
2074
+ }
2075
+ }
2076
+ async function callOllamaApi(imagePath) {
2077
+ const { readFileSync } = await import("fs");
2078
+ const imageBase64 = readFileSync(imagePath).toString("base64");
2079
+ const model = process.env.KORDOC_OLLAMA_MODEL || "gemma4:27b";
2080
+ const host = process.env.KORDOC_OLLAMA_HOST || "http://localhost:11434";
2081
+ const response = await fetch(`${host}/api/chat`, {
2082
+ method: "POST",
2083
+ headers: { "Content-Type": "application/json" },
2084
+ body: JSON.stringify({
2085
+ model,
2086
+ messages: [{
2087
+ role: "user",
2088
+ content: OCR_PROMPT,
2089
+ images: [imageBase64]
2090
+ }],
2091
+ stream: false
2092
+ }),
2093
+ signal: AbortSignal.timeout(6e4)
2094
+ });
2095
+ if (!response.ok) {
2096
+ throw new Error(`Ollama API \uC624\uB958: ${response.status} ${response.statusText}`);
2097
+ }
2098
+ const data = await response.json();
2099
+ return data.message?.content || "";
2100
+ }
2101
+ function stripCodeFence(text) {
2102
+ const match = text.match(/^```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/m);
2103
+ return match ? match[1].trim() : text;
2104
+ }
2105
+ var OCR_PROMPT, _tempDir;
2106
+ var init_cli_provider = __esm({
2107
+ "src/ocr/cli-provider.ts"() {
2108
+ "use strict";
2109
+ OCR_PROMPT = "\uC774 PDF \uD398\uC774\uC9C0 \uC774\uBBF8\uC9C0\uC5D0\uC11C \uD14D\uC2A4\uD2B8\uC640 \uD14C\uC774\uBE14\uC744 \uCD94\uCD9C\uD558\uC5EC \uC21C\uC218 Markdown\uC73C\uB85C \uBCC0\uD658\uD558\uC138\uC694.\n\uADDC\uCE59:\n- \uD14C\uC774\uBE14\uC740 Markdown \uD14C\uC774\uBE14 \uBB38\uBC95 \uC0AC\uC6A9 (| \uAD6C\uBD84, |---|---| \uD5E4\uB354 \uAD6C\uBD84\uC120 \uD3EC\uD568)\n- \uBCD1\uD569\uB41C \uC140\uC740 \uD574\uB2F9 \uC704\uCE58\uC5D0 \uB0B4\uC6A9 \uAE30\uC7AC\n- \uD5E4\uB529\uC740 \uAE00\uC790 \uD06C\uAE30\uC5D0 \uB530\uB77C ## ~ ###### \uC0AC\uC6A9\n- \uB9AC\uC2A4\uD2B8\uB294 - \uB610\uB294 1. \uC0AC\uC6A9\n- \uC774\uBBF8\uC9C0, \uB3C4\uD615 \uB4F1 \uBE44\uD14D\uC2A4\uD2B8 \uC694\uC18C\uB294 \uBB34\uC2DC\n- \uC6D0\uBB38\uC758 \uC77D\uAE30 \uC21C\uC11C\uC640 \uAD6C\uC870\uB97C \uC720\uC9C0\n- ```\uB85C \uAC10\uC2F8\uC9C0 \uB9D0\uACE0 \uC21C\uC218 Markdown\uB9CC \uCD9C\uB825";
2110
+ _tempDir = null;
2111
+ }
2112
+ });
2113
+
2114
+ // src/ocr/tesseract-provider.ts
2115
+ var tesseract_provider_exports = {};
2116
+ __export(tesseract_provider_exports, {
2117
+ createTesseractProvider: () => createTesseractProvider
2118
+ });
2119
+ import { createWorker } from "tesseract.js";
2120
+ async function createTesseractProvider() {
2121
+ const worker = await createWorker("kor+eng");
2122
+ let terminated = false;
2123
+ const provider = async (pageImage, _pageNumber, _mimeType) => {
2124
+ const { data } = await worker.recognize(pageImage);
2125
+ return data.text;
2126
+ };
2127
+ provider.terminate = async () => {
2128
+ if (!terminated) {
2129
+ await worker.terminate();
2130
+ terminated = true;
2131
+ }
2132
+ };
2133
+ return provider;
2134
+ }
2135
+ var init_tesseract_provider = __esm({
2136
+ "src/ocr/tesseract-provider.ts"() {
2137
+ "use strict";
2138
+ }
2139
+ });
2140
+
2141
+ // src/ocr/resolve.ts
2142
+ var resolve_exports = {};
2143
+ __export(resolve_exports, {
2144
+ resolveOcrProvider: () => resolveOcrProvider
2145
+ });
2146
+ async function resolveOcrProvider(mode, warnings) {
2147
+ if (mode === "off") {
2148
+ throw new Error("OCR\uC774 \uBE44\uD65C\uC131\uD654\uB418\uC5B4 \uC788\uC2B5\uB2C8\uB2E4 (--ocr off).");
2149
+ }
2150
+ if (mode !== "auto") {
2151
+ validateOcrMode(mode);
2152
+ if (mode === "tesseract") {
2153
+ const { createTesseractProvider: createTesseractProvider2 } = await Promise.resolve().then(() => (init_tesseract_provider(), tesseract_provider_exports));
2154
+ return createTesseractProvider2();
2155
+ }
2156
+ return createCliOcrProvider(mode);
2157
+ }
2158
+ const detected = detectAvailableOcr();
2159
+ if (detected !== "gemini") {
2160
+ if (detected === "tesseract") {
2161
+ warnings?.push({
2162
+ message: getTesseractFallbackMessage(),
2163
+ code: "OCR_CLI_FALLBACK"
2164
+ });
2165
+ } else {
2166
+ warnings?.push({
2167
+ message: `OCR: '${detected}' \uC0AC\uC6A9 \uC911 (gemini CLI\uAC00 \uC5C6\uC5B4 fallback). \uB354 \uB098\uC740 \uD488\uC9C8\uC744 \uC704\uD574 gemini CLI \uC124\uCE58\uB97C \uAD8C\uC7A5\uD569\uB2C8\uB2E4.`,
2168
+ code: "OCR_CLI_FALLBACK"
2169
+ });
2170
+ }
2171
+ }
2172
+ if (detected === "tesseract") {
2173
+ const { createTesseractProvider: createTesseractProvider2 } = await Promise.resolve().then(() => (init_tesseract_provider(), tesseract_provider_exports));
2174
+ return createTesseractProvider2();
2175
+ }
2176
+ return createCliOcrProvider(detected);
2177
+ }
2178
+ var init_resolve = __esm({
2179
+ "src/ocr/resolve.ts"() {
2180
+ "use strict";
2181
+ init_auto_detect();
2182
+ init_cli_provider();
2183
+ }
2184
+ });
2185
+
2186
+ // src/ocr/markdown-to-blocks.ts
2187
+ function markdownToBlocks(markdown, pageNumber) {
2188
+ const blocks = [];
2189
+ const lines = markdown.split("\n");
2190
+ let i = 0;
2191
+ while (i < lines.length) {
2192
+ const line = lines[i];
2193
+ if (line.trim() === "") {
2194
+ i++;
2195
+ continue;
2196
+ }
2197
+ const headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
2198
+ if (headingMatch) {
2199
+ blocks.push({
2200
+ type: "heading",
2201
+ level: headingMatch[1].length,
2202
+ text: headingMatch[2].trim(),
2203
+ pageNumber
2204
+ });
2205
+ i++;
2206
+ continue;
2207
+ }
2208
+ if (/^[-*_]{3,}\s*$/.test(line.trim())) {
2209
+ blocks.push({ type: "separator", pageNumber });
2210
+ i++;
2211
+ continue;
2212
+ }
2213
+ if (line.trim().startsWith("|")) {
2214
+ const tableLines = [];
2215
+ while (i < lines.length && lines[i].trim().startsWith("|")) {
2216
+ tableLines.push(lines[i]);
2217
+ i++;
2218
+ }
2219
+ const table = parseMarkdownTable(tableLines);
2220
+ if (table) {
2221
+ blocks.push({ type: "table", table, pageNumber });
2222
+ }
2223
+ continue;
2224
+ }
2225
+ const ulMatch = line.match(/^(\s*)[-*+]\s+(.+)$/);
2226
+ if (ulMatch) {
2227
+ blocks.push({
2228
+ type: "list",
2229
+ listType: "unordered",
2230
+ text: ulMatch[2].trim(),
2231
+ pageNumber
2232
+ });
2233
+ i++;
2234
+ continue;
2235
+ }
2236
+ const olMatch = line.match(/^(\s*)\d+\.\s+(.+)$/);
2237
+ if (olMatch) {
2238
+ blocks.push({
2239
+ type: "list",
2240
+ listType: "ordered",
2241
+ text: olMatch[2].trim(),
2242
+ pageNumber
2243
+ });
2244
+ i++;
2245
+ continue;
2246
+ }
2247
+ const paraLines = [];
2248
+ while (i < lines.length && lines[i].trim() !== "" && !isStructuralLine(lines[i])) {
2249
+ paraLines.push(lines[i].trim());
2250
+ i++;
2251
+ }
2252
+ if (paraLines.length > 0) {
2253
+ blocks.push({
2254
+ type: "paragraph",
2255
+ text: paraLines.join("\n"),
2256
+ pageNumber
2257
+ });
2258
+ }
25
2259
  }
26
- if (typeof spec !== "string" || spec.trim() === "") return result;
27
- const parts = spec.split(",");
28
- for (const part of parts) {
29
- const trimmed = part.trim();
30
- if (!trimmed) continue;
31
- const rangeMatch = trimmed.match(/^(\d+)\s*-\s*(\d+)$/);
32
- if (rangeMatch) {
33
- const start = Math.max(1, parseInt(rangeMatch[1], 10));
34
- const end = Math.min(maxPages, parseInt(rangeMatch[2], 10));
35
- for (let i = start; i <= end; i++) result.add(i);
36
- } else {
37
- const page = parseInt(trimmed, 10);
38
- if (!isNaN(page) && page >= 1 && page <= maxPages) result.add(page);
2260
+ return blocks;
2261
+ }
2262
+ function isStructuralLine(line) {
2263
+ if (/^#{1,6}\s+/.test(line)) return true;
2264
+ if (line.trim().startsWith("|")) return true;
2265
+ if (/^[-*_]{3,}\s*$/.test(line.trim())) return true;
2266
+ if (/^\s*[-*+]\s+/.test(line)) return true;
2267
+ if (/^\s*\d+\.\s+/.test(line)) return true;
2268
+ return false;
2269
+ }
2270
+ function parseMarkdownTable(lines) {
2271
+ const hasSeparator = lines.some((line) => /^\|[\s:|-]+\|$/.test(line.trim()));
2272
+ const rows = [];
2273
+ let maxCols = 0;
2274
+ for (const line of lines) {
2275
+ if (/^\|\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/.test(line.trim())) continue;
2276
+ const parts = line.split("|");
2277
+ const cells = parts.slice(1, parts[parts.length - 1].trim() === "" ? -1 : void 0).map((cell) => ({
2278
+ text: cell.trim(),
2279
+ colSpan: 1,
2280
+ rowSpan: 1
2281
+ }));
2282
+ if (cells.length > 0) {
2283
+ rows.push(cells);
2284
+ maxCols = Math.max(maxCols, cells.length);
39
2285
  }
40
2286
  }
41
- return result;
2287
+ if (rows.length === 0) return null;
2288
+ for (const row of rows) {
2289
+ while (row.length < maxCols) {
2290
+ row.push({ text: "", colSpan: 1, rowSpan: 1 });
2291
+ }
2292
+ }
2293
+ return {
2294
+ rows: rows.length,
2295
+ cols: maxCols,
2296
+ cells: rows,
2297
+ hasHeader: hasSeparator && rows.length > 1
2298
+ };
42
2299
  }
43
- var init_page_range = __esm({
44
- "src/page-range.ts"() {
2300
+ var init_markdown_to_blocks = __esm({
2301
+ "src/ocr/markdown-to-blocks.ts"() {
45
2302
  "use strict";
46
2303
  }
47
2304
  });
@@ -51,18 +2308,31 @@ var provider_exports = {};
51
2308
  __export(provider_exports, {
52
2309
  ocrPages: () => ocrPages
53
2310
  });
54
- async function ocrPages(doc, provider, pageFilter, effectivePageCount) {
2311
+ async function ocrPages(doc, provider, pageFilter, effectivePageCount, warnings) {
55
2312
  const blocks = [];
56
2313
  for (let i = 1; i <= effectivePageCount; i++) {
57
2314
  if (pageFilter && !pageFilter.has(i)) continue;
58
2315
  const page = await doc.getPage(i);
59
2316
  try {
60
2317
  const imageData = await renderPageToPng(page);
61
- const text = await provider(imageData, i, "image/png");
62
- if (text.trim()) {
63
- blocks.push({ type: "paragraph", text: text.trim(), pageNumber: i });
2318
+ const result = await provider(imageData, i, "image/png");
2319
+ if (typeof result === "string") {
2320
+ if (result.trim()) {
2321
+ blocks.push({ type: "paragraph", text: result.trim(), pageNumber: i });
2322
+ }
2323
+ } else if (result && typeof result === "object" && "markdown" in result) {
2324
+ const structured = result;
2325
+ if (structured.markdown.trim()) {
2326
+ const pageBlocks = markdownToBlocks(structured.markdown, i);
2327
+ for (const b of pageBlocks) blocks.push(b);
2328
+ }
64
2329
  }
65
- } catch {
2330
+ } catch (err) {
2331
+ warnings?.push({
2332
+ page: i,
2333
+ message: `\uD398\uC774\uC9C0 ${i} OCR \uC2E4\uD328: ${err instanceof Error ? err.message : "\uC54C \uC218 \uC5C6\uB294 \uC624\uB958"}`,
2334
+ code: "OCR_PAGE_FAILED"
2335
+ });
66
2336
  }
67
2337
  }
68
2338
  return blocks;
@@ -85,6 +2355,7 @@ async function renderPageToPng(page) {
85
2355
  var init_provider = __esm({
86
2356
  "src/ocr/provider.ts"() {
87
2357
  "use strict";
2358
+ init_markdown_to_blocks();
88
2359
  }
89
2360
  });
90
2361
 
@@ -137,7 +2408,7 @@ import JSZip2 from "jszip";
137
2408
  import { DOMParser } from "@xmldom/xmldom";
138
2409
 
139
2410
  // src/utils.ts
140
- var VERSION = true ? "2.1.6" : "0.0.0-dev";
2411
+ var VERSION = true ? "2.2.1" : "0.0.0-dev";
141
2412
  function toArrayBuffer(buf) {
142
2413
  if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
143
2414
  return buf.buffer;
@@ -470,7 +2741,7 @@ var HEADING_RATIO_H3 = 1.15;
470
2741
  // src/hwpx/parser.ts
471
2742
  init_page_range();
472
2743
  var MAX_DECOMPRESS_SIZE = 500 * 1024 * 1024;
473
- var MAX_ZIP_ENTRIES = 500;
2744
+ var MAX_ZIP_ENTRIES = 2e3;
474
2745
  function clampSpan(val, max) {
475
2746
  return Math.max(1, Math.min(val, max));
476
2747
  }
@@ -629,6 +2900,16 @@ function imageExtToMime(ext) {
629
2900
  return "application/octet-stream";
630
2901
  }
631
2902
  }
2903
+ function detectImageMimeFromBytes(data) {
2904
+ if (data.length >= 3 && data[0] === 255 && data[1] === 216 && data[2] === 255) return "image/jpeg";
2905
+ if (data.length >= 4 && data[0] === 137 && data[1] === 80 && data[2] === 78 && data[3] === 71) return "image/png";
2906
+ if (data.length >= 3 && data[0] === 71 && data[1] === 73 && data[2] === 70) return "image/gif";
2907
+ if (data.length >= 2 && data[0] === 66 && data[1] === 77) return "image/bmp";
2908
+ if (data.length >= 4 && data[0] === 215 && data[1] === 205 && data[2] === 198 && data[3] === 154) return "image/wmf";
2909
+ if (data.length >= 4 && (data[0] === 1 || data[0] === 2) && data[1] === 0 && data[2] === 9 && data[3] === 0) return "image/wmf";
2910
+ if (data.length >= 4 && data[0] === 1 && data[1] === 0 && data[2] === 0 && data[3] === 0) return "image/emf";
2911
+ return "image/png";
2912
+ }
632
2913
  function mimeToExt(mime) {
633
2914
  if (mime.includes("jpeg")) return "jpg";
634
2915
  if (mime.includes("png")) return "png";
@@ -646,12 +2927,12 @@ async function extractImagesFromZip(zip, blocks, decompressed, warnings) {
646
2927
  for (const block of blocks) {
647
2928
  if (block.type !== "image" || !block.text) continue;
648
2929
  const ref = block.text;
649
- const candidates = [
650
- `BinData/${ref}`,
651
- `Contents/BinData/${ref}`,
652
- ref
653
- // 절대 경로일 수도 있음
654
- ];
2930
+ const exts = ref.includes(".") ? [""] : [".jpg", ".jpeg", ".png", ".bmp", ".gif", ".wmf", ".emf", ".tif", ""];
2931
+ const candidates = exts.flatMap((ext) => [
2932
+ `BinData/${ref}${ext}`,
2933
+ `Contents/BinData/${ref}${ext}`,
2934
+ `${ref}${ext}`
2935
+ ]);
655
2936
  let found = false;
656
2937
  for (const path of candidates) {
657
2938
  if (isPathTraversal(path)) continue;
@@ -661,8 +2942,10 @@ async function extractImagesFromZip(zip, blocks, decompressed, warnings) {
661
2942
  const data = await file.async("uint8array");
662
2943
  decompressed.total += data.length;
663
2944
  if (decompressed.total > MAX_DECOMPRESS_SIZE) throw new KordocError("ZIP \uC555\uCD95 \uD574\uC81C \uD06C\uAE30 \uCD08\uACFC (ZIP bomb \uC758\uC2EC)");
664
- const ext = ref.includes(".") ? ref.split(".").pop() : "png";
665
- const mimeType = imageExtToMime(ext);
2945
+ const refExt = ref.includes(".") ? ref.split(".").pop().toLowerCase() : "";
2946
+ const pathExt = !refExt && path.includes(".") ? path.split(".").pop().toLowerCase() : "";
2947
+ const ext = refExt || pathExt;
2948
+ const mimeType = ext ? imageExtToMime(ext) : detectImageMimeFromBytes(data);
666
2949
  imageIndex++;
667
2950
  const filename = `image_${String(imageIndex).padStart(3, "0")}.${mimeToExt(mimeType)}`;
668
2951
  images.push({ filename, data, mimeType });
@@ -985,13 +3268,18 @@ function walkSection(node, blocks, tableCtx, tableStack, styleMap, warnings, sec
985
3268
  }
986
3269
  break;
987
3270
  case "p": {
988
- const { text, href, footnote, style } = extractParagraphInfo(el, styleMap);
3271
+ const { text, href, footnote, style, headingLevel } = extractParagraphInfo(el, styleMap);
989
3272
  if (text) {
990
3273
  if (tableCtx?.cell) {
991
3274
  tableCtx.cell.text += (tableCtx.cell.text ? "\n" : "") + text;
992
3275
  } else if (!tableCtx) {
993
- const block = { type: "paragraph", text, pageNumber: sectionNum };
994
- if (style) block.style = style;
3276
+ let block;
3277
+ if (headingLevel) {
3278
+ block = { type: "heading", text, level: headingLevel, pageNumber: sectionNum };
3279
+ } else {
3280
+ block = { type: "paragraph", text, pageNumber: sectionNum };
3281
+ if (style) block.style = style;
3282
+ }
995
3283
  if (href) block.href = href;
996
3284
  if (footnote) block.footnoteText = footnote;
997
3285
  blocks.push(block);
@@ -1225,7 +3513,19 @@ function extractParagraphInfo(para, styleMap) {
1225
3513
  if (!style.fontSize && !style.bold && !style.italic) style = void 0;
1226
3514
  }
1227
3515
  }
1228
- return { text: cleanText, href, footnote, style };
3516
+ let headingLevel;
3517
+ const styleIdRef = para.getAttribute("styleIDRef");
3518
+ if (styleMap && styleIdRef) {
3519
+ const styleDef = styleMap.styles.get(styleIdRef);
3520
+ if (styleDef?.name) {
3521
+ const sn = styleDef.name;
3522
+ if (/장제목|대제목|간지제목|제목[\s_]?1|개요[\s_]?1|heading[\s_]?1/i.test(sn)) headingLevel = 1;
3523
+ else if (/절제목|제목[\s_]?2|개요[\s_]?2|heading[\s_]?2|^B-1\.$|[\s(]1\.$/i.test(sn)) headingLevel = 2;
3524
+ else if (/제목[\s_]?3|개요[\s_]?3|heading[\s_]?3|1\.1\s*제목|1\.1[\s_]|^B-1\.1/i.test(sn)) headingLevel = 3;
3525
+ else if (/제목[\s_]?4|개요[\s_]?4|heading[\s_]?4/i.test(sn)) headingLevel = 4;
3526
+ }
3527
+ }
3528
+ return { text: cleanText, href, footnote, style, headingLevel };
1229
3529
  }
1230
3530
  function extractTextFromNode(node) {
1231
3531
  let result = "";
@@ -2291,9 +4591,7 @@ function parseLenientCfb(data) {
2291
4591
 
2292
4592
  // src/hwp5/parser.ts
2293
4593
  init_page_range();
2294
- import { createRequire } from "module";
2295
- var require2 = createRequire(import.meta.url);
2296
- var CFB = require2("cfb");
4594
+ var CFB = __toESM(require_cfb(), 1);
2297
4595
  var MAX_SECTIONS = 100;
2298
4596
  var MAX_TOTAL_DECOMPRESS = 500 * 1024 * 1024;
2299
4597
  function parseHwp5Document(buffer, options) {
@@ -3152,7 +5450,7 @@ function clusterCoordinates(values) {
3152
5450
  }
3153
5451
  function groupConnectedLines(lines) {
3154
5452
  const parent = lines.map((_, i) => i);
3155
- function find(x) {
5453
+ function find2(x) {
3156
5454
  while (parent[x] !== x) {
3157
5455
  parent[x] = parent[parent[x]];
3158
5456
  x = parent[x];
@@ -3160,7 +5458,7 @@ function groupConnectedLines(lines) {
3160
5458
  return x;
3161
5459
  }
3162
5460
  function union(a, b) {
3163
- const ra = find(a), rb = find(b);
5461
+ const ra = find2(a), rb = find2(b);
3164
5462
  if (ra !== rb) parent[ra] = rb;
3165
5463
  }
3166
5464
  for (let i = 0; i < lines.length; i++) {
@@ -3172,7 +5470,7 @@ function groupConnectedLines(lines) {
3172
5470
  }
3173
5471
  const groups = /* @__PURE__ */ new Map();
3174
5472
  for (let i = 0; i < lines.length; i++) {
3175
- const root = find(i);
5473
+ const root = find2(i);
3176
5474
  if (!groups.has(root)) groups.set(root, []);
3177
5475
  groups.get(root).push(lines[i]);
3178
5476
  }
@@ -3622,18 +5920,43 @@ async function parsePdfDocument(buffer, options) {
3622
5920
  }
3623
5921
  const parsedPageCount = parsedPages || (pageFilter ? pageFilter.size : effectivePageCount);
3624
5922
  if (totalChars / Math.max(parsedPageCount, 1) < 10) {
3625
- if (options?.ocr) {
5923
+ let ocrProvider = options?.ocr ?? null;
5924
+ const ocrMode = options?.ocrMode;
5925
+ if (!ocrProvider && ocrMode && ocrMode !== "off") {
5926
+ try {
5927
+ const { resolveOcrProvider: resolveOcrProvider2 } = await Promise.resolve().then(() => (init_resolve(), resolve_exports));
5928
+ ocrProvider = await resolveOcrProvider2(ocrMode, warnings);
5929
+ } catch (resolveErr) {
5930
+ if (ocrMode !== "auto") {
5931
+ throw Object.assign(
5932
+ new KordocError(resolveErr instanceof Error ? resolveErr.message : "OCR \uD504\uB85C\uBC14\uC774\uB354 \uCD08\uAE30\uD654 \uC2E4\uD328"),
5933
+ { isImageBased: true }
5934
+ );
5935
+ }
5936
+ }
5937
+ }
5938
+ if (ocrProvider) {
3626
5939
  try {
3627
5940
  const { ocrPages: ocrPages2 } = await Promise.resolve().then(() => (init_provider(), provider_exports));
3628
- const ocrBlocks = await ocrPages2(doc, options.ocr, pageFilter, effectivePageCount);
5941
+ const ocrBlocks = await ocrPages2(doc, ocrProvider, pageFilter, effectivePageCount, warnings);
3629
5942
  if (ocrBlocks.length > 0) {
3630
- const ocrMarkdown = ocrBlocks.map((b) => b.text || "").filter(Boolean).join("\n\n");
3631
- return { markdown: ocrMarkdown, blocks: ocrBlocks, metadata, warnings, isImageBased: true };
5943
+ const ocrMarkdown = blocksToMarkdown(ocrBlocks);
5944
+ return {
5945
+ markdown: ocrMarkdown,
5946
+ blocks: ocrBlocks,
5947
+ metadata,
5948
+ warnings: warnings.length > 0 ? warnings : void 0,
5949
+ isImageBased: true
5950
+ };
3632
5951
  }
3633
5952
  } catch {
3634
5953
  }
3635
5954
  }
3636
- throw Object.assign(new KordocError(`\uC774\uBBF8\uC9C0 \uAE30\uBC18 PDF (${pageCount}\uD398\uC774\uC9C0, ${totalChars}\uC790)`), { isImageBased: true });
5955
+ if (ocrMode === "off") {
5956
+ throw Object.assign(new KordocError(`\uC774\uBBF8\uC9C0 \uAE30\uBC18 PDF (${pageCount}\uD398\uC774\uC9C0, ${totalChars}\uC790)`), { isImageBased: true });
5957
+ }
5958
+ const errMsg = ocrMode ? `\uC774\uBBF8\uC9C0 \uAE30\uBC18 PDF \u2014 OCR \uC2E4\uD328 (${pageCount}\uD398\uC774\uC9C0, ${totalChars}\uC790)` : `\uC774\uBBF8\uC9C0 \uAE30\uBC18 PDF (${pageCount}\uD398\uC774\uC9C0, ${totalChars}\uC790)`;
5959
+ throw Object.assign(new KordocError(errMsg), { isImageBased: true });
3637
5960
  }
3638
5961
  if (options?.removeHeaderFooter !== false && parsedPageCount >= 3) {
3639
5962
  const removed = removeHeaderFooterBlocks(blocks, pageHeights, warnings);
@@ -5245,8 +7568,8 @@ function levenshtein(a, b) {
5245
7568
  var SIMILARITY_THRESHOLD = 0.4;
5246
7569
  async function compare(bufferA, bufferB, options) {
5247
7570
  const [resultA, resultB] = await Promise.all([
5248
- parse(bufferA, options),
5249
- parse(bufferB, options)
7571
+ parse2(bufferA, options),
7572
+ parse2(bufferB, options)
5250
7573
  ]);
5251
7574
  if (!resultA.success) throw new Error(`\uBB38\uC11CA \uD30C\uC2F1 \uC2E4\uD328: ${resultA.error}`);
5252
7575
  if (!resultB.success) throw new Error(`\uBB38\uC11CB \uD30C\uC2F1 \uC2E4\uD328: ${resultB.error}`);
@@ -5567,7 +7890,7 @@ var HEADER_XML = `<?xml version='1.0' encoding='UTF-8'?>
5567
7890
  </hh:font>
5568
7891
  </hh:fontface>
5569
7892
  </hh:fontfaces>
5570
- <hh:borderFills itemCnt="3">
7893
+ <hh:borderFills itemCnt="5">
5571
7894
  <hh:borderFill id="1" threeD="0" shadow="0" centerLine="NONE" breakCellSeparateLine="0">
5572
7895
  <hh:slash type="NONE" Crooked="0" isCounter="0"/>
5573
7896
  <hh:backSlash type="NONE" Crooked="0" isCounter="0"/>
@@ -5598,8 +7921,26 @@ var HEADER_XML = `<?xml version='1.0' encoding='UTF-8'?>
5598
7921
  <hh:bottomBorder type="SOLID" width="0.12 mm" color="#000000"/>
5599
7922
  <hh:diagonal type="SOLID" width="0.1 mm" color="#000000"/>
5600
7923
  </hh:borderFill>
7924
+ <hh:borderFill id="4" threeD="0" shadow="0" centerLine="NONE" breakCellSeparateLine="0">
7925
+ <hh:slash type="NONE" Crooked="0" isCounter="0"/>
7926
+ <hh:backSlash type="NONE" Crooked="0" isCounter="0"/>
7927
+ <hh:leftBorder type="SOLID" width="0.5 mm" color="#AAAAAA"/>
7928
+ <hh:rightBorder type="NONE" width="0.1 mm" color="#000000"/>
7929
+ <hh:topBorder type="NONE" width="0.1 mm" color="#000000"/>
7930
+ <hh:bottomBorder type="NONE" width="0.1 mm" color="#000000"/>
7931
+ <hh:diagonal type="SOLID" width="0.1 mm" color="#000000"/>
7932
+ </hh:borderFill>
7933
+ <hh:borderFill id="5" threeD="0" shadow="0" centerLine="NONE" breakCellSeparateLine="0">
7934
+ <hh:slash type="NONE" Crooked="0" isCounter="0"/>
7935
+ <hh:backSlash type="NONE" Crooked="0" isCounter="0"/>
7936
+ <hh:leftBorder type="NONE" width="0.1 mm" color="#000000"/>
7937
+ <hh:rightBorder type="NONE" width="0.1 mm" color="#000000"/>
7938
+ <hh:topBorder type="NONE" width="0.1 mm" color="#000000"/>
7939
+ <hh:bottomBorder type="SOLID" width="0.4 mm" color="#888888"/>
7940
+ <hh:diagonal type="SOLID" width="0.1 mm" color="#000000"/>
7941
+ </hh:borderFill>
5601
7942
  </hh:borderFills>
5602
- <hh:charProperties itemCnt="15">
7943
+ <hh:charProperties itemCnt="16">
5603
7944
  <hh:charPr id="0" height="1000" textColor="#000000" shadeColor="none" useFontSpace="0" useKerning="0" symMark="NONE" borderFillIDRef="2">
5604
7945
  <hh:fontRef hangul="1" latin="1" hanja="1" japanese="1" other="1" symbol="1" user="1"/>
5605
7946
  <hh:ratio hangul="100" latin="100" hanja="100" japanese="100" other="100" symbol="100" user="100"/>
@@ -5774,6 +8115,17 @@ var HEADER_XML = `<?xml version='1.0' encoding='UTF-8'?>
5774
8115
  <hh:outline type="NONE"/>
5775
8116
  <hh:shadow type="NONE" color="#C0C0C0" offsetX="10" offsetY="10"/>
5776
8117
  </hh:charPr>
8118
+ <hh:charPr id="15" height="1000" textColor="#000000" shadeColor="none" useFontSpace="0" useKerning="0" symMark="NONE" borderFillIDRef="2">
8119
+ <hh:fontRef hangul="1" latin="1" hanja="1" japanese="1" other="1" symbol="1" user="1"/>
8120
+ <hh:ratio hangul="100" latin="100" hanja="100" japanese="100" other="100" symbol="100" user="100"/>
8121
+ <hh:spacing hangul="0" latin="0" hanja="0" japanese="0" other="0" symbol="0" user="0"/>
8122
+ <hh:relSz hangul="100" latin="100" hanja="100" japanese="100" other="100" symbol="100" user="100"/>
8123
+ <hh:offset hangul="0" latin="0" hanja="0" japanese="0" other="0" symbol="0" user="0"/>
8124
+ <hh:underline type="NONE" shape="SOLID" color="#000000"/>
8125
+ <hh:strikeout shape="SINGLE" color="#000000"/>
8126
+ <hh:outline type="NONE"/>
8127
+ <hh:shadow type="NONE" color="#C0C0C0" offsetX="10" offsetY="10"/>
8128
+ </hh:charPr>
5777
8129
  </hh:charProperties>
5778
8130
  <hh:tabProperties itemCnt="3">
5779
8131
  <hh:tabPr id="0" autoTabLeft="0" autoTabRight="0"/>
@@ -5794,7 +8146,7 @@ var HEADER_XML = `<?xml version='1.0' encoding='UTF-8'?>
5794
8146
  <hh:paraHead start="1" level="10" align="LEFT" useInstWidth="1" autoIndent="1" widthAdjust="0" textOffsetType="PERCENT" textOffset="50" numFormat="ROMAN_SMALL" charPrIDRef="4294967295" checkable="1"/>
5795
8147
  </hh:numbering>
5796
8148
  </hh:numberings>
5797
- <hh:paraProperties itemCnt="20">
8149
+ <hh:paraProperties itemCnt="22">
5798
8150
  <hh:paraPr id="0" tabPrIDRef="0" condense="0" fontLineHeight="0" snapToGrid="1" suppressLineNumbers="0" checked="0" textDir="LTR">
5799
8151
  <hh:align horizontal="JUSTIFY" vertical="BASELINE"/>
5800
8152
  <hh:heading type="NONE" idRef="0" level="0"/>
@@ -6396,6 +8748,64 @@ var HEADER_XML = `<?xml version='1.0' encoding='UTF-8'?>
6396
8748
  </hp:switch>
6397
8749
  <hh:border borderFillIDRef="2" offsetLeft="0" offsetRight="0" offsetTop="0" offsetBottom="0" connect="0" ignoreMargin="0"/>
6398
8750
  </hh:paraPr>
8751
+ <hh:paraPr id="20" tabPrIDRef="0" condense="0" fontLineHeight="0" snapToGrid="1" suppressLineNumbers="0" checked="0" textDir="LTR">
8752
+ <hh:align horizontal="JUSTIFY" vertical="BASELINE"/>
8753
+ <hh:heading type="NONE" idRef="0" level="0"/>
8754
+ <hh:breakSetting breakLatinWord="KEEP_WORD" breakNonLatinWord="BREAK_WORD" widowOrphan="0" keepWithNext="0" keepLines="0" pageBreakBefore="0" lineWrap="BREAK"/>
8755
+ <hh:autoSpacing eAsianEng="0" eAsianNum="0"/>
8756
+ <hp:switch>
8757
+ <hp:case hp:required-namespace="http://www.hancom.co.kr/hwpml/2016/HwpUnitChar">
8758
+ <hh:margin>
8759
+ <hc:intent value="0" unit="HWPUNIT"/>
8760
+ <hc:left value="4252" unit="HWPUNIT"/>
8761
+ <hc:right value="0" unit="HWPUNIT"/>
8762
+ <hc:prev value="0" unit="HWPUNIT"/>
8763
+ <hc:next value="0" unit="HWPUNIT"/>
8764
+ </hh:margin>
8765
+ <hh:lineSpacing type="PERCENT" value="160" unit="HWPUNIT"/>
8766
+ </hp:case>
8767
+ <hp:default>
8768
+ <hh:margin>
8769
+ <hc:intent value="0" unit="HWPUNIT"/>
8770
+ <hc:left value="4252" unit="HWPUNIT"/>
8771
+ <hc:right value="0" unit="HWPUNIT"/>
8772
+ <hc:prev value="0" unit="HWPUNIT"/>
8773
+ <hc:next value="0" unit="HWPUNIT"/>
8774
+ </hh:margin>
8775
+ <hh:lineSpacing type="PERCENT" value="160" unit="HWPUNIT"/>
8776
+ </hp:default>
8777
+ </hp:switch>
8778
+ <hh:border borderFillIDRef="4" offsetLeft="0" offsetRight="0" offsetTop="0" offsetBottom="0" connect="0" ignoreMargin="0"/>
8779
+ </hh:paraPr>
8780
+ <hh:paraPr id="21" tabPrIDRef="0" condense="0" fontLineHeight="0" snapToGrid="1" suppressLineNumbers="0" checked="0" textDir="LTR">
8781
+ <hh:align horizontal="JUSTIFY" vertical="BASELINE"/>
8782
+ <hh:heading type="NONE" idRef="0" level="0"/>
8783
+ <hh:breakSetting breakLatinWord="KEEP_WORD" breakNonLatinWord="BREAK_WORD" widowOrphan="0" keepWithNext="0" keepLines="0" pageBreakBefore="0" lineWrap="BREAK"/>
8784
+ <hh:autoSpacing eAsianEng="0" eAsianNum="0"/>
8785
+ <hp:switch>
8786
+ <hp:case hp:required-namespace="http://www.hancom.co.kr/hwpml/2016/HwpUnitChar">
8787
+ <hh:margin>
8788
+ <hc:intent value="0" unit="HWPUNIT"/>
8789
+ <hc:left value="0" unit="HWPUNIT"/>
8790
+ <hc:right value="0" unit="HWPUNIT"/>
8791
+ <hc:prev value="0" unit="HWPUNIT"/>
8792
+ <hc:next value="0" unit="HWPUNIT"/>
8793
+ </hh:margin>
8794
+ <hh:lineSpacing type="PERCENT" value="160" unit="HWPUNIT"/>
8795
+ </hp:case>
8796
+ <hp:default>
8797
+ <hh:margin>
8798
+ <hc:intent value="0" unit="HWPUNIT"/>
8799
+ <hc:left value="0" unit="HWPUNIT"/>
8800
+ <hc:right value="0" unit="HWPUNIT"/>
8801
+ <hc:prev value="0" unit="HWPUNIT"/>
8802
+ <hc:next value="0" unit="HWPUNIT"/>
8803
+ </hh:margin>
8804
+ <hh:lineSpacing type="PERCENT" value="160" unit="HWPUNIT"/>
8805
+ </hp:default>
8806
+ </hp:switch>
8807
+ <hh:border borderFillIDRef="5" offsetLeft="0" offsetRight="0" offsetTop="0" offsetBottom="0" connect="0" ignoreMargin="0"/>
8808
+ </hh:paraPr>
6399
8809
  </hh:paraProperties>
6400
8810
  <hh:styles itemCnt="23">
6401
8811
  <hh:style id="0" type="PARA" name="\uBC14\uD0D5\uAE00" engName="Normal" paraPrIDRef="0" charPrIDRef="0" nextStyleIDRef="0" langID="1042" lockForm="0"/>
@@ -6499,7 +8909,11 @@ async function extractTemplateStyles(templateArrayBuffer) {
6499
8909
  charPr: /* @__PURE__ */ new Map(),
6500
8910
  paraPr: /* @__PURE__ */ new Map(),
6501
8911
  borderFill: /* @__PURE__ */ new Map(),
6502
- fontfaces: /* @__PURE__ */ new Map()
8912
+ fontfaces: /* @__PURE__ */ new Map(),
8913
+ styles: /* @__PURE__ */ new Map(),
8914
+ stylesById: /* @__PURE__ */ new Map(),
8915
+ masterpages: [],
8916
+ headerXml: headerXmlText
6503
8917
  };
6504
8918
  const fontfaces = doc.getElementsByTagNameNS(ns.hh, "fontFamily");
6505
8919
  for (let i = 0; i < fontfaces.length; i++) {
@@ -6574,6 +8988,34 @@ async function extractTemplateStyles(templateArrayBuffer) {
6574
8988
  if (fillColor) borderFillProp.fillColor = fillColor;
6575
8989
  template.borderFill.set(id, borderFillProp);
6576
8990
  }
8991
+ const styleEls = doc.getElementsByTagNameNS(ns.hh, "style");
8992
+ for (let i = 0; i < styleEls.length; i++) {
8993
+ const el = styleEls.item(i);
8994
+ const id = el.getAttribute("id");
8995
+ const name = el.getAttribute("name") || "";
8996
+ const engName = el.getAttribute("engName") || "";
8997
+ const charPrIDRef = el.getAttribute("charPrIDRef") || "0";
8998
+ const paraPrIDRef = el.getAttribute("paraPrIDRef") || "0";
8999
+ if (!id) continue;
9000
+ const def = { id, name, engName, charPrIDRef, paraPrIDRef };
9001
+ template.styles.set(name, def);
9002
+ template.stylesById.set(id, def);
9003
+ }
9004
+ const section0File = zip.file("Contents/section0.xml");
9005
+ if (section0File) {
9006
+ const sec0 = await section0File.async("text");
9007
+ const secPrMatch = sec0.match(/<hp:secPr[\s\S]*?<\/hp:secPr>/);
9008
+ if (secPrMatch) template.secPrXml = secPrMatch[0];
9009
+ const colPrMatch = sec0.match(/<hp:ctrl>[\s\S]*?<\/hp:ctrl>/);
9010
+ if (colPrMatch) template.colPrXml = colPrMatch[0];
9011
+ }
9012
+ for (const [path, file] of Object.entries(zip.files)) {
9013
+ if (/^Contents\/masterpage\d+\.xml$/.test(path)) {
9014
+ const content = await file.async("text");
9015
+ template.masterpages.push({ filename: path, content });
9016
+ }
9017
+ }
9018
+ template.masterpages.sort((a, b) => a.filename.localeCompare(b.filename));
6577
9019
  return template;
6578
9020
  }
6579
9021
  function findCharPrByCharacteristic(charPrMap, characteristic) {
@@ -6634,35 +9076,61 @@ function getDefaultBorderFillId(borderFillMap) {
6634
9076
  }
6635
9077
 
6636
9078
  // src/hwpx/style-matcher.ts
9079
+ function findStyleByName(styles, candidates) {
9080
+ for (const cand of candidates) {
9081
+ if (styles.has(cand)) return styles.get(cand);
9082
+ }
9083
+ for (const cand of candidates) {
9084
+ for (const [name, def] of styles) {
9085
+ if (name === `B-${cand}` || name.endsWith(` ${cand}`) || name.endsWith(`-${cand}`)) return def;
9086
+ }
9087
+ }
9088
+ for (const cand of candidates) {
9089
+ let best = null;
9090
+ for (const [name, def] of styles) {
9091
+ if (name.includes(cand)) {
9092
+ if (!best || name.length < best[0].length) best = [name, def];
9093
+ }
9094
+ }
9095
+ if (best) return best[1];
9096
+ }
9097
+ return null;
9098
+ }
6637
9099
  function createStyleMap(template, warnings = []) {
6638
9100
  const charPrMap = template.charPr || /* @__PURE__ */ new Map();
6639
- const paraPrMap = template.paraPr || /* @__PURE__ */ new Map();
6640
9101
  const borderFillMap = template.borderFill || /* @__PURE__ */ new Map();
9102
+ const styles = template.styles || /* @__PURE__ */ new Map();
6641
9103
  const defaultCharPr = getDefaultCharPrId(charPrMap);
6642
- const defaultParaPr = getDefaultParaPrId(paraPrMap);
9104
+ const defaultParaPr = getDefaultParaPrId(template.paraPr || /* @__PURE__ */ new Map());
6643
9105
  const defaultBorderFill = getDefaultBorderFillId(borderFillMap);
6644
- const h1CharPr = findCharPrByCharacteristic(charPrMap, "heading1") || defaultCharPr;
6645
- const h2CharPr = findCharPrByCharacteristic(charPrMap, "heading2") || defaultCharPr;
6646
- const h3CharPr = findCharPrByCharacteristic(charPrMap, "heading3") || defaultCharPr;
6647
- const boldCharPr = findCharPrByCharacteristic(charPrMap, "bold") || defaultCharPr;
6648
- const italicCharPr = findCharPrByCharacteristic(charPrMap, "italic") || defaultCharPr;
6649
- const bodyCharPr = findCharPrByCharacteristic(charPrMap, "normal") || defaultCharPr;
6650
- if (h1CharPr === defaultCharPr) {
6651
- warnings.push("[warn] \uD15C\uD50C\uB9BF\uC5D0\uC11C H1 \uC81C\uBAA9 \uC2A4\uD0C0\uC77C\uC744 \uAC10\uC9C0\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4. \uAE30\uBCF8\uAC12 \uC0AC\uC6A9");
6652
- }
6653
- if (h2CharPr === defaultCharPr) {
6654
- warnings.push("[warn] \uD15C\uD50C\uB9BF\uC5D0\uC11C H2 \uC81C\uBAA9 \uC2A4\uD0C0\uC77C\uC744 \uAC10\uC9C0\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4. \uAE30\uBCF8\uAC12 \uC0AC\uC6A9");
6655
- }
9106
+ const defaultStyleId = "0";
9107
+ const toEntry = (def, fallbackCharPr) => ({
9108
+ charPr: def?.charPrIDRef ?? fallbackCharPr,
9109
+ paraPr: def?.paraPrIDRef ?? defaultParaPr,
9110
+ styleId: def?.id ?? defaultStyleId
9111
+ });
9112
+ const bodyDef = findStyleByName(styles, ["\uBC14\uD0D5\uAE00", "Normal", "\uBCF8\uBB38", "\uBC14\uD0D5"]) || findStyleByName(styles, ["body", "normal"]);
9113
+ const h1Def = findStyleByName(styles, ["\uC81C\uBAA91", "\uC81C\uBAA9 1", "\uAC1C\uC694 1", "\uAC1C\uC6941", "Heading 1"]) || findStyleByName(styles, ["\uC7A5\uC81C\uBAA9", "\uB300\uC81C\uBAA9", "\uC81C\uBAA9"]);
9114
+ const h2Def = findStyleByName(styles, ["\uC81C\uBAA92", "\uC81C\uBAA9 2", "\uAC1C\uC694 2", "\uAC1C\uC6942", "Heading 2"]) || findStyleByName(styles, ["\uC808\uC81C\uBAA9", "1.", "1 "]);
9115
+ const h3Def = findStyleByName(styles, ["\uC81C\uBAA93", "\uC81C\uBAA9 3", "\uAC1C\uC694 3", "\uAC1C\uC6943", "Heading 3"]) || findStyleByName(styles, ["1.1", "\uD56D\uBAA9"]);
9116
+ const tableCellDef = findStyleByName(styles, ["\uD45C \uB0B4\uC6A9", "\uD45C\uB0B4\uC6A9", "B-\uD45C\uB0B4\uC6A9", "\uD45C \uB0B4\uC6A9(\uC77C\uBC18)"]) || findStyleByName(styles, ["\uD45C", "table"]);
9117
+ const tableHeaderDef = findStyleByName(styles, ["\uD45C\uC81C\uBAA9", "\uD45C \uC81C\uBAA9", "B-\uD45C\uC81C\uBAA9", "\uD45C \uB0B4\uC6A9(\uAC15\uC870)"]) || tableCellDef;
9118
+ const bodyCharPr = bodyDef?.charPrIDRef ?? findCharPrByCharacteristic(charPrMap, "normal") ?? defaultCharPr;
9119
+ const h1CharPr = h1Def?.charPrIDRef ?? findCharPrByCharacteristic(charPrMap, "heading1") ?? defaultCharPr;
9120
+ const h2CharPr = h2Def?.charPrIDRef ?? findCharPrByCharacteristic(charPrMap, "heading2") ?? defaultCharPr;
9121
+ const h3CharPr = h3Def?.charPrIDRef ?? findCharPrByCharacteristic(charPrMap, "heading3") ?? defaultCharPr;
9122
+ const boldCharPr = findCharPrByCharacteristic(charPrMap, "bold") ?? defaultCharPr;
9123
+ const italicCharPr = findCharPrByCharacteristic(charPrMap, "italic") ?? defaultCharPr;
6656
9124
  return {
6657
- h1: { charPr: h1CharPr, paraPr: defaultParaPr },
6658
- h2: { charPr: h2CharPr, paraPr: defaultParaPr },
6659
- h3: { charPr: h3CharPr, paraPr: defaultParaPr },
6660
- h456: { charPr: defaultCharPr, paraPr: defaultParaPr },
6661
- body: { charPr: bodyCharPr, paraPr: defaultParaPr },
9125
+ h1: { charPr: h1CharPr, paraPr: h1Def?.paraPrIDRef ?? defaultParaPr, styleId: h1Def?.id ?? defaultStyleId },
9126
+ h2: { charPr: h2CharPr, paraPr: h2Def?.paraPrIDRef ?? defaultParaPr, styleId: h2Def?.id ?? defaultStyleId },
9127
+ h3: { charPr: h3CharPr, paraPr: h3Def?.paraPrIDRef ?? defaultParaPr, styleId: h3Def?.id ?? defaultStyleId },
9128
+ h456: { charPr: h3CharPr, paraPr: h3Def?.paraPrIDRef ?? defaultParaPr, styleId: h3Def?.id ?? defaultStyleId },
9129
+ body: { charPr: bodyCharPr, paraPr: bodyDef?.paraPrIDRef ?? defaultParaPr, styleId: bodyDef?.id ?? defaultStyleId },
6662
9130
  bold: { charPr: boldCharPr },
6663
9131
  italic: { charPr: italicCharPr },
6664
- tableCell: { charPr: bodyCharPr, borderFill: defaultBorderFill },
6665
- tableHeader: { charPr: boldCharPr, borderFill: defaultBorderFill }
9132
+ tableCell: { charPr: tableCellDef?.charPrIDRef ?? bodyCharPr, paraPr: tableCellDef?.paraPrIDRef ?? defaultParaPr, styleId: tableCellDef?.id ?? defaultStyleId, borderFill: defaultBorderFill },
9133
+ tableHeader: { charPr: tableHeaderDef?.charPrIDRef ?? bodyCharPr, paraPr: tableHeaderDef?.paraPrIDRef ?? defaultParaPr, styleId: tableHeaderDef?.id ?? defaultStyleId, borderFill: defaultBorderFill }
6666
9134
  };
6667
9135
  }
6668
9136
  function getStyleForBlock(styleMap, blockType, inlineStyle) {
@@ -6698,7 +9166,10 @@ var CHAR_BOLD = "11";
6698
9166
  var CHAR_ITALIC = "12";
6699
9167
  var CHAR_BOLD_ITALIC = "13";
6700
9168
  var CHAR_CODE = "14";
9169
+ var CHAR_STRIKETHROUGH = "15";
6701
9170
  var PARA_NORMAL = "0";
9171
+ var PARA_BLOCKQUOTE = "20";
9172
+ var PARA_HR = "21";
6702
9173
  var SEC_NS = [
6703
9174
  `xmlns:ha="http://www.hancom.co.kr/hwpml/2011/app"`,
6704
9175
  `xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph"`,
@@ -6725,7 +9196,7 @@ function escapeXml(text) {
6725
9196
  }
6726
9197
  function parseInlineRuns(text) {
6727
9198
  const runs = [];
6728
- const re = /\*\*\*(.+?)\*\*\*|\*\*(.+?)\*\*|\*(.+?)\*|_(.+?)_|`(.+?)`|\[([^\]]+)\]\(([^)]+)\)/g;
9199
+ const re = /\*\*\*(.+?)\*\*\*|\*\*(.+?)\*\*|\*(.+?)\*|_(.+?)_|`(.+?)`|~~(.+?)~~|\[([^\]]+)\]\(([^)]+)\)/g;
6729
9200
  let last = 0;
6730
9201
  let m;
6731
9202
  while ((m = re.exec(text)) !== null) {
@@ -6735,7 +9206,8 @@ function parseInlineRuns(text) {
6735
9206
  else if (m[3]) runs.push({ text: m[3], italic: true });
6736
9207
  else if (m[4]) runs.push({ text: m[4], italic: true });
6737
9208
  else if (m[5]) runs.push({ text: m[5], code: true });
6738
- else if (m[6]) runs.push({ text: m[6], url: m[7] });
9209
+ else if (m[6]) runs.push({ text: m[6], strikethrough: true });
9210
+ else if (m[7]) runs.push({ text: m[7], url: m[8] });
6739
9211
  last = m.index + m[0].length;
6740
9212
  }
6741
9213
  if (last < text.length) runs.push({ text: text.slice(last) });
@@ -6743,6 +9215,7 @@ function parseInlineRuns(text) {
6743
9215
  }
6744
9216
  function charPrForRun(run) {
6745
9217
  if (run.code) return CHAR_CODE;
9218
+ if (run.strikethrough) return CHAR_STRIKETHROUGH;
6746
9219
  if (run.bold && run.italic) return CHAR_BOLD_ITALIC;
6747
9220
  if (run.bold) return CHAR_BOLD;
6748
9221
  if (run.italic) return CHAR_ITALIC;
@@ -6771,25 +9244,51 @@ function makeHyperlinkRun(text, url, charPrId, nextId) {
6771
9244
  ].join("\n");
6772
9245
  }
6773
9246
  function makeRunsFromText(text, defaultCharPr, nextId) {
9247
+ if (/<br\s*\/?>/i.test(text)) {
9248
+ const parts = text.split(/<br\s*\/?>/i);
9249
+ return parts.map((part, i) => {
9250
+ const seg = makeRunsFromText(part, defaultCharPr, nextId);
9251
+ return i < parts.length - 1 ? seg + `<hp:run charPrIDRef="${defaultCharPr}"><hp:lf/></hp:run>` : seg;
9252
+ }).join("");
9253
+ }
6774
9254
  const runs = parseInlineRuns(text);
6775
9255
  if (runs.length === 0) return makeRun("", defaultCharPr);
6776
- const isPlain = runs.length === 1 && !runs[0].bold && !runs[0].italic && !runs[0].code && !runs[0].url;
9256
+ const isPlain = runs.length === 1 && !runs[0].bold && !runs[0].italic && !runs[0].code && !runs[0].strikethrough && !runs[0].url;
6777
9257
  if (isPlain) return makeRun(runs[0].text, defaultCharPr);
6778
9258
  return runs.map((r) => {
6779
9259
  if (r.url && nextId) return makeHyperlinkRun(r.text, r.url, CHAR_NORMAL, nextId);
6780
9260
  return makeRun(r.text, charPrForRun(r));
6781
9261
  }).join("");
6782
9262
  }
6783
- var LINESEG = ` <hp:linesegarray>
6784
- <hp:lineseg textpos="0" vertpos="0" vertsize="1000" textheight="1000" baseline="850" spacing="600" horzpos="0" horzsize="42520" flags="393216"/>
9263
+ function makeLineseg(horzsize, vertsize) {
9264
+ const baseline = Math.round(vertsize * 0.85);
9265
+ return ` <hp:linesegarray>
9266
+ <hp:lineseg textpos="0" vertpos="0" vertsize="${vertsize}" textheight="${vertsize}" baseline="${baseline}" spacing="600" horzpos="0" horzsize="${horzsize}" flags="393216"/>
9267
+ </hp:linesegarray>`;
9268
+ }
9269
+ var CHAR_HWP = 1e3;
9270
+ var LINE_HWP = 1400;
9271
+ var BASELINE_RATIO = 0.85;
9272
+ function estimateCellLineseg(plainText, cellHorzsize) {
9273
+ const stripped = plainText.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim();
9274
+ const charsPerLine = Math.max(1, Math.floor(cellHorzsize / CHAR_HWP));
9275
+ const lineCount = Math.max(1, Math.ceil(stripped.length / charsPerLine));
9276
+ const baseline = Math.round(LINE_HWP * BASELINE_RATIO);
9277
+ const segs = Array.from({ length: lineCount }, (_, i) => {
9278
+ const textpos = i * charsPerLine;
9279
+ const vertpos = i * LINE_HWP;
9280
+ return ` <hp:lineseg textpos="${textpos}" vertpos="${vertpos}" vertsize="${LINE_HWP}" textheight="${LINE_HWP}" baseline="${vertpos + baseline}" spacing="600" horzpos="0" horzsize="${cellHorzsize}" flags="393216"/>`;
9281
+ });
9282
+ return ` <hp:linesegarray>
9283
+ ${segs.join("\n")}
6785
9284
  </hp:linesegarray>`;
6786
- function makeParagraph(text, charPrId, paraPrId, nextId) {
9285
+ }
9286
+ function makeParagraph(text, charPrId, paraPrId, nextId, styleId = "0") {
6787
9287
  const id = nextId();
6788
9288
  const runs = makeRunsFromText(text, charPrId, nextId);
6789
9289
  return [
6790
- `<hp:p id="${id}" paraPrIDRef="${paraPrId}" styleIDRef="0" pageBreak="0" columnBreak="0" merged="0">`,
9290
+ `<hp:p id="${id}" paraPrIDRef="${paraPrId}" styleIDRef="${styleId}" pageBreak="0" columnBreak="0" merged="0">`,
6791
9291
  ` ${runs}`,
6792
- LINESEG,
6793
9292
  `</hp:p>`
6794
9293
  ].join("\n");
6795
9294
  }
@@ -6798,7 +9297,23 @@ function makeEmptyParagraph(nextId) {
6798
9297
  return [
6799
9298
  `<hp:p id="${id}" paraPrIDRef="${PARA_NORMAL}" styleIDRef="0" pageBreak="0" columnBreak="0" merged="0">`,
6800
9299
  ` <hp:run charPrIDRef="${CHAR_NORMAL}"><hp:t/></hp:run>`,
6801
- LINESEG,
9300
+ `</hp:p>`
9301
+ ].join("\n");
9302
+ }
9303
+ function makeBlockquoteParagraph(text, nextId) {
9304
+ const id = nextId();
9305
+ const runs = makeRunsFromText(text, CHAR_ITALIC, nextId);
9306
+ return [
9307
+ `<hp:p id="${id}" paraPrIDRef="${PARA_BLOCKQUOTE}" styleIDRef="0" pageBreak="0" columnBreak="0" merged="0">`,
9308
+ ` ${runs}`,
9309
+ `</hp:p>`
9310
+ ].join("\n");
9311
+ }
9312
+ function makeHrParagraph(nextId) {
9313
+ const id = nextId();
9314
+ return [
9315
+ `<hp:p id="${id}" paraPrIDRef="${PARA_HR}" styleIDRef="0" pageBreak="0" columnBreak="0" merged="0">`,
9316
+ ` <hp:run charPrIDRef="${CHAR_NORMAL}"><hp:t/></hp:run>`,
6802
9317
  `</hp:p>`
6803
9318
  ].join("\n");
6804
9319
  }
@@ -6809,8 +9324,7 @@ function headingCharPr(level) {
6809
9324
  return CHAR_H456;
6810
9325
  }
6811
9326
  var BODY_WIDTH = 42520;
6812
- var ROW_HEIGHT = 2400;
6813
- function makeTableCell(text, colAddr, rowAddr, colWidth, isHeader, nextId, styleMap) {
9327
+ function makeTableCell(text, colAddr, rowAddr, colWidth, cellHeight, isHeader, nextId, styleMap) {
6814
9328
  let charPr;
6815
9329
  let borderFill = "3";
6816
9330
  if (styleMap) {
@@ -6820,20 +9334,28 @@ function makeTableCell(text, colAddr, rowAddr, colWidth, isHeader, nextId, style
6820
9334
  } else {
6821
9335
  charPr = isHeader ? CHAR_BOLD : CHAR_NORMAL;
6822
9336
  }
6823
- const paraId = nextId();
6824
9337
  const subId = nextId();
9338
+ const cellHorzsize = Math.max(1e3, colWidth - 2e3);
9339
+ const segments = text.split(/<br\s*\/?>/i);
9340
+ const cellParas = segments.map((seg) => {
9341
+ const pid = nextId();
9342
+ return [
9343
+ ` <hp:p id="${pid}" paraPrIDRef="0" styleIDRef="0" pageBreak="0" columnBreak="0" merged="0">`,
9344
+ ` ${makeRunsFromText(seg, charPr, nextId)}`,
9345
+ estimateCellLineseg(seg, cellHorzsize),
9346
+ ` </hp:p>`
9347
+ ].join("\n");
9348
+ }).join("\n");
6825
9349
  return [
6826
9350
  `<hp:tc name="" header="${isHeader ? 1 : 0}" hasMargin="0" protect="0" editable="0" dirty="1" borderFillIDRef="${borderFill}">`,
6827
9351
  ` <hp:subList id="${subId}" textDirection="HORIZONTAL" lineWrap="BREAK" vertAlign="CENTER"`,
6828
9352
  ` linkListIDRef="0" linkListNextIDRef="0" textWidth="0" textHeight="0"`,
6829
9353
  ` hasTextRef="0" hasNumRef="0">`,
6830
- ` <hp:p id="${paraId}" paraPrIDRef="0" styleIDRef="0" pageBreak="0" columnBreak="0" merged="0">`,
6831
- ` <hp:run charPrIDRef="${charPr}"><hp:t${text ? `>${escapeXml(text)}</hp:t` : "/"}></hp:run>`,
6832
- ` </hp:p>`,
9354
+ cellParas,
6833
9355
  ` </hp:subList>`,
6834
9356
  ` <hp:cellAddr colAddr="${colAddr}" rowAddr="${rowAddr}"/>`,
6835
9357
  ` <hp:cellSpan colSpan="1" rowSpan="1"/>`,
6836
- ` <hp:cellSz width="${colWidth}" height="${ROW_HEIGHT}"/>`,
9358
+ ` <hp:cellSz width="${colWidth}" height="${cellHeight}"/>`,
6837
9359
  ` <hp:cellMargin left="1000" right="1000" top="500" bottom="500"/>`,
6838
9360
  `</hp:tc>`
6839
9361
  ].join("\n");
@@ -6843,10 +9365,21 @@ function makeTable(rows, nextId, styleMap) {
6843
9365
  const colCnt = rows[0].length;
6844
9366
  const colWidth = Math.floor(BODY_WIDTH / colCnt);
6845
9367
  const totalWidth = colWidth * colCnt;
6846
- const totalHeight = ROW_HEIGHT * rows.length;
9368
+ const cellHorzsize = Math.max(1e3, colWidth - 2e3);
9369
+ const rowHeights = rows.map((row) => {
9370
+ const maxTotalLines = Math.max(1, ...row.map((cell) => {
9371
+ return cell.split(/<br\s*\/?>/i).reduce((sum, seg) => {
9372
+ const plain = seg.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim();
9373
+ const charsPerLine = Math.max(1, Math.floor(cellHorzsize / CHAR_HWP));
9374
+ return sum + Math.max(1, Math.ceil(plain.length / charsPerLine));
9375
+ }, 0);
9376
+ }));
9377
+ return maxTotalLines * LINE_HWP + 1e3;
9378
+ });
9379
+ const totalHeight = rowHeights.reduce((s, h) => s + h, 0);
6847
9380
  const trElements = rows.map(
6848
9381
  (row, rowIdx) => `<hp:tr>
6849
- ${row.map((cell, colIdx) => makeTableCell(cell, colIdx, rowIdx, colWidth, rowIdx === 0, nextId, styleMap)).join("\n")}
9382
+ ${row.map((cell, colIdx) => makeTableCell(cell, colIdx, rowIdx, colWidth, rowHeights[rowIdx], rowIdx === 0, nextId, styleMap)).join("\n")}
6850
9383
  </hp:tr>`
6851
9384
  ).join("\n");
6852
9385
  const tableId = nextId();
@@ -6867,7 +9400,7 @@ ${row.map((cell, colIdx) => makeTableCell(cell, colIdx, rowIdx, colWidth, rowIdx
6867
9400
  trElements,
6868
9401
  `</hp:tbl>`,
6869
9402
  `</hp:run>`,
6870
- LINESEG,
9403
+ makeLineseg(totalWidth, totalHeight),
6871
9404
  `</hp:p>`
6872
9405
  ].join("\n");
6873
9406
  }
@@ -6892,6 +9425,20 @@ function parseMarkdownToBlocks(md) {
6892
9425
  i++;
6893
9426
  continue;
6894
9427
  }
9428
+ if (/^(-{3,}|\*{3,}|_{3,})$/.test(trimmed)) {
9429
+ blocks.push({ type: "hr" });
9430
+ i++;
9431
+ continue;
9432
+ }
9433
+ if (trimmed.startsWith(">")) {
9434
+ const quoteLines = [];
9435
+ while (i < lines.length && lines[i].trim().startsWith(">")) {
9436
+ quoteLines.push(lines[i].trim().replace(/^>\s?/, ""));
9437
+ i++;
9438
+ }
9439
+ blocks.push({ type: "blockquote", text: quoteLines.join(" ") });
9440
+ continue;
9441
+ }
6895
9442
  const hm = trimmed.match(/^(#{1,6})\s+(.+)$/);
6896
9443
  if (hm) {
6897
9444
  blocks.push({ type: "heading", text: hm[2].trim(), level: hm[1].length });
@@ -6951,35 +9498,108 @@ function parseMarkdownToBlocks(md) {
6951
9498
  continue;
6952
9499
  }
6953
9500
  const paraLines = [];
6954
- while (i < lines.length && lines[i].trim() && !lines[i].trim().startsWith("#") && !lines[i].trim().startsWith("|") && !/^\s*[-*+]\s/.test(lines[i]) && !/^\s*\d+\.\s/.test(lines[i]) && !lines[i].trim().startsWith("```") && !lines[i].trim().match(/^!\[[^\]]*\]\([^)]+\)$/)) paraLines.push(lines[i++].trim());
9501
+ while (i < lines.length && lines[i].trim() && !lines[i].trim().startsWith("#") && !lines[i].trim().startsWith("|") && !lines[i].trim().startsWith(">") && !/^\s*[-*+]\s/.test(lines[i]) && !/^\s*\d+\.\s/.test(lines[i]) && !lines[i].trim().startsWith("```") && !lines[i].trim().match(/^!\[[^\]]*\]\([^)]+\)$/) && !/^(-{3,}|\*{3,}|_{3,})$/.test(lines[i].trim())) paraLines.push(lines[i++].trim());
6955
9502
  if (paraLines.length > 0) blocks.push({ type: "paragraph", text: paraLines.join(" ") });
6956
9503
  }
6957
9504
  return blocks;
6958
9505
  }
9506
+ function getImageDimensions(data) {
9507
+ if (data[0] === 137 && data[1] === 80 && data[2] === 78 && data[3] === 71) {
9508
+ if (data.length < 24) return null;
9509
+ const w = (data[16] << 24 | data[17] << 16 | data[18] << 8 | data[19]) >>> 0;
9510
+ const h = (data[20] << 24 | data[21] << 16 | data[22] << 8 | data[23]) >>> 0;
9511
+ return w > 0 && h > 0 ? { width: w, height: h } : null;
9512
+ }
9513
+ if (data[0] === 255 && data[1] === 216) {
9514
+ let i = 2;
9515
+ while (i < data.length - 8) {
9516
+ if (data[i] !== 255) break;
9517
+ const marker = data[i + 1];
9518
+ if (marker >= 192 && marker <= 195) {
9519
+ const h = data[i + 5] << 8 | data[i + 6];
9520
+ const w = data[i + 7] << 8 | data[i + 8];
9521
+ return w > 0 && h > 0 ? { width: w, height: h } : null;
9522
+ }
9523
+ if (marker === 217 || marker === 1 || marker >= 208 && marker <= 215) {
9524
+ i += 2;
9525
+ continue;
9526
+ }
9527
+ const segLen = data[i + 2] << 8 | data[i + 3];
9528
+ if (segLen < 2) break;
9529
+ i += 2 + segLen;
9530
+ }
9531
+ }
9532
+ return null;
9533
+ }
9534
+ function calcHwpSize(width, height) {
9535
+ if (width <= 0 || height <= 0) return { widthHwp: 28346, heightHwp: 19843 };
9536
+ const HWP_PER_PIXEL = 7200 / 96;
9537
+ const naturalW = Math.round(width * HWP_PER_PIXEL);
9538
+ const naturalH = Math.round(height * HWP_PER_PIXEL);
9539
+ const maxWidthHwp = 28346;
9540
+ if (naturalW <= maxWidthHwp) {
9541
+ return { widthHwp: naturalW, heightHwp: naturalH };
9542
+ }
9543
+ const ratio = height / width;
9544
+ return { widthHwp: maxWidthHwp, heightHwp: Math.round(maxWidthHwp * ratio) };
9545
+ }
6959
9546
  function mimeToFormat(mimeType) {
6960
9547
  if (mimeType.includes("jpeg") || mimeType.includes("jpg")) return "JPG";
6961
9548
  if (mimeType.includes("gif")) return "GIF";
6962
9549
  if (mimeType.includes("bmp")) return "BMP";
6963
9550
  return "PNG";
6964
9551
  }
6965
- function makeImageParagraph(binDataId, nextId, widthHwp = 28346, heightHwp = 19843) {
9552
+ function makeImageParagraph(ref, nextId, widthHwp = 28346, heightHwp = 19843, naturalWidth, naturalHeight) {
6966
9553
  const paraId = nextId();
6967
- return [
6968
- `<hp:p id="${paraId}" paraPrIDRef="0" styleIDRef="0" pageBreak="0" columnBreak="0" merged="0">`,
6969
- ` <hp:run charPrIDRef="0">`,
6970
- ` <hp:pic name="" zOrder="0" numberingType="NONE" textWrap="TOP_AND_BOTTOM" textFlow="BOTH_SIDES"`,
6971
- ` lock="0" dropcapstyle="None" pageBreak="CELL">`,
6972
- ` <hp:instSz width="${widthHwp}" height="${heightHwp}" widthRelTo="ABSOLUTE" heightRelTo="ABSOLUTE" protect="0"/>`,
9554
+ const picId = nextId();
9555
+ const natW = naturalWidth || widthHwp;
9556
+ const natH = naturalHeight || heightHwp;
9557
+ const cx = Math.round(widthHwp / 2);
9558
+ const cy = Math.round(heightHwp / 2);
9559
+ const imgLineseg = [
9560
+ ` <hp:linesegarray>`,
9561
+ ` <hp:lineseg textpos="0" vertpos="0" vertsize="${heightHwp}" textheight="${heightHwp}"`,
9562
+ ` baseline="${Math.round(heightHwp * 0.85)}" spacing="600"`,
9563
+ ` horzpos="0" horzsize="42520" flags="393216"/>`,
9564
+ ` </hp:linesegarray>`
9565
+ ].join("\n");
9566
+ const pic = [
9567
+ ` <hp:pic id="${picId}" zOrder="0" numberingType="NONE" textWrap="SQUARE" textFlow="BOTH_SIDES"`,
9568
+ ` lock="0" dropcapstyle="None" href="" groupLevel="0" instid="0" reverse="0">`,
9569
+ ` <hp:offset x="0" y="0"/>`,
9570
+ ` <hp:orgSz width="${widthHwp}" height="${heightHwp}"/>`,
9571
+ ` <hp:curSz width="${widthHwp}" height="${heightHwp}"/>`,
9572
+ ` <hp:flip horizontal="0" vertical="0"/>`,
9573
+ ` <hp:rotationInfo angle="0" centerX="${cx}" centerY="${cy}" rotateimage="1"/>`,
9574
+ ` <hp:renderingInfo>`,
9575
+ ` <hc:transMatrix e1="1" e2="0" e3="0" e4="0" e5="1" e6="0"/>`,
9576
+ ` <hc:scaMatrix e1="1" e2="0" e3="0" e4="0" e5="1" e6="0"/>`,
9577
+ ` <hc:rotMatrix e1="1" e2="0" e3="0" e4="0" e5="1" e6="0"/>`,
9578
+ ` </hp:renderingInfo>`,
9579
+ ` <hc:img binaryItemIDRef="${ref}" bright="0" contrast="0" effect="REAL_PIC" alpha="0"/>`,
9580
+ ` <hp:imgRect>`,
9581
+ ` <hc:pt0 x="0" y="0"/>`,
9582
+ ` <hc:pt1 x="${widthHwp}" y="0"/>`,
9583
+ ` <hc:pt2 x="${widthHwp}" y="${heightHwp}"/>`,
9584
+ ` <hc:pt3 x="0" y="${heightHwp}"/>`,
9585
+ ` </hp:imgRect>`,
9586
+ ` <hp:imgClip left="0" right="${natW}" top="0" bottom="${natH}"/>`,
9587
+ ` <hp:inMargin left="0" right="0" top="0" bottom="0"/>`,
9588
+ ` <hp:imgDim dimwidth="${natW}" dimheight="${natH}"/>`,
9589
+ ` <hp:effects/>`,
9590
+ ` <hp:sz width="${widthHwp}" widthRelTo="ABSOLUTE" height="${heightHwp}" heightRelTo="ABSOLUTE" protect="0"/>`,
6973
9591
  ` <hp:pos treatAsChar="1" affectLSpacing="0" flowWithText="1" allowOverlap="0"`,
6974
- ` holdAnchorAndSO="0" vertRelTo="PARA" horzRelTo="COLUMN"`,
9592
+ ` holdAnchorAndSO="0" vertRelTo="PARA" horzRelTo="PARA"`,
6975
9593
  ` vertAlign="TOP" horzAlign="LEFT" vertOffset="0" horzOffset="0"/>`,
6976
9594
  ` <hp:outMargin left="0" right="0" top="0" bottom="0"/>`,
6977
- ` <hp:content binaryItemIDRef="${binDataId}"/>`,
6978
- ` <hp:imgRect left="0" top="0" right="${widthHwp}" bottom="${heightHwp}"/>`,
6979
- ` <hp:imgClip left="0" top="0" right="${widthHwp}" bottom="${heightHwp}"/>`,
6980
- ` </hp:pic>`,
9595
+ ` </hp:pic>`
9596
+ ].join("\n");
9597
+ return [
9598
+ `<hp:p id="${paraId}" paraPrIDRef="0" styleIDRef="0" pageBreak="0" columnBreak="0" merged="0">`,
9599
+ ` <hp:run charPrIDRef="0">`,
9600
+ pic,
6981
9601
  ` </hp:run>`,
6982
- LINESEG,
9602
+ imgLineseg,
6983
9603
  `</hp:p>`
6984
9604
  ].join("\n");
6985
9605
  }
@@ -6991,57 +9611,51 @@ function makeCodeParagraphs(code, nextId) {
6991
9611
  return [
6992
9612
  `<hp:p id="${id}" paraPrIDRef="0" styleIDRef="0" pageBreak="0" columnBreak="0" merged="0">`,
6993
9613
  ` <hp:run charPrIDRef="${CHAR_CODE}"><hp:t>${safe}</hp:t></hp:run>`,
6994
- LINESEG,
6995
9614
  `</hp:p>`
6996
9615
  ].join("\n");
6997
9616
  }).join("\n");
6998
9617
  }
6999
- function generateSectionXml(blocks, styleMap, imageMap) {
9618
+ function generateSectionXml(blocks, styleMap, imageMap, imageDimsMap, secPrXml, colPrXml, masterPageCnt = 0) {
7000
9619
  const nextId = makeIdGen();
7001
9620
  const firstId = nextId();
7002
9621
  const defaultCharPr = styleMap ? styleMap.body.charPr : CHAR_NORMAL;
7003
9622
  const defaultParaPr = styleMap ? styleMap.body.paraPr : PARA_NORMAL;
9623
+ const secPrContent = secPrXml ? secPrXml.replace(/masterPageCnt="\d+"/, `masterPageCnt="${masterPageCnt}"`) : [
9624
+ `<hp:secPr id="" textDirection="HORIZONTAL" spaceColumns="1134" tabStop="8000" tabStopVal="4000" tabStopUnit="HWPUNIT" outlineShapeIDRef="1" memoShapeIDRef="0" textVerticalWidthHead="0" masterPageCnt="${masterPageCnt}">`,
9625
+ ` <hp:grid lineGrid="0" charGrid="0" wonggojiFormat="0"/>`,
9626
+ ` <hp:startNum pageStartsOn="BOTH" page="0" pic="0" tbl="0" equation="0"/>`,
9627
+ ` <hp:visibility hideFirstHeader="0" hideFirstFooter="0" hideFirstMasterPage="0" border="SHOW_ALL" fill="SHOW_ALL" hideFirstPageNum="0" hideFirstEmptyLine="0" showLineNumber="0"/>`,
9628
+ ` <hp:lineNumberShape restartType="0" countBy="0" distance="0" startNumber="0"/>`,
9629
+ ` <hp:pagePr landscape="WIDELY" width="59528" height="84186" gutterType="LEFT_ONLY">`,
9630
+ ` <hp:margin header="4252" footer="4252" gutter="0" left="8504" right="8504" top="8504" bottom="8504"/>`,
9631
+ ` </hp:pagePr>`,
9632
+ ` <hp:footNotePr>`,
9633
+ ` <hp:autoNumFormat type="DIGIT" userChar="" prefixChar="" suffixChar=")" supscript="0"/>`,
9634
+ ` <hp:noteLine length="-1" type="SOLID" width="0.12 mm" color="#000000"/>`,
9635
+ ` <hp:noteSpacing betweenNotes="283" belowLine="567" aboveLine="850"/>`,
9636
+ ` <hp:numbering type="CONTINUOUS" newNum="1"/>`,
9637
+ ` <hp:placement place="EACH_COLUMN" beneathText="0"/>`,
9638
+ ` </hp:footNotePr>`,
9639
+ ` <hp:endNotePr>`,
9640
+ ` <hp:autoNumFormat type="DIGIT" userChar="" prefixChar="" suffixChar=")" supscript="0"/>`,
9641
+ ` <hp:noteLine length="14692344" type="SOLID" width="0.12 mm" color="#000000"/>`,
9642
+ ` <hp:noteSpacing betweenNotes="0" belowLine="567" aboveLine="850"/>`,
9643
+ ` <hp:numbering type="CONTINUOUS" newNum="1"/>`,
9644
+ ` <hp:placement place="END_OF_DOCUMENT" beneathText="0"/>`,
9645
+ ` </hp:endNotePr>`,
9646
+ `</hp:secPr>`
9647
+ ].join("\n");
9648
+ const colPrContent = colPrXml || `<hp:ctrl>
9649
+ <hp:colPr id="" type="NEWSPAPER" layout="LEFT" colCount="1" sameSz="1" sameGap="0"/>
9650
+ </hp:ctrl>`;
7004
9651
  const secPrBlock = [
7005
9652
  `<hp:p id="${firstId}" paraPrIDRef="0" styleIDRef="0" pageBreak="0" columnBreak="0" merged="0">`,
7006
9653
  ` <hp:run charPrIDRef="0">`,
7007
- ` <hp:secPr id="" textDirection="HORIZONTAL" spaceColumns="1134" tabStop="8000" tabStopVal="4000" tabStopUnit="HWPUNIT" outlineShapeIDRef="1" memoShapeIDRef="0" textVerticalWidthHead="0" masterPageCnt="0">`,
7008
- ` <hp:grid lineGrid="0" charGrid="0" wonggojiFormat="0"/>`,
7009
- ` <hp:startNum pageStartsOn="BOTH" page="0" pic="0" tbl="0" equation="0"/>`,
7010
- ` <hp:visibility hideFirstHeader="0" hideFirstFooter="0" hideFirstMasterPage="0" border="SHOW_ALL" fill="SHOW_ALL" hideFirstPageNum="0" hideFirstEmptyLine="0" showLineNumber="0"/>`,
7011
- ` <hp:lineNumberShape restartType="0" countBy="0" distance="0" startNumber="0"/>`,
7012
- ` <hp:pagePr landscape="WIDELY" width="59528" height="84186" gutterType="LEFT_ONLY">`,
7013
- ` <hp:margin header="4252" footer="4252" gutter="0" left="8504" right="8504" top="8504" bottom="8504"/>`,
7014
- ` </hp:pagePr>`,
7015
- ` <hp:footNotePr>`,
7016
- ` <hp:autoNumFormat type="DIGIT" userChar="" prefixChar="" suffixChar=")" supscript="0"/>`,
7017
- ` <hp:noteLine length="-1" type="SOLID" width="0.12 mm" color="#000000"/>`,
7018
- ` <hp:noteSpacing betweenNotes="283" belowLine="567" aboveLine="850"/>`,
7019
- ` <hp:numbering type="CONTINUOUS" newNum="1"/>`,
7020
- ` <hp:placement place="EACH_COLUMN" beneathText="0"/>`,
7021
- ` </hp:footNotePr>`,
7022
- ` <hp:endNotePr>`,
7023
- ` <hp:autoNumFormat type="DIGIT" userChar="" prefixChar="" suffixChar=")" supscript="0"/>`,
7024
- ` <hp:noteLine length="14692344" type="SOLID" width="0.12 mm" color="#000000"/>`,
7025
- ` <hp:noteSpacing betweenNotes="0" belowLine="567" aboveLine="850"/>`,
7026
- ` <hp:numbering type="CONTINUOUS" newNum="1"/>`,
7027
- ` <hp:placement place="END_OF_DOCUMENT" beneathText="0"/>`,
7028
- ` </hp:endNotePr>`,
7029
- ` <hp:pageBorderFill type="BOTH" borderFillIDRef="1" textBorder="PAPER" headerInside="0" footerInside="0" fillArea="PAPER">`,
7030
- ` <hp:offset left="1417" right="1417" top="1417" bottom="1417"/>`,
7031
- ` </hp:pageBorderFill>`,
7032
- ` <hp:pageBorderFill type="EVEN" borderFillIDRef="1" textBorder="PAPER" headerInside="0" footerInside="0" fillArea="PAPER">`,
7033
- ` <hp:offset left="1417" right="1417" top="1417" bottom="1417"/>`,
7034
- ` </hp:pageBorderFill>`,
7035
- ` <hp:pageBorderFill type="ODD" borderFillIDRef="1" textBorder="PAPER" headerInside="0" footerInside="0" fillArea="PAPER">`,
7036
- ` <hp:offset left="1417" right="1417" top="1417" bottom="1417"/>`,
7037
- ` </hp:pageBorderFill>`,
7038
- ` </hp:secPr>`,
7039
- ` <hp:ctrl>`,
7040
- ` <hp:colPr id="" type="NEWSPAPER" layout="LEFT" colCount="1" sameSz="1" sameGap="0"/>`,
7041
- ` </hp:ctrl>`,
9654
+ secPrContent,
9655
+ colPrContent,
7042
9656
  ` </hp:run>`,
7043
9657
  ` <hp:run charPrIDRef="0"><hp:t/></hp:run>`,
7044
- LINESEG,
9658
+ makeLineseg(42520, 1e3),
7045
9659
  `</hp:p>`
7046
9660
  ].join("\n");
7047
9661
  const bodyParts = [];
@@ -7053,23 +9667,26 @@ function generateSectionXml(blocks, styleMap, imageMap) {
7053
9667
  const level = block.level || 1;
7054
9668
  let charPrId;
7055
9669
  let paraPrId;
9670
+ let styleId = "0";
7056
9671
  if (styleMap) {
7057
9672
  const blockType = level === 1 ? "h1" : level === 2 ? "h2" : level === 3 ? "h3" : "h4";
7058
9673
  const style = getStyleForBlock(styleMap, blockType);
7059
9674
  charPrId = style.charPr;
7060
9675
  paraPrId = style.paraPr || defaultParaPr;
9676
+ styleId = style.styleId ?? "0";
7061
9677
  } else {
7062
9678
  charPrId = headingCharPr(level);
7063
9679
  paraPrId = PARA_NORMAL;
7064
9680
  }
7065
- bodyParts.push(makeParagraph(block.text || "", charPrId, paraPrId, nextId));
9681
+ bodyParts.push(makeParagraph(block.text || "", charPrId, paraPrId, nextId, styleId));
7066
9682
  break;
7067
9683
  }
7068
9684
  case "paragraph": {
7069
9685
  if (block.text) {
7070
9686
  const charPrId = styleMap ? styleMap.body.charPr : CHAR_NORMAL;
7071
9687
  const paraPrId = styleMap ? styleMap.body.paraPr : PARA_NORMAL;
7072
- bodyParts.push(makeParagraph(block.text, charPrId, paraPrId, nextId));
9688
+ const styleId = styleMap ? styleMap.body.styleId ?? "0" : "0";
9689
+ bodyParts.push(makeParagraph(block.text, charPrId, paraPrId, nextId, styleId));
7073
9690
  } else {
7074
9691
  bodyParts.push(makeEmptyParagraph(nextId));
7075
9692
  }
@@ -7079,6 +9696,12 @@ function generateSectionXml(blocks, styleMap, imageMap) {
7079
9696
  bodyParts.push(makeCodeParagraphs(block.text || "", nextId));
7080
9697
  break;
7081
9698
  }
9699
+ case "blockquote":
9700
+ if (block.text) bodyParts.push(makeBlockquoteParagraph(block.text, nextId));
9701
+ break;
9702
+ case "hr":
9703
+ bodyParts.push(makeHrParagraph(nextId));
9704
+ break;
7082
9705
  case "empty":
7083
9706
  bodyParts.push(makeEmptyParagraph(nextId));
7084
9707
  break;
@@ -7111,9 +9734,16 @@ function generateSectionXml(blocks, styleMap, imageMap) {
7111
9734
  break;
7112
9735
  case "image": {
7113
9736
  const src = block.src || "";
7114
- const binId = imageMap?.get(src);
7115
- if (binId !== void 0) {
7116
- bodyParts.push(makeImageParagraph(binId, nextId));
9737
+ const srcBasename = src.includes("/") || src.includes("\\") ? src.split(/[\\/]/).pop() : src;
9738
+ const extLower = srcBasename.toLowerCase();
9739
+ if (extLower.endsWith(".wmf") || extLower.endsWith(".emf")) break;
9740
+ const ref = imageMap?.get(src) ?? imageMap?.get(srcBasename);
9741
+ if (ref !== void 0) {
9742
+ const dims = imageDimsMap?.get(ref);
9743
+ const { widthHwp, heightHwp } = dims ? calcHwpSize(dims.width, dims.height) : { widthHwp: 28346, heightHwp: 19843 };
9744
+ const natW = dims ? Math.round(dims.width * 75) : widthHwp;
9745
+ const natH = dims ? Math.round(dims.height * 75) : heightHwp;
9746
+ bodyParts.push(makeImageParagraph(ref, nextId, widthHwp, heightHwp, natW, natH));
7117
9747
  } else {
7118
9748
  const alt = block.alt || src || "(\uC774\uBBF8\uC9C0)";
7119
9749
  bodyParts.push(makeParagraph(`[\uC774\uBBF8\uC9C0: ${alt}]`, CHAR_NORMAL, PARA_NORMAL, nextId));
@@ -7140,44 +9770,86 @@ async function markdownToHwpx(markdown, options) {
7140
9770
  const warnings = opts.warnings || [];
7141
9771
  let styleMap = null;
7142
9772
  let headerXml = HEADER_XML;
7143
- let templateZip = null;
9773
+ let secPrXml;
9774
+ let colPrXml;
9775
+ let masterpages = [];
7144
9776
  if (opts.templateArrayBuffer) {
7145
9777
  try {
7146
9778
  const templateStyles = await extractTemplateStyles(opts.templateArrayBuffer);
7147
9779
  styleMap = createStyleMap(templateStyles, warnings);
7148
- templateZip = new JSZip6();
7149
- await templateZip.loadAsync(opts.templateArrayBuffer);
7150
- const headerFile = templateZip.file("Contents/header.xml");
7151
- if (headerFile) {
7152
- headerXml = await headerFile.async("text");
7153
- }
9780
+ if (templateStyles.headerXml) headerXml = templateStyles.headerXml;
9781
+ if (templateStyles.secPrXml) secPrXml = templateStyles.secPrXml;
9782
+ if (templateStyles.colPrXml) colPrXml = templateStyles.colPrXml;
9783
+ if (templateStyles.masterpages?.length) masterpages = templateStyles.masterpages;
7154
9784
  } catch (err) {
7155
9785
  const msg = err instanceof Error ? err.message : "\uC54C \uC218 \uC5C6\uB294 \uC624\uB958";
7156
9786
  warnings.push(`[warn] \uD15C\uD50C\uB9BF \uCC98\uB9AC \uC2E4\uD328: ${msg}. \uAE30\uBCF8 \uC2A4\uD0C0\uC77C \uC0AC\uC6A9`);
7157
9787
  }
7158
9788
  }
7159
9789
  const imageMap = /* @__PURE__ */ new Map();
9790
+ const imageDimsMap = /* @__PURE__ */ new Map();
7160
9791
  const binDataEntries = [];
9792
+ const usedRefs = /* @__PURE__ */ new Set();
7161
9793
  if (opts.images && opts.images.length > 0) {
7162
- for (let idx = 0; idx < opts.images.length; idx++) {
7163
- const img = opts.images[idx];
7164
- const binId = idx + 1;
7165
- const format = mimeToFormat(img.mimeType);
9794
+ for (const img of opts.images) {
7166
9795
  const nameWithoutExt = img.filename.replace(/\.[^.]+$/, "");
7167
- const binFilename = `BinData/${nameWithoutExt}`;
7168
- imageMap.set(img.filename, binId);
7169
- binDataEntries.push({ id: binId, format, filename: binFilename });
9796
+ const format = mimeToFormat(img.mimeType);
9797
+ const ext = format.toLowerCase() === "jpg" ? "jpg" : format.toLowerCase();
9798
+ let ref = nameWithoutExt;
9799
+ let counter = 1;
9800
+ while (usedRefs.has(ref)) ref = `${nameWithoutExt}_${counter++}`;
9801
+ usedRefs.add(ref);
9802
+ const dims = getImageDimensions(img.data) || void 0;
9803
+ binDataEntries.push({ ref, zipPath: `BinData/${ref}.${ext}`, data: img.data, dims });
9804
+ if (dims) imageDimsMap.set(ref, dims);
9805
+ imageMap.set(img.filename, ref);
9806
+ }
9807
+ }
9808
+ const allBlocks = parseMarkdownToBlocks(markdown);
9809
+ for (const block of allBlocks) {
9810
+ if (block.type === "image" && block.src?.startsWith("data:") && !imageMap.has(block.src)) {
9811
+ const commaIdx = block.src.indexOf(",");
9812
+ if (commaIdx === -1) continue;
9813
+ const header = block.src.slice(0, commaIdx);
9814
+ const b64 = block.src.slice(commaIdx + 1);
9815
+ const mimeMatch = header.match(/data:([^;]+)/);
9816
+ const mimeType = mimeMatch?.[1] || "image/png";
9817
+ const format = mimeToFormat(mimeType);
9818
+ const ext = format.toLowerCase() === "jpg" ? "jpg" : format.toLowerCase();
9819
+ const data = Buffer.from(b64, "base64");
9820
+ const ref = `datauri_${binDataEntries.length + 1}`;
9821
+ const dims = getImageDimensions(data) || void 0;
9822
+ imageMap.set(block.src, ref);
9823
+ binDataEntries.push({ ref, zipPath: `BinData/${ref}.${ext}`, data, dims });
9824
+ if (dims) imageDimsMap.set(ref, dims);
7170
9825
  }
7171
9826
  }
7172
- if (binDataEntries.length > 0) {
7173
- const binXml = binDataEntries.map((e) => ` <hh:binData id="${e.id}" type="LINK" format="${e.format}" compress="NO" access="PUBLIC"><hh:sourceFile href="${e.filename}"/></hh:binData>`).join("\n");
7174
- headerXml = headerXml.replace("</hh:refList>", `${binXml}
7175
- </hh:refList>`);
7176
- }
7177
9827
  const sectionXml = generateSectionXml(
7178
- parseMarkdownToBlocks(markdown),
9828
+ allBlocks,
7179
9829
  styleMap || void 0,
7180
- imageMap.size > 0 ? imageMap : void 0
9830
+ imageMap.size > 0 ? imageMap : void 0,
9831
+ imageDimsMap.size > 0 ? imageDimsMap : void 0,
9832
+ secPrXml,
9833
+ colPrXml,
9834
+ masterpages.length
9835
+ );
9836
+ const formatToMediaType = (zipPath) => {
9837
+ const ext = zipPath.split(".").pop()?.toLowerCase() || "";
9838
+ if (ext === "png") return "image/png";
9839
+ if (ext === "gif") return "image/gif";
9840
+ if (ext === "bmp") return "image/bmp";
9841
+ return "image/jpg";
9842
+ };
9843
+ const imageItems = binDataEntries.map((e) => ` <opf:item id="${e.ref}" href="${e.zipPath}" media-type="${formatToMediaType(e.zipPath)}" isEmbeded="1"/>`).join("\n");
9844
+ const masterpageItems = masterpages.map((mp) => {
9845
+ const id = mp.filename.replace("Contents/", "").replace(".xml", "");
9846
+ return ` <opf:item id="${id}" href="${mp.filename}" media-type="application/xml"/>`;
9847
+ }).join("\n");
9848
+ const extraItems = [imageItems, masterpageItems].filter(Boolean).join("\n");
9849
+ const contentHpf = CONTENT_HPF.replace(
9850
+ ` <opf:item id="header"`,
9851
+ extraItems ? `${extraItems}
9852
+ <opf:item id="header"` : ` <opf:item id="header"`
7181
9853
  );
7182
9854
  const zip = new JSZip6();
7183
9855
  zip.file("mimetype", "application/hwp+zip", { compression: "STORE" });
@@ -7187,20 +9859,173 @@ async function markdownToHwpx(markdown, options) {
7187
9859
  zip.file("version.xml", VERSION_XML);
7188
9860
  zip.file("settings.xml", SETTINGS_XML);
7189
9861
  zip.file("Preview/PrvText.txt", "");
7190
- zip.file("Contents/content.hpf", CONTENT_HPF);
9862
+ zip.file("Contents/content.hpf", contentHpf);
7191
9863
  zip.file("Contents/header.xml", headerXml);
7192
9864
  zip.file("Contents/section0.xml", sectionXml);
7193
- if (opts.images && opts.images.length > 0) {
7194
- for (const img of opts.images) {
7195
- const nameWithoutExt = img.filename.replace(/\.[^.]+$/, "");
7196
- zip.file(`BinData/${nameWithoutExt}`, img.data);
9865
+ for (const mp of masterpages) {
9866
+ zip.file(mp.filename, mp.content);
9867
+ }
9868
+ for (const entry of binDataEntries) {
9869
+ if (entry.data) {
9870
+ zip.file(entry.zipPath, entry.data);
7197
9871
  }
7198
9872
  }
7199
9873
  return await zip.generateAsync({ type: "arraybuffer" });
7200
9874
  }
7201
9875
 
9876
+ // src/xlsx/generator.ts
9877
+ import ExcelJS from "exceljs";
9878
+ function mimeToExtension(mimeType) {
9879
+ if (mimeType.includes("jpeg") || mimeType.includes("jpg")) return "jpeg";
9880
+ if (mimeType.includes("gif")) return "gif";
9881
+ return "png";
9882
+ }
9883
+ function buildImageMap(images) {
9884
+ const map = /* @__PURE__ */ new Map();
9885
+ if (!images) return map;
9886
+ for (const img of images) map.set(img.filename, img);
9887
+ return map;
9888
+ }
9889
+ async function fillBodySheet(sheet, workbook, blocks, imageMap) {
9890
+ sheet.getColumn(1).width = 80;
9891
+ for (const block of blocks) {
9892
+ switch (block.type) {
9893
+ case "heading": {
9894
+ const level = block.level || 1;
9895
+ const size = level === 1 ? 20 : level === 2 ? 16 : level === 3 ? 14 : 12;
9896
+ const row = sheet.addRow([block.text || ""]);
9897
+ row.getCell(1).font = { bold: true, size };
9898
+ row.getCell(1).alignment = { wrapText: true };
9899
+ break;
9900
+ }
9901
+ case "paragraph": {
9902
+ const row = sheet.addRow([block.text || ""]);
9903
+ row.getCell(1).alignment = { wrapText: true };
9904
+ break;
9905
+ }
9906
+ case "code": {
9907
+ const lines = (block.text || "").split("\n");
9908
+ for (const line of lines) {
9909
+ const row = sheet.addRow([line || " "]);
9910
+ row.getCell(1).font = { name: "Courier New", size: 9 };
9911
+ row.getCell(1).fill = {
9912
+ type: "pattern",
9913
+ pattern: "solid",
9914
+ fgColor: { argb: "FFF2F2F2" }
9915
+ };
9916
+ }
9917
+ break;
9918
+ }
9919
+ case "blockquote": {
9920
+ const row = sheet.addRow([block.text || ""]);
9921
+ row.getCell(1).font = { italic: true, color: { argb: "FF888888" } };
9922
+ row.getCell(1).alignment = { wrapText: true };
9923
+ break;
9924
+ }
9925
+ case "hr": {
9926
+ const row = sheet.addRow([""]);
9927
+ row.getCell(1).border = {
9928
+ bottom: { style: "medium", color: { argb: "FF888888" } }
9929
+ };
9930
+ break;
9931
+ }
9932
+ case "empty": {
9933
+ sheet.addRow([""]);
9934
+ break;
9935
+ }
9936
+ case "list": {
9937
+ for (const item of block.items || []) {
9938
+ const indent = " ".repeat(item.indent);
9939
+ const bullet = block.listType === "ordered" ? `${item.indent + 1}. ` : ["\u2022 ", "\u25E6 ", "\u25AA "][Math.min(item.indent, 2)];
9940
+ const row = sheet.addRow([`${indent}${bullet}${item.text}`]);
9941
+ row.getCell(1).alignment = { wrapText: true };
9942
+ }
9943
+ break;
9944
+ }
9945
+ case "image": {
9946
+ const src = block.src || "";
9947
+ const img = imageMap.get(src);
9948
+ if (img) {
9949
+ const currentRow = sheet.rowCount + 1;
9950
+ const ext = mimeToExtension(img.mimeType);
9951
+ const imageId = workbook.addImage({ base64: Buffer.from(img.data).toString("base64"), extension: ext });
9952
+ sheet.addRow([""]);
9953
+ sheet.addImage(imageId, {
9954
+ tl: { col: 0, row: currentRow - 1 },
9955
+ ext: { width: 300, height: 200 }
9956
+ });
9957
+ sheet.getRow(currentRow).height = 155;
9958
+ } else {
9959
+ const alt = block.alt || src || "(\uC774\uBBF8\uC9C0)";
9960
+ const row = sheet.addRow([`[\uC774\uBBF8\uC9C0: ${alt}]`]);
9961
+ row.getCell(1).font = { italic: true, color: { argb: "FF999999" } };
9962
+ }
9963
+ break;
9964
+ }
9965
+ }
9966
+ }
9967
+ }
9968
+ function fillTableSheet(sheet, rows) {
9969
+ for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {
9970
+ const cells = rows[rowIdx];
9971
+ const row = sheet.addRow(cells);
9972
+ cells.forEach((cell, colIdx) => {
9973
+ const col = sheet.getColumn(colIdx + 1);
9974
+ col.width = Math.max(col.width ?? 10, Math.min(cell.length + 4, 40));
9975
+ });
9976
+ if (rowIdx === 0) {
9977
+ row.eachCell((cell) => {
9978
+ cell.font = { bold: true };
9979
+ cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFD9E1F2" } };
9980
+ cell.border = {
9981
+ top: { style: "thin" },
9982
+ bottom: { style: "thin" },
9983
+ left: { style: "thin" },
9984
+ right: { style: "thin" }
9985
+ };
9986
+ cell.alignment = { wrapText: true };
9987
+ });
9988
+ } else {
9989
+ row.eachCell((cell) => {
9990
+ cell.border = {
9991
+ top: { style: "thin" },
9992
+ bottom: { style: "thin" },
9993
+ left: { style: "thin" },
9994
+ right: { style: "thin" }
9995
+ };
9996
+ cell.alignment = { wrapText: true };
9997
+ });
9998
+ }
9999
+ }
10000
+ }
10001
+ async function markdownToXlsx(markdown, options) {
10002
+ const warnings = options?.warnings || [];
10003
+ const imageMap = buildImageMap(options?.images);
10004
+ const blocks = parseMarkdownToBlocks(markdown);
10005
+ const workbook = new ExcelJS.Workbook();
10006
+ workbook.created = /* @__PURE__ */ new Date();
10007
+ const tableBlocks = blocks.filter((b) => b.type === "table");
10008
+ const bodyBlocks = blocks.filter((b) => b.type !== "table");
10009
+ const hasBodyContent = bodyBlocks.some((b) => b.type !== "empty");
10010
+ if (hasBodyContent) {
10011
+ const bodySheet = workbook.addWorksheet("\uBCF8\uBB38");
10012
+ await fillBodySheet(bodySheet, workbook, bodyBlocks, imageMap);
10013
+ }
10014
+ tableBlocks.forEach((block, idx) => {
10015
+ if (!block.rows?.length) return;
10016
+ const sheet = workbook.addWorksheet(`Table ${idx + 1}`);
10017
+ fillTableSheet(sheet, block.rows);
10018
+ });
10019
+ if (workbook.worksheets.length === 0) {
10020
+ workbook.addWorksheet("\uBCF8\uBB38");
10021
+ warnings.push("[warn] \uBCC0\uD658\uD560 \uB0B4\uC6A9\uC774 \uC5C6\uC5B4 \uBE48 \uC2DC\uD2B8\uB97C \uC0DD\uC131\uD588\uC2B5\uB2C8\uB2E4.");
10022
+ }
10023
+ const buffer = await workbook.xlsx.writeBuffer();
10024
+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
10025
+ }
10026
+
7202
10027
  // src/index.ts
7203
- async function parse(input, options) {
10028
+ async function parse2(input, options) {
7204
10029
  let buffer;
7205
10030
  if (typeof input === "string") {
7206
10031
  try {
@@ -7288,11 +10113,17 @@ export {
7288
10113
  isPdfFile,
7289
10114
  isZipFile,
7290
10115
  markdownToHwpx,
7291
- parse,
10116
+ markdownToXlsx,
10117
+ parse2 as parse,
7292
10118
  parseDocx,
7293
10119
  parseHwp,
7294
10120
  parseHwpx,
7295
10121
  parsePdf,
7296
10122
  parseXlsx
7297
10123
  };
10124
+ /*! Bundled license information:
10125
+
10126
+ cfb/cfb.js:
10127
+ (*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com *)
10128
+ */
7298
10129
  //# sourceMappingURL=index.js.map