hwpx2f 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +124 -2
  3. package/THIRD_PARTY_NOTICES.md +75 -0
  4. package/dist/cli.js +76 -0
  5. package/dist/index.d.ts +11 -0
  6. package/dist/index.js +32 -0
  7. package/dist/lib/chunk-36PRCVPO.js +131 -0
  8. package/dist/lib/chunk-45BAITEX.js +9749 -0
  9. package/dist/lib/chunk-4NRZ6MWV.js +133 -0
  10. package/dist/lib/chunk-6CFXTS7A.js +11971 -0
  11. package/dist/lib/chunk-6CPCDYOD.js +104 -0
  12. package/dist/lib/chunk-B6MTS4XP.js +313 -0
  13. package/dist/lib/chunk-BX24E7EG.js +1427 -0
  14. package/dist/lib/chunk-C64I2SU4.js +82 -0
  15. package/dist/lib/chunk-CEKQASS3.js +258 -0
  16. package/dist/lib/chunk-CMWTKXM2.js +204 -0
  17. package/dist/lib/chunk-E6KSYRHG.js +2189 -0
  18. package/dist/lib/chunk-IZDWVMTV.js +28786 -0
  19. package/dist/lib/chunk-JK6YR5NT.js +4276 -0
  20. package/dist/lib/chunk-O6FSHPNE.js +111 -0
  21. package/dist/lib/chunk-OYXOOP2U.js +199 -0
  22. package/dist/lib/chunk-PM4KBWF4.js +49 -0
  23. package/dist/lib/chunk-R5F3GHLO.js +290 -0
  24. package/dist/lib/chunk-R76DWHJR.js +1596 -0
  25. package/dist/lib/chunk-RFS3RTSR.js +6876 -0
  26. package/dist/lib/chunk-RYJRNK5Z.js +47 -0
  27. package/dist/lib/chunk-UOXPGSFH.js +43 -0
  28. package/dist/lib/chunk-UZH4UBMX.js +44 -0
  29. package/dist/lib/chunk-VZTE4GKI.js +52 -0
  30. package/dist/lib/chunk-WEOKEO6L.js +35291 -0
  31. package/dist/lib/detect-4XZNNYZA-O7IPA4XQ.js +32 -0
  32. package/dist/lib/dist-HVSOXNCJ.js +263 -0
  33. package/dist/lib/formula-LC62GV4D-K3VFC5GV.js +1173 -0
  34. package/dist/lib/generator-KYTTL4OS-TRAQ66QE.js +14 -0
  35. package/dist/lib/hancom-EM62ZVDM-WZKVI7XB.js +91 -0
  36. package/dist/lib/image-ocr-ZUZQXLYS-U66LBMRA.js +293 -0
  37. package/dist/lib/page-images-VCIFZAXK-KJLWQDRH.js +95 -0
  38. package/dist/lib/page-range-7R3JU6SQ-MDDQRZVK.js +10 -0
  39. package/dist/lib/parser-JQNH5QMM-HFFI4HYK.js +4310 -0
  40. package/dist/lib/pdf-ocr-C3MBR6J2-J3UGJKWT.js +46 -0
  41. package/dist/lib/to-hwpx-JUT2SOTT-MOPPK6OW.js +17 -0
  42. package/dist/notices/core-util-is/LICENSE +19 -0
  43. package/dist/notices/entities/LICENSE +11 -0
  44. package/dist/notices/immediate/LICENSE.txt +20 -0
  45. package/dist/notices/inherits/LICENSE +16 -0
  46. package/dist/notices/jszip/LICENSE.markdown +651 -0
  47. package/dist/notices/kordoc/LICENSE +21 -0
  48. package/dist/notices/kordoc/NOTICE +376 -0
  49. package/dist/notices/kordoc/THIRD_PARTY/apache-2.0.LICENSE +201 -0
  50. package/dist/notices/kordoc/THIRD_PARTY/claw-hwp.LICENSE +21 -0
  51. package/dist/notices/kordoc/THIRD_PARTY/hayro-pdf.txt +361 -0
  52. package/dist/notices/kordoc/THIRD_PARTY/hml-equation-parser.LICENSE +201 -0
  53. package/dist/notices/kordoc/THIRD_PARTY/hml-equation-parser.txt +35 -0
  54. package/dist/notices/kordoc/THIRD_PARTY/korean-report-hwpx.LICENSE +21 -0
  55. package/dist/notices/kordoc/THIRD_PARTY/memchr.LICENSE +21 -0
  56. package/dist/notices/kordoc/THIRD_PARTY/opendataloader-pdf.txt +32 -0
  57. package/dist/notices/kordoc/THIRD_PARTY/pix2text.txt +17 -0
  58. package/dist/notices/kordoc/THIRD_PARTY/quick-xml.LICENSE +23 -0
  59. package/dist/notices/kordoc/THIRD_PARTY/rhwp-forms.txt +35 -0
  60. package/dist/notices/lie/license.md +7 -0
  61. package/dist/notices/linkify-it/LICENSE +22 -0
  62. package/dist/notices/markdown-it/LICENSE +22 -0
  63. package/dist/notices/mdurl/LICENSE +45 -0
  64. package/dist/notices/pako/LICENSE +21 -0
  65. package/dist/notices/process-nextick-args/license.md +19 -0
  66. package/dist/notices/punycode.js/LICENSE-MIT.txt +20 -0
  67. package/dist/notices/readable-stream/LICENSE +47 -0
  68. package/dist/notices/safe-buffer/LICENSE +21 -0
  69. package/dist/notices/setimmediate/LICENSE.txt +20 -0
  70. package/dist/notices/string_decoder/LICENSE +48 -0
  71. package/dist/notices/uc.micro/LICENSE.txt +20 -0
  72. package/dist/notices/util-deprecate/LICENSE +24 -0
  73. package/package.json +66 -4
@@ -0,0 +1,4310 @@
1
+ import { createRequire as __hwpx2fRequire } from 'node:module'; const require = __hwpx2fRequire(import.meta.url);
2
+ import {
3
+ HayroOpenError,
4
+ QR_UNAVAILABLE,
5
+ blocksToPages,
6
+ hayroFontData,
7
+ hayroFontInfo,
8
+ hayroOps,
9
+ hayroTextPage,
10
+ isBlankRgba,
11
+ loadQrReader,
12
+ openHayro,
13
+ pdfInfo,
14
+ pdfLinkAnnotations,
15
+ remapControlGlyphs,
16
+ restoreNamedGlyphs,
17
+ restoreUnmappedCidSpaces,
18
+ restoreUnmappedGlyphs,
19
+ spaceMappedDots
20
+ } from "./chunk-E6KSYRHG.js";
21
+ import {
22
+ hasRequestedPagesAfter,
23
+ parsePageRange
24
+ } from "./chunk-VZTE4GKI.js";
25
+ import {
26
+ WEBP_UNAVAILABLE,
27
+ loadWebpEncoder
28
+ } from "./chunk-UZH4UBMX.js";
29
+ import {
30
+ encodePng,
31
+ encodePngAsync,
32
+ pngScanlineBytes
33
+ } from "./chunk-CEKQASS3.js";
34
+ import {
35
+ CELL_LINES,
36
+ CLIP_TABLES,
37
+ CONT_PARTS,
38
+ EMPTY_PARTS,
39
+ FILLER_CELLS,
40
+ FRAME_TITLE_BLOCKS,
41
+ IMAGE_CELLS,
42
+ IMAGE_CELL_BOXES,
43
+ NO_EDGES,
44
+ PART_COLXS,
45
+ ROW_RULES,
46
+ TABLE_COLXS,
47
+ TABLE_ROWYS,
48
+ TABLE_TAIL,
49
+ TOC_BLOCKS,
50
+ WrapLexicon,
51
+ collapseEvenSpacing,
52
+ computeBBox,
53
+ computeMedianFontSizeFromFreq,
54
+ detectDocumentStyleHeadings,
55
+ detectHeadings,
56
+ detectKoreanListBlocks,
57
+ detectMarkerHeadings,
58
+ detectPageLeadHeadings,
59
+ detectRepeatedPageLabels,
60
+ detectRightArrowRegions,
61
+ detectSiblingStyleHeadings,
62
+ detectTableCaptions,
63
+ detectTypographyHeadings,
64
+ dominantStyle,
65
+ extractImageRegions,
66
+ extractLines,
67
+ extractPageBlocksWithLines,
68
+ filterHiddenText,
69
+ groupByY,
70
+ handwritingFallbackModels,
71
+ hasOpenCellSeam,
72
+ joinCellEdges,
73
+ joinPageBreakWraps,
74
+ latinSoftWrap,
75
+ mergeLineSimple,
76
+ mergeOcrImageRegions,
77
+ mergeStackedHeadingLines,
78
+ normalizeItems,
79
+ ocrModelsCached,
80
+ refineDocumentStyleHeadings,
81
+ removeHeaderFooterBlocks,
82
+ removeSideTabs,
83
+ resolveOcrModels,
84
+ restoreImageBullets,
85
+ runningLinePatterns,
86
+ softWrapPair,
87
+ splitPageBreakWraps,
88
+ startsNewItem,
89
+ stripAbsorbedRunningLines,
90
+ trimTrailingEmptyTableCols,
91
+ wrapJoiner
92
+ } from "./chunk-6CFXTS7A.js";
93
+ import {
94
+ ImageKind,
95
+ OPS,
96
+ normalizeUnicode
97
+ } from "./chunk-O6FSHPNE.js";
98
+ import {
99
+ CELL_BASELINES,
100
+ CELL_EDGES,
101
+ CELL_PAGES,
102
+ CELL_SOFT_WRAPS,
103
+ CONTENT_CELLS,
104
+ WINGDINGS,
105
+ assignTableIds,
106
+ blocksToMarkdown,
107
+ carrySoftWraps,
108
+ cellParagraphs,
109
+ enclosedNumber,
110
+ escapeLiteralDollar,
111
+ escapeLiteralTags,
112
+ stripScriptTags,
113
+ toTex,
114
+ unframeLayoutTables
115
+ } from "./chunk-R76DWHJR.js";
116
+ import "./chunk-B6MTS4XP.js";
117
+ import {
118
+ validateOcrOptions
119
+ } from "./chunk-PM4KBWF4.js";
120
+ import {
121
+ KordocError,
122
+ sanitizeHref
123
+ } from "./chunk-OYXOOP2U.js";
124
+ import "./chunk-RYJRNK5Z.js";
125
+
126
+ // node_modules/kordoc/dist/parser-JQNH5QMM.js
127
+ import { createHash } from "node:crypto";
128
+ var IMAGE_RESOLVE_TIMEOUT_MS = 5e3;
129
+ function resolveImgData(page, objId) {
130
+ const store = objId.startsWith("g_") ? page.commonObjs : page.objs;
131
+ return new Promise((resolve) => {
132
+ let done = false;
133
+ const timer = setTimeout(() => {
134
+ if (!done) {
135
+ done = true;
136
+ resolve(null);
137
+ }
138
+ }, IMAGE_RESOLVE_TIMEOUT_MS);
139
+ try {
140
+ store.get(objId, (data) => {
141
+ if (!done) {
142
+ done = true;
143
+ clearTimeout(timer);
144
+ resolve(data ?? null);
145
+ }
146
+ });
147
+ } catch {
148
+ if (!done) {
149
+ done = true;
150
+ clearTimeout(timer);
151
+ resolve(null);
152
+ }
153
+ }
154
+ });
155
+ }
156
+ var MIN_DIM = 8;
157
+ var MAX_PIXELS = 36e6;
158
+ var MAX_IMAGES_PER_DOC = 200;
159
+ var MAX_TOTAL_IMAGE_BYTES = 128 * 1024 * 1024;
160
+ var MAX_PENDING_RAW_BYTES = 64 * 1024 * 1024;
161
+ var MAX_PENDING_PNG_IMAGES = 4;
162
+ var MIN_ASYNC_PNG_BYTES = 64 * 1024;
163
+ function createPdfImageState(webp, placement = false, dropBlank = false) {
164
+ return { imageIndex: 0, totalBytes: 0, seen: /* @__PURE__ */ new Map(), globalKeys: /* @__PURE__ */ new Map(), capWarned: false, webp, pending: [], pendingRaw: 0, renamed: /* @__PURE__ */ new Map(), oversize: 0, failed: /* @__PURE__ */ new Set(), placement, dropBlank };
165
+ }
166
+ function contentHash(data) {
167
+ return createHash("sha1").update(data).digest("hex");
168
+ }
169
+ var NO_BYTES = new Uint8Array(0);
170
+ function toRgba(img, convert = true) {
171
+ const { width: w, height: h, kind, data } = img;
172
+ if (!data || !w || !h) return null;
173
+ if (kind === ImageKind.RGBA_32BPP) {
174
+ if (data.length < w * h * 4) return null;
175
+ if (!convert) return NO_BYTES;
176
+ const rgba = new Uint8Array(w * h * 4);
177
+ rgba.set(data.subarray(0, w * h * 4));
178
+ return rgba;
179
+ }
180
+ if (kind === ImageKind.RGB_24BPP) {
181
+ if (data.length < w * h * 3) return null;
182
+ if (!convert) return NO_BYTES;
183
+ const rgba = new Uint8Array(w * h * 4);
184
+ for (let i = 0, s = 0, d = 0; i < w * h; i++, s += 3, d += 4) {
185
+ rgba[d] = data[s];
186
+ rgba[d + 1] = data[s + 1];
187
+ rgba[d + 2] = data[s + 2];
188
+ rgba[d + 3] = 255;
189
+ }
190
+ return rgba;
191
+ }
192
+ if (kind === ImageKind.GRAYSCALE_1BPP) {
193
+ const stride = w + 7 >> 3;
194
+ if (data.length < stride * h) return null;
195
+ if (!convert) return NO_BYTES;
196
+ const rgba = new Uint8Array(w * h * 4);
197
+ for (let y = 0; y < h; y++) {
198
+ for (let x = 0; x < w; x++) {
199
+ const bit = data[y * stride + (x >> 3)] >> 7 - (x & 7) & 1;
200
+ const v = bit ? 255 : 0;
201
+ const d = (y * w + x) * 4;
202
+ rgba[d] = v;
203
+ rgba[d + 1] = v;
204
+ rgba[d + 2] = v;
205
+ rgba[d + 3] = 255;
206
+ }
207
+ }
208
+ return rgba;
209
+ }
210
+ return null;
211
+ }
212
+ async function extractPageImages(page, fnArray, argsArray, pageNumber, state, warnings, withBytes = true, readQr) {
213
+ const blocks = [];
214
+ const images = [];
215
+ const pageSeenIds = /* @__PURE__ */ new Set();
216
+ const regions = state.placement ? /* @__PURE__ */ new Map() : void 0;
217
+ if (regions) extractImageRegions(fnArray, argsArray, false, regions);
218
+ const placed = (block, i) => {
219
+ const r = regions?.get(i);
220
+ if (r) block.bbox = { page: pageNumber, x: r.x1, y: r.y1, width: r.x2 - r.x1, height: r.y2 - r.y1 };
221
+ return block;
222
+ };
223
+ for (let i = 0; i < fnArray.length; i++) {
224
+ const op = fnArray[i];
225
+ let imgData = null;
226
+ let dedupeId = null;
227
+ if (op === OPS.paintImageXObject || op === OPS.paintImageXObjectRepeat) {
228
+ const objId = argsArray[i]?.[0];
229
+ if (typeof objId !== "string") continue;
230
+ if (pageSeenIds.has(objId)) continue;
231
+ if (await capReached(state, pageNumber, warnings)) continue;
232
+ pageSeenIds.add(objId);
233
+ dedupeId = objId;
234
+ } else if (op !== OPS.paintInlineImageXObject) {
235
+ continue;
236
+ }
237
+ if (await capReached(state, pageNumber, warnings)) continue;
238
+ if (dedupeId) {
239
+ imgData = await resolveImgData(page, dedupeId);
240
+ } else {
241
+ imgData = argsArray[i]?.[0];
242
+ }
243
+ if (!imgData?.data || !imgData.width || !imgData.height) continue;
244
+ const { width: w, height: h, kind, data } = imgData;
245
+ if (w < MIN_DIM || h < MIN_DIM) continue;
246
+ if (w * h > MAX_PIXELS) {
247
+ warnings.push({ page: pageNumber, message: `\uC774\uBBF8\uC9C0 \uD06C\uAE30 \uCD08\uACFC\uB85C \uCD94\uCD9C \uC0DD\uB7B5 (${w}\xD7${h})`, code: "SKIPPED_IMAGE" });
248
+ continue;
249
+ }
250
+ const globalId = dedupeId?.startsWith("g_") ? dedupeId : void 0;
251
+ let hash = globalId ? state.globalKeys.get(globalId) : void 0;
252
+ if (hash === void 0) {
253
+ hash = `${w}x${h}k${kind ?? "?"}h${contentHash(data)}${dedupeId ? "" : "inline"}`;
254
+ if (globalId) state.globalKeys.set(globalId, hash);
255
+ }
256
+ if (state.seen.has(hash)) continue;
257
+ const channels = kind === ImageKind.RGB_24BPP ? 3 : kind === ImageKind.RGBA_32BPP ? 4 : void 0;
258
+ let pixels;
259
+ if (channels && withBytes && !state.webp && !readQr && !state.dropBlank && pngScanlineBytes(w, h) >= MIN_ASYNC_PNG_BYTES) {
260
+ if (data.length < w * h * channels) continue;
261
+ pixels = { data, channels };
262
+ } else {
263
+ const rgba = toRgba(imgData, withBytes || !!readQr || state.dropBlank);
264
+ if (!rgba) continue;
265
+ if (state.dropBlank && isBlankRgba(rgba)) {
266
+ state.seen.set(hash, "");
267
+ continue;
268
+ }
269
+ pixels = { data: rgba };
270
+ }
271
+ state.imageIndex++;
272
+ const filename = imageFilename(state, w, h);
273
+ state.seen.set(hash, filename);
274
+ if (withBytes) await pushImage(state, filename, w, h, pixels, images);
275
+ const qr = readQr && pixels.channels === void 0 ? await readQr({ data: pixels.data, width: w, height: h }) : [];
276
+ blocks.push(placed({ type: "image", text: filename, pageNumber, ...qr.length ? { qr } : {} }, i));
277
+ }
278
+ return { blocks, images };
279
+ }
280
+ async function capReached(state, pageNumber, warnings) {
281
+ if (state.pending.length && state.totalBytes + state.pendingRaw * 1.1 + 1024 * state.pending.length >= MAX_TOTAL_IMAGE_BYTES) await drain(state, 0);
282
+ if (state.imageIndex < MAX_IMAGES_PER_DOC && state.totalBytes < MAX_TOTAL_IMAGE_BYTES) return false;
283
+ if (!state.capWarned) {
284
+ state.capWarned = true;
285
+ warnings.push({ page: pageNumber, message: `\uC774\uBBF8\uC9C0 \uCD94\uCD9C \uC0C1\uD55C \uB3C4\uB2EC (${MAX_IMAGES_PER_DOC}\uAC1C/128MB) \u2014 \uC774\uD6C4 \uC774\uBBF8\uC9C0 \uC0DD\uB7B5`, code: "SKIPPED_IMAGE" });
286
+ }
287
+ return true;
288
+ }
289
+ async function pushImage(state, filename, w, h, pixels, images) {
290
+ const webp = webpable(state, w, h) ? state.webp : void 0;
291
+ const raw = webp ? pixels.data.length : pngScanlineBytes(w, h);
292
+ const image = { filename, data: NO_BYTES, mimeType: webp ? "image/webp" : "image/png" };
293
+ const save = (data) => {
294
+ image.data = data;
295
+ state.totalBytes += data.length;
296
+ if (!webp && state.webp) state.oversize++;
297
+ };
298
+ const fail = () => {
299
+ state.failed.add(filename);
300
+ };
301
+ if (pixels.channels === void 0 && !webp && raw < MIN_ASYNC_PNG_BYTES) {
302
+ try {
303
+ save(encodePng(w, h, pixels.data));
304
+ images.push(image);
305
+ } catch {
306
+ fail();
307
+ }
308
+ return;
309
+ }
310
+ await drain(state, MAX_PENDING_RAW_BYTES - raw, webp ? void 0 : MAX_PENDING_PNG_IMAGES - 1);
311
+ images.push(image);
312
+ const encoded = pixels.channels === void 0 && webp ? encodeWebpImage(webp, state, image, w, h, pixels.data) : encodePngAsync(w, h, pixels.data, pixels.channels);
313
+ const done = encoded.then(save, fail);
314
+ if (!webp && raw > MAX_PENDING_RAW_BYTES) {
315
+ await done;
316
+ return;
317
+ }
318
+ state.pending.push({ done, raw });
319
+ state.pendingRaw += raw;
320
+ }
321
+ async function encodeWebpImage(webp, state, image, w, h, rgba) {
322
+ try {
323
+ return await webp(rgba, w, h);
324
+ } catch {
325
+ const png = encodePng(w, h, rgba);
326
+ const filename = image.filename.replace(/\.webp$/, ".png");
327
+ state.renamed.set(image.filename, filename);
328
+ image.filename = filename;
329
+ image.mimeType = "image/png";
330
+ return png;
331
+ }
332
+ }
333
+ async function drain(state, keepRaw, keepCount = Infinity) {
334
+ while (state.pendingRaw > keepRaw || state.pending.length > keepCount) {
335
+ const p = state.pending.shift();
336
+ if (!p) break;
337
+ await p.done;
338
+ state.pendingRaw -= p.raw;
339
+ }
340
+ }
341
+ async function flushPdfImages(state, warnings, pageImages, images) {
342
+ await drain(state, 0);
343
+ if (state.oversize) warnings.push({ message: `WebP \uD55C\uB3C4(\uAC00\uB85C\xB7\uC138\uB85C 16,383px)\uB97C \uB118\uB294 \uADF8\uB9BC ${state.oversize}\uAC1C\uB97C PNG \uB85C \uB0C8\uC2B5\uB2C8\uB2E4`, code: "SKIPPED_IMAGE" });
344
+ if (state.renamed.size) {
345
+ for (const list of pageImages.values()) for (const b of list) if (b.text) b.text = state.renamed.get(b.text) ?? b.text;
346
+ warnings.push({ message: `WebP \uC778\uCF54\uB529 \uC2E4\uD328\uB85C \uADF8\uB9BC ${state.renamed.size}\uAC1C\uB97C PNG \uB85C \uB0C8\uC2B5\uB2C8\uB2E4`, code: "SKIPPED_IMAGE" });
347
+ }
348
+ if (state.failed.size) {
349
+ for (let i = images.length - 1; i >= 0; i--) if (state.failed.has(images[i].filename)) images.splice(i, 1);
350
+ for (const [page, list] of pageImages) {
351
+ const kept = list.filter((b) => !b.text || !state.failed.has(b.text));
352
+ if (kept.length) pageImages.set(page, kept);
353
+ else pageImages.delete(page);
354
+ }
355
+ warnings.push({ message: `PNG \uC778\uCF54\uB529 \uC2E4\uD328\uB85C \uADF8\uB9BC ${state.failed.size}\uAC1C\uB97C \uCD94\uCD9C\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4`, code: "SKIPPED_IMAGE" });
356
+ }
357
+ }
358
+ var WEBP_MAX_DIM = 16383;
359
+ var webpable = (state, w, h) => !!state.webp && w <= WEBP_MAX_DIM && h <= WEBP_MAX_DIM;
360
+ var imageFilename = (state, w, h) => `image_${String(state.imageIndex).padStart(3, "0")}.${webpable(state, w, h) ? "webp" : "png"}`;
361
+ function injectPageImageBlocks(blocks, pageImages) {
362
+ if (pageImages.size === 0) return;
363
+ const lastIndexForPage = /* @__PURE__ */ new Map();
364
+ for (let i = 0; i < blocks.length; i++) {
365
+ const p = blocks[i].pageNumber;
366
+ if (p !== void 0) lastIndexForPage.set(p, i);
367
+ }
368
+ const pageAtIndex = /* @__PURE__ */ new Map();
369
+ for (const [p, last] of lastIndexForPage) pageAtIndex.set(last, p);
370
+ const result = [];
371
+ const injected = /* @__PURE__ */ new Set();
372
+ for (let i = 0; i < blocks.length; i++) {
373
+ result.push(blocks[i]);
374
+ const p = pageAtIndex.get(i);
375
+ if (p !== void 0 && pageImages.has(p)) {
376
+ result.push(...pageImages.get(p));
377
+ injected.add(p);
378
+ }
379
+ }
380
+ for (const p of [...pageImages.keys()].sort((a, b) => a - b)) {
381
+ if (injected.has(p)) continue;
382
+ let at = result.length;
383
+ for (let i = 0; i < result.length; i++) {
384
+ const bp = result[i].pageNumber;
385
+ if (bp !== void 0 && bp > p) {
386
+ at = i;
387
+ break;
388
+ }
389
+ }
390
+ result.splice(at, 0, ...pageImages.get(p));
391
+ }
392
+ blocks.length = 0;
393
+ for (const b of result) blocks.push(b);
394
+ }
395
+ function moveImagesInFlow(blocks) {
396
+ const pageImages = /* @__PURE__ */ new Map();
397
+ const rest = [];
398
+ for (const b of blocks) {
399
+ if (b.type === "image" && b.bbox && b.pageNumber !== void 0) (pageImages.get(b.pageNumber) ?? pageImages.set(b.pageNumber, []).get(b.pageNumber)).push(b);
400
+ else rest.push(b);
401
+ }
402
+ if (!pageImages.size) return;
403
+ blocks.length = 0;
404
+ for (const b of rest) blocks.push(b);
405
+ placeImagesInFlow(blocks, pageImages);
406
+ injectPageImageBlocks(blocks, pageImages);
407
+ }
408
+ function placeInImageCell(image, pageBlocks) {
409
+ const box = image.bbox;
410
+ const cx = box.x + box.width / 2, cy = box.y + box.height / 2;
411
+ const find = (bs) => {
412
+ for (const b of bs ?? []) {
413
+ if (b.type !== "table" || !b.table) continue;
414
+ for (const row of b.table.cells) for (const cell2 of row) {
415
+ const inner = find(cell2.blocks);
416
+ if (inner) return inner;
417
+ const c = IMAGE_CELL_BOXES.get(cell2);
418
+ if (c && cx > c.x1 && cx < c.x2 && cy > c.y1 && cy < c.y2) return cell2;
419
+ }
420
+ }
421
+ return void 0;
422
+ };
423
+ const cell = find(pageBlocks);
424
+ if (!cell) return false;
425
+ const own = cell.text.trim();
426
+ cell.blocks = [...cell.blocks ?? (own ? [{ type: "paragraph", text: own, pageNumber: image.pageNumber }] : []), image];
427
+ cell.text = (own ? own + "\n" : "") + `![image](${image.text})`;
428
+ return true;
429
+ }
430
+ function placeImagesInFlow(blocks, pageImages) {
431
+ const byPage = /* @__PURE__ */ new Map();
432
+ for (let i = 0; i < blocks.length; i++) {
433
+ const p = blocks[i].pageNumber;
434
+ if (p !== void 0 && blocks[i].bbox && pageImages.has(p)) (byPage.get(p) ?? byPage.set(p, []).get(p)).push(i);
435
+ }
436
+ const before = /* @__PURE__ */ new Map();
437
+ for (const [p, images] of pageImages) {
438
+ const placed = byPage.get(p);
439
+ if (!placed) continue;
440
+ const top = (b) => b.bbox.y + b.bbox.height;
441
+ const inCell = new Set(images.filter((b) => b.bbox && placeInImageCell(b, placed.map((i) => blocks[i]))));
442
+ const flowing = images.filter((b) => b.bbox && !inCell.has(b)).sort((a, b) => top(b) - top(a) || a.bbox.x - b.bbox.x);
443
+ for (const image of flowing) {
444
+ const box = image.bbox;
445
+ const overlaps = placed.filter((i) => {
446
+ const b = blocks[i].bbox;
447
+ return b.x < box.x + box.width && box.x < b.x + b.width;
448
+ });
449
+ const column = overlaps.length ? overlaps : placed;
450
+ const above = column.filter((i) => top(blocks[i]) >= top(image));
451
+ const at = above.length ? above[above.length - 1] + 1 : column[0];
452
+ (before.get(at) ?? before.set(at, []).get(at)).push(image);
453
+ }
454
+ const rest = images.filter((b) => !flowing.includes(b) && !inCell.has(b));
455
+ if (rest.length) pageImages.set(p, rest);
456
+ else pageImages.delete(p);
457
+ }
458
+ if (!before.size) return;
459
+ const result = [];
460
+ for (let i = 0; i <= blocks.length; i++) {
461
+ for (const image of before.get(i) ?? []) result.push(image);
462
+ if (i < blocks.length) result.push(blocks[i]);
463
+ }
464
+ blocks.length = 0;
465
+ for (const b of result) blocks.push(b);
466
+ }
467
+ var RARE_JONG = /* @__PURE__ */ new Set([3, 5, 6, 9, 10, 11, 12, 13, 14, 15, 18, 24, 25, 26]);
468
+ var MOJIBAKE_MIN_HANGUL = 30;
469
+ var MOJIBAKE_MAX_NOBATCHIM = 0.15;
470
+ var MOJIBAKE_MIN_RAREBATCHIM = 0.25;
471
+ var VECTOR_TEXT_MIN_GLYPHS = 40;
472
+ var VECTOR_TEXT_MIN_SHARE = 0.25;
473
+ function computePageQuality(page, text, vectorGlyphs = 0) {
474
+ let total = 0;
475
+ let hangul = 0;
476
+ let hangulNoBatchim = 0;
477
+ let hangulRareBatchim = 0;
478
+ let control = 0;
479
+ let replacement = 0;
480
+ let pua = 0;
481
+ for (let i = 0; i < text.length; i++) {
482
+ const code = text.charCodeAt(i);
483
+ if (code === 32 || code === 9 || code === 10 || code === 13) continue;
484
+ total++;
485
+ if (code < 32 || code === 127 || code >= 128 && code <= 159) {
486
+ control++;
487
+ continue;
488
+ }
489
+ if (code === 65533) {
490
+ replacement++;
491
+ continue;
492
+ }
493
+ if (code >= 44032 && code <= 55203) {
494
+ hangul++;
495
+ const jong = (code - 44032) % 28;
496
+ if (jong === 0) hangulNoBatchim++;
497
+ else if (RARE_JONG.has(jong)) hangulRareBatchim++;
498
+ continue;
499
+ }
500
+ if (code >= 57344 && code <= 63743 || code >= 56192 && code <= 56319) {
501
+ pua++;
502
+ continue;
503
+ }
504
+ }
505
+ const denom = total || 1;
506
+ const puaRatio = pua / denom;
507
+ const controlCharRatio = control / denom;
508
+ const replacementCharRatio = replacement / denom;
509
+ const hangulNoBatchimRatio = hangul > 0 ? hangulNoBatchim / hangul : 0;
510
+ const hangulRareBatchimRatio = hangul > 0 ? hangulRareBatchim / hangul : 0;
511
+ const garbledHangul = hangul >= MOJIBAKE_MIN_HANGUL && hangulNoBatchimRatio < MOJIBAKE_MAX_NOBATCHIM && hangulRareBatchimRatio >= MOJIBAKE_MIN_RAREBATCHIM;
512
+ let needsOcr = false;
513
+ let ocrReason;
514
+ if (vectorGlyphs >= VECTOR_TEXT_MIN_GLYPHS && vectorGlyphs >= (vectorGlyphs + total) * VECTOR_TEXT_MIN_SHARE) {
515
+ needsOcr = true;
516
+ ocrReason = "vector_text";
517
+ } else if (total < LOW_TEXT_THRESHOLD) {
518
+ needsOcr = true;
519
+ ocrReason = "low_text";
520
+ } else if (puaRatio >= HIGH_PUA_THRESHOLD) {
521
+ needsOcr = true;
522
+ ocrReason = "high_pua";
523
+ } else if (controlCharRatio >= HIGH_CONTROL_THRESHOLD) {
524
+ needsOcr = true;
525
+ ocrReason = "high_control";
526
+ } else if (replacementCharRatio >= HIGH_REPLACEMENT_THRESHOLD) {
527
+ needsOcr = true;
528
+ ocrReason = "high_replacement";
529
+ } else if (garbledHangul) {
530
+ needsOcr = true;
531
+ ocrReason = "garbled_hangul";
532
+ }
533
+ return {
534
+ page,
535
+ textChars: total,
536
+ hangulRatio: hangul / denom,
537
+ controlCharRatio,
538
+ replacementCharRatio,
539
+ puaRatio,
540
+ hangulNoBatchimRatio,
541
+ hangulRareBatchimRatio,
542
+ needsOcr,
543
+ ocrReason
544
+ };
545
+ }
546
+ var LOW_TEXT_THRESHOLD = 20;
547
+ var HIGH_PUA_THRESHOLD = 0.2;
548
+ var HIGH_CONTROL_THRESHOLD = 0.05;
549
+ var HIGH_REPLACEMENT_THRESHOLD = 0.05;
550
+ var DOC_NEEDS_OCR_PAGE_RATIO = 0.3;
551
+ function stripControlChars(text) {
552
+ return text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F\x80-\x9F]/g, "");
553
+ }
554
+ function summarizeDocumentQuality(pages) {
555
+ if (pages.length === 0) {
556
+ return {
557
+ totalPages: 0,
558
+ totalTextChars: 0,
559
+ avgHangulRatio: 0,
560
+ avgControlCharRatio: 0,
561
+ avgReplacementCharRatio: 0,
562
+ avgPuaRatio: 0,
563
+ lowTextPageCount: 0,
564
+ highPuaPageCount: 0,
565
+ needsOcr: false,
566
+ ocrCandidatePages: []
567
+ };
568
+ }
569
+ let textChars = 0;
570
+ let hangul = 0;
571
+ let control = 0;
572
+ let replacement = 0;
573
+ let pua = 0;
574
+ let lowText = 0;
575
+ let highPua = 0;
576
+ const ocrCandidatePages = [];
577
+ for (const p of pages) {
578
+ textChars += p.textChars;
579
+ hangul += p.hangulRatio;
580
+ control += p.controlCharRatio;
581
+ replacement += p.replacementCharRatio;
582
+ pua += p.puaRatio;
583
+ if (p.textChars < LOW_TEXT_THRESHOLD) lowText++;
584
+ if (p.puaRatio >= HIGH_PUA_THRESHOLD) highPua++;
585
+ if (p.needsOcr && !p.ocrApplied) ocrCandidatePages.push(p.page);
586
+ }
587
+ const n = pages.length;
588
+ return {
589
+ totalPages: n,
590
+ totalTextChars: textChars,
591
+ avgHangulRatio: hangul / n,
592
+ avgControlCharRatio: control / n,
593
+ avgReplacementCharRatio: replacement / n,
594
+ avgPuaRatio: pua / n,
595
+ lowTextPageCount: lowText,
596
+ highPuaPageCount: highPua,
597
+ needsOcr: ocrCandidatePages.length / n >= DOC_NEEDS_OCR_PAGE_RATIO,
598
+ ocrCandidatePages
599
+ };
600
+ }
601
+ var GLYPH_MIN_H = 3;
602
+ var GLYPH_MAX_H = 40;
603
+ var GLYPH_MAX_ASPECT = 2;
604
+ var GLYPH_MIN_SEGS = 8;
605
+ var GLYPH_MIN_SUBS = 2;
606
+ var RUN_GAP_EM = 1.5;
607
+ var RUN_MIN = 3;
608
+ var RUN_ALIGN_EM = 0.05;
609
+ var RUN_MAX_OVERLAP = 0.2;
610
+ var RUN_MIN_COLOR = 0.9;
611
+ var RUN_MIN_SHAPES = 0.5;
612
+ var mul = (m, t) => [
613
+ m[0] * t[0] + m[2] * t[1],
614
+ m[1] * t[0] + m[3] * t[1],
615
+ m[0] * t[2] + m[2] * t[3],
616
+ m[1] * t[2] + m[3] * t[3],
617
+ m[0] * t[4] + m[2] * t[5] + m[4],
618
+ m[1] * t[4] + m[3] * t[5] + m[5]
619
+ ];
620
+ function collectGlyphPaths(fnArray, argsArray) {
621
+ const out = [];
622
+ let ctm = [1, 0, 0, 1, 0, 0];
623
+ let color = 0;
624
+ const stack = [];
625
+ let x1 = Infinity, y1 = Infinity, x2 = -Infinity, y2 = -Infinity;
626
+ let segs = 0, subs = 0, rects = 0;
627
+ let ops = [];
628
+ const add = (x, y) => {
629
+ const tx = ctm[0] * x + ctm[2] * y + ctm[4], ty = ctm[1] * x + ctm[3] * y + ctm[5];
630
+ if (tx < x1) x1 = tx;
631
+ if (tx > x2) x2 = tx;
632
+ if (ty < y1) y1 = ty;
633
+ if (ty > y2) y2 = ty;
634
+ };
635
+ const reset = () => {
636
+ x1 = Infinity;
637
+ y1 = Infinity;
638
+ x2 = -Infinity;
639
+ y2 = -Infinity;
640
+ segs = 0;
641
+ subs = 0;
642
+ rects = 0;
643
+ ops = [];
644
+ };
645
+ for (let i = 0; i < fnArray.length; i++) {
646
+ const op = fnArray[i];
647
+ const args = argsArray[i];
648
+ switch (op) {
649
+ case OPS.save:
650
+ stack.push([ctm, color]);
651
+ break;
652
+ case OPS.restore:
653
+ [ctm, color] = stack.pop() ?? [[1, 0, 0, 1, 0, 0], 0];
654
+ break;
655
+ case OPS.transform:
656
+ ctm = mul(ctm, args);
657
+ break;
658
+ case OPS.paintFormXObjectBegin: {
659
+ stack.push([ctm, color]);
660
+ const m = args[0];
661
+ if (Array.isArray(m) && m.length >= 6) ctm = mul(ctm, m);
662
+ break;
663
+ }
664
+ case OPS.paintFormXObjectEnd:
665
+ [ctm, color] = stack.pop() ?? [[1, 0, 0, 1, 0, 0], 0];
666
+ break;
667
+ case OPS.setFillRGBColor: {
668
+ const c = args;
669
+ color = c[0] << 16 | c[1] << 8 | c[2];
670
+ break;
671
+ }
672
+ case OPS.constructPath: {
673
+ const [subOps, coords] = args;
674
+ if (!Array.isArray(subOps) || !Array.isArray(coords)) break;
675
+ ops.push(i);
676
+ let ci = 0;
677
+ for (const s of subOps) {
678
+ if (s === OPS.moveTo) {
679
+ add(coords[ci], coords[ci + 1]);
680
+ ci += 2;
681
+ subs++;
682
+ } else if (s === OPS.lineTo) {
683
+ add(coords[ci], coords[ci + 1]);
684
+ ci += 2;
685
+ segs++;
686
+ } else if (s === OPS.curveTo) {
687
+ add(coords[ci], coords[ci + 1]);
688
+ add(coords[ci + 2], coords[ci + 3]);
689
+ add(coords[ci + 4], coords[ci + 5]);
690
+ ci += 6;
691
+ segs++;
692
+ } else if (s === OPS.curveTo2 || s === OPS.curveTo3) {
693
+ add(coords[ci], coords[ci + 1]);
694
+ add(coords[ci + 2], coords[ci + 3]);
695
+ ci += 4;
696
+ segs++;
697
+ } else if (s === OPS.rectangle) {
698
+ const rx = coords[ci], ry = coords[ci + 1], rw = coords[ci + 2], rh = coords[ci + 3];
699
+ add(rx, ry);
700
+ add(rx + rw, ry + rh);
701
+ add(rx, ry + rh);
702
+ add(rx + rw, ry);
703
+ ci += 4;
704
+ rects++;
705
+ subs++;
706
+ segs += 4;
707
+ }
708
+ }
709
+ break;
710
+ }
711
+ case OPS.fill:
712
+ case OPS.eoFill:
713
+ case OPS.fillStroke:
714
+ case OPS.eoFillStroke:
715
+ case OPS.closeFillStroke:
716
+ case OPS.closeEOFillStroke: {
717
+ const w = x2 - x1, h = y2 - y1;
718
+ if (segs > rects * 4 && h >= GLYPH_MIN_H && h <= GLYPH_MAX_H && w <= h * GLYPH_MAX_ASPECT && segs >= GLYPH_MIN_SEGS && subs >= GLYPH_MIN_SUBS) {
719
+ out.push({ x1, y1, x2, y2, segs, subs, color, ops: [...ops, i] });
720
+ }
721
+ reset();
722
+ break;
723
+ }
724
+ case OPS.stroke:
725
+ case OPS.closeStroke:
726
+ case OPS.endPath:
727
+ reset();
728
+ break;
729
+ }
730
+ }
731
+ return out;
732
+ }
733
+ function coveredByText(b, texts) {
734
+ const cx = (b.x1 + b.x2) / 2, cy = (b.y1 + b.y2) / 2;
735
+ for (const t of texts) {
736
+ if (cx >= t.x - 1 && cx <= t.x + t.w + 1 && cy >= t.y - t.h * 0.3 - 1 && cy <= t.y + t.h + 1 && t.text.trim()) return true;
737
+ }
738
+ return false;
739
+ }
740
+ var median = (a) => {
741
+ const s = a.slice().sort((x, y) => x - y);
742
+ return s[s.length >> 1];
743
+ };
744
+ var spread = (a) => {
745
+ const c = median(a);
746
+ return median(a.map((v) => Math.abs(v - c)));
747
+ };
748
+ function isTextRun(m, em) {
749
+ if (m.length < RUN_MIN) return false;
750
+ if (Math.min(spread(m.map((b) => b.y2)), spread(m.map((b) => b.y1))) > em * RUN_ALIGN_EM) return false;
751
+ let overlaps = 0;
752
+ for (let i = 1; i < m.length; i++) if (m[i].x1 < m[i - 1].x2 - em * 0.1) overlaps++;
753
+ if (overlaps > (m.length - 1) * RUN_MAX_OVERLAP) return false;
754
+ const colors = /* @__PURE__ */ new Map();
755
+ for (const b of m) colors.set(b.color, (colors.get(b.color) ?? 0) + 1);
756
+ if (Math.max(...colors.values()) < m.length * RUN_MIN_COLOR) return false;
757
+ const shapes = new Set(m.map((b) => `${Math.round((b.x2 - b.x1) * 2)}:${Math.round((b.y2 - b.y1) * 2)}:${b.segs}`));
758
+ return shapes.size >= m.length * RUN_MIN_SHAPES;
759
+ }
760
+ function scanVectorGlyphs(fnArray, argsArray, texts) {
761
+ const paths = collectGlyphPaths(fnArray, argsArray);
762
+ if (paths.length < RUN_MIN) return { glyphs: 0, paths };
763
+ const free = paths.filter((b) => !coveredByText(b, texts));
764
+ const sorted = free.slice().sort((a, b) => a.y1 + a.y2 - (b.y1 + b.y2));
765
+ let glyphs = 0;
766
+ let row = [];
767
+ let rowCy = 0, rowH = 0;
768
+ const flushRow = () => {
769
+ if (row.length < RUN_MIN) return;
770
+ row.sort((a, b) => a.x1 - b.x1);
771
+ const em = median(row.map((b) => b.y2 - b.y1));
772
+ let start = 0, maxX = row[0].x2;
773
+ for (let i = 1; i <= row.length; i++) {
774
+ if (i < row.length && row[i].x1 - maxX <= em * RUN_GAP_EM) {
775
+ if (row[i].x2 > maxX) maxX = row[i].x2;
776
+ continue;
777
+ }
778
+ const run = row.slice(start, i);
779
+ if (isTextRun(run, em)) glyphs += run.length;
780
+ if (i < row.length) {
781
+ start = i;
782
+ maxX = row[i].x2;
783
+ }
784
+ }
785
+ };
786
+ for (const b of sorted) {
787
+ const cy = (b.y1 + b.y2) / 2, h = b.y2 - b.y1;
788
+ if (row.length && Math.abs(cy - rowCy) <= Math.max(h, rowH) * 0.5) {
789
+ row.push(b);
790
+ continue;
791
+ }
792
+ flushRow();
793
+ row = [b];
794
+ rowCy = cy;
795
+ rowH = h;
796
+ }
797
+ flushRow();
798
+ return { glyphs, paths };
799
+ }
800
+ function ocrVectorOps(opList, paths) {
801
+ const drop = /* @__PURE__ */ new Set();
802
+ for (const p of paths) for (const i of p.ops) drop.add(i);
803
+ const fnArray = [];
804
+ const argsArray = [];
805
+ for (let i = 0; i < opList.fnArray.length; i++) {
806
+ const op = opList.fnArray[i];
807
+ if (drop.has(i) || op === OPS.clip || op === OPS.eoClip) continue;
808
+ fnArray.push(op);
809
+ argsArray.push(opList.argsArray[i]);
810
+ }
811
+ return { fnArray, argsArray };
812
+ }
813
+ var textOf = (cell) => cell.text.replace(/<\/?u>|~~/g, "").trim();
814
+ var plain = (cell) => !cell.blocks?.length && !IMAGE_CELLS.has(cell);
815
+ var labelsOf = (cell) => {
816
+ const labels = textOf(cell).split("\n").map((s) => s.trim()).filter(Boolean);
817
+ return labels.length && labels.every((s) => new RegExp("^\\p{L}[\\p{L}\\p{N} ]{0,15}[:\uFF1A]$", "u").test(s)) ? labels.map((s) => s.replace(/\s+/g, "").replace(/:/g, ":")) : void 0;
818
+ };
819
+ var alignedLabels = (label, value, count) => {
820
+ const L = CELL_LINES.get(label), V = CELL_LINES.get(value);
821
+ let next = 0;
822
+ return !!L && !!V && L.length === count && V.length >= count && Math.abs(L[0].y - V[0].y) <= 1 && L.every((l) => {
823
+ while (next < V.length && Math.abs(l.y - V[next].y) > 1) next++;
824
+ return next++ < V.length;
825
+ });
826
+ };
827
+ function partialAlignedLabelCells(table, owner, first) {
828
+ const pageOf = (a) => CELL_PAGES.get(a.cell ?? table.cells[a.r][a.c]) ?? (a.r < first ? -1 : -2);
829
+ const pairs = [];
830
+ let carried = false;
831
+ for (let c = 0; c < table.cols; ) {
832
+ const u = owner[first - 1]?.[c], d = owner[first]?.[c];
833
+ if (u && u === d) {
834
+ carried = true;
835
+ c = u.c + u.cs;
836
+ continue;
837
+ }
838
+ const upper = u ? table.cells[u.r][u.c] : void 0, lower = d ? table.cells[d.r][d.c] : void 0;
839
+ if (!upper?.text.trim() && !lower?.text.trim()) {
840
+ c++;
841
+ continue;
842
+ }
843
+ if (!u || !d || !upper || !lower || u.r !== first - 1 || d.r !== first || u.c !== c || d.c !== c || u.rs !== 1 || d.rs !== 1 || u.cs !== d.cs || !plain(upper) || !plain(lower) || !textOf(upper) || !textOf(lower)) return;
844
+ pairs.push({ c, cs: u.cs, upper, lower });
845
+ c += u.cs;
846
+ }
847
+ if (!carried || pairs.length !== 3) return;
848
+ const keyed = pairs.filter((p) => labelsOf(p.upper) && labelsOf(p.lower));
849
+ if (keyed.length !== 1) return;
850
+ const label = keyed[0], value = pairs.find((p) => p.c === label.c + label.cs), context = pairs.find((p) => p.c + p.cs === label.c);
851
+ if (!value || !context || value === context || textOf(context.upper).replace(/\s+/g, "") === textOf(context.lower).replace(/\s+/g, "") || !CELL_EDGES.get(context.upper)?.b || !CELL_EDGES.get(context.lower)?.t) return;
852
+ const U = labelsOf(label.upper), D = labelsOf(label.lower), sequence = [...U, ...D];
853
+ if (D.length < 2 || sequence.length < 3 || new Set(sequence).size !== sequence.length || !alignedLabels(label.upper, value.upper, U.length)) return;
854
+ const L = CELL_LINES.get(label.lower), V = CELL_LINES.get(value.lower);
855
+ if (!L || !V || L.length !== D.length) return;
856
+ let next = V.findIndex((v) => Math.abs(v.y - L[0].y) <= 1);
857
+ if (next <= 0 || !V.slice(0, next).every((v) => v.y > L[0].y + 1) || !L.every((l) => {
858
+ while (next < V.length && Math.abs(l.y - V[next].y) > 1) next++;
859
+ return next++ < V.length;
860
+ })) return;
861
+ let peers = 0, shared = false;
862
+ for (let r = 0; r < table.rows; r++) {
863
+ if (r === first - 1 || r === first) continue;
864
+ const l = owner[r]?.[label.c], v = owner[r]?.[value.c];
865
+ if (!l || !v || l.r !== r || v.r !== r || l.c !== label.c || v.c !== value.c || l.cs !== label.cs || v.cs !== value.cs || l.rs !== v.rs) continue;
866
+ const lc = table.cells[r][l.c], vc = table.cells[r][v.c];
867
+ const list = labelsOf(lc);
868
+ if (!plain(lc) || !plain(vc) || !textOf(vc) || !list || pageOf(l) !== pageOf(v)) continue;
869
+ if (l.rs === 1) {
870
+ if (list.join("|") === sequence.join("|") && alignedLabels(lc, vc, list.length)) peers++;
871
+ continue;
872
+ }
873
+ if (list.length < 3 || new Set(list).size !== list.length) continue;
874
+ const visible = CELL_LINES.get(lc)?.length ?? 0, values = CELL_LINES.get(vc);
875
+ if (visible < 3 || visible > list.length || !values || !alignedLabels(lc, vc, visible)) continue;
876
+ const top = Math.max(...values.map((v2) => v2.y)), bottom = Math.min(...values.map((v2) => v2.y));
877
+ const contexts = [];
878
+ for (let rr = r; rr < r + l.rs && rr < table.rows; rr++) {
879
+ const a = owner[rr]?.[context.c], cell = a ? table.cells[a.r][a.c] : void 0;
880
+ if (!a || a.r !== rr || a.c !== context.c || a.cs !== context.cs || a.rs !== 1 || !cell || !plain(cell) || !textOf(cell) || pageOf(a) !== pageOf(l)) break;
881
+ const lines = CELL_LINES.get(cell);
882
+ if (!lines?.length || lines.some((line) => line.y > top + 1 || line.y < bottom - 1)) break;
883
+ contexts.push(textOf(cell).replace(/\s+/g, ""));
884
+ }
885
+ if (new Set(contexts).size >= 2) shared = true;
886
+ }
887
+ return peers >= 2 && shared ? { context, label, value } : void 0;
888
+ }
889
+ function matchesCompleteAlignedLabelListRow(table, owner, first) {
890
+ const pairs = [];
891
+ let carried = false;
892
+ for (let c = 0; c < table.cols; ) {
893
+ const u = owner[first - 1]?.[c], d = owner[first]?.[c];
894
+ if (u && u === d) {
895
+ carried = true;
896
+ c = u.c + u.cs;
897
+ continue;
898
+ }
899
+ const upper = u ? table.cells[u.r][u.c] : void 0, lower = d ? table.cells[d.r][d.c] : void 0;
900
+ if (!upper?.text.trim() && !lower?.text.trim()) {
901
+ c++;
902
+ continue;
903
+ }
904
+ if (!u || !d || !upper || !lower || u.r !== first - 1 || d.r !== first || u.c !== c || d.c !== c || u.rs !== 1 || d.rs !== 1 || u.cs !== d.cs || !plain(upper) || !plain(lower)) return false;
905
+ pairs.push({ c, cs: u.cs, upper, lower });
906
+ c += u.cs;
907
+ }
908
+ const filled = pairs.filter((p) => textOf(p.upper) && textOf(p.lower));
909
+ if (!carried || filled.length !== 2) return false;
910
+ const keyed = filled.filter((p) => labelsOf(p.upper) && labelsOf(p.lower));
911
+ if (keyed.length !== 1) return false;
912
+ const label = keyed[0], value = filled.find((p) => p !== label);
913
+ const U = labelsOf(label.upper), D = labelsOf(label.lower), sequence = [...U, ...D];
914
+ if (D.length < 2 || sequence.length < 3 || new Set(sequence).size !== sequence.length || value.c !== label.c + label.cs || pairs.some((p) => p !== label && p !== value && textOf(p.lower)) || !pairs.some((p) => p.c < label.c && textOf(p.upper) && !textOf(p.lower)) || !alignedLabels(label.upper, value.upper, U.length) || !alignedLabels(label.lower, value.lower, D.length)) return false;
915
+ let peers = 0;
916
+ for (let r = 0; r < table.rows; r++) {
917
+ if (r === first - 1 || r === first) continue;
918
+ const L = owner[r]?.[label.c], V = owner[r]?.[value.c];
919
+ if (L?.r !== r || V?.r !== r || L.c !== label.c || V.c !== value.c || L.rs !== 1 || V.rs !== 1 || L.cs !== label.cs || V.cs !== value.cs) continue;
920
+ const l = table.cells[r][label.c], v = table.cells[r][value.c];
921
+ if (!plain(l) || !plain(v) || !textOf(v) || labelsOf(l)?.join("|") !== sequence.join("|") || !alignedLabels(l, v, sequence.length)) continue;
922
+ if (++peers >= 2) return true;
923
+ }
924
+ return false;
925
+ }
926
+ function matchesIndependentRowPair(table, owner, first) {
927
+ const norm = (cell) => textOf(cell).replace(/\s+/g, "");
928
+ const pairs = [];
929
+ for (let c = 0; c < table.cols; ) {
930
+ const u = owner[first - 1]?.[c], d = owner[first]?.[c];
931
+ if (u && u === d) {
932
+ c = u.c + u.cs;
933
+ continue;
934
+ }
935
+ const upper = u ? table.cells[u.r][u.c] : void 0, lower = d ? table.cells[d.r][d.c] : void 0;
936
+ if (!upper?.text.trim() && !lower?.text.trim()) {
937
+ c++;
938
+ continue;
939
+ }
940
+ if (!u || !d || !upper || !lower || u.r !== first - 1 || d.r !== first || u.c !== c || d.c !== c || u.rs !== 1 || d.rs !== 1 || u.cs !== d.cs || !plain(upper) || !plain(lower) || !norm(upper) || !norm(lower)) return false;
941
+ pairs.push({ c, cs: u.cs, upper: norm(upper), lower: norm(lower) });
942
+ c += u.cs;
943
+ }
944
+ if (pairs.length < 2 || pairs.every((p) => p.upper === p.lower)) return false;
945
+ return table.cells.some((_, r) => {
946
+ if (r + 1 >= table.rows || r + 1 >= first - 1 && r <= first) return false;
947
+ return pairs.every((p) => [p.upper, p.lower].every((text, i) => {
948
+ const a = owner[r + i]?.[p.c], cell = table.cells[r + i]?.[p.c];
949
+ return a?.r === r + i && a.c === p.c && a.rs === 1 && a.cs === p.cs && !!cell && plain(cell) && norm(cell) === text;
950
+ }));
951
+ });
952
+ }
953
+ function matchesCompleteContextRow(table, owner, first) {
954
+ const norm = (s) => s.replace(/\s+/g, "");
955
+ const context = [];
956
+ let value;
957
+ for (let c = 0; c < table.cols; ) {
958
+ const u = owner[first - 1]?.[c], d = owner[first]?.[c];
959
+ if (u && u === d) {
960
+ const cell = table.cells[u.r][u.c];
961
+ if (u.r === first - 1 && u.rs === 2 && plain(cell) && textOf(cell)) context.push({ c, cs: u.cs, text: norm(textOf(cell)) });
962
+ c = u.c + u.cs;
963
+ continue;
964
+ }
965
+ const upper = u ? table.cells[u.r][u.c] : void 0, lower = d ? table.cells[d.r][d.c] : void 0;
966
+ if (!upper?.text.trim() && !lower?.text.trim()) {
967
+ c++;
968
+ continue;
969
+ }
970
+ if (value || !u || !d || !upper || !lower || u.r !== first - 1 || d.r !== first || u.c !== c || d.c !== c || u.rs !== 1 || d.rs !== 1 || u.cs !== d.cs || !plain(upper) || !plain(lower) || !textOf(upper) || !textOf(lower)) return false;
971
+ value = { c, cs: u.cs, text: norm(textOf(upper) + textOf(lower)) };
972
+ c += u.cs;
973
+ }
974
+ if (!value || !context.length) return false;
975
+ const proof = [...context, value];
976
+ return table.cells.some((row, r) => r !== first - 1 && r !== first && proof.every((p) => {
977
+ const a = owner[r]?.[p.c], cell = row[p.c];
978
+ return a?.r === r && a.c === p.c && a.rs === 1 && a.cs === p.cs && !!cell && plain(cell) && norm(textOf(cell)) === p.text;
979
+ }));
980
+ }
981
+ function matchesCompleteSiblingRow(table, owner, first) {
982
+ const pairs = [];
983
+ for (let c = 0; c < table.cols; ) {
984
+ const u = owner[first - 1][c], d = owner[first][c];
985
+ if (u && u === d) {
986
+ c = u.c + u.cs;
987
+ continue;
988
+ }
989
+ if (!u || !d || u.r !== first - 1 || d.r !== first || u.c !== c || d.c !== c || u.rs !== 1 || d.rs !== 1 || u.cs !== d.cs) return false;
990
+ const upper2 = table.cells[u.r][c], lower2 = table.cells[d.r][c];
991
+ if (!plain(upper2) || !plain(lower2)) return false;
992
+ pairs.push({ c, cs: u.cs, upper: upper2, lower: lower2 });
993
+ c += u.cs;
994
+ }
995
+ const filled = pairs.filter((p) => textOf(p.upper) && textOf(p.lower));
996
+ if (filled.length !== 1) return false;
997
+ const main = filled[0], upper = textOf(main.upper), lower = textOf(main.lower);
998
+ if (!/^[가-힣]\.\s*\S/.test(upper) || /(?:^|\n)\s*\d+\)/.test(upper)) return false;
999
+ const marks = lower.split("\n").map((s) => /^\s*(\d+)\)/.exec(s)).filter((m) => m !== null);
1000
+ if (!/^1\)/.test(lower) || marks.length < 2 || marks.some((m, i) => +m[1] !== i + 1)) return false;
1001
+ if (pairs.some((p) => p !== main && textOf(p.lower) && !/^[○●◯✓✔]+$/.test(textOf(p.lower)))) return false;
1002
+ if (!pairs.some((p) => p !== main && textOf(p.upper) && !textOf(p.lower))) return false;
1003
+ const norm = (s, title) => (title ? s.replace(/^[가-힣]\.\s*/, "") : s).replace(/\s+/g, "");
1004
+ return table.cells.some((row, r) => r !== first - 1 && r !== first && pairs.every((p) => {
1005
+ const anchor = owner[r][p.c], peer = row[p.c];
1006
+ return anchor?.r === r && anchor.c === p.c && anchor.rs === 1 && anchor.cs === p.cs && plain(peer) && norm(textOf(peer), p === main) === norm(textOf(p.upper) + "\n" + textOf(p.lower), p === main);
1007
+ }));
1008
+ }
1009
+ function matchesCompleteRubricRow(table, owner, first) {
1010
+ const pairs = [];
1011
+ let carriedLabel = false;
1012
+ for (let c = 0; c < table.cols; ) {
1013
+ const u = owner[first - 1][c], d = owner[first][c];
1014
+ if (u && u === d) {
1015
+ if (u.r === first - 1 && u.rs === 2 && textOf(table.cells[u.r][u.c])) carriedLabel = true;
1016
+ c = u.c + u.cs;
1017
+ continue;
1018
+ }
1019
+ if (!u || !d || u.r !== first - 1 || d.r !== first || u.c !== c || d.c !== c || u.rs !== 1 || d.rs !== 1 || u.cs !== d.cs) return false;
1020
+ const upper2 = table.cells[u.r][c], lower2 = table.cells[d.r][c];
1021
+ if (!plain(upper2) || !plain(lower2) || !textOf(upper2) || !textOf(lower2)) return false;
1022
+ pairs.push({ c, cs: u.cs, upper: upper2, lower: lower2 });
1023
+ c += u.cs;
1024
+ }
1025
+ if (!carriedLabel || pairs.length !== 2) return false;
1026
+ const values = (cell) => textOf(cell).split("\n").map((s) => s.trim()).filter(Boolean);
1027
+ const score = pairs.find((p) => [...values(p.upper), ...values(p.lower)].every((s) => /^-?\d+(?:\.\d+)?$/.test(s)));
1028
+ if (!score) return false;
1029
+ const main = pairs.find((p) => p !== score);
1030
+ const items = (s) => [...s.matchAll(/(?:^|\n)\s*([A-Z])\.\s+/g)].map((m) => ({ n: m[1].charCodeAt(0), at: m.index + m[0].lastIndexOf(m[1]) }));
1031
+ const upper = textOf(main.upper), lower = textOf(main.lower), um = items(upper), dm = items(lower), marks = [...um, ...dm];
1032
+ if (!/^A\.\s/.test(upper) || !/^B\.\s/.test(lower) || um.length !== 1 || dm.length < 2 || marks.some((m, i) => m.n !== 65 + i)) return false;
1033
+ const upScores = values(score.upper), downScores = values(score.lower), scores = [...upScores, ...downScores];
1034
+ if (upScores.length !== um.length || downScores.length !== dm.length) return false;
1035
+ const norm = (s) => s.replace(/\s+/g, "");
1036
+ const tail = norm(lower.slice(dm[dm.length - 1].at));
1037
+ return table.cells.some((row, r) => {
1038
+ if (r === first - 1 || r === first || !pairs.every((p) => {
1039
+ const a = owner[r][p.c];
1040
+ return a?.r === r && a.c === p.c && a.rs === 1 && a.cs === p.cs && plain(row[p.c]);
1041
+ })) return false;
1042
+ const peer = textOf(row[main.c]), peerMarks = items(peer);
1043
+ return peerMarks.length === marks.length && peerMarks.every((m, i) => m.n === marks[i].n) && values(row[score.c]).join("|") === scores.join("|") && norm(peer.slice(peerMarks[peerMarks.length - 1].at)) === tail;
1044
+ });
1045
+ }
1046
+ var KO_ORDER = "\uAC00\uB098\uB2E4\uB77C\uB9C8\uBC14\uC0AC\uC544\uC790\uCC28\uCE74\uD0C0\uD30C\uD558";
1047
+ function itemMark(line) {
1048
+ line = line.replace(/<\/?u>|~~/g, "").trim();
1049
+ let m = /^(\d{1,2})([.)])(?!\d)/.exec(line);
1050
+ if (m) return { style: "1" + m[2], n: +m[1] };
1051
+ if (m = /^\((\d{1,2})\)/.exec(line)) return { style: "(1)", n: +m[1] };
1052
+ if ((m = /^([가-하])([.)])/.exec(line)) && KO_ORDER.includes(m[1])) return { style: "\uAC00" + m[2], n: KO_ORDER.indexOf(m[1]) };
1053
+ if ((m = /^\(([가-하])\)/.exec(line)) && KO_ORDER.includes(m[1])) return { style: "(\uAC00)", n: KO_ORDER.indexOf(m[1]) };
1054
+ if (m = /^[①-⑳]/.exec(line)) return { style: "\u2460", n: m[0].charCodeAt(0) };
1055
+ if (m = /^([A-Z])\.\s/.exec(line)) return { style: "A.", n: m[1].charCodeAt(0) };
1056
+ return null;
1057
+ }
1058
+ function hasNumberedRowSequence(table, owner, first, openCut = false) {
1059
+ const rows = openCut ? [first - 2, first - 1, first, first + 1] : [first - 3, first - 2, first - 1, first];
1060
+ if (rows[0] < 0 || rows[3] >= table.rows) return false;
1061
+ const separate = (c, cs) => rows.every((r) => {
1062
+ const a = owner[r]?.[c], cell = table.cells[r]?.[c];
1063
+ return a?.r === r && a.c === c && a.rs === 1 && a.cs === cs && !!cell && plain(cell) && !!textOf(cell);
1064
+ });
1065
+ for (let c = 0; c < table.cols; c++) {
1066
+ const a = owner[first]?.[c];
1067
+ if (!a || !separate(c, a.cs)) continue;
1068
+ const marks = rows.map((r) => {
1069
+ const lines = textOf(table.cells[r][c]).split("\n"), firstMark = itemMark(lines[0]);
1070
+ return firstMark && lines.slice(1).every((l) => !itemMark(l)) ? firstMark : null;
1071
+ });
1072
+ const head = marks[0];
1073
+ if (!head || marks.some((m, i) => !m || m.style !== head.style || m.n !== head.n + i)) continue;
1074
+ let valueColumns = 0;
1075
+ for (let d = 0; d < table.cols; d++) {
1076
+ const side = owner[first]?.[d];
1077
+ if (!side || d + side.cs > c && d < c + a.cs || !separate(d, side.cs)) continue;
1078
+ if (!openCut) return true;
1079
+ const cells = rows.map((r) => table.cells[r][d]);
1080
+ if (cells.every((cell) => CELL_LINES.get(cell)?.length === 1) && new Set(cells.map(textOf)).size === rows.length) valueColumns++;
1081
+ if (valueColumns === 2) return true;
1082
+ }
1083
+ }
1084
+ return false;
1085
+ }
1086
+ var CONTACT_HEAD = /^(?:담당\s*부서|<[^<>]+>)$/;
1087
+ var CONTACT_ROLE = /^(?:책임자|담당자)$/;
1088
+ var PERSON = /^(.+?)\s+([가-힣]{2,4})\s*(\([^()]*\d[^()]*\)?|\S+@\S+)$/;
1089
+ var spaced = (m) => /\s/.test(m[0][m[0].length - m[3].length - 1] ?? "");
1090
+ function splitContactTables(blocks) {
1091
+ for (const b of blocks) {
1092
+ const t = b.type === "table" ? b.table : void 0;
1093
+ if (!t || t.cols !== 4 || t.rows < 2) continue;
1094
+ const rows = t.cells;
1095
+ if (!CONTACT_HEAD.test(rows[0][0].text.replace(/\s+/g, " ").trim())) continue;
1096
+ const people = rows.map((r) => {
1097
+ const lines = r[3].text.split("\n").map((line) => PERSON.exec(line.replace(/\s+/g, " ").trim()));
1098
+ if (lines.length > 1 && lines.every(Boolean)) return lines;
1099
+ const whole = PERSON.exec(r[3].text.replace(/\s+/g, " ").trim());
1100
+ return whole ? [whole] : null;
1101
+ });
1102
+ if (people.some((p) => !p) || rows.some((r) => r[3].rowSpan !== 1 || r[3].colSpan !== 1)) continue;
1103
+ let roleEnd = 0;
1104
+ const validRoles = rows.every((r, i) => {
1105
+ const role = r[2];
1106
+ if (role.colSpan !== 1) return false;
1107
+ if (i < roleEnd) return !role.text.trim() && role.rowSpan === 1;
1108
+ if (!CONTACT_ROLE.test(role.text.replace(/\s+/g, "")) || role.rowSpan < 1 || i + role.rowSpan > t.rows) return false;
1109
+ roleEnd = i + role.rowSpan;
1110
+ return true;
1111
+ });
1112
+ if (!validRoles) continue;
1113
+ if (!people.some((p) => p.some(spaced))) continue;
1114
+ const one = (text) => ({ text, colSpan: 1, rowSpan: 1 });
1115
+ const part = (i, k) => one(people[i].map((p) => p[k]).join("\n"));
1116
+ if (rows.some((r) => r[2].rowSpan > 1)) {
1117
+ t.cells = rows.map((r, i) => [...r.slice(0, 3), part(i, 1), part(i, 2), part(i, 3)]);
1118
+ t.cols = 6;
1119
+ continue;
1120
+ }
1121
+ const lead = [];
1122
+ let ok = true;
1123
+ for (const c of [0, 1]) {
1124
+ const col = rows.map(() => "");
1125
+ for (let r = 0; r < t.rows; ) {
1126
+ const cell = rows[r][c], span = Math.min(Math.max(1, cell.rowSpan), t.rows - r);
1127
+ const lines = span === 1 ? [cell.text] : cell.text.split("\n").map((s) => s.trim()).filter(Boolean);
1128
+ if (lines.length > span) {
1129
+ ok = false;
1130
+ break;
1131
+ }
1132
+ lines.forEach((line, k) => {
1133
+ col[r + k] = line;
1134
+ });
1135
+ r += span;
1136
+ }
1137
+ if (!ok) break;
1138
+ lead.push(col);
1139
+ }
1140
+ if (!ok) continue;
1141
+ t.cells = rows.map((r, i) => [one(lead[0][i]), one(lead[1][i]), one(r[2].text), part(i, 1), part(i, 2), part(i, 3)]);
1142
+ t.cols = 6;
1143
+ }
1144
+ }
1145
+ var CELL_SPLITS = /* @__PURE__ */ new WeakMap();
1146
+ function relocate(src, dst, from = 0) {
1147
+ const out = [];
1148
+ for (const s of CELL_SPLITS.get(src) ?? []) {
1149
+ const at = dst.text.indexOf(src.text.slice(s.at, s.at + 20).trimEnd(), Math.max(from, out.at(-1)?.at ?? 0));
1150
+ if (at >= 0) out.push({ at, page: s.page });
1151
+ }
1152
+ return out;
1153
+ }
1154
+ var withoutBox = ({ bbox: _, ...cell }) => cell;
1155
+ var setSplits = (cell, splits) => {
1156
+ if (splits.length) CELL_SPLITS.set(cell, splits.sort((a, b) => a.at - b.at));
1157
+ };
1158
+ function markContinuedText(cell, add, page) {
1159
+ if (!add.text.trim()) return;
1160
+ const base = cell.text.trim() ? cell.text.length + 1 : 0;
1161
+ setSplits(cell, [
1162
+ ...CELL_SPLITS.get(cell) ?? [],
1163
+ { at: base, page },
1164
+ ...(CELL_SPLITS.get(add) ?? []).map((s) => ({ at: base + s.at, page: s.page }))
1165
+ ]);
1166
+ }
1167
+ function rowStarts(t) {
1168
+ const covered = /* @__PURE__ */ new Set();
1169
+ const rows = [];
1170
+ for (let r = 0; r < t.rows; r++) {
1171
+ const starts = [];
1172
+ for (let c = 0; c < t.cols; c++) {
1173
+ if (covered.has(r * 1e5 + c)) continue;
1174
+ const cell = t.cells[r]?.[c];
1175
+ if (!cell) continue;
1176
+ for (let dr = 0; dr < cell.rowSpan; dr++) for (let dc = 0; dc < cell.colSpan; dc++) if (dr || dc) covered.add((r + dr) * 1e5 + c + dc);
1177
+ starts.push({ cell, c });
1178
+ }
1179
+ rows.push(starts);
1180
+ }
1181
+ return rows;
1182
+ }
1183
+ var covering = (t, r) => rowStarts(t).slice(0, r + 1).flatMap((starts, rr) => starts.filter((s) => rr + s.cell.rowSpan > r).map((s) => s.cell));
1184
+ function cellPage(cell) {
1185
+ const p = CELL_PAGES.get(cell);
1186
+ if (p !== void 0 || !cell.blocks?.length || cell.blocks.some((b) => b.pageNumber === void 0)) return p;
1187
+ return Math.min(...cell.blocks.map((b) => b.pageNumber));
1188
+ }
1189
+ function tableRowPages(t, pageNumber) {
1190
+ const pages = [];
1191
+ let prev = pageNumber;
1192
+ for (const starts of rowStarts(t)) {
1193
+ let mark, text = false;
1194
+ for (const { cell } of starts) {
1195
+ const p = cellPage(cell);
1196
+ if (p !== void 0) mark = Math.max(mark ?? p, p);
1197
+ else if (cell.text.trim() || cell.blocks?.length) text = true;
1198
+ }
1199
+ const page = mark ?? (text ? pageNumber : prev);
1200
+ prev = page !== void 0 && prev !== void 0 ? Math.max(prev, page) : page ?? prev;
1201
+ pages.push(prev);
1202
+ }
1203
+ return pages;
1204
+ }
1205
+ function markJoinedPages(table, prev, curr) {
1206
+ const pt = prev.table, ct = curr.table;
1207
+ if (!curr.pageNumber || table.rows < pt.rows) return;
1208
+ const pp = tableRowPages(pt, prev.pageNumber), cp = tableRowPages(ct, curr.pageNumber);
1209
+ const off = table.rows - ct.rows;
1210
+ const rows = rowStarts(table), ptRows = rowStarts(pt), ctRows = rowStarts(ct);
1211
+ rows.forEach((starts, r) => {
1212
+ const page2 = r < pt.rows ? pp[r] : cp[r - off];
1213
+ for (const { cell } of starts) {
1214
+ if (page2 !== void 0 && page2 !== prev.pageNumber) CELL_PAGES.set(cell, page2);
1215
+ const src = (r < pt.rows ? ptRows[r] : ctRows[r - off])?.find((s) => s.cell !== cell && s.cell.text === cell.text && CELL_SPLITS.has(s.cell));
1216
+ if (src) setSplits(cell, relocate(src.cell, cell));
1217
+ }
1218
+ });
1219
+ const cr = pt.rows - 1 - off, page = cp[cr];
1220
+ if (cr === -1 && table.cols === pt.cols && pt.cols === ct.cols) {
1221
+ const tailPage = cp[0];
1222
+ if (tailPage === void 0 || tailPage === prev.pageNumber) return;
1223
+ for (let r = 0; r < pt.rows; r++) for (const { cell, c } of rows[r]) {
1224
+ const head = ptRows[r]?.find((s) => s.c === c)?.cell, tail = ctRows[0]?.find((s) => s.c === c)?.cell;
1225
+ if (!head?.text.trim() || !tail?.text.trim() || cell.blocks?.length || cell.colSpan !== head.colSpan || cell.colSpan !== tail.colSpan || cell.rowSpan <= head.rowSpan || r + head.rowSpan !== pt.rows || r + cell.rowSpan <= pt.rows || !cell.text.startsWith(head.text.trimEnd()) || !cell.text.trimEnd().endsWith(tail.text.trimEnd())) continue;
1226
+ const from = head.text.trimEnd().length, at = cell.text.indexOf(tail.text.trim().slice(0, 20), from);
1227
+ if (at >= from) setSplits(cell, [...relocate(head, cell), { at, page: tailPage }, ...relocate(tail, cell, at)]);
1228
+ }
1229
+ return;
1230
+ }
1231
+ if (cr < 0 || page === void 0 || page === prev.pageNumber) return;
1232
+ const tails = ctRows[cr].filter((s) => s.cell.text.trim());
1233
+ for (const { cell } of ctRows[cr]) for (const b of cell.blocks ?? []) b.pageNumber ??= page;
1234
+ const heads = covering(pt, pt.rows - 1);
1235
+ for (const cell of covering(table, pt.rows - 1)) {
1236
+ if (cell.blocks?.length) continue;
1237
+ const head = heads.filter((h) => h.text.trim() && cell.text.startsWith(h.text.trimEnd()) && cell.text.trim().length > h.text.trim().length).sort((a, b) => b.text.length - a.text.length)[0];
1238
+ if (!head) continue;
1239
+ const from = head.text.trimEnd().length;
1240
+ const hit = tails.map((t) => ({ t: t.cell, at: cell.text.indexOf(t.cell.text.trim().slice(0, 20), from) })).filter((h) => h.at >= from).sort((a, b) => a.at - b.at)[0];
1241
+ if (!hit) continue;
1242
+ setSplits(cell, [...relocate(head, cell), { at: hit.at, page }, ...relocate(hit.t, cell, hit.at)]);
1243
+ }
1244
+ }
1245
+ function splitCell(cell, page) {
1246
+ if (page === void 0) return null;
1247
+ if (cell.blocks?.length) {
1248
+ const k2 = cell.blocks.findIndex((b) => (b.pageNumber ?? page) > page);
1249
+ if (k2 <= 0) return null;
1250
+ const head = cell.blocks.slice(0, k2), tail = cell.blocks.slice(k2);
1251
+ const text = (bs) => bs.map((b) => b.text ?? "").filter(Boolean).join("\n");
1252
+ return { head: { text: text(head), blocks: head }, tail: { text: text(tail), blocks: tail }, page: tail[0].pageNumber, rest: [] };
1253
+ }
1254
+ const splits = CELL_SPLITS.get(cell) ?? [];
1255
+ const k = splits.findIndex((s2) => s2.page > page && s2.at < cell.text.length);
1256
+ if (k < 0) return null;
1257
+ const s = splits[k];
1258
+ const rest = cell.text.slice(s.at), lead = rest.length - rest.trimStart().length;
1259
+ return {
1260
+ head: { text: cell.text.slice(0, s.at).trimEnd() },
1261
+ tail: { text: rest.trim() },
1262
+ page: s.page,
1263
+ rest: splits.slice(k + 1).map((x) => ({ at: x.at - s.at - lead, page: x.page })).filter((x) => x.at > 0)
1264
+ };
1265
+ }
1266
+ function splitCrossPageRows(t, pageNumber) {
1267
+ const pages = tableRowPages(t, pageNumber);
1268
+ const rows = rowStarts(t);
1269
+ for (let r = 0; r < t.rows; r++) {
1270
+ const splits = rows[r].map((s) => ({ ...s, split: splitCell(s.cell, pages[r]) })).filter((s) => s.split);
1271
+ if (!splits.length) continue;
1272
+ const clone = (cell, patch) => {
1273
+ const out = { ...cell, ...patch };
1274
+ carrySoftWraps(cell, out);
1275
+ const p = CELL_PAGES.get(cell);
1276
+ if (p !== void 0) CELL_PAGES.set(out, p);
1277
+ if (!("text" in patch) && CELL_SPLITS.has(cell)) CELL_SPLITS.set(out, CELL_SPLITS.get(cell));
1278
+ return out;
1279
+ };
1280
+ const e = Math.max(...splits.map((s) => r + s.cell.rowSpan - 1));
1281
+ const cells = t.cells.map((row2) => row2.slice());
1282
+ const cut = pages.findIndex((p, rr) => rr > r && p !== pages[r]);
1283
+ if (cut > r && splits.every((s) => cut < r + s.cell.rowSpan && pages[cut] === s.split.page)) {
1284
+ for (const { cell, c, split } of splits) {
1285
+ cells[r][c] = clone(cell, { ...split.head, rowSpan: cut - r });
1286
+ const tail = { ...withoutBox(cell), ...split.tail, rowSpan: r + cell.rowSpan - cut };
1287
+ CELL_PAGES.set(tail, split.page);
1288
+ setSplits(tail, split.rest);
1289
+ cells[cut][c] = tail;
1290
+ }
1291
+ return splitCrossPageRows({ ...t, cells }, pageNumber);
1292
+ }
1293
+ const row = Array.from({ length: t.cols }, () => ({ text: "", colSpan: 1, rowSpan: 1 }));
1294
+ for (const { cell, c, split } of splits) {
1295
+ cells[r][c] = clone(cell, split.head);
1296
+ const tail = { ...withoutBox(cell), ...split.tail, rowSpan: 1 };
1297
+ CELL_PAGES.set(tail, split.page);
1298
+ setSplits(tail, split.rest);
1299
+ row[c] = tail;
1300
+ }
1301
+ rows.forEach((starts, rr) => {
1302
+ for (const { cell, c } of starts) {
1303
+ if (splits.some((s) => s.cell === cell) || rr > e || rr + cell.rowSpan - 1 <= e) continue;
1304
+ cells[rr][c] = clone(cells[rr][c], { rowSpan: cell.rowSpan + 1 });
1305
+ }
1306
+ });
1307
+ cells.splice(e + 1, 0, row);
1308
+ return splitCrossPageRows({ ...t, rows: t.rows + 1, cells }, pageNumber);
1309
+ }
1310
+ return t;
1311
+ }
1312
+ function splitPageTables(blocks) {
1313
+ return blocks.flatMap((b) => {
1314
+ if (b.type !== "table" || !b.table) return [b];
1315
+ const t = splitCrossPageRows(b.table, b.pageNumber);
1316
+ const pages = tableRowPages(t, b.pageNumber);
1317
+ const cuts = [0];
1318
+ for (let r = 1; r < t.rows; r++) if (pages[r] !== pages[r - 1]) cuts.push(r);
1319
+ if (cuts.length === 1) return t === b.table ? [b] : [{ ...b, table: t }];
1320
+ const cut = (cell, rowSpan) => {
1321
+ const out = { ...cell, rowSpan };
1322
+ carrySoftWraps(cell, out);
1323
+ return out;
1324
+ };
1325
+ return cuts.map((from, k) => {
1326
+ const end = cuts[k + 1] ?? t.rows;
1327
+ const cells = t.cells.slice(from, end).map((row, dr) => row.map((cell) => cell && from + dr + cell.rowSpan > end ? cut(cell, end - from - dr) : cell));
1328
+ const table = { ...t, rows: end - from, cells, ...k ? { caption: void 0, captionBlocks: void 0 } : {} };
1329
+ return { ...b, table, pageNumber: pages[from] };
1330
+ });
1331
+ });
1332
+ }
1333
+ var flowText = (text) => text.replace(/<\/?u>|~~/g, "");
1334
+ var PART_COL_TOL = 1;
1335
+ var PART_COL_SNAP = 0.3;
1336
+ function anchorsOf(table) {
1337
+ const out = [];
1338
+ const covered = /* @__PURE__ */ new Set();
1339
+ for (let r = 0; r < table.rows; r++) {
1340
+ for (let c = 0; c < table.cols; c++) {
1341
+ if (covered.has(r * 1e5 + c)) continue;
1342
+ const cell = table.cells[r]?.[c];
1343
+ if (!cell) continue;
1344
+ out.push({ r, c, rs: cell.rowSpan, cs: cell.colSpan, cell });
1345
+ for (let dr = 0; dr < cell.rowSpan; dr++) {
1346
+ for (let dc = 0; dc < cell.colSpan; dc++) if (dr || dc) covered.add((r + dr) * 1e5 + (c + dc));
1347
+ }
1348
+ }
1349
+ }
1350
+ return out;
1351
+ }
1352
+ function unionCoords(a, b) {
1353
+ const drift = a.length === b.length && a.every((x, i) => Math.abs(x - b[i]) <= PART_COL_TOL);
1354
+ const tol = drift ? PART_COL_TOL : PART_COL_SNAP;
1355
+ const pairs = [];
1356
+ for (const v of b) for (const x of a) if (Math.abs(x - v) <= tol) pairs.push([Math.abs(x - v), v, x]);
1357
+ pairs.sort((p, q) => p[0] - q[0]);
1358
+ const map = /* @__PURE__ */ new Map(), taken = /* @__PURE__ */ new Set();
1359
+ for (const [, v, x] of pairs) if (!map.has(v) && !taken.has(x)) {
1360
+ map.set(v, x);
1361
+ taken.add(x);
1362
+ }
1363
+ const out = [...a];
1364
+ for (const v of b) if (!map.has(v)) {
1365
+ map.set(v, v);
1366
+ out.push(v);
1367
+ }
1368
+ return { U: out.sort((x, y) => x - y), map };
1369
+ }
1370
+ var indexOf = (coords, x) => {
1371
+ let best = -1, bestD = Infinity;
1372
+ for (let i = 0; i < coords.length; i++) {
1373
+ const d = Math.abs(coords[i] - x);
1374
+ if (d < bestD) {
1375
+ bestD = d;
1376
+ best = i;
1377
+ }
1378
+ }
1379
+ return bestD <= PART_COL_TOL ? best : -1;
1380
+ };
1381
+ var rowText = (anchors, r) => anchors.filter((a) => a.r === r).map((a) => flowText(a.cell.text).replace(/\s+/g, "")).join("|");
1382
+ var hasText = (t) => t.replace(/\|/g, "") !== "";
1383
+ function joinSplitParts(prev, pcx, curr, ccx, dx = 0, prevBottom, lex) {
1384
+ if (pcx.length !== prev.cols + 1 || ccx.length !== curr.cols + 1) return null;
1385
+ const { U, map } = unionCoords(pcx, ccx);
1386
+ const cxU = ccx.map((v) => map.get(v) ?? v);
1387
+ const cols = U.length - 1;
1388
+ if (cols < 1) return null;
1389
+ const pa = anchorsOf(prev), ca = anchorsOf(curr);
1390
+ const cutOpen = (() => {
1391
+ const u = ROW_RULES.get(prev), d = ROW_RULES.get(curr);
1392
+ return !!u && !!d && !u.bottom && !d.top;
1393
+ })();
1394
+ let skip = 0, head = 0;
1395
+ while (!cutOpen && skip < Math.min(3, curr.rows - 1, prev.rows) && rowText(ca, skip) !== "" && rowText(ca, skip) === rowText(pa, skip)) skip++;
1396
+ for (let h = 1; h <= 2 && !skip && !cutOpen; h++) {
1397
+ head = h;
1398
+ while (skip < Math.min(3, curr.rows - 1, prev.rows - h) && hasText(rowText(ca, skip)) && rowText(ca, skip) === rowText(pa, h + skip)) skip++;
1399
+ }
1400
+ const sameSpans = (u, d) => {
1401
+ if (u.length !== d.length || !u.length) return false;
1402
+ const shift = pcx[u[u.length - 1].c + u[u.length - 1].cs] - ccx[d[d.length - 1].c + d[d.length - 1].cs];
1403
+ return u.every((a, n) => Math.abs(pcx[a.c] - ccx[d[n].c] - shift) <= CONTINUATION_COL_TOL && Math.abs(pcx[a.c + a.cs] - ccx[d[n].c + d[n].cs] - shift) <= CONTINUATION_COL_TOL);
1404
+ };
1405
+ for (let k = 0; k < skip; k++) {
1406
+ if (sameSpans(pa.filter((a) => a.r === head + k), ca.filter((a) => a.r === k))) continue;
1407
+ if (hasText(rowText(ca, k))) return null;
1408
+ skip = k;
1409
+ }
1410
+ const rows = prev.rows + curr.rows - skip;
1411
+ const grid = Array.from({ length: rows }, () => Array.from({ length: cols }, () => ({ text: "", colSpan: 1, rowSpan: 1 })));
1412
+ const owner = Array.from({ length: rows }, () => new Array(cols).fill(null));
1413
+ let edged = false;
1414
+ const place = (a, x, rowOff, shift = 0) => {
1415
+ const c1 = indexOf(U, x[a.c]), c2 = indexOf(U, x[a.c + a.cs]);
1416
+ if (c1 < 0 || c2 <= c1) return false;
1417
+ const r = a.r + rowOff;
1418
+ const placed = { r, c: c1, rs: a.rs, cs: c2 - c1, cell: a.cell };
1419
+ for (let dr = 0; dr < a.rs; dr++) for (let dc = c1; dc < c2; dc++) {
1420
+ if (r + dr < rows) owner[r + dr][dc] = placed;
1421
+ }
1422
+ grid[r][c1] = { ...a.cell, colSpan: c2 - c1, rowSpan: a.rs };
1423
+ const lines = CELL_LINES.get(a.cell);
1424
+ if (lines) CELL_LINES.set(grid[r][c1], shift ? lines.map((l) => ({ ...l, l: l.l + shift, r: l.r + shift })) : lines);
1425
+ if (IMAGE_CELLS.has(a.cell)) IMAGE_CELLS.add(grid[r][c1]);
1426
+ carrySoftWraps(a.cell, grid[r][c1]);
1427
+ const edges = CELL_EDGES.get(a.cell);
1428
+ if (edges) {
1429
+ CELL_EDGES.set(grid[r][c1], edges);
1430
+ edged = true;
1431
+ }
1432
+ return true;
1433
+ };
1434
+ for (const a of pa) if (!FILLER_CELLS.has(a.cell) && !place(a, pcx, 0)) return null;
1435
+ for (const a of ca) {
1436
+ if (a.r < skip || FILLER_CELLS.has(a.cell)) continue;
1437
+ if (!place(a, cxU, prev.rows - skip, dx)) return null;
1438
+ }
1439
+ const first = prev.rows;
1440
+ for (let c = 0; c < cols; c++) {
1441
+ const above = owner[first - 1]?.[c];
1442
+ if (!above) continue;
1443
+ let r = first;
1444
+ while (r < rows && owner[r][c] === null) r++;
1445
+ if (r === first) continue;
1446
+ const span = r - first;
1447
+ let ok = true;
1448
+ for (let dc = above.c; dc < above.c + above.cs && ok; dc++) {
1449
+ for (let rr = first; rr < first + span; rr++) if (owner[rr][dc] !== null) {
1450
+ ok = false;
1451
+ break;
1452
+ }
1453
+ }
1454
+ if (!ok) continue;
1455
+ const newRs = above.rs + span;
1456
+ grid[above.r][above.c].rowSpan = newRs;
1457
+ const grown = { ...above, rs: newRs };
1458
+ for (let rr = above.r; rr < above.r + newRs; rr++) for (let dc = above.c; dc < above.c + above.cs; dc++) owner[rr][dc] = grown;
1459
+ }
1460
+ for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) if (owner[r][c] === null) FILLER_CELLS.add(grid[r][c]);
1461
+ if (edged) {
1462
+ for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) if (owner[r][c] === null) CELL_EDGES.set(grid[r][c], NO_EDGES);
1463
+ }
1464
+ for (let c = 0; c < cols && U[c + 1] <= pcx[0] + PART_COL_TOL; c++) {
1465
+ let r = prev.rows;
1466
+ while (r < rows && owner[r][c] === null) r++;
1467
+ const through = { r: 0, c, rs: r, cs: 1, cell: grid[0][c] };
1468
+ for (let rr = 0; rr < r; rr++) owner[rr][c] = through;
1469
+ }
1470
+ const table = { rows, cols, cells: grid, hasHeader: prev.hasHeader, ...prev.caption ? { caption: prev.caption } : {} };
1471
+ const pr = ROW_RULES.get(prev), cr = ROW_RULES.get(curr);
1472
+ const shifted = dx !== 0;
1473
+ const cut = {
1474
+ open: !!pr && !!cr && !pr.bottom && !cr.top && pr.innerOpen + cr.innerOpen === 0 && pr.innerRuled + cr.innerRuled > 0,
1475
+ ruled: !!pr && !!cr && pr.bottom && cr.top,
1476
+ list: !shifted ? "any" : skip > 0 && ca.filter((a) => a.r < skip && a.cell.text.trim()).length < 2 ? "none" : "multi"
1477
+ };
1478
+ let partial = !skip && cols === prev.cols && cols === curr.cols && cut.ruled && prevBottom !== void 0 ? partialAlignedLabelCells(table, owner, first) : void 0;
1479
+ if (partial && (continuesAcross(partial.context.upper, partial.context.lower, U[partial.context.c], U[partial.context.c + partial.context.cs]) || clauseContinues(partial.context.upper, partial.context.lower) || quantityContinues(partial.context.upper, partial.context.lower) || !continuesAcross(partial.value.upper, partial.value.lower, U[partial.value.c], U[partial.value.c + partial.value.cs]) || startsNewItem(partial.value.upper.text, partial.value.lower.text))) partial = void 0;
1480
+ const selected = partial ? /* @__PURE__ */ new Set([partial.label.c, partial.value.c]) : void 0;
1481
+ let split = !selected && rows > prev.rows && mergeSplitRow(table, owner, prev.rows, U, false, cut, lex);
1482
+ if (rows > prev.rows && !split && prevBottom !== void 0 && mergeStraddlingCells(table, owner, prev.rows, prevBottom, lex, U, selected) && !selected) split = mergeSplitRow(table, owner, prev.rows, U, true, { ...cut, open: false }, lex);
1483
+ if (pr && cr) {
1484
+ const cutRuled = pr.bottom || cr.top;
1485
+ ROW_RULES.set(table, { top: pr.top, bottom: cr.bottom, innerRuled: pr.innerRuled + cr.innerRuled + (!split && cutRuled ? 1 : 0), innerOpen: pr.innerOpen + cr.innerOpen + (!split && !cutRuled ? 1 : 0) });
1486
+ }
1487
+ return { table, colXs: U, split, header: ca.filter((a) => a.r < skip && a.cell.text.trim()).length >= 2 };
1488
+ }
1489
+ function mergeStraddlingCells(table, owner, first, prevBottom, lex, colXs, selected) {
1490
+ const last = first - 1;
1491
+ const straddles = owner[first].some((o, c) => o !== null && o === owner[last][c]);
1492
+ let firstNew = table.cols;
1493
+ for (let c = 0; c < table.cols; c++) {
1494
+ const d = owner[first][c];
1495
+ if (d && d.r === first && d !== owner[last][c] && hasContent(table.cells[d.r][d.c])) {
1496
+ firstNew = c;
1497
+ break;
1498
+ }
1499
+ }
1500
+ let midWord = false;
1501
+ if (lex) for (let c = 0; c < table.cols && !midWord; ) {
1502
+ const u = owner[last][c], d = owner[first][c];
1503
+ if (!u) {
1504
+ c++;
1505
+ continue;
1506
+ }
1507
+ c = u.c + u.cs;
1508
+ if (!d || d === u || u.r + u.rs - 1 !== last || d.r !== first || d.c !== u.c || d.cs !== u.cs) continue;
1509
+ if (u.r !== last || d.rs < 2) continue;
1510
+ const tail = table.cells[u.r][u.c].text.trim().split(/\s+/).pop() ?? "", head = table.cells[first][d.c].text.trim().split(/\s+/)[0] ?? "";
1511
+ if (/^[가-힣]{2,}$/.test(tail) && /^[가-힣]{2,}/.test(head) && lex.evidence2(tail, head) === "") midWord = true;
1512
+ }
1513
+ const crossed = /* @__PURE__ */ new Set();
1514
+ const shape = (u, d) => `${u.r}:${u.rs}:${d.rs}`;
1515
+ if (straddles && colXs) for (let c = 0; c < table.cols; ) {
1516
+ const u = owner[last][c], d = owner[first][c];
1517
+ if (!u) {
1518
+ c++;
1519
+ continue;
1520
+ }
1521
+ c = u.c + u.cs;
1522
+ if (!d || d === u || u.r + u.rs - 1 !== last || d.r !== first || d.c !== u.c || d.cs !== u.cs || u.rs < 2) continue;
1523
+ const a = table.cells[u.r][u.c], b = table.cells[first][d.c];
1524
+ if (hasContent(a) && hasContent(b) && continuesAcross(a, b, colXs[u.c], colXs[u.c + u.cs])) crossed.add(shape(u, d));
1525
+ }
1526
+ let itemBreak = false;
1527
+ for (let c = 0; c < table.cols && !itemBreak; ) {
1528
+ const u = owner[last][c], d = owner[first][c];
1529
+ if (!u) {
1530
+ c++;
1531
+ continue;
1532
+ }
1533
+ c = u.c + u.cs;
1534
+ if (d && d !== u && d.r === first) itemBreak = nextItemHead(table.cells[u.r][u.c].text, table.cells[d.r][d.c].text);
1535
+ }
1536
+ let merged = false;
1537
+ for (let c = 0; c < table.cols; ) {
1538
+ const u = owner[last][c], d = owner[first][c];
1539
+ if (!u) {
1540
+ c++;
1541
+ continue;
1542
+ }
1543
+ c = u.c + u.cs;
1544
+ if (!d || d === u || u.r + u.rs - 1 !== last || d.r !== first || d.c !== u.c || d.cs !== u.cs) continue;
1545
+ const a = table.cells[u.r][u.c], b = table.cells[first][d.c];
1546
+ if (selected && !selected.has(u.c)) continue;
1547
+ const flowsOn = itemBreak && straddles && !!colXs && hasContent(a) && hasContent(b) && longLastLine(a) && !startsNewItem(a.text, b.text) && continuesAcross(a, b, colXs[u.c], colXs[u.c + u.cs]);
1548
+ const openSeam = hasContent(a) && hasContent(b) && hasOpenCellSeam(a, b) && !owner.some((row, r) => {
1549
+ if (!r || r === first) return false;
1550
+ const up = owner[r - 1][u.c], down = row[u.c];
1551
+ if (!up || !down || up === down || up.c !== u.c || down.c !== u.c || up.cs !== u.cs || down.cs !== u.cs) return false;
1552
+ const ue = CELL_EDGES.get(table.cells[up.r][up.c]), de = CELL_EDGES.get(table.cells[down.r][down.c]);
1553
+ return !!ue && !!de && !ue.b && !de.t;
1554
+ });
1555
+ if (!selected && !openSeam && !flowsOn && !crossed.has(shape(u, d)) && !(u.rs >= 2 && u.c + u.cs <= firstNew && hasContent(a) && !hasContent(b))) {
1556
+ if (!straddles && !midWord) continue;
1557
+ if (u.r >= last && d.rs < 2) continue;
1558
+ const U = CELL_LINES.get(a);
1559
+ if (!U?.length || !hasContent(b)) continue;
1560
+ if (!(straddles && filledToBottom(U, prevBottom) && clauseContinues(a, b))) {
1561
+ if (U.length > STRADDLE_MAX_LINES) continue;
1562
+ const lu = U[U.length - 1];
1563
+ if (!midWord && lu.y - prevBottom > (u.r >= last ? STRADDLE_BOTTOM_ONE_ROW : STRADDLE_BOTTOM) * (lu.h || 10)) continue;
1564
+ }
1565
+ }
1566
+ appendCell(a, b, !!colXs && continuesAcross(a, b, colXs[u.c], colXs[u.c + u.cs]), lex);
1567
+ a.rowSpan = first + d.rs - u.r;
1568
+ table.cells[first][d.c] = { text: "", colSpan: 1, rowSpan: 1 };
1569
+ const grown = { ...u, rs: a.rowSpan };
1570
+ for (let rr = u.r; rr < u.r + grown.rs; rr++) for (let dc = u.c; dc < u.c + u.cs; dc++) owner[rr][dc] = grown;
1571
+ merged = true;
1572
+ }
1573
+ return merged;
1574
+ }
1575
+ function longLastLine(c) {
1576
+ const L = CELL_LINES.get(c), l = L?.[L.length - 1];
1577
+ return !!l && l.r - l.l >= 6 * (l.h || 10);
1578
+ }
1579
+ function filledToBottom(U, bottom) {
1580
+ if (U.length < 2) return false;
1581
+ const lu = U[U.length - 1];
1582
+ return lu.y - bottom < (U[0].y - lu.y) / (U.length - 1) + FILL_SLACK * (lu.h || 10);
1583
+ }
1584
+ var FULL_LINE_TOL = 1;
1585
+ var FULL_LINE_MIN_FRAC = 0.5;
1586
+ var FULL_LINE_EDGE_MIN = 12;
1587
+ var SINGLE_LINE_WORD_GAP = 3.5;
1588
+ var SHORT_LINE_GAP = 1.5;
1589
+ var STRADDLE_MAX_LINES = 3;
1590
+ var STRADDLE_BOTTOM = 1.2;
1591
+ var STRADDLE_BOTTOM_ONE_ROW = 0.55;
1592
+ var FILL_SLACK = 0.5;
1593
+ var CARRIED_MIN_COL_W = 4;
1594
+ var LABEL_ROOM = 1.5;
1595
+ var HANGING_MIN = 0.5;
1596
+ var HANGING_TOL = 1;
1597
+ var KO_ITEMS = "\uAC00\uB098\uB2E4\uB77C\uB9C8\uBC14\uC0AC\uC544\uC790\uCC28\uCE74\uD0C0\uD30C\uD558\uAC70\uB108\uB354\uB7EC\uBA38\uBC84\uC11C\uC5B4\uC800\uCC98\uCEE4\uD130\uD37C\uD5C8\uACE0\uB178\uB3C4\uB85C\uBAA8\uBCF4\uC18C\uC624\uC870\uCD08\uCF54\uD1A0\uD3EC\uD638\uAD6C\uB204\uB450\uB8E8\uBB34\uBD80\uC218\uC6B0\uC8FC\uCD94\uCFE0\uD22C\uD478\uD6C4";
1598
+ var ITEM_MARK = /^\s*(?:([가-힣])[.)]|(\d{1,3})[.)]|\(([가-힣\d]{1,3})\))(?=\s)/;
1599
+ function nextItemHead(prev, next) {
1600
+ const a = ITEM_MARK.exec(prev), b = ITEM_MARK.exec(next);
1601
+ if (!a || !b) return false;
1602
+ const succ = (x, y) => /^\d+$/.test(x) ? /^\d+$/.test(y) && Number(y) === Number(x) + 1 : KO_ITEMS.indexOf(x) >= 0 && KO_ITEMS.indexOf(y) === KO_ITEMS.indexOf(x) + 1;
1603
+ if (a[1] && b[1]) return succ(a[1], b[1]) && prev.trimStart()[1] === next.trimStart()[1];
1604
+ if (a[2] && b[2]) return succ(a[2], b[2]) && prev.trimStart()[a[2].length] === next.trimStart()[b[2].length];
1605
+ if (a[3] && b[3]) return succ(a[3], b[3]);
1606
+ return false;
1607
+ }
1608
+ function continuesAcross(u, d, x1, x2) {
1609
+ const U = CELL_LINES.get(u), D = CELL_LINES.get(d);
1610
+ if (!U?.length || !D?.length) return false;
1611
+ const last = U[U.length - 1];
1612
+ const fs = last.h || 10;
1613
+ let minL = Infinity, maxR = -Infinity;
1614
+ for (const l of U) {
1615
+ minL = Math.min(minL, l.l);
1616
+ maxR = Math.max(maxR, l.r);
1617
+ }
1618
+ for (const l of D) {
1619
+ minL = Math.min(minL, l.l);
1620
+ maxR = Math.max(maxR, l.r);
1621
+ }
1622
+ maxR = Math.max(maxR, x2 - (minL - x1));
1623
+ if (maxR - last.r > FULL_LINE_TOL * fs) return false;
1624
+ if (U.length === 1 && x2 - last.r > Math.max(FULL_LINE_EDGE_MIN, SINGLE_LINE_WORD_GAP * fs)) return false;
1625
+ const indented = last.l - minL >= HANGING_MIN * fs;
1626
+ if (last.r - last.l < FULL_LINE_MIN_FRAC * (indented ? x2 - last.l : x2 - x1)) return false;
1627
+ const newItem = startsNewItem(u.text, d.text);
1628
+ const all = D.length ? U.concat(D) : U;
1629
+ const leftAligned = (l) => maxR - l.r > SHORT_LINE_GAP * fs && (l.l - minL <= fs || !newItem && all.some((o) => o !== l && Math.abs(o.l - l.l) <= HANGING_TOL && Math.abs(o.r - l.r) >= HANGING_MIN * fs));
1630
+ const hanging = U.length >= 2 && U.every((l) => maxR - l.r <= FULL_LINE_TOL * fs) && indented && Math.abs(D[0].l - last.l) <= HANGING_TOL;
1631
+ const hangingHead = !indented && D.length >= 2 && D[0].l - last.l >= HANGING_MIN * fs && maxR - D[0].r <= FULL_LINE_TOL * fs && D.every((l) => Math.abs(l.l - D[0].l) <= HANGING_TOL);
1632
+ const d0 = D[0];
1633
+ const hangStart = U.length === 1 && !newItem && d0.l - last.l >= HANGING_MIN * fs && D.every((l) => l.l >= d0.l - HANGING_TOL) && (Math.abs(d0.r - last.r) <= HANGING_TOL && d0.r - d0.l >= FULL_LINE_MIN_FRAC * (x2 - x1) || last.r - d0.r > SHORT_LINE_GAP * fs && Math.abs(d0.l + d0.r - last.l - last.r) / 2 >= HANGING_MIN * fs);
1634
+ return U.some(leftAligned) || D.some(leftAligned) || hanging || hangingHead || hangStart;
1635
+ }
1636
+ var OUTLINE_HEAD = /^[□■]\s*\S/;
1637
+ var OUTLINE_ITEM = /^[ㅇ○◦\-‐–·․‧※*]\s*\S/;
1638
+ function outlineContinues(u, d) {
1639
+ const U = flowText(u.text).split("\n").map((l) => l.trim()).filter(Boolean);
1640
+ const D = flowText(d.text).split("\n").map((l) => l.trim()).filter(Boolean);
1641
+ return U.length >= 2 && D.length >= 1 && U.some((l) => OUTLINE_HEAD.test(l)) && OUTLINE_ITEM.test(D[0]);
1642
+ }
1643
+ function lineEnded(c, x1, x2, next) {
1644
+ const L = CELL_LINES.get(c);
1645
+ if (!L || L.length !== 1) return false;
1646
+ const l = L[0], h = l.h || 10;
1647
+ const d0 = next ? CELL_LINES.get(next)?.[0] : void 0;
1648
+ if (d0 && d0.l - l.l >= HANGING_MIN * h) return false;
1649
+ return x2 - l.r - (l.l - x1) >= Math.max(LABEL_ROOM, firstWordUnits(next?.text ?? "")) * h;
1650
+ }
1651
+ function firstWordUnits(text) {
1652
+ const word = flowText(text).trim().replace(/^([(\[「『<〈])\s+/, "$1").split(/\s+/)[0] ?? "";
1653
+ let units = 0;
1654
+ for (const ch of word) units += /[가-힣\u3400-\u9fff]/.test(ch) ? 1 : 0.55;
1655
+ return units;
1656
+ }
1657
+ function appendCell(a, b, flows = false, lex) {
1658
+ if (IMAGE_CELLS.has(b)) IMAGE_CELLS.add(a);
1659
+ if (a.blocks?.length || b.blocks?.length) {
1660
+ const asBlocks = (c) => c.blocks?.length ? c.blocks : cellParagraphs(c).map((text) => ({ type: "paragraph", text }));
1661
+ a.blocks = [...asBlocks(a), ...asBlocks(b)];
1662
+ }
1663
+ if (b.text.trim() && a.text.trim() && flows && !midWordAcross(a.text, b.text, lex)) {
1664
+ const prev = a.text.slice(a.text.lastIndexOf("\n") + 1).trim(), next = b.text.split("\n", 1)[0].trim();
1665
+ if (prev && next && softWrapPair(prev, next)) CELL_SOFT_WRAPS.set(a, /* @__PURE__ */ new Set([...CELL_SOFT_WRAPS.get(a) ?? [], prev + "\n" + next]));
1666
+ }
1667
+ if (b.text.trim()) a.text = a.text.trim() ? a.text + (flows && midWordAcross(a.text, b.text, lex) ? "" : "\n") + b.text : b.text;
1668
+ carrySoftWraps(b, a);
1669
+ joinCellEdges(a, b);
1670
+ }
1671
+ function midWordAcross(upper, lower, lex) {
1672
+ const prev = upper.slice(upper.lastIndexOf("\n") + 1), next = lower.split("\n", 1)[0];
1673
+ return !!prev.trim() && !!next.trim() && !startsNewItem(prev, next) && wrapJoiner(prev, next, lex, false) === "";
1674
+ }
1675
+ var hasContent = (cell) => !!cell.text.trim() || !!cell.blocks?.length || IMAGE_CELLS.has(cell);
1676
+ var CLAUSE_OPEN_ENDING = /(?:하는|되는|하고|하며|하여|되어|되고|되며|이며|으며|어야|아야|여야)$/;
1677
+ var batchim = (ch) => {
1678
+ const k = ch.charCodeAt(0) - 44032;
1679
+ return k >= 0 && k < 11172 && k % 28 !== 0;
1680
+ };
1681
+ function clauseContinues(u, d) {
1682
+ const tail = flowText(u.text).trim().split(/\s+/).pop() ?? "", head = flowText(d.text).trim();
1683
+ if (!/^[가-힣]{2,}$/.test(tail) || !/^[가-힣]/.test(head) || startsNewItem(u.text, head)) return false;
1684
+ const last = tail[tail.length - 1], before = tail[tail.length - 2];
1685
+ return last === "\uC744" && batchim(before) || last === "\uB97C" && !batchim(before) || CLAUSE_OPEN_ENDING.test(tail);
1686
+ }
1687
+ function quantityContinues(u, d) {
1688
+ return /\d[\d,.]*\s*(?:%|[가-힣]{1,2})?$/.test(flowText(u.text).trim()) && /^(?:미만|이상|이하|초과)(?![가-힣])/.test(flowText(d.text).trim());
1689
+ }
1690
+ function wordOverflows(u, d, x1, x2) {
1691
+ const U = CELL_LINES.get(u);
1692
+ if (!U?.length || startsNewItem(u.text, d.text)) return false;
1693
+ const last = U[U.length - 1], units = firstWordUnits(d.text);
1694
+ return units > 0 && last.r - last.l + units * (last.h || 10) > x2 - x1;
1695
+ }
1696
+ function listContinues(u, d, multi = false) {
1697
+ const head = itemMark(d.text.trim());
1698
+ if (!head) return false;
1699
+ const marks = u.text.split("\n").map((l) => itemMark(l.trim()));
1700
+ let last = -1, count = 0;
1701
+ marks.forEach((m, i) => {
1702
+ if (m?.style === head.style) {
1703
+ last = i;
1704
+ count++;
1705
+ }
1706
+ });
1707
+ return last >= 0 && marks[last].n + 1 === head.n && (count >= 2 || !multi && last > 0);
1708
+ }
1709
+ function outlineOnly(pairs, cell) {
1710
+ const filled = pairs.filter(([, d]) => hasContent(d.cell));
1711
+ return filled.length === 1 && outlineContinues(cell(filled[0][0]), cell(filled[0][1]));
1712
+ }
1713
+ function joinNestedParts(u, d) {
1714
+ const prev = u.blocks?.[u.blocks.length - 1], curr = d.blocks?.[0];
1715
+ if (!prev?.table || !curr?.table || !prev.pageNumber || curr.pageNumber !== prev.pageNumber + 1) return null;
1716
+ const px = TABLE_COLXS.get(prev.table), cx = TABLE_COLXS.get(curr.table);
1717
+ if (!px || !cx || !shiftedSame(px, cx, false) || curr.table.cells[0].filter((c) => c.text.trim()).length < 2 || repeatedHeaderRows(prev.table, curr.table) <= 0) return null;
1718
+ const table = joinClipParts(prev, curr);
1719
+ if (!table || table.rows >= prev.table.rows + curr.table.rows) return null;
1720
+ markJoinedPages(table, prev, curr);
1721
+ return { ...prev, table };
1722
+ }
1723
+ var NO_CUT = { open: false, ruled: false, list: "any" };
1724
+ function mergeSplitRow(table, owner, first, colXs, textOnly = false, cut = NO_CUT, lex) {
1725
+ const last = first - 1;
1726
+ const pairs = [];
1727
+ let carried = false;
1728
+ const starts = [];
1729
+ for (let c = 0; c < table.cols; ) {
1730
+ const b = owner[first][c];
1731
+ if (b && b.r === first) starts.push(b);
1732
+ c = b ? b.c + b.cs : c + 1;
1733
+ }
1734
+ const tall = starts.filter((b) => b.rs > 1 && hasContent(b.cell));
1735
+ const band = !textOnly && tall.length > 0 && starts.every((b) => b.rs > 1 || !hasContent(b.cell)) && tall.every((b) => {
1736
+ const a = owner[last][b.c];
1737
+ return !!a && a.rs > 1 && a.c === b.c && a.cs === b.cs && a.r + a.rs - 1 === last && hasContent(a.cell);
1738
+ });
1739
+ for (let c = 0; c < table.cols; ) {
1740
+ const a = owner[last][c], b = owner[first][c];
1741
+ if (!a && !b) {
1742
+ if (colXs[c + 1] - colXs[c] >= CARRIED_MIN_COL_W) carried = true;
1743
+ c++;
1744
+ continue;
1745
+ }
1746
+ if (!a || !b) return false;
1747
+ if (a !== b) {
1748
+ if (a.c !== b.c || a.cs !== b.cs || a.r + a.rs - 1 !== last || b.r !== first) return false;
1749
+ if (b.rs > 1 && (a.rs > 1 || !hasContent(a.cell)) && !band) return false;
1750
+ pairs.push([a, b]);
1751
+ } else if (a.r === last && a.rs === 2) carried = true;
1752
+ c = a.c + a.cs;
1753
+ }
1754
+ const newCell = pairs.some(([u, d]) => !hasContent(u.cell) && hasContent(d.cell));
1755
+ const cell = (a) => table.cells[a.r][a.c];
1756
+ const serial = (c) => {
1757
+ const t = flowText(c.text).trim();
1758
+ return /^\d{1,3}$/.test(t) ? +t : null;
1759
+ };
1760
+ if (pairs.some(([u, d]) => {
1761
+ const a = serial(cell(u)), b = serial(cell(d));
1762
+ return a !== null && b === a + 1;
1763
+ })) return false;
1764
+ if ((cut.ruled || cut.open) && hasNumberedRowSequence(table, owner, first, cut.open)) return false;
1765
+ if (cut.ruled && matchesIndependentRowPair(table, owner, first)) return false;
1766
+ const contentPairs = pairs.filter(([u, d]) => hasContent(u.cell) && hasContent(d.cell));
1767
+ const nested = !textOnly && pairs.length === 1 ? joinNestedParts(cell(pairs[0][0]), cell(pairs[0][1])) : null;
1768
+ const carriedSplit = !textOnly && carried && !newCell && (contentPairs.length <= 1 || contentPairs.every(([, d]) => d.rs > 1) || !cut.ruled && contentPairs.some(([u, d]) => wordOverflows(cell(u), cell(d), colXs[u.c], colXs[u.c + u.cs])));
1769
+ if (!nested && !carriedSplit && !band) {
1770
+ const norm = (c) => flowText(c.text).replace(/\s+/g, "");
1771
+ const openCut = cut.open && !newCell;
1772
+ if (!openCut && pairs.some(([u, d]) => hasContent(d.cell) && norm(cell(d)) !== norm(cell(u)) && lineEnded(cell(u), colXs[u.c], colXs[u.c + u.cs], cell(d)))) return false;
1773
+ const oneLine = (c) => CELL_LINES.get(c)?.length === 1;
1774
+ if (!openCut && pairs.some(([u, d]) => nextItemHead(cell(u).text, cell(d).text)) && pairs.some(([u, d]) => hasContent(u.cell) && hasContent(d.cell) && oneLine(cell(u)) && oneLine(cell(d)) && norm(cell(u)) !== norm(cell(d)))) return false;
1775
+ if (cut.ruled && pairs.some(([u, d]) => u.rs >= 2 && hasContent(u.cell) && hasContent(d.cell) && oneLine(cell(u)) && oneLine(cell(d)) && norm(cell(u)) !== norm(cell(d)))) return false;
1776
+ const flows = ([u, d]) => continuesAcross(cell(u), cell(d), colXs[u.c], colXs[u.c + u.cs]) || clauseContinues(cell(u), cell(d)) || quantityContinues(cell(u), cell(d));
1777
+ if (!(cut.open && !newCell)) {
1778
+ if (pairs.some((p) => p[1].rs > 1 && !flows(p))) return false;
1779
+ const one = pairs.filter(([, d]) => d.rs === 1);
1780
+ if (!matchesCompleteSiblingRow(table, owner, first) && !matchesCompleteRubricRow(table, owner, first) && !(cut.ruled && (matchesCompleteContextRow(table, owner, first) || matchesCompleteAlignedLabelListRow(table, owner, first))) && !outlineOnly(pairs, cell) && !one.some(flows) && (cut.list === "none" || !one.some(([u, d]) => listContinues(cell(u), cell(d), cut.list === "multi")))) return false;
1781
+ }
1782
+ }
1783
+ for (const [u, d] of pairs) {
1784
+ appendCell(table.cells[u.r][u.c], table.cells[d.r][d.c], continuesAcross(cell(u), cell(d), colXs[u.c], colXs[u.c + u.cs]), lex);
1785
+ if (d.rs > 1) table.cells[u.r][u.c].rowSpan = u.rs + d.rs;
1786
+ }
1787
+ if (nested) {
1788
+ const blocks = cell(pairs[0][0]).blocks;
1789
+ blocks.splice(blocks.indexOf(cell(pairs[0][1]).blocks[0]) - 1, 2, nested);
1790
+ }
1791
+ for (let r = 0; r < first; r++) for (let c = 0; c < table.cols; c++) {
1792
+ const o = owner[r][c];
1793
+ if (o && o.r === r && o.c === c && r + table.cells[r][c].rowSpan > first) table.cells[r][c].rowSpan--;
1794
+ }
1795
+ table.cells.splice(first, 1);
1796
+ table.rows--;
1797
+ return true;
1798
+ }
1799
+ var NEIGHBOR_TABLE_EPSILON = 0.2;
1800
+ function besideOwn(b, p, c) {
1801
+ if (!b.bbox) return false;
1802
+ if (b.type === "table") return leftColumnOf(b, p);
1803
+ const t = (b.pageNumber === p.pageNumber ? p : c).bbox;
1804
+ const bx1 = b.bbox.x, bx2 = b.bbox.x + b.bbox.width;
1805
+ return bx2 <= t.x + 1 || bx1 >= t.x + t.width - 1;
1806
+ }
1807
+ var PAGE_NUMBER_TEXT = /^[-–—]?\s*\d{1,4}\s*[-–—]?$/;
1808
+ function pageNumberBetween(b, p, c, pageHeights) {
1809
+ if (b.type !== "paragraph" || !b.bbox || !PAGE_NUMBER_TEXT.test(b.text?.trim() ?? "")) return false;
1810
+ const h = b.pageNumber ? pageHeights?.get(b.pageNumber) : void 0;
1811
+ if (!h) return false;
1812
+ if (b.pageNumber === p.pageNumber) return b.bbox.y + b.bbox.height <= Math.min(p.bbox.y, h * PAGE_EDGE_BAND) + 1;
1813
+ if (b.pageNumber === c.pageNumber) return b.bbox.y >= Math.max(c.bbox.y + c.bbox.height, h * (1 - PAGE_EDGE_BAND)) - 1;
1814
+ return false;
1815
+ }
1816
+ function leftColumnOf(b, t) {
1817
+ return !!b.bbox && b.pageNumber === t.pageNumber && b.bbox.x + b.bbox.width <= t.bbox.x + 1;
1818
+ }
1819
+ function placeJoined(blocks, i, j, table) {
1820
+ const prev = blocks[i];
1821
+ markJoinedPages(table, prev, blocks[j]);
1822
+ blocks[i] = { ...prev, table };
1823
+ blocks.splice(j, 1);
1824
+ let k = j - 1;
1825
+ while (k > i && !leftColumnOf(blocks[k], prev)) k--;
1826
+ if (k > i) blocks.splice(k, 0, blocks.splice(i, 1)[0]);
1827
+ }
1828
+ function insideTable(b, t) {
1829
+ if (!b.bbox || b.pageNumber !== t.pageNumber) return false;
1830
+ const o = t.bbox;
1831
+ return b.bbox.x >= o.x - 1 && b.bbox.x + b.bbox.width <= o.x + o.width + 1 && b.bbox.y >= o.y - 1 && b.bbox.y + b.bbox.height <= o.y + o.height + 1;
1832
+ }
1833
+ function startsWithUnitRow(table) {
1834
+ return /^\s*\(\s*단위\s*[::]/.test(table.cells[0]?.[0]?.text ?? "") && table.cells[0]?.slice(1).every((c) => !c.text.trim());
1835
+ }
1836
+ function sameHeadShape(a, b) {
1837
+ if (!a || !b || a.length !== b.length) return false;
1838
+ let tall = false;
1839
+ for (let c = 0; c < a.length; c++) {
1840
+ if (a[c].colSpan !== b[c].colSpan || a[c].rowSpan !== b[c].rowSpan) return false;
1841
+ if (a[c].rowSpan >= 2 && a[c].text.trim() && b[c].text.trim()) tall = true;
1842
+ }
1843
+ return tall;
1844
+ }
1845
+ function hasBoxTitle(t) {
1846
+ const titles = t.cells[0]?.filter((c) => c.text.trim()) ?? [];
1847
+ if (titles.length !== 1 || titles[0].rowSpan < 2) return false;
1848
+ const body = t.cells[titles[0].rowSpan];
1849
+ return !!body && body[0].colSpan === t.cols && !!body[0].text.trim();
1850
+ }
1851
+ function mergeCrossPageTables(blocks, pageHeights, lex) {
1852
+ mergeColumnFlow(blocks, pageHeights, lex);
1853
+ for (let i = blocks.length - 2; i >= 0; i--) {
1854
+ const tail = tailOf(blocks[i]);
1855
+ if (tail.type !== "table" || !tail.table || !tail.bbox || !tail.pageNumber) continue;
1856
+ let j = i + 1;
1857
+ const skip = (b) => b.type !== "table" || [blocks[i], tail].some((t) => insideTable(b, t) || leftColumnOf(b, t));
1858
+ while (j < blocks.length && skip(blocks[j]) && (blocks[j].pageNumber ?? 0) <= tail.pageNumber + 1) j++;
1859
+ const curr = blocks[j];
1860
+ const prev = tail !== blocks[i] && curr?.pageNumber === tail.pageNumber ? blocks[i] : tail;
1861
+ if (!prev.table || !prev.bbox || !prev.pageNumber) continue;
1862
+ if (!curr || curr.type !== "table" || !curr.table || !curr.bbox || curr.pageNumber !== prev.pageNumber + 1) continue;
1863
+ if (startsWithUnitRow(prev.table) && startsWithUnitRow(curr.table)) continue;
1864
+ if (hasBoxTitle(prev.table) && hasBoxTitle(curr.table) && !rowTextsEqual(prev.table.cells[0], curr.table.cells[0]) && sameHeadShape(prev.table.cells[0], curr.table.cells[0])) continue;
1865
+ const joined = j === i + 1 || blocks.slice(i + 1, j).every((b) => besideOwn(b, prev, curr) || insideTable(b, prev) || insideTable(b, curr) || pageNumberBetween(b, prev, curr, pageHeights)) ? looksContinued(prev, curr, pageHeights) && !restartsTable(blocks, i, curr.table, pageHeights) ? joinClipParts(prev, curr, pageHeights, lex) ?? false : null : null;
1866
+ if (joined) {
1867
+ placeJoined(blocks, i, j, joined);
1868
+ continue;
1869
+ }
1870
+ if (EMPTY_PARTS.has(curr.table)) {
1871
+ blocks.splice(j, 1);
1872
+ i++;
1873
+ continue;
1874
+ }
1875
+ if (joined === null) continue;
1876
+ if (prev.table.cols !== curr.table.cols || prev.table.renderAsTable !== curr.table.renderAsTable || EMPTY_PARTS.has(prev.table)) continue;
1877
+ const width = Math.max(prev.bbox.width, curr.bbox.width, 1);
1878
+ const leftDiff = Math.abs(prev.bbox.x - curr.bbox.x);
1879
+ const rightDiff = Math.abs(prev.bbox.x + prev.bbox.width - (curr.bbox.x + curr.bbox.width));
1880
+ if (leftDiff > width * NEIGHBOR_TABLE_EPSILON || rightDiff > width * NEIGHBOR_TABLE_EPSILON) continue;
1881
+ const px = TABLE_COLXS.get(prev.table), cx = TABLE_COLXS.get(curr.table);
1882
+ if (px && cx && !shiftedSame(px, cx, !CLIP_TABLES.has(prev.table) && !CLIP_TABLES.has(curr.table))) continue;
1883
+ if (!px !== !cx) continue;
1884
+ if (!rowTextsEqual(prev.table.cells[0], curr.table.cells[0]) && sameHeadShape(prev.table.cells[0], curr.table.cells[0])) continue;
1885
+ let currCells = curr.table.cells;
1886
+ const headRows = repeatedHeaderRows(prev.table, curr.table);
1887
+ if (headRows < 0) continue;
1888
+ if (headRows) currCells = currCells.slice(headRows);
1889
+ if (currCells.length) continueRowSpans(prev.table.cells, currCells);
1890
+ if (currCells.length === 0) {
1891
+ blocks.splice(j, 1);
1892
+ continue;
1893
+ }
1894
+ if (px && cx && !CLIP_TABLES.has(prev.table) && !CLIP_TABLES.has(curr.table) && currCells.length < curr.table.cells.length && curr.table.cells[0].filter((c) => c.text.trim()).length >= 2 && prev.table.cells.at(-1).concat(currCells[0]).every((c) => c.rowSpan === 1 && c.colSpan === 1 && CELL_LINES.has(c))) {
1895
+ const dx = px[0] - cx[0];
1896
+ const part = joinSplitParts(prev.table, px, curr.table, cx.map((x) => x + dx), dx, void 0, lex);
1897
+ if (part?.split && part.table.rows === prev.table.rows + currCells.length - 1) {
1898
+ const last = prev.table.rows - 1;
1899
+ for (let c = 0; c < part.table.cols; c++) {
1900
+ const U = CELL_LINES.get(prev.table.cells[last][c]), D = CELL_LINES.get(currCells[0][c]);
1901
+ CELL_LINES.set(part.table.cells[last][c], U.concat(D.map((l) => ({ ...l, l: l.l + dx, r: l.r + dx }))));
1902
+ }
1903
+ TABLE_COLXS.set(part.table, part.colXs);
1904
+ placeJoined(blocks, i, j, part.table);
1905
+ continue;
1906
+ }
1907
+ }
1908
+ const merged = {
1909
+ rows: prev.table.rows + currCells.length,
1910
+ cols: prev.table.cols,
1911
+ cells: [...prev.table.cells, ...currCells],
1912
+ hasHeader: prev.table.hasHeader,
1913
+ caption: prev.table.caption,
1914
+ ...prev.table.renderAsTable ? { renderAsTable: true } : {}
1915
+ };
1916
+ if (px ?? cx) TABLE_COLXS.set(merged, px ?? cx);
1917
+ if (CLIP_TABLES.has(prev.table) || CLIP_TABLES.has(curr.table)) CLIP_TABLES.add(merged);
1918
+ placeJoined(blocks, i, j, merged);
1919
+ }
1920
+ for (let i = blocks.length - 1; i >= 0; i--) {
1921
+ const t = blocks[i].table;
1922
+ if (blocks[i].type === "table" && t && EMPTY_PARTS.has(t)) blocks.splice(i, 1);
1923
+ }
1924
+ }
1925
+ function mergeColumnFlow(blocks, pageHeights, lex) {
1926
+ if (!pageHeights) return;
1927
+ for (let i = 0; i < blocks.length; i++) {
1928
+ const L = blocks[i];
1929
+ if (L.type !== "table" || !L.table || !L.bbox || !L.pageNumber || !CLIP_TABLES.has(L.table) || EMPTY_PARTS.has(L.table)) continue;
1930
+ const ph = pageHeights.get(L.pageNumber);
1931
+ if (!ph || L.bbox.y > ph * PAGE_EDGE_BAND) continue;
1932
+ let s0 = i, s1 = i;
1933
+ while (s0 > 0 && blocks[s0 - 1].pageNumber === L.pageNumber) s0--;
1934
+ while (s1 + 1 < blocks.length && blocks[s1 + 1].pageNumber === L.pageNumber) s1++;
1935
+ let k = -1;
1936
+ for (let q = s0; q <= s1; q++) {
1937
+ const R2 = blocks[q];
1938
+ if (q === i || R2.type !== "table" || !R2.table || !R2.bbox || !leftColumnOf(L, R2)) continue;
1939
+ const top2 = R2.bbox.y + R2.bbox.height;
1940
+ if (top2 < ph * (1 - PAGE_EDGE_BAND)) continue;
1941
+ if (k < 0 || top2 > blocks[k].bbox.y + blocks[k].bbox.height) k = q;
1942
+ }
1943
+ if (k < 0) continue;
1944
+ const R = blocks[k];
1945
+ if (Math.abs(R.bbox.width - L.bbox.width) > Math.max(R.bbox.width, L.bbox.width) * NEIGHBOR_TABLE_EPSILON) continue;
1946
+ if (!looksContinued(L, R) || restartsTable(blocks, i, R.table, pageHeights)) continue;
1947
+ const rt = R.table;
1948
+ if (rt.rows === 1 && rt.cols === 1 && !CLIP_TABLES.has(rt) && L.table.rows >= 2) {
1949
+ const px = TABLE_COLXS.get(L.table), lb = L.bbox;
1950
+ const dx = lb.x + lb.width - (R.bbox.x + R.bbox.width);
1951
+ const last = L.table.cells[L.table.rows - 1];
1952
+ let col = 0;
1953
+ const target = px && last.find((c) => {
1954
+ const x1 = px[col], x2 = px[Math.min(px.length - 1, col + c.colSpan)];
1955
+ col += c.colSpan;
1956
+ return c.rowSpan === 1 && x2 - x1 >= lb.width * 0.8 && Math.abs(x1 - (R.bbox.x + dx)) <= 3 && Math.abs(x2 - (R.bbox.x + R.bbox.width + dx)) <= 3;
1957
+ });
1958
+ if (target && target.text.trim() && rt.cells[0][0].text.trim()) {
1959
+ appendCell(target, rt.cells[0][0]);
1960
+ const top2 = L.bbox.y + L.bbox.height;
1961
+ blocks[Math.min(i, k)] = { ...L, bbox: { ...L.bbox, y: R.bbox.y, height: Math.max(0, top2 - R.bbox.y) } };
1962
+ blocks.splice(Math.max(i, k), 1);
1963
+ i = Math.min(i, k) - 1;
1964
+ continue;
1965
+ }
1966
+ }
1967
+ const joined = joinClipParts(L, R, pageHeights, lex);
1968
+ if (!joined) continue;
1969
+ const top = L.bbox.y + L.bbox.height;
1970
+ const at = Math.min(i, k);
1971
+ blocks[at] = { ...L, table: joined, bbox: { ...L.bbox, y: R.bbox.y, height: Math.max(0, top - R.bbox.y) } };
1972
+ blocks.splice(Math.max(i, k), 1);
1973
+ i = at - 1;
1974
+ }
1975
+ }
1976
+ function joinClipParts(prev, curr, pageHeights, lex) {
1977
+ const pt = prev.table, ct = curr.table;
1978
+ if (!CLIP_TABLES.has(pt) || !CLIP_TABLES.has(ct)) return null;
1979
+ const px = TABLE_COLXS.get(pt), cx = TABLE_COLXS.get(ct);
1980
+ if (!px || !cx) return null;
1981
+ let xs = cx, shifted = false, dx = 0, foreign = false, within = false;
1982
+ if (!shiftedSame(px, cx, false)) {
1983
+ if (!pageHeights?.get(prev.pageNumber) || !pageHeights?.get(curr.pageNumber)) return null;
1984
+ dx = px[px.length - 1] - cx[cx.length - 1];
1985
+ within = Math.abs(dx) > CONTINUATION_COL_TOL && cx.length >= 3 && cx.every((x) => px.some((p) => Math.abs(p - x) <= CONTINUATION_COL_TOL));
1986
+ if (Math.abs(dx) > CONTINUATION_COL_TOL && !within) {
1987
+ xs = cx.map((x) => x + dx);
1988
+ shifted = true;
1989
+ } else dx = 0;
1990
+ if (!px.some((x) => Math.abs(x - xs[0]) <= CONTINUATION_COL_TOL) && !prevLacksLeftCols(prev, px, xs, pageHeights)) return null;
1991
+ const unrelated = (b) => {
1992
+ const inner = b.slice(1, -1).map((x) => x + dx);
1993
+ return inner.length > 0 && !inner.some((x) => px.some((p) => Math.abs(p - x) <= CONTINUATION_COL_TOL));
1994
+ };
1995
+ foreign = unrelated(cx) && unrelated(PART_COLXS.get(ct) ?? cx) && (headingRow(ct.cells[0] ?? []) || px.length > FOREIGN_FIRST_ROW_CELLS && anchorsOf(ct).filter((a) => a.r === 0).length >= FOREIGN_FIRST_ROW_CELLS);
1996
+ }
1997
+ const res = joinSplitParts(pt, px, ct, xs, dx, prev.bbox?.y, lex);
1998
+ if (!res || (shifted || foreign || within) && !res.split && !res.header) return null;
1999
+ TABLE_COLXS.set(res.table, res.colXs);
2000
+ const ys = TABLE_ROWYS.get(pt);
2001
+ if (ys) TABLE_ROWYS.set(res.table, ys);
2002
+ PART_COLXS.set(res.table, PART_COLXS.get(pt) ?? px);
2003
+ CLIP_TABLES.add(res.table);
2004
+ return res.table;
2005
+ }
2006
+ function prevLacksLeftCols(prev, px, xs, pageHeights) {
2007
+ const ph = pageHeights?.get(prev.pageNumber);
2008
+ if (!ph || prev.bbox.y + prev.bbox.height < ph * (1 - PAGE_EDGE_BAND)) return false;
2009
+ return xs[0] < px[0] && xs.slice(1, -1).some((x) => Math.abs(x - px[0]) <= CONTINUATION_COL_TOL);
2010
+ }
2011
+ function headingRow(row) {
2012
+ const heads = row.map((c) => flowText(c.text).replace(/\s+/g, "")).filter(Boolean);
2013
+ if (heads.length === 1) return heads[0].length <= 8 || /^[①-⑳❶-❿]/.test(heads[0]);
2014
+ return heads.length === 2 && /^(?:\d{1,2}|[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ]+|[①-⑳❶-❿])$/.test(heads[0]);
2015
+ }
2016
+ var ANNEX_HEAD_RE = /^\s*[<\[(【]?\s*(?:붙\s*임|참\s*고|별\s*첨|별\s*지|별\s*표|첨\s*부|부\s*록)(?:\s*\d|\s*$|\s*[>\])】])|^\s*■/;
2017
+ function looksContinued(prev, curr, pageHeights) {
2018
+ const ph = pageHeights?.get(prev.pageNumber), ch = pageHeights?.get(curr.pageNumber);
2019
+ if (ph && ch && (prev.bbox.y > ph * PAGE_EDGE_BAND && !pushedLead(prev, curr) || curr.bbox.y + curr.bbox.height < ch * (1 - PAGE_EDGE_BAND))) return false;
2020
+ const firstRow = curr.table.cells[0] ?? [];
2021
+ const firstText = firstRow.find((c) => c.text.trim())?.text ?? "";
2022
+ if (!ANNEX_HEAD_RE.test(firstText)) return true;
2023
+ const filled = firstRow.map((c) => flowText(c.text).replace(/\s+/g, "")).filter(Boolean);
2024
+ return filled.length >= 2 && filled.every((t) => t === filled[0]);
2025
+ }
2026
+ function pushedLead(prev, curr) {
2027
+ if (!CLIP_TABLES.has(prev.table) || !CLIP_TABLES.has(curr.table)) return false;
2028
+ const lead = leadRows(curr.table);
2029
+ return lead.image && lead.height > prev.bbox.y;
2030
+ }
2031
+ function leadRows(t) {
2032
+ const ys = TABLE_ROWYS.get(t);
2033
+ if (!ys || ys.length < 2) return { height: 0, image: false };
2034
+ const anchors = anchorsOf(t);
2035
+ let end = 1, image = false;
2036
+ for (let r = 0; r < end; r++) {
2037
+ for (const a of anchors) {
2038
+ if (a.r !== r) continue;
2039
+ end = Math.max(end, r + a.rs);
2040
+ if (IMAGE_CELLS.has(a.cell)) image = true;
2041
+ }
2042
+ }
2043
+ return { height: ys[0] - ys[Math.min(end, ys.length - 1)], image };
2044
+ }
2045
+ function tailOf(b) {
2046
+ const t = b.table && TABLE_TAIL.get(b.table);
2047
+ return t && b.bbox ? { ...b, pageNumber: t.page, bbox: { ...b.bbox, page: t.page, y: t.y, height: t.height } } : b;
2048
+ }
2049
+ function firstRowSig(t) {
2050
+ const x = TABLE_COLXS.get(t);
2051
+ if (!x || x.length !== t.cols + 1) return null;
2052
+ return anchorsOf(t).filter((a) => a.r === 0).map((a) => ({ x1: x[a.c], x2: x[a.c + a.cs], t: flowText(a.cell.text).replace(/\s+/g, "") }));
2053
+ }
2054
+ function restartsTable(blocks, i, curr, pageHeights) {
2055
+ const cs = firstRowSig(curr);
2056
+ if (!cs) return false;
2057
+ const head = blocks[chainHead(blocks, i, pageHeights)].table;
2058
+ if (cs.length === 1 && restartsTitledForm(head, curr)) return true;
2059
+ if (cs.length < RESTART_MIN_ANCHORS) return false;
2060
+ if (CONTACT_HEAD.test(cs[0].t) && cs.some((c) => CONTACT_ROLE.test(c.t))) return false;
2061
+ const hs = firstRowSig(head);
2062
+ if (!hs || hs.length !== cs.length) return false;
2063
+ const dx = hs[hs.length - 1].x2 - cs[cs.length - 1].x2;
2064
+ if (!hs.every((h, n) => Math.abs(h.x1 - cs[n].x1 - dx) <= CONTINUATION_COL_TOL && Math.abs(h.x2 - cs[n].x2 - dx) <= CONTINUATION_COL_TOL)) return false;
2065
+ let same = 0, diff = 0;
2066
+ for (let n = 0; n < hs.length; n++) {
2067
+ if (!hs[n].t && !cs[n].t) continue;
2068
+ if (hs[n].t === cs[n].t) same++;
2069
+ else diff++;
2070
+ }
2071
+ return same >= 2 && diff >= 1;
2072
+ }
2073
+ function restartsTitledForm(head, curr) {
2074
+ if (head.rows < 2 || curr.rows < 2 || head.cols !== curr.cols) return false;
2075
+ const full = (t) => t.cells[0][0]?.colSpan === t.cols;
2076
+ if (!full(head) || !full(curr)) return false;
2077
+ const norm = (c) => flowText(c?.text ?? "").replace(/\s+/g, "");
2078
+ const ht = norm(head.cells[0][0]), ct = norm(curr.cells[0][0]);
2079
+ if (!ht || !ct || ht === ct) return false;
2080
+ const titleLike = (t) => t.length <= TITLE_ROW_MAX_CHARS && !/^[ㅇ○◦•·\-–※*□■▪☞]/.test(t);
2081
+ if (!titleLike(ht) || !titleLike(ct)) return false;
2082
+ const spans = (t) => anchorsOf(t).filter((a) => a.r === 1).map((a) => `${a.c}:${a.cs}`).join(",");
2083
+ const label = norm(head.cells[1][0]);
2084
+ return spans(head) === spans(curr) && label !== "" && label === norm(curr.cells[1][0]);
2085
+ }
2086
+ function chainHead(blocks, i, pageHeights) {
2087
+ let k = i;
2088
+ for (let steps = 0; steps < RESTART_LOOKBACK_PAGES; steps++) {
2089
+ const cur = blocks[k];
2090
+ let p = k - 1;
2091
+ while (p >= 0 && blocks[p].type !== "table" && (blocks[p].pageNumber ?? 0) >= (cur.pageNumber ?? 0) - 1) p--;
2092
+ if (p < 0 || blocks[p].type !== "table" || !blocks[p].table || !blocks[p].bbox) break;
2093
+ for (let q = p - 1; q >= 0 && blocks[q].pageNumber === blocks[p].pageNumber; q--) {
2094
+ if (blocks[q].type === "table" && blocks[q].bbox && insideTable(blocks[p], blocks[q])) {
2095
+ p = q;
2096
+ break;
2097
+ }
2098
+ }
2099
+ const pb = tailOf(blocks[p]);
2100
+ if (pb.pageNumber !== (cur.pageNumber ?? 0) - 1) break;
2101
+ if (!blocks.slice(p + 1, k).every((b) => besideOwn(b, pb, cur) || insideTable(b, pb) || pageNumberBetween(b, pb, cur, pageHeights))) break;
2102
+ if (!looksContinued(pb, cur, pageHeights)) break;
2103
+ const px = TABLE_COLXS.get(pb.table), cx = TABLE_COLXS.get(cur.table);
2104
+ if (!px || !cx) break;
2105
+ const dx = px[px.length - 1] - cx[cx.length - 1];
2106
+ if (!shiftedSame(px, cx) && !px.some((x) => Math.abs(x - (cx[0] + dx)) <= CONTINUATION_COL_TOL) && !prevLacksLeftCols(pb, px, cx, pageHeights)) break;
2107
+ k = p;
2108
+ }
2109
+ return k;
2110
+ }
2111
+ var ROW_CONTINUATIONS = /* @__PURE__ */ new WeakMap();
2112
+ function continueRowSpans(prevCells, currCells) {
2113
+ const first = currCells[0];
2114
+ const last = prevCells.length;
2115
+ for (let c = 0; c < first.length; c++) {
2116
+ const cell = first[c];
2117
+ if (hasContent(cell) || (cell.rowSpan || 1) < 2) continue;
2118
+ let anchor;
2119
+ for (let r = last - 1; r >= 0 && !anchor; r--) {
2120
+ const a = prevCells[r]?.[c];
2121
+ if (a && r + (a.rowSpan || 1) === last && (a.colSpan || 1) === (cell.colSpan || 1) && (hasContent(a) || a.rowSpan >= 2)) anchor = a;
2122
+ }
2123
+ if (!anchor) continue;
2124
+ if (!hasContent(anchor)) {
2125
+ ROW_CONTINUATIONS.set(anchor, cell);
2126
+ continue;
2127
+ }
2128
+ for (let part = cell; part; ) {
2129
+ const next = ROW_CONTINUATIONS.get(part);
2130
+ anchor.rowSpan = (anchor.rowSpan || 1) + part.rowSpan;
2131
+ part.rowSpan = 1;
2132
+ part.colSpan = 1;
2133
+ ROW_CONTINUATIONS.delete(part);
2134
+ part = next;
2135
+ }
2136
+ }
2137
+ }
2138
+ function repeatedHeaderRows(prev, curr) {
2139
+ if (!rowTextsEqual(prev.cells[0], curr.cells[0])) return 0;
2140
+ const pa = anchorsOf(prev), ca = anchorsOf(curr);
2141
+ let depth = 1;
2142
+ for (let r = 0; r < depth && r < prev.rows; r++) {
2143
+ for (const a of pa) if (a.r === r) depth = Math.max(depth, r + a.rs);
2144
+ }
2145
+ if (depth >= curr.rows || depth > prev.rows) return -1;
2146
+ const p = pa.filter((a) => a.r < depth), d = ca.filter((a) => a.r < depth);
2147
+ const norm = (text) => flowText(text).replace(/\s+/g, "");
2148
+ return p.length === d.length && p.every((a, i) => a.r === d[i].r && a.c === d[i].c && a.rs === d[i].rs && a.cs === d[i].cs && norm(a.cell.text) === norm(d[i].cell.text)) ? depth : -1;
2149
+ }
2150
+ function rowTextsEqual(a, b) {
2151
+ if (a.length !== b.length) return false;
2152
+ const norm = (t) => flowText(t).replace(/\s+/g, "");
2153
+ for (let i = 0; i < a.length; i++) {
2154
+ if (norm(a[i].text) !== norm(b[i].text)) return false;
2155
+ }
2156
+ return a.some((c) => c.text.trim() !== "");
2157
+ }
2158
+ var CONTINUATION_COL_TOL = 2;
2159
+ var FOREIGN_FIRST_ROW_CELLS = 3;
2160
+ function shiftedSame(px, cx, allowShift = true) {
2161
+ if (px.length !== cx.length) return false;
2162
+ const dx = allowShift ? px[px.length - 1] - cx[cx.length - 1] : 0;
2163
+ return px.every((x, k) => Math.abs(x - cx[k] - dx) <= CONTINUATION_COL_TOL);
2164
+ }
2165
+ var PAGE_EDGE_BAND = 0.16;
2166
+ var RESTART_MIN_ANCHORS = 3;
2167
+ var TITLE_ROW_MAX_CHARS = 40;
2168
+ var RESTART_LOOKBACK_PAGES = 5;
2169
+ var COL_MATCH_TOL = 0.5;
2170
+ var CONTINUED_TABLE_PAGE_BAND = 0.16;
2171
+ function lastRowCell(t, x1, x2) {
2172
+ const xs = TABLE_COLXS.get(t);
2173
+ const covered = /* @__PURE__ */ new Set();
2174
+ for (let r = 0; r < t.rows; r++) {
2175
+ for (let c = 0; c < t.cols; c++) {
2176
+ if (covered.has(r * 1e5 + c)) continue;
2177
+ const cell = t.cells[r]?.[c];
2178
+ if (!cell) continue;
2179
+ for (let dr = 0; dr < cell.rowSpan; dr++) for (let dc = 0; dc < cell.colSpan; dc++) covered.add((r + dr) * 1e5 + c + dc);
2180
+ if (r + cell.rowSpan !== t.rows) continue;
2181
+ if (xs ? Math.abs(xs[c] - x1) <= COL_MATCH_TOL && Math.abs(xs[c + cell.colSpan] - x2) <= COL_MATCH_TOL : t.cols === 1) return cell;
2182
+ }
2183
+ }
2184
+ return void 0;
2185
+ }
2186
+ var cellBlocks = (cell, pageNumber) => cell.blocks ?? cellParagraphs(cell).map((text) => ({ type: "paragraph", text, pageNumber }));
2187
+ function mergeContinuedCells(blocks, pageHeights) {
2188
+ for (let j = blocks.length - 1; j > 0; j--) {
2189
+ const part = blocks[j];
2190
+ const from = part.table ? CONT_PARTS.get(part.table) : void 0;
2191
+ if (!from || !part.table) {
2192
+ unwrapContinuedTable(blocks, j, pageHeights, true);
2193
+ continue;
2194
+ }
2195
+ let i = j - 1;
2196
+ while (i >= 0 && blocks[i].type !== "table") i--;
2197
+ const prev = blocks[i];
2198
+ if (i < 0 || !prev.table || prev.pageNumber !== (part.pageNumber ?? 0) - 1) continue;
2199
+ const cell = lastRowCell(prev.table, from.x1, from.x2);
2200
+ const add = part.table.cells[0]?.[0];
2201
+ if (!cell || !add) continue;
2202
+ const at = cell.blocks || add.blocks ? cellBlocks(cell, prev.pageNumber).length : -1;
2203
+ if (cell.blocks || add.blocks) cell.blocks = [...cellBlocks(cell, prev.pageNumber), ...cellBlocks(add, part.pageNumber)];
2204
+ else if (part.pageNumber) markContinuedText(cell, add, part.pageNumber);
2205
+ cell.text = [cell.text, add.text].filter((s) => s.trim()).join("\n");
2206
+ carrySoftWraps(add, cell);
2207
+ if (IMAGE_CELLS.has(add)) IMAGE_CELLS.add(cell);
2208
+ joinCellEdges(cell, add);
2209
+ const lines = CELL_LINES.get(add);
2210
+ if (lines?.length) CELL_LINES.set(cell, [...CELL_LINES.get(cell) ?? [], ...lines]);
2211
+ if (part.pageNumber && part.bbox) TABLE_TAIL.set(prev.table, TABLE_TAIL.get(part.table) ?? { page: part.pageNumber, y: part.bbox.y, height: part.bbox.height });
2212
+ if (cell.text.trim() || cell.blocks?.length || IMAGE_CELLS.has(cell)) EMPTY_PARTS.delete(prev.table);
2213
+ blocks.splice(j, 1);
2214
+ if (cell.blocks && at > 0) {
2215
+ const nextAt = cell.blocks[at];
2216
+ fillNestedContinuation(cell.blocks, at);
2217
+ if (cell.blocks[at] === nextAt) unwrapContinuedTable(cell.blocks, at, pageHeights);
2218
+ }
2219
+ if (cell.blocks) mergeCrossPageTables(cell.blocks, pageHeights);
2220
+ }
2221
+ }
2222
+ function unwrapContinuedTable(blocks, at, pageHeights, splitOnly = false) {
2223
+ const prev = blocks[at - 1], frame = blocks[at];
2224
+ if (!prev?.table || !frame?.table || frame.table.rows !== 1 || frame.table.cols !== 1 || !CLIP_TABLES.has(frame.table)) return;
2225
+ const inner = frame.table.cells[0]?.[0]?.blocks;
2226
+ const next = inner?.[0];
2227
+ if (!inner || !next?.table || !prev.bbox || !next.bbox || !prev.pageNumber || next.pageNumber !== prev.pageNumber + 1 || !CLIP_TABLES.has(prev.table) || !CLIP_TABLES.has(next.table) || prev.table.cols !== next.table.cols) return;
2228
+ const px = TABLE_COLXS.get(prev.table), nx = TABLE_COLXS.get(next.table);
2229
+ if (!px || !nx || px.length !== nx.length || px.some((x, i) => Math.abs(x - nx[i]) > COL_MATCH_TOL)) return;
2230
+ const ph = pageHeights?.get(prev.pageNumber), nh = pageHeights?.get(next.pageNumber);
2231
+ if (!ph || !nh || prev.bbox.y > ph * CONTINUED_TABLE_PAGE_BAND || next.bbox.y + next.bbox.height < nh * (1 - CONTINUED_TABLE_PAGE_BAND)) return;
2232
+ if (splitOnly && (inner.length !== 1 || !joinSplitParts(prev.table, px, next.table, nx, 0, prev.bbox.y)?.split)) return;
2233
+ blocks.splice(at, 1, ...inner);
2234
+ }
2235
+ function fillNestedContinuation(blocks, at) {
2236
+ const prev = blocks[at - 1], next = blocks[at];
2237
+ const t = prev?.table, u = next?.table;
2238
+ if (!t || !u || u.rows !== 1 || u.cols !== 1 || !CLIP_TABLES.has(t) || !CLIP_TABLES.has(u) || next.pageNumber !== (prev.pageNumber ?? 0) + 1) return;
2239
+ const xs = TABLE_COLXS.get(u);
2240
+ const cell = xs ? lastRowCell(t, xs[0], xs[xs.length - 1]) : void 0;
2241
+ const add = u.cells[0]?.[0];
2242
+ if (!cell || !add || cell.text.trim() || cell.blocks?.length || IMAGE_CELLS.has(cell)) return;
2243
+ cell.text = add.text;
2244
+ carrySoftWraps(add, cell);
2245
+ if (add.blocks) cell.blocks = add.blocks;
2246
+ if (IMAGE_CELLS.has(add)) IMAGE_CELLS.add(cell);
2247
+ joinCellEdges(cell, add);
2248
+ blocks.splice(at, 1);
2249
+ }
2250
+ function selectionContextPages(selected, pageCount) {
2251
+ const out = /* @__PURE__ */ new Set();
2252
+ for (const page of selected) {
2253
+ for (let distance = 1; distance <= 4; distance++) {
2254
+ for (const neighbor of [page - distance, page + distance]) {
2255
+ if (neighbor < 1 || neighbor > pageCount || selected.has(neighbor)) continue;
2256
+ out.add(neighbor);
2257
+ }
2258
+ }
2259
+ }
2260
+ return [...out].sort((a, b) => a - b);
2261
+ }
2262
+ function marginContextBlocks(raw, page, view) {
2263
+ const [x1, y1, x2, y2] = view;
2264
+ const width = x2 - x1, height = y2 - y1;
2265
+ const items = filterHiddenText(normalizeItems(raw), width, height, x1, y1).visible;
2266
+ for (const item of items) {
2267
+ item.x -= x1;
2268
+ item.y -= y1;
2269
+ }
2270
+ return groupByY(items).flatMap((line) => {
2271
+ const bbox = computeBBox(line, page);
2272
+ if (bbox.y + bbox.height < height * 0.88 && bbox.y > height * 0.12) return [];
2273
+ return [{ type: "paragraph", text: mergeLineSimple(line), pageNumber: page, bbox, style: dominantStyle(line) }];
2274
+ });
2275
+ }
2276
+ var mul2 = (m, t) => [
2277
+ m[0] * t[0] + m[2] * t[1],
2278
+ m[1] * t[0] + m[3] * t[1],
2279
+ m[0] * t[2] + m[2] * t[3],
2280
+ m[1] * t[2] + m[3] * t[3],
2281
+ m[0] * t[4] + m[2] * t[5] + m[4],
2282
+ m[1] * t[4] + m[3] * t[5] + m[5]
2283
+ ];
2284
+ function filledDots(fnArray, argsArray) {
2285
+ const dots = [];
2286
+ let ctm = [1, 0, 0, 1, 0, 0];
2287
+ const stack = [];
2288
+ let path = null;
2289
+ for (let i = 0; i < fnArray.length; i++) {
2290
+ const op = fnArray[i], args = argsArray[i];
2291
+ if (op === OPS.save) stack.push(ctm);
2292
+ else if (op === OPS.restore) ctm = stack.pop() ?? [1, 0, 0, 1, 0, 0];
2293
+ else if (op === OPS.paintFormXObjectBegin) {
2294
+ stack.push(ctm);
2295
+ const m = args?.[0];
2296
+ if (Array.isArray(m) && m.length >= 6) ctm = mul2(ctm, m);
2297
+ } else if (op === OPS.paintFormXObjectEnd) ctm = stack.pop() ?? [1, 0, 0, 1, 0, 0];
2298
+ else if (op === OPS.transform && Array.isArray(args) && args.length >= 6) ctm = mul2(ctm, args);
2299
+ else if (op === OPS.constructPath) {
2300
+ const [subOps, coords] = args;
2301
+ path = null;
2302
+ if (!Array.isArray(subOps) || subOps.length < 6 || subOps[0] !== OPS.moveTo || subOps[subOps.length - 1] !== OPS.closePath || subOps.slice(1, -1).some((s) => s !== OPS.curveTo)) continue;
2303
+ let x1 = Infinity, y1 = Infinity, x2 = -Infinity, y2 = -Infinity;
2304
+ for (let k = 0; k + 1 < coords.length; k += 2) {
2305
+ const x = ctm[0] * coords[k] + ctm[2] * coords[k + 1] + ctm[4], y = ctm[1] * coords[k] + ctm[3] * coords[k + 1] + ctm[5];
2306
+ x1 = Math.min(x1, x);
2307
+ x2 = Math.max(x2, x);
2308
+ y1 = Math.min(y1, y);
2309
+ y2 = Math.max(y2, y);
2310
+ }
2311
+ path = { x1, y1, x2, y2 };
2312
+ } else if (op === OPS.fill || op === OPS.eoFill) {
2313
+ if (path) {
2314
+ const w = path.x2 - path.x1, h = path.y2 - path.y1;
2315
+ if (w >= 1.2 && w <= 6 && h >= 1.2 && h <= 6 && Math.abs(w - h) <= Math.max(w, h) * 0.15) dots.push(path);
2316
+ }
2317
+ path = null;
2318
+ }
2319
+ }
2320
+ return dots;
2321
+ }
2322
+ function restoreVectorBullets(items, fnArray, argsArray) {
2323
+ const found = [];
2324
+ for (const dot of filledDots(fnArray, argsArray)) {
2325
+ const cy = (dot.y1 + dot.y2) / 2;
2326
+ const line = items.filter((it) => !it.isHidden && it.fontSize > 0 && it.text.trim() && it.x >= dot.x2 && it.x - dot.x2 <= it.fontSize * 1.2 && cy >= it.y - it.fontSize * 0.1 && cy <= it.y + it.fontSize * 0.7 && dot.y2 - dot.y1 <= it.fontSize * 0.6).sort((a, b) => a.x - b.x)[0];
2327
+ if (!line || !new RegExp("^\\p{L}", "u").test(line.text.trim())) continue;
2328
+ if (items.some((it) => it !== line && !it.isHidden && it.text.trim() && Math.abs(it.y - line.y) <= line.fontSize * 0.3 && it.x < dot.x2 && it.x + it.w > dot.x1 - line.fontSize * 2)) continue;
2329
+ found.push({ dot, line, lx: line.x });
2330
+ }
2331
+ let restored = 0;
2332
+ const used = /* @__PURE__ */ new Set();
2333
+ for (const f of found) {
2334
+ const w = f.dot.x2 - f.dot.x1;
2335
+ const repeated = found.some((o) => o !== f && o.line !== f.line && Math.abs(o.dot.x1 - f.dot.x1) <= 1 && Math.abs(o.dot.x2 - o.dot.x1 - w) <= 0.5 && Math.abs(o.lx - f.lx) <= 1);
2336
+ if (!repeated || used.has(f.line)) continue;
2337
+ used.add(f.line);
2338
+ const line = f.line;
2339
+ line.w += line.x - f.dot.x1;
2340
+ line.x = f.dot.x1;
2341
+ line.text = "\u2022 " + line.text;
2342
+ line.fx = void 0;
2343
+ line.fw = void 0;
2344
+ restored++;
2345
+ }
2346
+ return restored;
2347
+ }
2348
+ var WINANSI_REVERSE = {
2349
+ 8364: 128,
2350
+ 8218: 130,
2351
+ 402: 131,
2352
+ 8222: 132,
2353
+ 8230: 133,
2354
+ 8224: 134,
2355
+ 8225: 135,
2356
+ 710: 136,
2357
+ 8240: 137,
2358
+ 352: 138,
2359
+ 8249: 139,
2360
+ 338: 140,
2361
+ 381: 142,
2362
+ 8216: 145,
2363
+ 8217: 146,
2364
+ 8220: 147,
2365
+ 8221: 148,
2366
+ 8226: 149,
2367
+ 8211: 150,
2368
+ 8212: 151,
2369
+ 732: 152,
2370
+ 8482: 153,
2371
+ 353: 154,
2372
+ 8250: 155,
2373
+ 339: 156,
2374
+ 382: 158,
2375
+ 376: 159
2376
+ };
2377
+ function symbolFontTable(fontName) {
2378
+ if (!fontName) return void 0;
2379
+ if (/wingdings(?![\s-]*[23])/i.test(fontName)) return WINGDINGS;
2380
+ return void 0;
2381
+ }
2382
+ function remapSymbolText(text, table) {
2383
+ let out = "";
2384
+ for (const ch of text) {
2385
+ let code = ch.codePointAt(0);
2386
+ if (code >= 128 && WINANSI_REVERSE[code] !== void 0) code = WINANSI_REVERSE[code];
2387
+ if (code >= 33 && code <= 255) {
2388
+ const mapped = table[code - 33];
2389
+ out += mapped !== void 0 && mapped !== "" ? mapped : ch;
2390
+ } else {
2391
+ out += ch;
2392
+ }
2393
+ }
2394
+ return out;
2395
+ }
2396
+ function remapSymbolFontItems(items, resolveFontName) {
2397
+ const cache = /* @__PURE__ */ new Map();
2398
+ const marlett = /* @__PURE__ */ new Map();
2399
+ let changed = 0;
2400
+ let box = null;
2401
+ const drop = /* @__PURE__ */ new Set();
2402
+ for (const it of items) {
2403
+ if (!it.fontName || !it.text) continue;
2404
+ if (!marlett.has(it.fontName)) marlett.set(it.fontName, /marlett/i.test(resolveFontName(it.fontName) ?? ""));
2405
+ if (marlett.get(it.fontName)) {
2406
+ const t = it.text.trim();
2407
+ if (t === "g") {
2408
+ it.text = "\u2610";
2409
+ box = it;
2410
+ changed++;
2411
+ } else if (/^[c-f]$/.test(t)) {
2412
+ drop.add(it);
2413
+ changed++;
2414
+ } else if (t === "b" && box && Math.abs(box.x - it.x) <= 1 && Math.abs(box.y - it.y) <= 1) {
2415
+ box.text = "\u2611";
2416
+ drop.add(it);
2417
+ changed++;
2418
+ }
2419
+ continue;
2420
+ }
2421
+ let table = cache.get(it.fontName);
2422
+ if (!cache.has(it.fontName)) {
2423
+ table = symbolFontTable(resolveFontName(it.fontName));
2424
+ cache.set(it.fontName, table);
2425
+ }
2426
+ if (!table) continue;
2427
+ const mapped = remapSymbolText(it.text, table);
2428
+ if (mapped !== it.text) {
2429
+ it.text = mapped;
2430
+ changed++;
2431
+ }
2432
+ }
2433
+ if (drop.size) {
2434
+ for (let k = items.length - 1; k >= 0; k--) if (drop.has(items[k])) items.splice(k, 1);
2435
+ }
2436
+ return changed;
2437
+ }
2438
+ var EQ_FONT_RE = /^(?:Hy)?hwpEQ/i;
2439
+ var BAR = 109;
2440
+ var GREEK = ["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu", "nu", "xi", "o", "pi", "rho", "sigma", "tau", "upsilon", "phi", "chi", "psi", "omega"];
2441
+ var PLAIN = {
2442
+ "\u2192": "\\to ",
2443
+ "\u2264": "\\le ",
2444
+ "\u2265": "\\ge ",
2445
+ "\xD7": "\\times ",
2446
+ "\xB7": "\\cdot ",
2447
+ "\u22C5": "\\cdot ",
2448
+ "\u2219": "\\cdot ",
2449
+ "\u221E": "\\infty ",
2450
+ "\u2212": "-",
2451
+ "\u22EF": "\\cdots ",
2452
+ "\u2220": "\\angle ",
2453
+ "\u2234": "\\therefore ",
2454
+ "\u2235": "\\because ",
2455
+ "\u2229": "\\cap ",
2456
+ "\u222A": "\\cup ",
2457
+ "\u2260": "\\ne ",
2458
+ "\xB0": "^{\\circ}",
2459
+ "\u22A5": "\\perp ",
2460
+ "\u220F": "\\prod ",
2461
+ "\xB1": "\\pm ",
2462
+ "\u2209": "\\notin ",
2463
+ "\u2282": "\\subset ",
2464
+ "\u21D2": "\\Rightarrow "
2465
+ };
2466
+ var SYMBOLS = {
2467
+ 68: "(",
2468
+ 69: ")",
2469
+ 70: "-",
2470
+ 71: "=",
2471
+ 72: "+",
2472
+ 73: "[",
2473
+ 74: "]",
2474
+ 75: "\\{",
2475
+ 76: "\\}",
2476
+ 77: "|",
2477
+ 79: ":",
2478
+ 82: ",",
2479
+ 83: ".",
2480
+ 85: "<",
2481
+ 86: ">",
2482
+ 91: "\\int ",
2483
+ 92: "\\sqrt",
2484
+ 103: "\\sum "
2485
+ };
2486
+ function decodeEq(ch) {
2487
+ const cp = ch.codePointAt(0);
2488
+ if (cp < 57344 || cp > 57599) return PLAIN[ch] ?? ch;
2489
+ const c = cp - 57344;
2490
+ if (c <= 25) return String.fromCharCode(65 + c);
2491
+ if (c >= 52 && c <= 60) return String(c - 51);
2492
+ if (c === 61) return "0";
2493
+ if (c >= 229 && c <= 254) return String.fromCharCode(97 + c - 229);
2494
+ if (c >= 157 && c < 157 + GREEK.length) return `\\${GREEK[c - 157]} `;
2495
+ return SYMBOLS[c] ?? "";
2496
+ }
2497
+ var FUNC_RE = /^(lim|sin|cos|tan|log|ln|exp|max|min)$/;
2498
+ function layout(toks) {
2499
+ let rest = toks.filter((t) => t.bar || t.text.trim());
2500
+ for (const rt of rest.filter((t) => t.text === "\\sqrt").sort((a, b) => b.x - a.x)) {
2501
+ const size = Math.max(rt.size, 1);
2502
+ const bar = rest.find((t) => t.bar && t.x >= rt.x && t.x <= rt.x + rt.w + 2 && Math.abs(t.y - rt.y) <= size * 1.5);
2503
+ if (!bar) continue;
2504
+ const inner = rest.filter((t) => !t.bar && t !== rt && t.x + t.w / 2 > bar.x && t.x + t.w / 2 < bar.x + bar.w && bar.y - t.y > 0 && bar.y - t.y <= size * 1.4);
2505
+ const tok = { text: `\\sqrt{${linear(inner)}}`, x: rt.x, w: bar.x + bar.w - rt.x, y: inner[0]?.y ?? rt.y, size: Math.max(rt.size, ...inner.map((t) => t.size)), bar: false };
2506
+ rest = [...rest.filter((t) => t !== rt && t !== bar && !inner.includes(t)), tok];
2507
+ }
2508
+ const bars = rest.filter((t) => t.bar).sort((a, b) => a.w - b.w);
2509
+ for (const bar of bars) {
2510
+ const inX = (t) => t !== bar && t.x + t.w / 2 >= bar.x - 1 && t.x + t.w / 2 <= bar.x + bar.w + 1;
2511
+ const num = rest.filter((t) => inX(t) && t.y > bar.y), den = rest.filter((t) => inX(t) && t.y < bar.y);
2512
+ if (!num.length || !den.length) continue;
2513
+ const fsize = Math.max(...num.map((t) => t.size), ...den.map((t) => t.size));
2514
+ const frac = { text: `\\frac{${linear(num)}}{${linear(den)}}`, x: bar.x, w: bar.w, y: Math.round(bar.y + fsize * 0.3), size: fsize, bar: false };
2515
+ rest = [...rest.filter((t) => t !== bar && !num.includes(t) && !den.includes(t)), frac];
2516
+ }
2517
+ return linear(rest.filter((t) => !t.bar));
2518
+ }
2519
+ function linear(toks) {
2520
+ const sorted = [...toks].sort((a, b) => a.x - b.x);
2521
+ if (!sorted.length) return "";
2522
+ const size = Math.max(...sorted.map((t) => t.size));
2523
+ const base = sorted.find((t) => t.size === size).y;
2524
+ let out = "", scr = "", kind = "";
2525
+ const flushScr = () => {
2526
+ if (scr) {
2527
+ out += `${kind}{${scr.trim()}}`;
2528
+ scr = "";
2529
+ kind = "";
2530
+ }
2531
+ };
2532
+ for (const t of sorted) {
2533
+ const small = t.size < size * 0.9;
2534
+ const k = small && t.y > base + size * 0.2 ? "^" : small && t.y < base - size * 0.1 || t.y < base - size * 0.3 ? "_" : "";
2535
+ if (k) {
2536
+ if (kind && kind !== k) flushScr();
2537
+ kind = k;
2538
+ scr += t.text;
2539
+ continue;
2540
+ }
2541
+ flushScr();
2542
+ out += FUNC_RE.test(t.text) ? `\\${t.text} ` : t.text;
2543
+ }
2544
+ flushScr();
2545
+ return out.replace(/\s+/g, " ").trim();
2546
+ }
2547
+ var isBarItem = (it) => it.text.length === 1 && it.text.codePointAt(0) === 57344 + BAR;
2548
+ var sizeOf = (it) => isBarItem(it) ? 0 : it.fontSize;
2549
+ function near(a, b) {
2550
+ const size = Math.max(sizeOf(a), sizeOf(b), 1);
2551
+ const gap = Math.max(a.x, b.x) - Math.min(a.x + a.w, b.x + b.w);
2552
+ const dy = Math.abs(a.y - b.y);
2553
+ if (gap <= size * 0.8 && dy <= size * 0.6) return true;
2554
+ for (const [bar, o] of [[a, b], [b, a]]) {
2555
+ if (!isBarItem(bar) || isBarItem(o)) continue;
2556
+ const cx = o.x + o.w / 2;
2557
+ if (cx > bar.x && cx < bar.x + bar.w && dy > 0 && dy <= size * 1.2) return true;
2558
+ }
2559
+ return false;
2560
+ }
2561
+ function wrapEquationRuns(items, faceName) {
2562
+ const eqIdx = [];
2563
+ items.forEach((it, i) => {
2564
+ if (it.text.trim() && EQ_FONT_RE.test(faceName(it.fontName) ?? "")) eqIdx.push(i);
2565
+ });
2566
+ if (!eqIdx.length) return 0;
2567
+ const overBar = (bar, it) => {
2568
+ const cx = it.x + it.w / 2, dy = Math.abs(it.y - bar.y);
2569
+ return cx > bar.x && cx < bar.x + bar.w && dy > 0 && dy <= Math.max(it.fontSize, 1) * 1.2;
2570
+ };
2571
+ const barItems = eqIdx.map((i) => items[i]).filter((bar) => isBarItem(bar) && !eqIdx.some((j) => !isBarItem(items[j]) && overBar(bar, items[j])));
2572
+ const plain2 = /* @__PURE__ */ new Set();
2573
+ if (barItems.length) {
2574
+ items.forEach((it, i) => {
2575
+ if (!it.text.trim() || EQ_FONT_RE.test(faceName(it.fontName) ?? "")) return;
2576
+ if (barItems.some((bar) => overBar(bar, it))) plain2.add(i);
2577
+ });
2578
+ if (plain2.size) eqIdx.push(...plain2);
2579
+ eqIdx.sort((a, b) => a - b);
2580
+ }
2581
+ const parent = eqIdx.map((_, k) => k);
2582
+ const find = (k) => {
2583
+ while (parent[k] !== k) {
2584
+ parent[k] = parent[parent[k]];
2585
+ k = parent[k];
2586
+ }
2587
+ return k;
2588
+ };
2589
+ for (let a = 0; a < eqIdx.length; a++) {
2590
+ for (let b = a + 1; b < eqIdx.length; b++) {
2591
+ const A = items[eqIdx[a]], B = items[eqIdx[b]];
2592
+ if (A.y - B.y > Math.max(sizeOf(A), sizeOf(B), 12) * 3) break;
2593
+ if (near(A, B)) parent[find(a)] = find(b);
2594
+ }
2595
+ }
2596
+ const clusters = /* @__PURE__ */ new Map();
2597
+ eqIdx.forEach((idx, k) => {
2598
+ const r = find(k);
2599
+ const arr = clusters.get(r);
2600
+ if (arr) arr.push(idx);
2601
+ else clusters.set(r, [idx]);
2602
+ });
2603
+ const drop = /* @__PURE__ */ new Set();
2604
+ const added = [];
2605
+ for (const members of clusters.values()) {
2606
+ const cur = members.map((i) => items[i]);
2607
+ for (const i of members) drop.add(i);
2608
+ const toks = cur.map((it) => {
2609
+ const bar2 = isBarItem(it);
2610
+ const text = bar2 ? "" : plain2.has(items.indexOf(it)) ? toTex(it.text) : FUNC_RE.test(it.text.trim()) ? it.text.trim() : [...it.text].map(decodeEq).join("");
2611
+ return { text, x: it.x, y: it.y, w: it.w, size: sizeOf(it), bar: bar2 };
2612
+ });
2613
+ const tex = layout(toks).replace(/\}\\text\{/g, "");
2614
+ if (!tex) continue;
2615
+ const size = Math.max(...cur.map(sizeOf));
2616
+ const mains = cur.filter((i) => !isBarItem(i) && i.fontSize === size);
2617
+ const ys = /* @__PURE__ */ new Map();
2618
+ for (const i of mains) ys.set(i.y, (ys.get(i.y) ?? 0) + 1);
2619
+ const top = [...ys].sort((p, q) => q[1] - p[1]);
2620
+ const bar = cur.find(isBarItem);
2621
+ const lineY = bar && top.length > 1 && top[0][1] === top[1][1] ? Math.round(bar.y + size * 0.3) : top[0]?.[0] ?? cur[0].y;
2622
+ const base = { ...mains[0] ?? cur[0], y: lineY, fontSize: size || cur[0].fontSize };
2623
+ const x1 = Math.min(...cur.map((i) => i.x)), x2 = Math.max(...cur.map((i) => i.x + i.w));
2624
+ added.push({ ...base, text: `$${tex}$`, x: x1, w: x2 - x1, hasSpaceBefore: true });
2625
+ }
2626
+ const kept = items.filter((_, i) => !drop.has(i));
2627
+ items.length = 0;
2628
+ items.push(...kept, ...added);
2629
+ items.sort((a, b) => b.y - a.y || a.x - b.x);
2630
+ return added.length;
2631
+ }
2632
+ var glyphText = (s) => normalizeUnicode(s).replace(/\s+/g, "");
2633
+ function occludedTextItems(items, fnArray, argsArray) {
2634
+ const covers = [];
2635
+ let drawn = "";
2636
+ let ctm = [1, 0, 0, 1, 0, 0];
2637
+ let alpha = 1, normalBlend = true;
2638
+ let pattern = false;
2639
+ let clip = void 0;
2640
+ let path = [];
2641
+ let pathOk = true;
2642
+ const stack = [];
2643
+ const box = (x, y, w, h) => {
2644
+ const xs = [], ys = [];
2645
+ for (const [px, py] of [[x, y], [x + w, y], [x, y + h], [x + w, y + h]]) {
2646
+ xs.push(ctm[0] * px + ctm[2] * py + ctm[4]);
2647
+ ys.push(ctm[1] * px + ctm[3] * py + ctm[5]);
2648
+ }
2649
+ return { x1: Math.min(...xs), y1: Math.min(...ys), x2: Math.max(...xs), y2: Math.max(...ys) };
2650
+ };
2651
+ const meet = (a, b) => ({ x1: Math.max(a.x1, b.x1), y1: Math.max(a.y1, b.y1), x2: Math.min(a.x2, b.x2), y2: Math.min(a.y2, b.y2) });
2652
+ for (let i = 0; i < fnArray.length; i++) {
2653
+ const fn = fnArray[i];
2654
+ const args = argsArray[i];
2655
+ if (fn === OPS.save || fn === OPS.paintFormXObjectBegin) {
2656
+ stack.push({ ctm: ctm.slice(), alpha, normalBlend, pattern, clip });
2657
+ const m = fn === OPS.paintFormXObjectBegin ? args[0] : null;
2658
+ if (Array.isArray(m) && m.length >= 6) ctm = mul3(ctm, m);
2659
+ const bbox = fn === OPS.paintFormXObjectBegin ? args[1] : null;
2660
+ if (Array.isArray(bbox) && bbox.length === 4 && clip !== null) {
2661
+ const axisAligned = ctm[1] === 0 && ctm[2] === 0 || ctm[0] === 0 && ctm[3] === 0;
2662
+ const bounds = box(bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]);
2663
+ clip = axisAligned ? clip ? meet(clip, bounds) : bounds : null;
2664
+ }
2665
+ } else if (fn === OPS.restore || fn === OPS.paintFormXObjectEnd) {
2666
+ const s = stack.pop();
2667
+ if (s) ({ ctm, alpha, normalBlend, pattern, clip } = s);
2668
+ } else if (fn === OPS.transform) ctm = mul3(ctm, args);
2669
+ else if (fn === OPS.setFillColorN) pattern = true;
2670
+ else if (fn === OPS.setFillRGBColor || fn === OPS.setFillGray || fn === OPS.setFillCMYKColor || fn === OPS.setFillColor) pattern = false;
2671
+ else if (fn === OPS.setGState) {
2672
+ const entries = args[0];
2673
+ if (Array.isArray(entries)) for (const e of entries) {
2674
+ if (!Array.isArray(e)) continue;
2675
+ if (e[0] === "ca" && typeof e[1] === "number") alpha = e[1];
2676
+ else if (e[0] === "BM") normalBlend = e[1] === "source-over" || e[1] === "Normal";
2677
+ else if (e[0] === "SMask" && e[1]) normalBlend = false;
2678
+ }
2679
+ } else if (fn === OPS.showText) {
2680
+ for (const g of args[0]) {
2681
+ if (g && typeof g === "object" && typeof g.unicode === "string") drawn += glyphText(g.unicode);
2682
+ }
2683
+ } else if (fn === OPS.constructPath) {
2684
+ const sub = args[0];
2685
+ const coords = args[1];
2686
+ if (!Array.isArray(sub)) {
2687
+ pathOk = false;
2688
+ continue;
2689
+ }
2690
+ let ci = 0;
2691
+ for (const op of sub) {
2692
+ if (op === OPS.rectangle) {
2693
+ path.push(box(coords[ci], coords[ci + 1], coords[ci + 2], coords[ci + 3]));
2694
+ ci += 4;
2695
+ } else {
2696
+ pathOk = false;
2697
+ ci += op === OPS.curveTo ? 6 : op === OPS.curveTo2 || op === OPS.curveTo3 ? 4 : op === OPS.closePath ? 0 : 2;
2698
+ }
2699
+ }
2700
+ } else if (fn === OPS.clip || fn === OPS.eoClip) {
2701
+ clip = clip === null || !pathOk || path.length !== 1 ? null : clip ? meet(clip, path[0]) : path[0];
2702
+ } else if (fn === OPS.fill || fn === OPS.eoFill || fn === OPS.fillStroke || fn === OPS.eoFillStroke || fn === OPS.endPath || fn === OPS.stroke || fn === OPS.closeStroke || fn === OPS.closeFillStroke || fn === OPS.closeEOFillStroke) {
2703
+ const fills = fn !== OPS.endPath && fn !== OPS.stroke && fn !== OPS.closeStroke;
2704
+ if (fills && pathOk && path.length === 1 && alpha >= 1 && normalBlend && !pattern && clip !== null && drawn.length > 0) {
2705
+ const rect = clip ? meet(path[0], clip) : path[0];
2706
+ if (rect.x2 > rect.x1 && rect.y2 > rect.y1) covers.push({ at: drawn.length, rect });
2707
+ }
2708
+ path = [];
2709
+ pathOk = true;
2710
+ }
2711
+ }
2712
+ const hidden = /* @__PURE__ */ new Set();
2713
+ if (covers.length === 0) return hidden;
2714
+ let pos = 0;
2715
+ for (const it of items) {
2716
+ const t = glyphText(it.str ?? "");
2717
+ const start = pos;
2718
+ pos += t.length;
2719
+ if (!t) continue;
2720
+ if (drawn.slice(start, pos) !== t) break;
2721
+ const [a, b, , , e, f] = it.transform;
2722
+ const size = Math.hypot(a, b) || it.height;
2723
+ const r = { x1: e, y1: f, x2: e + it.width, y2: f + size };
2724
+ if (covers.some((c) => c.at >= pos && r.x1 >= c.rect.x1 - 1 && r.x2 <= c.rect.x2 + 1 && r.y1 >= c.rect.y1 - 1 && r.y2 <= c.rect.y2 + 1)) hidden.add(it);
2725
+ }
2726
+ return hidden;
2727
+ }
2728
+ function mul3(m, t) {
2729
+ return [
2730
+ m[0] * t[0] + m[2] * t[1],
2731
+ m[1] * t[0] + m[3] * t[1],
2732
+ m[0] * t[2] + m[2] * t[3],
2733
+ m[1] * t[2] + m[3] * t[3],
2734
+ m[0] * t[4] + m[2] * t[5] + m[4],
2735
+ m[1] * t[4] + m[3] * t[5] + m[5]
2736
+ ];
2737
+ }
2738
+ var CJK = /^[ㄱ-ㆎ가-힣一-鿿]$/;
2739
+ var PUNCT = /^[、。,.,.·ㆍ!?]$/;
2740
+ function joinVerticalColumns(items) {
2741
+ const singles = items.filter((i) => !i.rotated && CJK.test(i.text) && i.fontSize > 0);
2742
+ if (singles.length < 8) return joinLoneColumns(items);
2743
+ const cols = [];
2744
+ for (const it of [...singles].sort((a, b) => a.x - b.x)) {
2745
+ const c = cols.find((col) => Math.abs(col.x - it.x) <= it.fontSize * 0.15);
2746
+ if (c) c.items.push(it);
2747
+ else cols.push({ x: it.x, items: [it] });
2748
+ }
2749
+ const columns = cols.filter((c) => {
2750
+ if (c.items.length < 4) return false;
2751
+ c.items.sort((a, b) => b.y - a.y);
2752
+ const fs = c.items[0].fontSize;
2753
+ for (let k = 1; k < c.items.length; k++) {
2754
+ const step = c.items[k - 1].y - c.items[k].y;
2755
+ if (step < fs * 0.8 || step > fs * 2) return false;
2756
+ }
2757
+ return true;
2758
+ }).sort((a, b) => b.x - a.x);
2759
+ if (columns.length < 2) return joinLoneColumns(items);
2760
+ const groups = [];
2761
+ for (const col of columns) {
2762
+ const g = groups[groups.length - 1];
2763
+ const last = g?.[g.length - 1];
2764
+ const fs = col.items[0].fontSize;
2765
+ if (last && last.x - col.x >= fs * 1.2 && last.x - col.x <= fs * 4 && Math.abs(last.items[0].y - col.items[0].y) <= fs * 1.2) g.push(col);
2766
+ else groups.push([col]);
2767
+ }
2768
+ const drop = /* @__PURE__ */ new Set();
2769
+ const add = [];
2770
+ for (const g of groups) {
2771
+ if (g.length < 2) continue;
2772
+ const fs = g[0].items[0].fontSize;
2773
+ const med = (v) => v.sort((a, b) => a - b)[v.length >> 1];
2774
+ const step = med(g.flatMap((c) => c.items.slice(1).map((it, k) => c.items[k].y - it.y)));
2775
+ const colGap = med(g.slice(1).map((c, k) => g[k].x - c.x));
2776
+ if (step > colGap * 0.8 || step > fs * 1.15) continue;
2777
+ const gapped = g.filter((c) => c.items.slice(1).some((it, k) => c.items[k].y - it.y > fs * 1.3)).length;
2778
+ if (gapped * 2 < g.length) continue;
2779
+ const x1 = Math.min(...g.map((c) => c.x)), x2 = Math.max(...g.map((c) => c.x)) + fs;
2780
+ const top = Math.max(...g.map((c) => c.items[0].y)) + fs * 0.2;
2781
+ const bottom = Math.min(...g.map((c) => c.items[c.items.length - 1].y)) - fs * 0.2;
2782
+ const members = new Set(g.flatMap((c) => c.items));
2783
+ const inside = items.filter((i) => !members.has(i) && i.x + i.w / 2 >= x1 - 1 && i.x + i.w / 2 <= x2 + 1 && i.y <= top && i.y >= bottom - fs);
2784
+ if (inside.some((i) => !PUNCT.test(i.text))) continue;
2785
+ const spread2 = fs * 2.2;
2786
+ const lineH = items.some((i) => !members.has(i) && !inside.includes(i) && i.x + i.w > x1 && i.x < x2 && i.y < bottom && i.y >= top - spread2 * g.length) ? (top - bottom) / g.length : spread2;
2787
+ for (const p of inside) {
2788
+ const col = [...g].filter((c) => c.x <= p.x).sort((a, b) => b.x - a.x)[0];
2789
+ if (col) {
2790
+ col.items.push(p);
2791
+ members.add(p);
2792
+ }
2793
+ }
2794
+ const hangul = g.some((c) => c.items.some((it) => /[가-힣]/.test(it.text)));
2795
+ g.forEach((col, k) => {
2796
+ col.items.sort((a, b) => b.y - a.y);
2797
+ let text = "";
2798
+ for (let n = 0; n < col.items.length; n++) {
2799
+ const it = col.items[n];
2800
+ if (n > 0 && col.items[n - 1].y - it.y > fs * 1.3 && !PUNCT.test(it.text)) text += " ";
2801
+ text += hangul ? it.text.replace(/[、,]/g, ",").replace(/[。.]/g, ".") : it.text;
2802
+ }
2803
+ add.push({ ...col.items[0], text, x: x1, y: top - fs * 0.2 - k * lineH, w: [...text].length * fs * 0.5, h: fs });
2804
+ });
2805
+ for (const m of members) drop.add(m);
2806
+ }
2807
+ const out = drop.size ? [...items.filter((i) => !drop.has(i)), ...add] : items;
2808
+ return joinLoneColumns(out);
2809
+ }
2810
+ var LONE = /^[ㄱ-ㆎ가-힣一-鿿0-9․·.]$/;
2811
+ function joinLoneColumns(items) {
2812
+ const singles = items.filter((i) => !i.rotated && LONE.test(i.text) && i.fontSize > 0);
2813
+ if (singles.length < 6) return items;
2814
+ const cols = [];
2815
+ for (const it of [...singles].sort((a, b) => a.x - b.x)) {
2816
+ const c = cols.find((col) => Math.abs(col.x - it.x) <= Math.max(1.5, it.fontSize * 0.3));
2817
+ if (c) c.items.push(it);
2818
+ else cols.push({ x: it.x, items: [it] });
2819
+ }
2820
+ const drop = /* @__PURE__ */ new Set();
2821
+ const add = [];
2822
+ for (const col of cols) {
2823
+ if (col.items.length < 6) continue;
2824
+ col.items.sort((a, b) => b.y - a.y);
2825
+ const fs = col.items[0].fontSize;
2826
+ if (col.items.some((it) => Math.abs(it.fontSize - fs) > 1)) continue;
2827
+ const members = new Set(col.items);
2828
+ const others = items.filter((i) => !members.has(i));
2829
+ const colR = Math.max(...col.items.map((it) => it.x + it.w));
2830
+ if (!(others.every((i) => i.x + i.w <= col.x - fs * 5) || others.every((i) => i.x >= colR + fs * 5))) continue;
2831
+ if (col.items.some((m) => others.some((i) => Math.abs(i.y - m.y) <= fs * 0.5))) continue;
2832
+ const segs = [[col.items[0]]];
2833
+ for (let k = 1; k < col.items.length; k++) {
2834
+ if (col.items[k - 1].y - col.items[k].y > fs * 4) segs.push([col.items[k]]);
2835
+ else segs[segs.length - 1].push(col.items[k]);
2836
+ }
2837
+ if (segs.some((g) => g.slice(1).some((it, k) => g[k].y - it.y < fs * 0.8))) continue;
2838
+ for (const g of segs) {
2839
+ const steps = g.slice(1).map((it, k) => g[k].y - it.y).sort((a, b) => a - b);
2840
+ const med = steps[steps.length >> 1] ?? 0;
2841
+ let text = "";
2842
+ g.forEach((it, k) => {
2843
+ if (k && g[k - 1].y - it.y > med * 1.2) text += " ";
2844
+ text += it.text;
2845
+ });
2846
+ add.push({ ...g[0], text, x: col.x, w: [...text].length * fs * 0.5, h: fs });
2847
+ }
2848
+ for (const m of members) drop.add(m);
2849
+ }
2850
+ return drop.size ? [...items.filter((i) => !drop.has(i)), ...add] : items;
2851
+ }
2852
+ var TRACKED = /^(?:[^\s\u1100-\u11ff\u3130-\u318f\uac00-\ud7a3] ){3,}[^\s\u1100-\u11ff\u3130-\u318f\uac00-\ud7a3]$/;
2853
+ var SPACED_NUMBER = /^(?=[^\d]*\d)(?=\S* )[\d\s\-().·,☎]+$/;
2854
+ function restoreTrackedSpacing(items, fnArray, argsArray) {
2855
+ if (!items.some((it) => TRACKED.test(it.str ?? "") || SPACED_NUMBER.test((it.str ?? "").trim()))) return 0;
2856
+ const streams = /* @__PURE__ */ new Map();
2857
+ const saved = [];
2858
+ let font = "";
2859
+ for (let i = 0; i < fnArray.length; i++) {
2860
+ const fn = fnArray[i];
2861
+ const args = argsArray[i];
2862
+ if (fn === OPS.setFont) font = String(args[0]);
2863
+ else if (fn === OPS.save || fn === OPS.paintFormXObjectBegin) saved.push(font);
2864
+ else if (fn === OPS.restore || fn === OPS.paintFormXObjectEnd) font = saved.pop() ?? font;
2865
+ else if (fn === OPS.showText) {
2866
+ let list = streams.get(font);
2867
+ if (!list) streams.set(font, list = []);
2868
+ for (const g of args[0]) {
2869
+ if (g && typeof g === "object" && typeof g.unicode === "string") list.push(normalizeUnicode(g.unicode));
2870
+ }
2871
+ }
2872
+ }
2873
+ const cursor = /* @__PURE__ */ new Map();
2874
+ const failed = /* @__PURE__ */ new Set();
2875
+ let changed = 0;
2876
+ for (const it of items) {
2877
+ const f = it.fontName ?? "";
2878
+ const glyphs = streams.get(f);
2879
+ if (!glyphs || failed.has(f) || typeof it.str !== "string") continue;
2880
+ const want = it.str.replace(/\s+/g, "");
2881
+ if (!want) continue;
2882
+ let gi = cursor.get(f) ?? 0;
2883
+ while (gi < glyphs.length && /^\s*$/.test(glyphs[gi])) gi++;
2884
+ let got = "", text = "";
2885
+ while (gi < glyphs.length && got.length < want.length) {
2886
+ const g = glyphs[gi++];
2887
+ text += g;
2888
+ got += g.replace(/\s+/g, "");
2889
+ }
2890
+ if (got !== want) {
2891
+ failed.add(f);
2892
+ continue;
2893
+ }
2894
+ cursor.set(f, gi);
2895
+ if (TRACKED.test(it.str)) {
2896
+ const rebuilt = text.replace(/\s+/g, " ").trim();
2897
+ if (rebuilt.split(" ").length < it.str.split(" ").length) {
2898
+ it.str = rebuilt;
2899
+ changed++;
2900
+ }
2901
+ } else if (SPACED_NUMBER.test(it.str.trim()) && /\S\s+\S/.test(text)) {
2902
+ it.str = text.replace(/\s+/g, " ").trim();
2903
+ it.glyphSpaced = true;
2904
+ changed++;
2905
+ }
2906
+ }
2907
+ return changed;
2908
+ }
2909
+ function markSyntheticSpaces(items, fnArray, argsArray) {
2910
+ if (!items.some((it) => typeof it.str === "string" && it.str.length > 0 && !it.str.trim())) return;
2911
+ const streams = /* @__PURE__ */ new Map();
2912
+ const saved = [];
2913
+ let font = "";
2914
+ for (let i = 0; i < fnArray.length; i++) {
2915
+ const fn = fnArray[i];
2916
+ const args = argsArray[i];
2917
+ if (fn === OPS.setFont) font = String(args[0]);
2918
+ else if (fn === OPS.save || fn === OPS.paintFormXObjectBegin) saved.push(font);
2919
+ else if (fn === OPS.restore || fn === OPS.paintFormXObjectEnd) font = saved.pop() ?? font;
2920
+ else if (fn === OPS.showText) {
2921
+ let list = streams.get(font);
2922
+ if (!list) streams.set(font, list = []);
2923
+ for (const g of args[0]) {
2924
+ if (g && typeof g === "object" && typeof g.unicode === "string") list.push(normalizeUnicode(g.unicode));
2925
+ }
2926
+ }
2927
+ }
2928
+ const cursor = /* @__PURE__ */ new Map();
2929
+ const failed = /* @__PURE__ */ new Set();
2930
+ const marks = [];
2931
+ for (const it of items) {
2932
+ const f = it.fontName ?? "";
2933
+ const glyphs = streams.get(f);
2934
+ if (!glyphs || failed.has(f) || typeof it.str !== "string" || !it.str) continue;
2935
+ let gi = cursor.get(f) ?? 0;
2936
+ if (!it.str.trim()) {
2937
+ if (gi < glyphs.length && /^\s+$/.test(glyphs[gi])) {
2938
+ while (gi < glyphs.length && /^\s+$/.test(glyphs[gi])) gi++;
2939
+ cursor.set(f, gi);
2940
+ } else marks.push(it);
2941
+ continue;
2942
+ }
2943
+ const want = it.str.replace(/\s+/g, "");
2944
+ while (gi < glyphs.length && /^\s*$/.test(glyphs[gi])) gi++;
2945
+ let got = "";
2946
+ while (gi < glyphs.length && got.length < want.length) got += glyphs[gi++].replace(/\s+/g, "");
2947
+ if (got !== want) {
2948
+ failed.add(f);
2949
+ continue;
2950
+ }
2951
+ cursor.set(f, gi);
2952
+ }
2953
+ for (const it of marks) if (!failed.has(it.fontName ?? "")) it.synthetic = true;
2954
+ }
2955
+ var TRACKING_MAX_EM = 0.15;
2956
+ function joinTrackedHangul(items, fnArray, argsArray) {
2957
+ if (!items.some((it) => typeof it.str === "string" && /[가-힣] [가-힣]/.test(it.str))) return;
2958
+ const streams = /* @__PURE__ */ new Map();
2959
+ const saved = [];
2960
+ let font = "";
2961
+ for (let i = 0; i < fnArray.length; i++) {
2962
+ const fn = fnArray[i];
2963
+ const args = argsArray[i];
2964
+ if (fn === OPS.setFont) font = String(args[0]);
2965
+ else if (fn === OPS.save || fn === OPS.paintFormXObjectBegin) saved.push(font);
2966
+ else if (fn === OPS.restore || fn === OPS.paintFormXObjectEnd) font = saved.pop() ?? font;
2967
+ else if (fn === OPS.showText) {
2968
+ let list = streams.get(font);
2969
+ if (!list) streams.set(font, list = []);
2970
+ let gap = null;
2971
+ for (const g of args[0]) {
2972
+ if (typeof g === "number") {
2973
+ if (gap !== null) gap -= g / 1e3;
2974
+ continue;
2975
+ }
2976
+ if (g && typeof g === "object" && typeof g.unicode === "string") {
2977
+ list.push({ u: normalizeUnicode(g.unicode), gap });
2978
+ gap = 0;
2979
+ }
2980
+ }
2981
+ }
2982
+ }
2983
+ const isSpace = (g) => g !== void 0 && /^\s+$/.test(g.u);
2984
+ const cursor = /* @__PURE__ */ new Map();
2985
+ const failed = /* @__PURE__ */ new Set();
2986
+ const edits = [];
2987
+ for (const it of items) {
2988
+ const f = it.fontName ?? "";
2989
+ const glyphs = streams.get(f);
2990
+ if (!glyphs || failed.has(f) || typeof it.str !== "string" || !it.str) continue;
2991
+ let gi = cursor.get(f) ?? 0;
2992
+ const s = it.str;
2993
+ if (!s.trim()) {
2994
+ while (isSpace(glyphs[gi])) gi++;
2995
+ cursor.set(f, gi);
2996
+ continue;
2997
+ }
2998
+ while (gi < glyphs.length && /^\s*$/.test(glyphs[gi].u)) gi++;
2999
+ const fake = /* @__PURE__ */ new Set();
3000
+ let ok = true;
3001
+ for (let k = 0; k < s.length && ok; k++) {
3002
+ if (/\s/.test(s[k])) {
3003
+ if (isSpace(glyphs[gi])) {
3004
+ while (isSpace(glyphs[gi])) gi++;
3005
+ while (k + 1 < s.length && /\s/.test(s[k + 1])) k++;
3006
+ } else {
3007
+ const gap = glyphs[gi]?.gap;
3008
+ if (gap != null && gap <= TRACKING_MAX_EM && /[가-힣]/.test(s[k - 1] ?? "") && /[가-힣]/.test(s[k + 1] ?? "")) fake.add(k);
3009
+ }
3010
+ continue;
3011
+ }
3012
+ let g = "";
3013
+ while (gi < glyphs.length && !g) g = glyphs[gi++].u.replace(/\s+/g, "");
3014
+ if (!g || s.slice(k, k + g.length) !== g) ok = false;
3015
+ else k += g.length - 1;
3016
+ }
3017
+ if (!ok) {
3018
+ failed.add(f);
3019
+ continue;
3020
+ }
3021
+ cursor.set(f, gi);
3022
+ if (fake.size && !/^\S(?: \S){2,}$/.test(s)) edits.push([it, fake]);
3023
+ }
3024
+ for (const [it, fake] of edits) if (!failed.has(it.fontName ?? "")) it.str = [...it.str].filter((_, k) => !fake.has(k)).join("");
3025
+ }
3026
+ function markTrailingSpaceGlyphs(items, fnArray, argsArray) {
3027
+ const glyphs = [];
3028
+ for (let i = 0; i < fnArray.length; i++) {
3029
+ if (fnArray[i] !== OPS.showText) continue;
3030
+ for (const g of argsArray[i][0]) {
3031
+ if (g && typeof g === "object" && typeof g.unicode === "string") glyphs.push(normalizeUnicode(g.unicode));
3032
+ }
3033
+ }
3034
+ const text = items.filter((it) => typeof it.str === "string" && it.str.trim());
3035
+ const ends = [];
3036
+ let gi = 0;
3037
+ for (let k = 0; k < text.length; k++) {
3038
+ const it = text[k];
3039
+ const want = it.str.replace(/\s+/g, "");
3040
+ while (gi < glyphs.length && /^\s*$/.test(glyphs[gi])) gi++;
3041
+ let got = "";
3042
+ while (gi < glyphs.length && got.length < want.length) got += glyphs[gi++].replace(/\s+/g, "");
3043
+ if (got !== want) break;
3044
+ let next = gi;
3045
+ while (next < glyphs.length && glyphs[next] === "") next++;
3046
+ const after = text[k + 1];
3047
+ if (after && Math.abs(after.transform[5] - it.transform[5]) < 3) continue;
3048
+ ends.push([it, next < glyphs.length && /^\s+$/.test(glyphs[next])]);
3049
+ }
3050
+ const spaced2 = ends.filter(([, s]) => s).length;
3051
+ const emits = ends.length >= EMIT_MIN_LINES && spaced2 >= ends.length * EMIT_MIN_RATIO;
3052
+ for (const [it, s] of ends) if (s || emits) it.spaceAfter = s;
3053
+ }
3054
+ function softHyphenHeads(items, fnArray, argsArray) {
3055
+ const glyphs = [];
3056
+ for (let i = 0; i < fnArray.length; i++) {
3057
+ if (fnArray[i] !== OPS.showText) continue;
3058
+ for (const g of argsArray[i][0]) {
3059
+ const o = g;
3060
+ if (g && typeof g === "object" && typeof o.unicode === "string") glyphs.push({ u: o.unicode, w: typeof o.width === "number" ? o.width : 0 });
3061
+ }
3062
+ }
3063
+ if (!glyphs.some((g) => g.u === "\xAD" && g.w > 0)) return () => {
3064
+ };
3065
+ const text = items.filter((it) => typeof it.str === "string" && it.str.trim());
3066
+ const heads = [];
3067
+ let gi = 0;
3068
+ for (let k = 0; k < text.length; k++) {
3069
+ const it = text[k], prev = text[k - 1];
3070
+ const want = it.str.replace(/\s+/g, "");
3071
+ let soft = -1, spaced2 = false;
3072
+ while (gi < glyphs.length && (/^\s*$/.test(glyphs[gi].u) || glyphs[gi].u === "\xAD")) {
3073
+ if (glyphs[gi].u === "\xAD") {
3074
+ soft = glyphs[gi].w > 0 ? gi : -1;
3075
+ spaced2 = false;
3076
+ } else if (soft >= 0) spaced2 = true;
3077
+ gi++;
3078
+ }
3079
+ if (soft >= 0) {
3080
+ const before = glyphs[soft - 1]?.u ?? "";
3081
+ const wrapped = !!prev && Math.abs(prev.transform[5] - it.transform[5]) >= 3 && new RegExp("\\p{Script=Latin}$", "u").test(before) && new RegExp("^\\p{Ll}", "u").test(it.str.trimStart());
3082
+ if (!wrapped) heads.push([it, spaced2 || !/^[\d.,]+%?(?:\s|$)/.test(it.str.trimStart()) ? "- " : "-"]);
3083
+ }
3084
+ const pushed = heads.length;
3085
+ let got = "";
3086
+ while (gi < glyphs.length && got.length < want.length) {
3087
+ if (glyphs[gi].u !== "\xAD") got += normalizeUnicode(glyphs[gi].u).replace(/\s+/g, "");
3088
+ gi++;
3089
+ }
3090
+ if (got !== want) {
3091
+ if (pushed && heads[pushed - 1][0] === it) heads.pop();
3092
+ break;
3093
+ }
3094
+ }
3095
+ return () => {
3096
+ for (const [it, head] of heads) it.str = head + it.str;
3097
+ };
3098
+ }
3099
+ var EMIT_MIN_LINES = 5;
3100
+ var EMIT_MIN_RATIO = 0.2;
3101
+ var NOTE_MARK = /^\s*(문\d{1,5}[))]|\d{1,5}\)|\(\d{1,5}\))/;
3102
+ function isContentsReference(text, at) {
3103
+ if (/(?:^|\n)\s*\|?\s*(?:목\s*차|(?:table of )?contents\b)/i.test(text.slice(0, 120))) return true;
3104
+ const lineStart = text.lastIndexOf("\n", at - 1) + 1;
3105
+ const lineEnd = text.indexOf("\n", at);
3106
+ const line = text.slice(lineStart, lineEnd < 0 ? text.length : lineEnd);
3107
+ return /[·⋯.…]{5,}/.test(line);
3108
+ }
3109
+ function blockText(b) {
3110
+ if (b.table) return b.table.cells.flat().map((c) => c.text).join("\n");
3111
+ return b.text ?? "";
3112
+ }
3113
+ function relocateEndnotes(blocks) {
3114
+ const texts = blocks.map(blockText);
3115
+ const occurrences = (mark, end, cap) => {
3116
+ const out2 = [];
3117
+ for (let j = 0; j < end && out2.length < cap; j++) {
3118
+ for (let at = texts[j].indexOf(mark); at >= 0 && out2.length < cap; at = texts[j].indexOf(mark, at + mark.length)) {
3119
+ const notRef = isContentsReference(texts[j], at) || !mark.startsWith("\uBB38") && !texts[j].slice(0, at).trim();
3120
+ out2.push(notRef ? -1 : j);
3121
+ }
3122
+ }
3123
+ return out2;
3124
+ };
3125
+ const cands = [];
3126
+ for (let i = 0; i < blocks.length; i++) {
3127
+ const b = blocks[i];
3128
+ if (b.type !== "paragraph" && b.type !== "list" && b.type !== "heading") continue;
3129
+ const m = NOTE_MARK.exec(texts[i]);
3130
+ if (m) cands.push({ idx: i, mark: m[1], shape: m[1].replace(/\d+/g, "#") });
3131
+ }
3132
+ const heads = [];
3133
+ for (const c of cands) {
3134
+ const refs = occurrences(c.mark, c.idx, 2);
3135
+ if (refs.length === 1 && refs[0] >= 0) heads.push({ idx: c.idx, ref: refs[0], shape: c.shape });
3136
+ }
3137
+ const shapes = /* @__PURE__ */ new Map();
3138
+ for (const h of heads) shapes.set(h.shape, (shapes.get(h.shape) ?? 0) + 1);
3139
+ const main = [...shapes].sort((a, b) => b[1] - a[1])[0]?.[0];
3140
+ if (!main || !/#/.test(main)) return blocks;
3141
+ const lastRun = (hs) => {
3142
+ let run2 = [];
3143
+ for (const h of hs) {
3144
+ if (run2.length && (h.ref < run2[run2.length - 1].ref || h.ref >= run2[0].idx)) run2 = [];
3145
+ run2.push(h);
3146
+ }
3147
+ return run2;
3148
+ };
3149
+ const firstRun = lastRun(heads.filter((h) => h.shape === main));
3150
+ if (firstRun.length < 3) return blocks;
3151
+ const tailByMark = /* @__PURE__ */ new Map();
3152
+ for (const c of cands) if (c.idx >= firstRun[0].idx && c.shape === main) tailByMark.set(c.mark, [...tailByMark.get(c.mark) ?? [], c.idx]);
3153
+ const paired = [];
3154
+ for (const [mark, idxs] of tailByMark) {
3155
+ const refs = occurrences(mark, firstRun[0].idx, idxs.length + 1);
3156
+ if (refs.length === idxs.length && refs.every((r) => r >= 0)) idxs.forEach((idx, k) => paired.push({ idx, ref: refs[k], shape: main }));
3157
+ }
3158
+ const run = lastRun(paired.sort((a, b) => a.idx - b.idx));
3159
+ if (run.length < 3) return blocks;
3160
+ const nums = run.map((h) => Number(/\d+/.exec(texts[h.idx])[0]));
3161
+ if (nums[0] !== 1 || new Set(nums).size < Math.max(...nums) * 0.8) return blocks;
3162
+ const start = run[0].idx;
3163
+ const groups = run.map((h, k) => ({ ref: h.ref, blocks: blocks.slice(h.idx, k + 1 < run.length ? run[k + 1].idx : blocks.length) }));
3164
+ const byRef = /* @__PURE__ */ new Map();
3165
+ for (const g of groups) byRef.set(g.ref, [...byRef.get(g.ref) ?? [], ...g.blocks]);
3166
+ const out = [];
3167
+ for (let i = 0; i < start; i++) {
3168
+ out.push(blocks[i]);
3169
+ const notes = byRef.get(i);
3170
+ if (notes) out.push(...notes);
3171
+ }
3172
+ return out;
3173
+ }
3174
+ var MIN_DOTS = 4;
3175
+ var INLINE = /\s*·{4,}\s*(?=\d{1,4}\s*$)/;
3176
+ var PAGE_NO = /^\d{1,4}$/;
3177
+ var DOTS = /^·+$/;
3178
+ var DOTS_PAGE = /^·+(\d{1,4})$/;
3179
+ var PAREN_PAGE = /^\(\s*(?:페이지|쪽)/;
3180
+ var TRAILING = /([^\s·])\s*·{4,}\s*$/;
3181
+ function dropTabLeaderDots(items) {
3182
+ if (!items.some((it) => it.text.includes("\xB7"))) return items;
3183
+ const sameLine = (a, b) => Math.abs(a.y - b.y) <= Math.max(a.fontSize, b.fontSize) * 0.3;
3184
+ const pageNoAfter = (right, ref) => items.some((it) => PAGE_NO.test(it.text.trim()) && sameLine(it, ref) && it.x >= right - 2) || PAREN_PAGE.test(items.filter((it) => sameLine(it, ref) && it.x > ref.x && !DOTS.test(it.text.trim())).sort((a, b) => a.x - b.x).slice(0, 2).map((it) => it.text.trim()).join(""));
3185
+ const drop = /* @__PURE__ */ new Set();
3186
+ const edit = /* @__PURE__ */ new Map();
3187
+ for (const it of items) if (!DOTS.test(it.text.trim()) && it.text.includes("\xB7\xB7\xB7\xB7") && INLINE.test(it.text)) edit.set(it, { text: it.text.replace(INLINE, " ") });
3188
+ for (const it of items) {
3189
+ if (edit.has(it) || !it.text.includes("\xB7\xB7\xB7\xB7") || !TRAILING.test(it.text)) continue;
3190
+ const page = items.find((p) => PAGE_NO.test(p.text.trim()) && sameLine(p, it) && p.x >= it.x + it.w - 2);
3191
+ if (page) edit.set(it, { text: it.text.replace(TRAILING, "$1 "), right: page.x });
3192
+ }
3193
+ const byLine = /* @__PURE__ */ new Map();
3194
+ for (const d of items) if (DOTS.test(d.text.trim()) || DOTS_PAGE.test(d.text.trim())) byLine.set(Math.round(d.y * 2), [...byLine.get(Math.round(d.y * 2)) ?? [], d]);
3195
+ for (const line of byLine.values()) {
3196
+ line.sort((a, b) => a.x - b.x);
3197
+ let run = [];
3198
+ const flush = () => {
3199
+ const last = run[run.length - 1];
3200
+ const tailPage = DOTS_PAGE.exec(last.text.trim())?.[1];
3201
+ const dots = run.reduce((n, d) => n + d.text.trim().replace(/\d+$/, "").length, 0);
3202
+ if (dots >= MIN_DOTS && (tailPage ? run.length > 1 : pageNoAfter(last.x + last.w, last))) {
3203
+ const body = tailPage ? run.slice(0, -1) : run;
3204
+ edit.set(run[0], { text: " ", right: tailPage ? last.x : last.x + last.w });
3205
+ for (const d of body.slice(1)) drop.add(d);
3206
+ if (tailPage) edit.set(last, { text: tailPage });
3207
+ const head = items.find((it) => it !== run[0] && sameLine(it, run[0]) && /[^\s·]\s*·+$/.test(it.text) && it.x < run[0].x && run[0].x - (it.x + it.w) <= run[0].fontSize * 0.7);
3208
+ if (head && !edit.has(head)) edit.set(head, { text: head.text.replace(/\s*·+$/, "") });
3209
+ }
3210
+ run = [];
3211
+ };
3212
+ for (const d of line) {
3213
+ const prev = run[run.length - 1];
3214
+ if (prev && (DOTS_PAGE.test(prev.text.trim()) || !(d.x > prev.x && d.x - (prev.x + prev.w) <= Math.max(prev.fontSize, d.fontSize) * 0.7))) flush();
3215
+ run.push(d);
3216
+ }
3217
+ if (run.length) flush();
3218
+ }
3219
+ if (!drop.size && !edit.size) return items;
3220
+ return items.filter((it) => !drop.has(it)).map((it) => {
3221
+ const e = edit.get(it);
3222
+ return e ? { ...it, text: e.text, w: (e.right ?? it.x + it.w) - it.x } : it;
3223
+ });
3224
+ }
3225
+ var SHAPES = /* @__PURE__ */ new Set(["\u25EF", "\u25A1"]);
3226
+ function mergeEnclosedDigits(items) {
3227
+ const drop = /* @__PURE__ */ new Set();
3228
+ for (const s of items) {
3229
+ if (!SHAPES.has(s.text)) continue;
3230
+ const inside = items.filter((d) => !drop.has(d) && /^\d\d?$/.test(d.text) && d.fontSize < s.fontSize && d.x >= s.x - 1 && d.x + d.w <= s.x + s.w + 1 && Math.abs(d.y - s.y) <= s.fontSize * 0.5).sort((a, b) => a.x - b.x);
3231
+ const digits = inside.map((d) => d.text).join("");
3232
+ if (!/^\d\d?$/.test(digits)) continue;
3233
+ const mid = (inside[0].x + inside[inside.length - 1].x + inside[inside.length - 1].w) / 2;
3234
+ if (Math.abs(mid - (s.x + s.w / 2)) > s.fontSize * 0.15) continue;
3235
+ s.text = enclosedNumber(Number(digits));
3236
+ for (const d of inside) drop.add(d);
3237
+ }
3238
+ if (!drop.size) return;
3239
+ let k = 0;
3240
+ for (const it of items) if (!drop.has(it)) items[k++] = it;
3241
+ items.length = k;
3242
+ }
3243
+ function orderTwoUpPage(blocks, pageWidth, pageHeight) {
3244
+ if (pageWidth < pageHeight * 1.2 || blocks.length < 2) return blocks;
3245
+ const mid = pageWidth / 2, tol = pageWidth * 0.01;
3246
+ const left = [], right = [], rest = [];
3247
+ let side = null;
3248
+ const pending = [];
3249
+ for (const b of blocks) {
3250
+ if (!b.bbox) {
3251
+ if (side) side.push(b);
3252
+ else pending.push(b);
3253
+ continue;
3254
+ }
3255
+ if (b.type === "paragraph" && /^[-–—-\s\d]+$/.test(b.text ?? "")) {
3256
+ rest.push(b);
3257
+ continue;
3258
+ }
3259
+ if (b.bbox.x + b.bbox.width <= mid + tol) side = left;
3260
+ else if (b.bbox.x >= mid - tol) side = right;
3261
+ else return blocks;
3262
+ if (pending.length) side.push(...pending.splice(0));
3263
+ side.push(b);
3264
+ }
3265
+ if (pending.length) return blocks;
3266
+ const span = (bs) => {
3267
+ const boxed = bs.filter((b) => b.bbox);
3268
+ return boxed.length ? Math.max(...boxed.map((b) => b.bbox.y + b.bbox.height)) - Math.min(...boxed.map((b) => b.bbox.y)) : 0;
3269
+ };
3270
+ if (!left.some((b) => b.bbox) || !right.some((b) => b.bbox) || Math.max(span(left), span(right)) < pageHeight * 0.5) return blocks;
3271
+ return [...left, ...right, ...rest];
3272
+ }
3273
+ var MARK = /^\d{1,3}\)$/;
3274
+ function footnoteSeparators(horizontals, pageWidth, pageHeight) {
3275
+ return horizontals.filter((l) => l.x2 - l.x1 >= 30 && l.x2 - l.x1 <= pageWidth * 0.45 && l.y1 < pageHeight * 0.6).map((l) => l.y1);
3276
+ }
3277
+ function superscriptNoteMarks(items) {
3278
+ const out = [];
3279
+ for (const m of items) {
3280
+ if (!MARK.test(m.text)) continue;
3281
+ const glued = items.some((p) => p !== m && Math.abs(p.x + p.w - m.x) <= 1.5 && m.fontSize <= p.fontSize * 0.85 && m.y - p.y >= p.fontSize * 0.1 && m.y - p.y <= p.fontSize * 0.6 && /[\p{L}\p{N}.,)'"’”」』]$/u.test(p.text));
3282
+ if (glued && !out.some((o) => o.mark === m.text)) out.push({ mark: m.text, y: m.y });
3283
+ }
3284
+ return out;
3285
+ }
3286
+ function refAt(text, mark) {
3287
+ for (let at = text.indexOf(mark); at >= 0; at = text.indexOf(mark, at + 1)) if (at > 0 && !/\s/.test(text[at - 1])) return true;
3288
+ return false;
3289
+ }
3290
+ function inlineFootnotes(blocks, pages) {
3291
+ if (!pages.size) return blocks;
3292
+ const byPage = /* @__PURE__ */ new Map();
3293
+ for (const b of blocks) if (b.pageNumber !== void 0) byPage.set(b.pageNumber, [...byPage.get(b.pageNumber) ?? [], b]);
3294
+ const drop = /* @__PURE__ */ new Set();
3295
+ const isText = (b) => (b.type === "paragraph" || b.type === "list") && !!b.text;
3296
+ const top = (b) => b.bbox.y + b.bbox.height;
3297
+ for (const [page, { marks, seps }] of pages) {
3298
+ const pb = byPage.get(page);
3299
+ if (!pb || !seps.length) continue;
3300
+ const markOf = (b) => b.bbox ? marks.find((m) => {
3301
+ const t = b.text.trimStart();
3302
+ return t.startsWith(m.mark) && /^\s/.test(t.slice(m.mark.length)) && top(b) < m.y && seps.some((y) => y >= top(b));
3303
+ }) : void 0;
3304
+ let start = -1;
3305
+ for (let j = pb.length - 1; j >= 0 && isText(pb[j]); j--) if (markOf(pb[j])) start = j;
3306
+ if (start < 0) continue;
3307
+ if (!seps.some((y) => y >= top(pb[start]) && y - top(pb[start]) <= 20)) continue;
3308
+ const notes = [];
3309
+ let open = true;
3310
+ for (let j = start; j < pb.length; j++) {
3311
+ const b = pb[j], m = markOf(b);
3312
+ if (m) {
3313
+ notes.push({ text: b.text.trim(), blocks: [b], mark: m.mark });
3314
+ open = true;
3315
+ continue;
3316
+ }
3317
+ const prev = pb[j - 1], line = (b.style?.fontSize ?? b.bbox?.height ?? 10) * 1.5;
3318
+ if (open && b.bbox && prev.bbox && prev.bbox.y - top(b) <= line && !/^[-–—\s\d]+$/.test(b.text)) {
3319
+ notes[notes.length - 1].text += " " + b.text.trim();
3320
+ notes[notes.length - 1].blocks.push(b);
3321
+ } else open = false;
3322
+ }
3323
+ const body = pb.slice(0, start);
3324
+ for (const n of notes) {
3325
+ const host = body.find((b) => (b.type === "paragraph" || b.type === "list" || b.type === "heading") && !!b.text && refAt(b.text, n.mark));
3326
+ if (!host) continue;
3327
+ host.footnoteText = host.footnoteText ? `${host.footnoteText}; ${n.text}` : n.text;
3328
+ for (const b of n.blocks) drop.add(b);
3329
+ }
3330
+ }
3331
+ return drop.size ? blocks.filter((b) => !drop.has(b)) : blocks;
3332
+ }
3333
+ var PAGE_NUMBER = /^(?:\d{1,4}|[ivxlc]{1,7})$/i;
3334
+ var CAPTION = /^(?:Table|Figure|Fig\.?)\s*\d+(?:\.\d+)*\s*[.:]/i;
3335
+ var EQUATION_NUMBER = /\t\(\d{1,3}[a-z]?\)\s*$/;
3336
+ var DISPLAY_MATH = /=|[√∑∏∫∂∇≤≥≈≠∈∀∃]/;
3337
+ function isRunningHead(block, page, pageHeight) {
3338
+ const box = block.bbox, text = block.text?.trim();
3339
+ if (!box || !text || !pageHeight) return false;
3340
+ const top = box.y + box.height >= pageHeight * 0.9;
3341
+ const bottom = box.y <= pageHeight * 0.1;
3342
+ if (!top && !bottom) return false;
3343
+ const others = page.filter((o) => o !== block && o.bbox && o.type !== "image" && o.type !== "separator");
3344
+ if (top && others.some((o) => o.bbox.y + o.bbox.height > box.y + box.height)) return false;
3345
+ if (bottom && others.some((o) => o.bbox.y < box.y)) return false;
3346
+ if (bottom && box.height <= (block.style?.fontSize ?? 0) * 1.6) return true;
3347
+ if (!text.includes(" ")) return false;
3348
+ const parts = text.split(/\t+/).map((part) => part.trim()).filter(Boolean);
3349
+ if (parts.length >= 2 && (PAGE_NUMBER.test(parts[0]) || PAGE_NUMBER.test(parts[parts.length - 1]))) return true;
3350
+ const left = Math.min(...page.filter((o) => o.bbox).map((o) => o.bbox.x));
3351
+ const right = Math.max(...page.filter((o) => o.bbox).map((o) => o.bbox.x + o.bbox.width));
3352
+ return right > left && box.width >= (right - left) * 0.6;
3353
+ }
3354
+ function unbalancedClose(text) {
3355
+ return (text.match(/\)/g)?.length ?? 0) > (text.match(/\(/g)?.length ?? 0);
3356
+ }
3357
+ function demoteNonHeadingRoles(blocks, pageHeights, faceNames) {
3358
+ const byPage = /* @__PURE__ */ new Map();
3359
+ for (const block of blocks) {
3360
+ const page = byPage.get(block.pageNumber ?? 0) ?? [];
3361
+ page.push(block);
3362
+ byPage.set(block.pageNumber ?? 0, page);
3363
+ }
3364
+ const bodyStyle = /* @__PURE__ */ new Map();
3365
+ const bodySizes = /* @__PURE__ */ new Map();
3366
+ for (const [pageNumber, page] of byPage) {
3367
+ const chars = /* @__PURE__ */ new Map();
3368
+ const sizes = /* @__PURE__ */ new Map();
3369
+ let proseChars = 0;
3370
+ for (const b of page) {
3371
+ if (b.type !== "paragraph" && b.type !== "heading" || !b.text || !b.style?.fontName || !b.style.fontSize) continue;
3372
+ const key2 = `${b.style.fontName}:${b.style.fontSize}`;
3373
+ chars.set(key2, (chars.get(key2) ?? 0) + b.text.length);
3374
+ if (b.type === "paragraph" && b.style.fontName === "ocr") {
3375
+ sizes.set(b.style.fontSize, (sizes.get(b.style.fontSize) ?? 0) + b.text.length);
3376
+ proseChars += b.text.length;
3377
+ }
3378
+ }
3379
+ const [key, count] = [...chars].sort((a, b) => b[1] - a[1])[0] ?? [];
3380
+ if (key && count >= 300) bodyStyle.set(pageNumber, key);
3381
+ if (proseChars >= 300) {
3382
+ let cumulative = 0;
3383
+ for (const [size, count2] of [...sizes].sort((a, b) => a[0] - b[0])) {
3384
+ cumulative += count2;
3385
+ if (cumulative > proseChars / 2) {
3386
+ bodySizes.set(pageNumber, size);
3387
+ break;
3388
+ }
3389
+ }
3390
+ }
3391
+ }
3392
+ const citedProse = /* @__PURE__ */ new Set();
3393
+ const numberedProse = /* @__PURE__ */ new Set();
3394
+ for (const page of byPage.values()) {
3395
+ const numbered = page.filter((b) => (b.type === "heading" || b.type === "paragraph") && /^[①-⑮]\s*/.test(b.text?.trim() ?? "") && b.bbox && b.style?.fontName && b.style.fontSize && !/Bold|Black|Heavy|Semibold/i.test(faceNames?.get(b.style.fontName) ?? ""));
3396
+ let chain = [];
3397
+ const finish = () => {
3398
+ if (chain.length < 3 || !chain.some((b) => (b.text?.length ?? 0) >= 40 && b.bbox.height >= b.style.fontSize * 2.4)) return;
3399
+ for (const b of chain) numberedProse.add(b);
3400
+ const first = chain[0], size = first.style.fontSize;
3401
+ for (const b of page) if (/^[○●•◦]\s/.test(b.text?.trim() ?? "") && b.style?.fontName === first.style?.fontName && b.style?.fontSize === size && b.bbox && Math.abs(b.bbox.x - first.bbox.x) <= size * 0.5 && (b.text?.length ?? 0) >= 15) numberedProse.add(b);
3402
+ };
3403
+ for (const b of numbered) {
3404
+ const prev = chain.at(-1), size = b.style.fontSize;
3405
+ if (!prev || b.text.trim().charCodeAt(0) !== prev.text.trim().charCodeAt(0) + 1 || b.style.fontName !== prev.style.fontName || size !== prev.style.fontSize || Math.abs(b.bbox.x - prev.bbox.x) > size * 0.5 || prev.bbox.y - (b.bbox.y + b.bbox.height) > size * 8) {
3406
+ finish();
3407
+ chain = [];
3408
+ }
3409
+ chain.push(b);
3410
+ }
3411
+ finish();
3412
+ }
3413
+ for (let i = 0; i + 1 < blocks.length; i++) {
3414
+ const prose = blocks[i], reference = blocks[i + 1];
3415
+ const a = prose.bbox, b = reference.bbox, size = prose.style?.fontSize ?? 0;
3416
+ const source = reference.text?.replace(/<[^>]+>/g, "").trim() ?? "";
3417
+ if (prose.type !== "heading" && prose.type !== "paragraph" && prose.type !== "list" || reference.type !== "heading" && reference.type !== "paragraph" || (prose.text?.length ?? 0) < 40 || !a || !b || size <= 0 || a.height < size * 2.4 || prose.pageNumber !== reference.pageNumber || prose.style?.fontName !== reference.style?.fontName || prose.style?.fontSize !== reference.style?.fontSize || Math.abs(a.x - b.x) > size && !(/^[○●•◦]\s/.test(prose.text ?? "") && b.x >= a.x && b.x - a.x <= size * 2) || a.y - (b.y + b.height) < 0 || a.y - (b.y + b.height) > size || !/^[((].*(?:제\s*\d+\s*조|(?:Article|Section)\s+\d+).*[))]$/i.test(source)) continue;
3418
+ citedProse.add(prose);
3419
+ citedProse.add(reference);
3420
+ }
3421
+ for (let i = 0; i < blocks.length; i++) {
3422
+ const block = blocks[i];
3423
+ if (block.type !== "heading" || !block.text) continue;
3424
+ const text = block.text.replace(/<[^>]+>/g, "").trim();
3425
+ const fsz = block.style?.fontSize ?? 0;
3426
+ const tocEntry = i > 0 && TOC_BLOCKS.has(blocks[i - 1]) && TOC_BLOCKS.has(blocks[i + 1]);
3427
+ const page = byPage.get(block.pageNumber ?? 0) ?? [];
3428
+ const proseStyle = block.style?.fontName && bodyStyle.get(block.pageNumber ?? 0) === `${block.style.fontName}:${block.style.fontSize}` && text.length > 60;
3429
+ const next = blocks[i + 1];
3430
+ const nb = next?.bbox, bb = block.bbox;
3431
+ const chapterNumber = !!nb && !!bb && fsz >= (next?.style?.fontSize ?? 0) * 1.2 && Math.abs(bb.x - nb.x) > fsz && Math.abs(bb.x + bb.width / 2 - (nb.x + nb.width / 2)) < nb.width * 0.1;
3432
+ if (/^\d+(?:\.\d+)*\.?$/.test(text) && next?.type === "heading" && next.text && next.pageNumber === block.pageNumber && !chapterNumber) {
3433
+ next.text = `${block.text.trim()} ${next.text.trim()}`;
3434
+ blocks.splice(i--, 1);
3435
+ continue;
3436
+ }
3437
+ if ((next?.type === "paragraph" || next?.type === "heading" && !CAPTION.test(text)) && next.pageNumber === block.pageNumber && next.text && next.bbox && block.bbox && next.style?.fontName === block.style?.fontName && next.style?.fontSize === block.style?.fontSize && fsz > 0 && /^[a-z]/.test(next.text.trim()) && next.text.trim().length <= 40 && !/[.:;!?]$/.test(next.text.trim()) && block.bbox.y - (next.bbox.y + next.bbox.height) < fsz * 1.2 && Math.abs(next.bbox.x - block.bbox.x) < fsz) {
3438
+ block.text = `${block.text.trim()} ${next.text.trim()}`;
3439
+ block.bbox = { ...block.bbox, y: next.bbox.y, height: block.bbox.y + block.bbox.height - next.bbox.y };
3440
+ blocks.splice(i + 1, 1);
3441
+ }
3442
+ const after = blocks[i + 2];
3443
+ if ((next?.type === "paragraph" || next?.type === "heading") && /^(?:&|\+|and|or)$/i.test(next.text?.trim() ?? "") && after?.type === "heading" && after.text && after.pageNumber === block.pageNumber && next.pageNumber === block.pageNumber && after.style?.fontSize === block.style?.fontSize) {
3444
+ block.text = `${block.text.trim()} ${next.text.trim()} ${after.text.trim()}`;
3445
+ blocks.splice(i + 1, 2);
3446
+ }
3447
+ const tiny = fsz > 0 && fsz < 7.5;
3448
+ const prev = blocks[i - 1];
3449
+ if (prev?.type === "paragraph" && prev.pageNumber === block.pageNumber && /^[a-z]{1,3}[.)]$/.test(prev.text?.trim() ?? "") && prev.bbox && block.bbox && Math.abs(prev.bbox.y - block.bbox.y) < 2 && prev.bbox.x + prev.bbox.width <= block.bbox.x) {
3450
+ prev.text = `${prev.text.trim()} ${block.text.trim()}`;
3451
+ prev.bbox = { ...prev.bbox, width: block.bbox.x + block.bbox.width - prev.bbox.x };
3452
+ blocks.splice(i--, 1);
3453
+ continue;
3454
+ }
3455
+ if (prev?.type === "paragraph" && prev.pageNumber === block.pageNumber && /^\d{1,2}(?:\.\d{1,2})*\.?$/.test(prev.text?.trim() ?? "") && prev.bbox && block.bbox && fsz > 0 && (Math.abs(prev.bbox.y - block.bbox.y) < 2 && prev.bbox.x + prev.bbox.width <= block.bbox.x && block.bbox.x - (prev.bbox.x + prev.bbox.width) < fsz * 3 || Math.abs(prev.bbox.x - block.bbox.x) < 2 && (prev.style?.fontSize ?? 0) >= fsz && prev.bbox.y - (block.bbox.y + block.bbox.height) < fsz * 1.5)) {
3456
+ block.text = `${prev.text.trim()} ${block.text.trim()}`;
3457
+ blocks.splice(i - 1, 1);
3458
+ i -= 2;
3459
+ continue;
3460
+ }
3461
+ const box = block.bbox, size = block.style?.fontSize ?? 0;
3462
+ const kicker = !!box && size > 0 && next?.type === "heading" && next.pageNumber === block.pageNumber && !!next.bbox && (block.style?.fontName !== "ocr" || size < (bodySizes.get(block.pageNumber ?? 0) ?? Infinity) * 2) && (next.style?.fontSize ?? 0) >= size * 1.3 && box.y - (next.bbox.y + next.bbox.height) <= size * 3 && Math.min(box.x + box.width, next.bbox.x + next.bbox.width) - Math.max(box.x, next.bbox.x) >= Math.min(box.width, next.bbox.width) * 0.5 && !page.some((o) => o !== block && o.bbox && o.bbox.y > box.y + box.height && o.type !== "image");
3463
+ const face = faceNames?.get(block.style?.fontName ?? "") ?? "";
3464
+ const [bodyFace, bodySize] = (bodyStyle.get(block.pageNumber ?? 0) ?? "").split(":");
3465
+ const byline = /Italic|Oblique/i.test(face) && !/Bold|Black|Heavy|Semibold/i.test(face) && !!bodyFace && size <= Number(bodySize) + 0.5 && blocks[i - 1]?.type === "heading" && blocks[i - 1].pageNumber === block.pageNumber;
3466
+ const ocrFragment = block.style?.fontName === "ocr" && (/^[.,;:…·•-]/.test(text) || text.includes("\u2026") || (text.match(new RegExp("\\p{L}", "gu"))?.length ?? 0) < 2 || text.split(/\s+/).length > 7);
3467
+ const crowdedOcr = block.style?.fontName === "ocr" && !!box && [prev, next].every((o) => o?.type === "paragraph" && o.pageNumber === block.pageNumber && o.style?.fontName === "ocr" && !!o.bbox && (o.text?.length ?? 0) >= 15 && Math.abs(o.bbox.x - box.x) <= size * 0.25 && Math.min(o.bbox.y + o.bbox.height, box.y + box.height) - Math.max(o.bbox.y, box.y) >= o.bbox.height * 0.2) && prev.bbox.y > box.y && next.bbox.y < box.y;
3468
+ if (numberedProse.has(block) || citedProse.has(block) || ocrFragment || crowdedOcr || tocEntry || proseStyle || kicker || byline || tiny || !new RegExp("\\p{L}", "u").test(text) && !chapterNumber || /^[a-z]/.test(text) || CAPTION.test(text) || EQUATION_NUMBER.test(block.text) || DISPLAY_MATH.test(text) || // 닫는 괄호가 여는 괄호보다 많으면 앞 줄에서 이어진 문장 조각이다 ("Fact-checking) and is used …") — "1)"·"가)" 앞머리 번호는 빼고 센다
3469
+ unbalancedClose(text.replace(/^\s*[\dA-Za-z가-힣ⅰ-ⅹ]{1,3}\)\s*/, "")) || isRunningHead(block, page, pageHeights.get(block.pageNumber ?? 0))) {
3470
+ block.type = "paragraph";
3471
+ block.level = void 0;
3472
+ }
3473
+ }
3474
+ }
3475
+ function collectPdfOutline(blocks) {
3476
+ const outline = [];
3477
+ const visit = (bs) => {
3478
+ for (const b of bs) {
3479
+ if (b.type === "heading" && b.level && b.text) outline.push({ level: b.level, text: b.text, pageNumber: b.pageNumber });
3480
+ if (b.type === "table" && b.table) for (const row of b.table.cells) for (const cell of row) {
3481
+ if (cell.blocks) visit(cell.blocks);
3482
+ }
3483
+ }
3484
+ };
3485
+ visit(blocks);
3486
+ return outline;
3487
+ }
3488
+ function normalizeAraea(text) {
3489
+ return text.replace(/(?<![\u1100-\u115F])\u119E/g, "\u318D");
3490
+ }
3491
+ var stripNoUnicodeGlyph = (text) => text.includes("\uF000") ? text.replace(/\uF000/g, "") : text;
3492
+ var CHOSEONG_COMPAT = "\u3131\u3132\u3134\u3137\u3138\u3139\u3141\u3142\u3143\u3145\u3146\u3147\u3148\u3149\u314A\u314B\u314C\u314D\u314E";
3493
+ var normalizeLoneChoseong = (text) => /[\u1100-\u1112]/.test(text) ? text.replace(/[\u1100-\u1112](?![\u1160-\u11A7\uD7B0-\uD7C6])/g, (c) => CHOSEONG_COMPAT[c.charCodeAt(0) - 4352]) : text;
3494
+ var cleanChars = (text) => normalizeLoneChoseong(normalizeAraea(stripNoUnicodeGlyph(stripControlChars(text))));
3495
+ function sanitizeBlockControlChars(blocks) {
3496
+ for (const b of blocks) {
3497
+ if (b.text) b.text = cleanChars(b.text);
3498
+ if (b.table) {
3499
+ for (const row of b.table.cells) {
3500
+ for (const cell of row) {
3501
+ if (cell.text) cell.text = cleanChars(cell.text);
3502
+ if (cell.blocks) sanitizeBlockControlChars(cell.blocks);
3503
+ }
3504
+ }
3505
+ }
3506
+ if (b.children) sanitizeBlockControlChars(b.children);
3507
+ }
3508
+ }
3509
+ var CAPTION_LABEL = /^(?:figure|fig\.|diagram|table|chart|graph|exhibit|box)\s*[\dIVX][\w.\-]*$/i;
3510
+ function captionTableText(t) {
3511
+ if (!t || t.rows !== 1 || t.cols !== 2) return null;
3512
+ const [label, body] = t.cells[0];
3513
+ if (!label || !body || label.blocks?.length || body.blocks?.length || !CAPTION_LABEL.test(label.text.trim()) || !body.text.trim()) return null;
3514
+ return `${label.text.trim()} ${body.text.replace(/\s*\n\s*/g, " ").trim()}`;
3515
+ }
3516
+ function splitSingleCellTables(blocks) {
3517
+ const out = [];
3518
+ for (const b of blocks) {
3519
+ const t = b.type === "table" ? b.table : void 0;
3520
+ const title = t && FRAME_TITLE_BLOCKS.get(t);
3521
+ if (title) {
3522
+ out.push({ ...title, text: `${t.cells[0][0].text.trim()} ${t.cells[0][2].text.trim()}` });
3523
+ continue;
3524
+ }
3525
+ const only = t && t.rows === 1 && t.cols === 1 && t.cells[0]?.[0]?.blocks?.length === 1 ? t.cells[0][0].blocks[0] : void 0;
3526
+ const squash = (s) => s.replace(/\s/g, "");
3527
+ const inner = only && (!squash(t.cells[0][0].text) || only.type === "table" && squash(t.cells[0][0].text) === squash(only.table.cells.flat().map((c) => c.text).join(""))) ? only : void 0;
3528
+ const caption = captionTableText(t) ?? (inner?.type === "table" ? captionTableText(inner.table) : null);
3529
+ if (caption) {
3530
+ out.push({ type: "paragraph", text: caption, pageNumber: b.pageNumber, bbox: b.bbox });
3531
+ continue;
3532
+ }
3533
+ const cell = t && t.rows === 1 && t.cols === 1 ? t.cells[0]?.[0] : void 0;
3534
+ if (!cell) {
3535
+ out.push(b);
3536
+ continue;
3537
+ }
3538
+ const lines = (cell.text ?? "").split(/\n/).map((l) => l.trim()).filter(Boolean);
3539
+ if (t?.caption?.trim()) out.push({ type: "paragraph", text: t.caption.trim(), pageNumber: b.pageNumber, bbox: b.bbox });
3540
+ if (cell.blocks?.length) {
3541
+ out.push(...splitSingleCellTables(cell.blocks));
3542
+ continue;
3543
+ }
3544
+ for (const text of lines) out.push({ type: "paragraph", text, pageNumber: b.pageNumber, bbox: b.bbox });
3545
+ }
3546
+ return out;
3547
+ }
3548
+ function joinLatinCellWraps(blocks) {
3549
+ for (const b of blocks) {
3550
+ if (b.type !== "table" || !b.table) continue;
3551
+ for (const row of b.table.cells) for (const cell of row) {
3552
+ if (cell.text.includes("\n")) {
3553
+ const lines = cell.text.split("\n");
3554
+ const out = [lines[0]];
3555
+ for (const line of lines.slice(1)) {
3556
+ if (latinSoftWrap(out[out.length - 1], line)) out[out.length - 1] = out[out.length - 1].trimEnd() + " " + line.trim();
3557
+ else out.push(line);
3558
+ }
3559
+ cell.text = out.join("\n");
3560
+ }
3561
+ if (cell.blocks) joinLatinCellWraps(cell.blocks);
3562
+ }
3563
+ }
3564
+ }
3565
+ function cleanPdfText(text, opts) {
3566
+ let clean = normalizeAraea(stripControlChars(text));
3567
+ if (!opts?.keepLoneNumbers) {
3568
+ clean = clean.replace(/^\d{1,4}\n/, "").replace(/\n\d{1,4}\n/g, "\n").replace(/\n\d{1,4}$/, "");
3569
+ }
3570
+ if (!opts?.keepLoneNumbers) clean = clean.replace(/^#{1,6}\s*\d{1,4}\s*$/gm, "");
3571
+ return mergeKoreanLines(
3572
+ clean.replace(/^[\s]*[-–—]\s*[-–—]?\d+[-–—]?[\s]*[-–—]?[\s]*$/gm, "").replace(/^\s*\d+\s*\/\s*\d+\s*$/gm, "").replace(/\.(?: \.){3,}/g, (m) => ".".repeat(m.length + 1 >> 1))
3573
+ ).replace(/^(?!\| ---).*$/gm, (line) => {
3574
+ if (/^\s*\${1,2}.+\${1,2}\s*$/.test(line)) return line;
3575
+ if (line.startsWith("|")) {
3576
+ return line.replace(/(?:\\.|[^|\\])+/g, (cell) => cell.split("<br>").map((seg) => seg.replace(/\S(?:.*\S)?/, (t) => collapseEvenSpacing(t, false))).join("<br>"));
3577
+ }
3578
+ const mark = /^(?:#{1,6}|-) /.exec(line)?.[0] ?? "";
3579
+ return mark + collapseEvenSpacing(line.slice(mark.length), false);
3580
+ }).replace(/\\~\\~/g, "~~").replace(/~~~~/g, "").replace(/<u>\s*<\/u>/g, "").replace(/<(sup|sub)>\s*<\/\1>/g, "").replace(/\n{3,}/g, "\n\n").trim();
3581
+ }
3582
+ function startsWithMarker(line) {
3583
+ const t = line.trimStart();
3584
+ return /^[가-힣ㄱ-ㅎ][.)]/.test(t) || /^\d+[.)]/.test(t) || /^\([가-힣ㄱ-ㅎ\d]+\)/.test(t) || /^[○●※▶▷◆◇■□★☆\-·]\s/.test(t) || /^제\d+[조항호장절]/.test(t);
3585
+ }
3586
+ function isStandaloneHeader(line) {
3587
+ return /^제\d+[조항호장절](\([^)]*\))?(\s+\S+){0,7}$/.test(line.trim());
3588
+ }
3589
+ function mergeKoreanLines(text) {
3590
+ if (!text) return "";
3591
+ const lines = text.split("\n");
3592
+ if (lines.length <= 1) return text;
3593
+ const result = [lines[0]];
3594
+ for (let i = 1; i < lines.length; i++) {
3595
+ const prev = result[result.length - 1];
3596
+ const curr = lines[i];
3597
+ const currTrimmed = curr.trim();
3598
+ if (/^#{1,6}\s/.test(prev) || /^#{1,6}\s/.test(curr) || /^\|/.test(currTrimmed) || /^---/.test(currTrimmed)) {
3599
+ result.push(curr);
3600
+ continue;
3601
+ }
3602
+ if (/,$/.test(prev.trim()) && currTrimmed.length > 0) {
3603
+ result[result.length - 1] = prev + "\n" + curr;
3604
+ continue;
3605
+ }
3606
+ if (/^\(※/.test(currTrimmed)) {
3607
+ result[result.length - 1] = prev + " " + currTrimmed;
3608
+ continue;
3609
+ }
3610
+ if (/[가-힣·,\-]$/.test(prev) && /^[가-힣(]/.test(curr) && !startsWithMarker(curr) && !isStandaloneHeader(prev) && !startsWithMarker(prev)) {
3611
+ result[result.length - 1] = prev + wrapJoiner(prev, curr) + curr;
3612
+ } else {
3613
+ result.push(curr);
3614
+ }
3615
+ }
3616
+ return result.join("\n");
3617
+ }
3618
+ var LINK_Y_TOL = 2;
3619
+ var LINK_MIN_OVERLAP_RATIO = 0.5;
3620
+ function applyLinkAnnotations(items, annots) {
3621
+ if (items.length === 0 || annots.length === 0) return;
3622
+ const wrapped = /* @__PURE__ */ new Set();
3623
+ for (const a of annots) {
3624
+ if (a.subtype !== "Link" || !a.url || !a.rect || a.rect.length < 4) continue;
3625
+ const url = sanitizeHref(a.url);
3626
+ if (!url) continue;
3627
+ const x1 = Math.min(a.rect[0], a.rect[2]), x2 = Math.max(a.rect[0], a.rect[2]);
3628
+ const y1 = Math.min(a.rect[1], a.rect[3]), y2 = Math.max(a.rect[1], a.rect[3]);
3629
+ const matches = [];
3630
+ for (const item of items) {
3631
+ if (wrapped.has(item) || item.w <= 0 || !item.text.trim()) continue;
3632
+ if (item.y < y1 - LINK_Y_TOL || item.y > y2 + LINK_Y_TOL) continue;
3633
+ const overlap = Math.min(x2, item.x + item.w) - Math.max(x1, item.x);
3634
+ if (overlap / item.w < LINK_MIN_OVERLAP_RATIO) continue;
3635
+ matches.push(item);
3636
+ }
3637
+ if (matches.length === 0) continue;
3638
+ const lines = /* @__PURE__ */ new Map();
3639
+ for (const m of matches) {
3640
+ const key = Math.round(m.y / 3);
3641
+ const arr = lines.get(key) || [];
3642
+ arr.push(m);
3643
+ lines.set(key, arr);
3644
+ }
3645
+ for (const arr of lines.values()) {
3646
+ arr.sort((p, q) => p.x - q.x);
3647
+ arr[0].text = "[" + arr[0].text;
3648
+ arr[arr.length - 1].text = arr[arr.length - 1].text + `](${url})`;
3649
+ for (const m of arr) wrapped.add(m);
3650
+ }
3651
+ }
3652
+ }
3653
+ function addressKey(s) {
3654
+ let t = s.replace(/\\(.)/g, "$1").replace(/\s+/g, "");
3655
+ try {
3656
+ t = decodeURI(t);
3657
+ } catch {
3658
+ }
3659
+ return t.toLowerCase().replace(/^(?:[a-z][a-z0-9+.-]*:)?(?:\/\/)?(?:www\.)?/, "").replace(/[/.,;:)\]]+$/, "");
3660
+ }
3661
+ var MD_LINK = String.raw`(?<!!)\[([^\]\n]*)\]\(([^)\s]+)\)`;
3662
+ function mergeLinkRuns(markdown) {
3663
+ let out = markdown.replace(
3664
+ new RegExp(String.raw`<u>${MD_LINK}</u>`, "g"),
3665
+ (_m, text, url) => `[${text.replace(/<\/u>(\s*)<u>/g, "$1")}](${url})`
3666
+ );
3667
+ const run = new RegExp(MD_LINK + String.raw`(\s+)` + String.raw`(?<!!)\[([^\]\n]*)\]\(\2\)`, "g");
3668
+ for (let prev = ""; prev !== out; ) {
3669
+ prev = out;
3670
+ out = out.replace(run, (_m, a, url, _gap, b) => `[${a} ${b}](${url})`);
3671
+ }
3672
+ return out.replace(new RegExp(MD_LINK, "g"), (m, text, url) => text.trim() && addressKey(text) === addressKey(url) ? text : m);
3673
+ }
3674
+ async function applyFormulaOcr(buffer, blocks, pageFilter, effectivePageCount, warnings, _onProgress) {
3675
+ const formulaMod = await import("./formula-LC62GV4D-K3VFC5GV.js");
3676
+ const { FormulaPipeline, ensureFormulaModels } = formulaMod;
3677
+ await ensureFormulaModels((p) => {
3678
+ if (p.phase === "download" && p.total) {
3679
+ const pct = Math.floor(p.downloaded / p.total * 100);
3680
+ process.stderr.write(`\r[kordoc-formula] ${p.spec.name} ${pct}% (${formatMb(p.downloaded)}/${formatMb(p.total)})`);
3681
+ if (p.downloaded >= p.total) process.stderr.write("\n");
3682
+ } else if (p.phase === "verify") {
3683
+ process.stderr.write(`[kordoc-formula] ${p.spec.name} SHA-256 \uAC80\uC99D \uC911...
3684
+ `);
3685
+ } else if (p.phase === "done") {
3686
+ process.stderr.write(`[kordoc-formula] ${p.spec.name} \uC900\uBE44 \uC644\uB8CC
3687
+ `);
3688
+ } else if (p.phase === "skip") {
3689
+ }
3690
+ });
3691
+ const pipeline = await FormulaPipeline.create();
3692
+ try {
3693
+ const effectiveFilter = pageFilter ?? new Set(Array.from({ length: effectivePageCount }, (_, i) => i + 1));
3694
+ const pagesResult = await pipeline.runOnBuffer(buffer, effectiveFilter);
3695
+ if (pagesResult.length === 0) return;
3696
+ let insertedCount = 0;
3697
+ let removedDupCount = 0;
3698
+ for (const page of pagesResult) {
3699
+ const pageNumber = page.pageNumber;
3700
+ const pdfHeight = page.pdfHeight;
3701
+ const scaleX = page.renderedWidth > 0 ? page.pdfWidth / page.renderedWidth : 0.5;
3702
+ const scaleY = page.renderedHeight > 0 ? page.pdfHeight / page.renderedHeight : 0.5;
3703
+ const candidates = [];
3704
+ for (const r of page.regions) {
3705
+ if (!r.latex || !r.latex.trim()) continue;
3706
+ const wrapped = r.kind === "display" ? `$$${r.latex}$$` : `$${r.latex}$`;
3707
+ const x1 = r.bbox.x1 * scaleX;
3708
+ const x2 = r.bbox.x2 * scaleX;
3709
+ const yTop = pdfHeight - r.bbox.y1 * scaleY;
3710
+ const yBottom = pdfHeight - r.bbox.y2 * scaleY;
3711
+ const centerY = (yTop + yBottom) / 2;
3712
+ const width = x2 - x1;
3713
+ const height = yTop - yBottom;
3714
+ candidates.push({
3715
+ block: {
3716
+ type: "paragraph",
3717
+ text: wrapped,
3718
+ pageNumber,
3719
+ bbox: { page: pageNumber, x: x1, y: yBottom, width, height }
3720
+ },
3721
+ pdfBbox: { x1, x2, yTop, yBottom },
3722
+ centerY
3723
+ });
3724
+ }
3725
+ if (candidates.length === 0) continue;
3726
+ const OVERLAP_THRESHOLD = 0.6;
3727
+ const indicesToRemove = /* @__PURE__ */ new Set();
3728
+ for (let i = 0; i < blocks.length; i++) {
3729
+ const b = blocks[i];
3730
+ if (b.pageNumber !== pageNumber) continue;
3731
+ if (b.type === "table") continue;
3732
+ if (!b.bbox || b.bbox.width <= 0 || b.bbox.height <= 0) continue;
3733
+ const blockArea = b.bbox.width * b.bbox.height;
3734
+ if (blockArea <= 0) continue;
3735
+ for (const c of candidates) {
3736
+ const ox1 = Math.max(b.bbox.x, c.pdfBbox.x1);
3737
+ const ox2 = Math.min(b.bbox.x + b.bbox.width, c.pdfBbox.x2);
3738
+ const oy1 = Math.max(b.bbox.y, c.pdfBbox.yBottom);
3739
+ const oy2 = Math.min(b.bbox.y + b.bbox.height, c.pdfBbox.yTop);
3740
+ const interArea = Math.max(0, ox2 - ox1) * Math.max(0, oy2 - oy1);
3741
+ if (interArea / blockArea >= OVERLAP_THRESHOLD) {
3742
+ indicesToRemove.add(i);
3743
+ break;
3744
+ }
3745
+ }
3746
+ }
3747
+ if (indicesToRemove.size > 0) {
3748
+ const sorted = [...indicesToRemove].sort((a, b) => b - a);
3749
+ for (const idx of sorted) blocks.splice(idx, 1);
3750
+ removedDupCount += indicesToRemove.size;
3751
+ }
3752
+ candidates.sort((a, b) => b.centerY - a.centerY);
3753
+ for (const c of candidates) {
3754
+ let insertIdx = -1;
3755
+ let pageFirstIdx = -1;
3756
+ let pageLastIdx = -1;
3757
+ for (let i = 0; i < blocks.length; i++) {
3758
+ const b = blocks[i];
3759
+ if (b.pageNumber !== pageNumber) continue;
3760
+ if (pageFirstIdx === -1) pageFirstIdx = i;
3761
+ pageLastIdx = i;
3762
+ if (!b.bbox) continue;
3763
+ const blockCenter = b.bbox.y + b.bbox.height / 2;
3764
+ if (blockCenter < c.centerY) {
3765
+ insertIdx = i;
3766
+ break;
3767
+ }
3768
+ }
3769
+ if (insertIdx !== -1) {
3770
+ blocks.splice(insertIdx, 0, c.block);
3771
+ } else if (pageLastIdx !== -1) {
3772
+ blocks.splice(pageLastIdx + 1, 0, c.block);
3773
+ } else {
3774
+ blocks.push(c.block);
3775
+ }
3776
+ insertedCount++;
3777
+ }
3778
+ }
3779
+ if (insertedCount > 0 || removedDupCount > 0) {
3780
+ process.stderr.write(
3781
+ `[kordoc-formula] ${insertedCount}\uAC1C \uC218\uC2DD \uC0BD\uC785, ${removedDupCount}\uAC1C \uC911\uBCF5 block \uC81C\uAC70 (${pagesResult.length}\uAC1C \uD398\uC774\uC9C0)
3782
+ `
3783
+ );
3784
+ }
3785
+ } finally {
3786
+ await pipeline.destroy().catch(() => {
3787
+ });
3788
+ }
3789
+ }
3790
+ function formatMb(bytes) {
3791
+ return `${(bytes / 1024 / 1024).toFixed(1)}MB`;
3792
+ }
3793
+ function ocrImageRegions(regions, large, all) {
3794
+ if (all) return regions;
3795
+ const out = /* @__PURE__ */ new Map();
3796
+ for (const [p, rs] of regions) {
3797
+ const big = rs.filter((r) => large.has(r));
3798
+ if (big.length) out.set(p, big);
3799
+ }
3800
+ return out;
3801
+ }
3802
+ var MAX_PAGES = 5e3;
3803
+ var MAX_TOTAL_TEXT = 100 * 1024 * 1024;
3804
+ async function loadPdf(buffer) {
3805
+ try {
3806
+ return await openHayro(new Uint8Array(buffer));
3807
+ } catch (e) {
3808
+ if (!(e instanceof HayroOpenError)) throw e;
3809
+ throw new KordocError(e.reason === "password" ? "\uC554\uD638\uB85C \uBCF4\uD638\uB41C PDF \uD30C\uC77C\uC785\uB2C8\uB2E4 (PDF \uC5F4\uAE30 \uC554\uD638\uB294 \uC9C0\uC6D0\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4)" : e.reason === "encryption" ? "\uC9C0\uC6D0\uD558\uC9C0 \uC54A\uB294 PDF \uC554\uD638\uD654\uC785\uB2C8\uB2E4" : "PDF \uD30C\uC77C\uC744 \uC77D\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4");
3810
+ }
3811
+ }
3812
+ async function parsePdfDocument(buffer, options) {
3813
+ const formulaBuffer = options?.formulaOcr ? buffer : null;
3814
+ const ocrOptionError = validateOcrOptions(options);
3815
+ if (ocrOptionError) throw new KordocError(ocrOptionError);
3816
+ const autoOcr = options?.ocr === void 0 && await ocrModelsCached(resolveOcrModels(options)) && (options?.ocrRec !== "auto" || await ocrModelsCached(handwritingFallbackModels(resolveOcrModels(options))));
3817
+ const ocrBuffer = options?.ocr || autoOcr ? buffer : null;
3818
+ const doc = await loadPdf(buffer);
3819
+ const imageObjs = { get(id, cb) {
3820
+ const v = doc.image(id);
3821
+ cb?.(v);
3822
+ return v;
3823
+ } };
3824
+ const imagePage = { objs: imageObjs, commonObjs: imageObjs };
3825
+ const fontObjs = /* @__PURE__ */ new Map();
3826
+ const fontObj = (key) => {
3827
+ if (!key.startsWith("hy_")) return void 0;
3828
+ if (!fontObjs.has(key)) {
3829
+ try {
3830
+ const info = hayroFontInfo(doc, key);
3831
+ if (!info) fontObjs.set(key, null);
3832
+ else {
3833
+ const differences = [], map = [];
3834
+ for (const [c, n] of info.differences) differences[c] = n;
3835
+ for (const [c, u] of info.toUnicode) map[c] = u;
3836
+ fontObjs.set(key, { name: info.name, isType3Font: info.subtype === "Type3", composite: info.composite, differences, toUnicode: { _map: map }, data: hayroFontData(doc.fontFile(key)) });
3837
+ }
3838
+ } catch {
3839
+ fontObjs.set(key, null);
3840
+ }
3841
+ }
3842
+ return fontObjs.get(key);
3843
+ };
3844
+ try {
3845
+ const pageCount = doc.pageCount();
3846
+ if (pageCount === 0) throw new KordocError("PDF\uC5D0 \uD398\uC774\uC9C0\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4.");
3847
+ const metadata = { pageCount, pageMode: "layout" };
3848
+ const info = pdfInfo(doc);
3849
+ extractPdfMetadata(info, metadata);
3850
+ const blocks = [];
3851
+ const warnings = [];
3852
+ const pageQuality = [];
3853
+ let totalChars = 0;
3854
+ let totalTextBytes = 0;
3855
+ const effectivePageCount = Math.min(pageCount, MAX_PAGES);
3856
+ const pageFilter = options?.pages ? parsePageRange(options.pages, effectivePageCount) : null;
3857
+ if (pageCount > MAX_PAGES && (!options?.pages || hasRequestedPagesAfter(options.pages, MAX_PAGES, pageCount))) {
3858
+ warnings.push({ message: `${pageCount}\uCABD \uC911 \uC55E ${MAX_PAGES}\uCABD\uB9CC \uD30C\uC2F1\uD588\uC2B5\uB2C8\uB2E4 (\uCABD \uC218 \uC0C1\uD55C)`, code: "PARTIAL_PARSE" });
3859
+ }
3860
+ const totalTarget = pageFilter ? pageFilter.size : effectivePageCount;
3861
+ const fontSizeFreq = /* @__PURE__ */ new Map();
3862
+ const pageHeights = /* @__PURE__ */ new Map();
3863
+ const pageWidths = /* @__PURE__ */ new Map();
3864
+ const faceNames = /* @__PURE__ */ new Map();
3865
+ const pagesWithLargeImage = /* @__PURE__ */ new Set();
3866
+ const skippedImagePages = /* @__PURE__ */ new Map();
3867
+ const uncoveredImageRegions = /* @__PURE__ */ new Map();
3868
+ const largeImageRegions = /* @__PURE__ */ new Set();
3869
+ const wantWebp = options?.imageFormat === "webp" && options.images !== false;
3870
+ const encodeWebp = wantWebp ? await loadWebpEncoder() : null;
3871
+ if (wantWebp && !encodeWebp) warnings.push(WEBP_UNAVAILABLE);
3872
+ const imageState = createPdfImageState(encodeWebp ?? void 0, options?.imagePlacement === "flow", !!options?.dropBlankImages && options?.images !== false);
3873
+ const readQr = options?.qrCodes ? await loadQrReader() : null;
3874
+ if (options?.qrCodes && !readQr) warnings.push(QR_UNAVAILABLE);
3875
+ const imageBulletShapes = /* @__PURE__ */ new Map();
3876
+ const imageArrowDirections = /* @__PURE__ */ new Map();
3877
+ const extractedImages = [];
3878
+ const pageImageBlocks = /* @__PURE__ */ new Map();
3879
+ const carry = {};
3880
+ const hancomPdf = isHancomPdf(info);
3881
+ const preciseGaps = hancomPdf || isPreciseGapProducer(info);
3882
+ const vectorPageOps = /* @__PURE__ */ new Map();
3883
+ const wrapLexicon = new WrapLexicon();
3884
+ const noteMarks = /* @__PURE__ */ new Map();
3885
+ const headerContext = [];
3886
+ if (pageFilter && options?.removeHeaderFooter !== false && pageFilter.size < effectivePageCount) {
3887
+ for (const number of selectionContextPages(pageFilter, effectivePageCount)) {
3888
+ try {
3889
+ const view = doc.pageView(number - 1);
3890
+ const content = hayroTextPage(doc, number);
3891
+ pageHeights.set(number, view[3] - view[1]);
3892
+ headerContext.push(...marginContextBlocks(content.items, number, view));
3893
+ } catch {
3894
+ }
3895
+ }
3896
+ }
3897
+ let parsedPages = 0;
3898
+ for (let i = 1; i <= effectivePageCount; i++) {
3899
+ if (pageFilter && !pageFilter.has(i)) continue;
3900
+ try {
3901
+ const page = hayroTextPage(doc, i);
3902
+ const rotate = doc.pageRotate(i - 1);
3903
+ const [viewX1, viewY1, viewX2, viewY2] = doc.pageView(i - 1);
3904
+ const pageW = viewX2 - viewX1, pageH = viewY2 - viewY1;
3905
+ pageHeights.set(i, pageH);
3906
+ pageWidths.set(i, pageW);
3907
+ const rawItems = page.items;
3908
+ const rawOps = hayroOps(page.events, page.strings);
3909
+ const differencesOf = (loadedName) => fontObj(loadedName)?.differences;
3910
+ const occluded = occludedTextItems(rawItems, rawOps.fnArray, rawOps.argsArray);
3911
+ markTrailingSpaceGlyphs(rawItems, rawOps.fnArray, rawOps.argsArray);
3912
+ const restoreSoftHyphens = softHyphenHeads(rawItems, rawOps.fnArray, rawOps.argsArray);
3913
+ restoreNamedGlyphs(rawItems, rawOps.fnArray, rawOps.argsArray, differencesOf, (n) => fontObj(n)?.name);
3914
+ restoreUnmappedGlyphs(rawItems, rawOps.fnArray, rawOps.argsArray, (n) => fontObj(n));
3915
+ restoreUnmappedCidSpaces(rawItems, rawOps.fnArray, rawOps.argsArray, (n) => fontObj(n));
3916
+ restoreTrackedSpacing(rawItems, rawOps.fnArray, rawOps.argsArray);
3917
+ markSyntheticSpaces(rawItems, rawOps.fnArray, rawOps.argsArray);
3918
+ if (hancomPdf) joinTrackedHangul(rawItems, rawOps.fnArray, rawOps.argsArray);
3919
+ restoreSoftHyphens();
3920
+ rawItems.push(...spaceMappedDots(rawOps.fnArray, rawOps.argsArray, (n) => fontObj(n)));
3921
+ const items = normalizeItems(occluded.size ? rawItems.filter((it) => !occluded.has(it)) : rawItems);
3922
+ if (!preciseGaps) for (const it of items) {
3923
+ delete it.fx;
3924
+ delete it.fw;
3925
+ }
3926
+ const filtered = filterHiddenText(items, pageW, pageH, viewX1, viewY1);
3927
+ const joined = joinVerticalColumns(filtered.visible);
3928
+ const visible = dropTabLeaderDots(joined);
3929
+ const hiddenCount = filtered.hiddenCount + occluded.size;
3930
+ if (hiddenCount > 0) {
3931
+ warnings.push({ page: i, message: `${hiddenCount}\uAC1C \uC228\uACA8\uC9C4 \uD14D\uC2A4\uD2B8 \uC694\uC18C \uD544\uD130\uB9C1\uB428`, code: "HIDDEN_TEXT_FILTERED" });
3932
+ }
3933
+ for (const item of joined) {
3934
+ if (item.fontSize > 0) fontSizeFreq.set(item.fontSize, (fontSizeFreq.get(item.fontSize) || 0) + 1);
3935
+ }
3936
+ mergeEnclosedDigits(visible);
3937
+ try {
3938
+ applyLinkAnnotations(visible, pdfLinkAnnotations(doc, i - 1));
3939
+ } catch {
3940
+ }
3941
+ const shifted = viewX1 !== 0 || viewY1 !== 0;
3942
+ if (shifted) for (const item of visible) {
3943
+ item.x -= viewX1;
3944
+ item.y -= viewY1;
3945
+ }
3946
+ const opList = shifted ? {
3947
+ fnArray: [OPS.transform, ...rawOps.fnArray],
3948
+ argsArray: [[1, 0, 0, 1, -viewX1, -viewY1], ...rawOps.argsArray]
3949
+ } : rawOps;
3950
+ remapSymbolFontItems(visible, (loadedName) => fontObj(loadedName)?.name);
3951
+ remapControlGlyphs(visible, differencesOf);
3952
+ await restoreImageBullets(visible, imagePage, opList.fnArray, opList.argsArray, imageBulletShapes);
3953
+ restoreVectorBullets(visible, opList.fnArray, opList.argsArray);
3954
+ const faces = /* @__PURE__ */ new Map();
3955
+ for (const it of visible) {
3956
+ if (!it.fontName) continue;
3957
+ let face = faces.get(it.fontName);
3958
+ if (face === void 0) {
3959
+ const obj = fontObj(it.fontName);
3960
+ face = obj?.isType3Font && /^[A-Z]{6}\+./.test(obj.name ?? "") && obj.name.slice(7) || it.fontName;
3961
+ faces.set(it.fontName, face);
3962
+ }
3963
+ it.fontName = face;
3964
+ if (!faceNames.has(face)) faceNames.set(face, (fontObj(face)?.name ?? "").replace(/^[A-Z]{6}\+/, ""));
3965
+ }
3966
+ for (const it of visible) if (it.text.includes("$")) it.text = escapeLiteralDollar(it.text);
3967
+ for (const it of visible) if (it.text.includes("<")) it.text = escapeLiteralTags(it.text);
3968
+ wrapEquationRuns(visible, (face) => faceNames.get(face));
3969
+ const pageArea = pageW * pageH;
3970
+ if (pageArea > 0) {
3971
+ const imageRegions = extractImageRegions(opList.fnArray, opList.argsArray);
3972
+ let uncovered = 0;
3973
+ for (const r of imageRegions) {
3974
+ const area = (r.x2 - r.x1) * (r.y2 - r.y1);
3975
+ const headerLogo = area >= pageArea * 5e-3 && r.y1 >= pageH * 0.8;
3976
+ const textStrip = area >= pageArea * 5e-3 && r.x2 - r.x1 >= (r.y2 - r.y1) * 6 && r.y2 - r.y1 <= pageH * 0.04;
3977
+ if (area < pageArea * 0.02 && !headerLogo && !textStrip) continue;
3978
+ const large = area >= pageArea * 0.05;
3979
+ if (large) pagesWithLargeImage.add(i);
3980
+ const hasText2 = visible.some((it) => {
3981
+ const cx = it.x + it.w / 2;
3982
+ const cy = it.y + (it.h || it.fontSize) / 2;
3983
+ return cx >= r.x1 && cx <= r.x2 && cy >= r.y1 && cy <= r.y2;
3984
+ });
3985
+ if (!hasText2) {
3986
+ if (large) uncovered++;
3987
+ if (rotate % 360 === 0 && viewX1 === 0 && viewY1 === 0) {
3988
+ const regions = uncoveredImageRegions.get(i) ?? [];
3989
+ regions.push(r);
3990
+ uncoveredImageRegions.set(i, regions);
3991
+ if (large) largeImageRegions.add(r);
3992
+ }
3993
+ }
3994
+ }
3995
+ if (uncovered > 0) skippedImagePages.set(i, uncovered);
3996
+ }
3997
+ const marks = superscriptNoteMarks(visible);
3998
+ if (marks.length) noteMarks.set(i, { marks, seps: footnoteSeparators(extractLines(opList.fnArray, opList.argsArray).horizontals, pageW, pageH) });
3999
+ const stamp = marginStamp(visible);
4000
+ const flow = stamp.length ? visible.filter((it) => !stamp.includes(it)) : visible;
4001
+ const rightArrows = options?.tables !== false ? await detectRightArrowRegions(imagePage, opList.fnArray, opList.argsArray, imageArrowDirections) : [];
4002
+ const pageBlocks = orderTwoUpPage(extractPageBlocksWithLines(flow, i, opList, pageW, pageH, void 0, options?.tables !== false, carry, wrapLexicon, rightArrows), pageW, pageH);
4003
+ if (stamp.length) pageBlocks.unshift({ type: "paragraph", text: [...stamp].sort((a, b) => a.y - b.y).map((it) => it.text).join(" "), pageNumber: i });
4004
+ for (const b of pageBlocks) blocks.push(b);
4005
+ try {
4006
+ const { blocks: imgBlocks, images: pageImages2 } = await extractPageImages(imagePage, opList.fnArray, opList.argsArray, i, imageState, warnings, options?.images !== false, readQr ?? void 0);
4007
+ if (imgBlocks.length > 0) pageImageBlocks.set(i, imgBlocks);
4008
+ extractedImages.push(...pageImages2);
4009
+ } catch {
4010
+ }
4011
+ let pageText = "";
4012
+ for (const b of pageBlocks) {
4013
+ let t = b.text || "";
4014
+ if (b.type === "table" && b.table) {
4015
+ const cellText = b.table.cells.map((row) => row.map((c) => c.text).join(" ")).join("\n");
4016
+ t = t ? t + "\n" + cellText : cellText;
4017
+ }
4018
+ totalChars += t.replace(/\s/g, "").length;
4019
+ totalTextBytes += t.length * 2;
4020
+ pageText += pageText ? "\n" + t : t;
4021
+ }
4022
+ const vector = scanVectorGlyphs(opList.fnArray, opList.argsArray, visible);
4023
+ const quality = computePageQuality(i, pageText, vector.glyphs);
4024
+ pageQuality.push(quality);
4025
+ if (options?.ocr && quality.ocrReason === "vector_text" && rotate % 360 === 0 && viewX1 === 0 && viewY1 === 0) {
4026
+ vectorPageOps.set(i, ocrVectorOps(opList, vector.paths));
4027
+ }
4028
+ if (totalTextBytes > MAX_TOTAL_TEXT) throw new KordocError("\uD14D\uC2A4\uD2B8 \uCD94\uCD9C \uD06C\uAE30 \uCD08\uACFC");
4029
+ parsedPages++;
4030
+ options?.onProgress?.(parsedPages, totalTarget);
4031
+ } catch (pageErr) {
4032
+ if (pageErr instanceof KordocError) throw pageErr;
4033
+ warnings.push({ page: i, message: `\uD398\uC774\uC9C0 ${i} \uD30C\uC2F1 \uC2E4\uD328: ${pageErr instanceof Error ? pageErr.message : "\uC54C \uC218 \uC5C6\uB294 \uC624\uB958"}`, code: "PARTIAL_PARSE" });
4034
+ }
4035
+ }
4036
+ const parsedPageCount = parsedPages || (pageFilter ? pageFilter.size : effectivePageCount);
4037
+ const isImageBased = pageFilter?.size !== 0 && totalChars / Math.max(parsedPageCount, 1) < 10;
4038
+ const ocrDone = /* @__PURE__ */ new Set();
4039
+ const ocrLinesOut = /* @__PURE__ */ new Map();
4040
+ const pageRasters = options?.pageImages ? new (await import("./page-images-VCIFZAXK-KJLWQDRH.js")).PageImageSink(options.pageImages) : null;
4041
+ const allRegions = options?.ocr === true || typeof options?.ocr === "function";
4042
+ const ocrRegions = allRegions || autoOcr ? ocrImageRegions(uncoveredImageRegions, largeImageRegions, allRegions) : /* @__PURE__ */ new Map();
4043
+ if (ocrBuffer) {
4044
+ const inScope = (p) => !pageFilter || pageFilter.has(p);
4045
+ const targets = /* @__PURE__ */ new Set();
4046
+ if (options?.ocr === "force" || isImageBased) {
4047
+ for (let i = 1; i <= effectivePageCount; i++) if (inScope(i)) targets.add(i);
4048
+ } else {
4049
+ for (const pq of pageQuality) {
4050
+ if (!pq.needsOcr) continue;
4051
+ if (pq.ocrReason === "low_text" && !pagesWithLargeImage.has(pq.page)) continue;
4052
+ if (autoOcr && pq.ocrReason !== "low_text" && pq.ocrReason !== "vector_text") continue;
4053
+ targets.add(pq.page);
4054
+ }
4055
+ for (const p of ocrRegions.keys()) targets.add(p);
4056
+ }
4057
+ if (targets.size > 0) {
4058
+ try {
4059
+ const { runPdfOcr } = await import("./pdf-ocr-C3MBR6J2-J3UGJKWT.js");
4060
+ const mode = typeof options?.ocr === "function" ? options.ocr : "builtin";
4061
+ const regionPages = new Map([...ocrRegions].filter(([p]) => options?.ocr !== "force" && !isImageBased && !pageQuality.find((q) => q.page === p)?.needsOcr));
4062
+ const { builtinOcrConfig } = await import("./pdf-ocr-C3MBR6J2-J3UGJKWT.js");
4063
+ const ocrPageBlocks = await runPdfOcr(ocrBuffer, targets, mode, warnings, options?.onProgress, options?.tables !== false, vectorPageOps, regionPages, builtinOcrConfig(options), ocrLinesOut, pageRasters ?? void 0);
4064
+ for (const obs of ocrPageBlocks.values()) stripScriptTags({ blocks: obs });
4065
+ if (ocrPageBlocks.size > 0) {
4066
+ const replacePages = /* @__PURE__ */ new Set();
4067
+ for (const [p, obs] of ocrPageBlocks) {
4068
+ const needsOcr = pageQuality.find((q) => q.page === p)?.needsOcr;
4069
+ if (options?.ocr === "force" || isImageBased || needsOcr) {
4070
+ replacePages.add(p);
4071
+ ocrDone.add(p);
4072
+ continue;
4073
+ }
4074
+ const regions = ocrRegions.get(p);
4075
+ if (!regions || mergeOcrImageRegions(blocks, p, regions, obs) === 0) continue;
4076
+ ocrDone.add(p);
4077
+ if (pageImageBlocks.get(p)?.length === 1) pageImageBlocks.delete(p);
4078
+ }
4079
+ if (replacePages.size) {
4080
+ const merged = blocks.filter((b) => !(b.pageNumber && replacePages.has(b.pageNumber)));
4081
+ for (const [p, obs] of ocrPageBlocks) if (replacePages.has(p)) merged.push(...obs);
4082
+ merged.sort((a, b) => (a.pageNumber ?? 0) - (b.pageNumber ?? 0));
4083
+ blocks.length = 0;
4084
+ blocks.push(...merged);
4085
+ }
4086
+ for (const pq of pageQuality) if (ocrDone.has(pq.page)) pq.ocrApplied = true;
4087
+ warnings.push({
4088
+ message: `${ocrDone.size}\uAC1C \uD398\uC774\uC9C0\uC5D0 OCR \uC801\uC6A9 (${mode === "builtin" ? "\uB0B4\uC7A5 PP-OCRv5" : "\uC0AC\uC6A9\uC790 \uD504\uB85C\uBC14\uC774\uB354"})`,
4089
+ code: "OCR_APPLIED"
4090
+ });
4091
+ }
4092
+ } catch (e) {
4093
+ warnings.push({
4094
+ message: `OCR \uC2E4\uD589 \uBD88\uAC00: ${e instanceof Error ? e.message : String(e)}`,
4095
+ code: "OCR_FAILED"
4096
+ });
4097
+ }
4098
+ }
4099
+ }
4100
+ if (pageRasters) {
4101
+ const rest = [];
4102
+ for (let i = 1; i <= effectivePageCount; i++) if ((!pageFilter || pageFilter.has(i)) && !pageRasters.has(i)) rest.push(i);
4103
+ try {
4104
+ const { renderPdfPageImages } = await import("./pdf-ocr-C3MBR6J2-J3UGJKWT.js");
4105
+ await renderPdfPageImages(buffer, rest, pageRasters, warnings);
4106
+ } catch (e) {
4107
+ warnings.push({ message: `pageImages \uC2E4\uD589 \uBD88\uAC00: ${e instanceof Error ? e.message : String(e)}`, code: "SKIPPED_IMAGE" });
4108
+ }
4109
+ }
4110
+ const pageImages = pageRasters?.finish(warnings);
4111
+ if (isImageBased && ocrDone.size === 0) {
4112
+ warnings.push({
4113
+ message: `\uC774\uBBF8\uC9C0 \uAE30\uBC18 PDF (${pageCount}\uD398\uC774\uC9C0, \uD14D\uC2A4\uD2B8 ${totalChars}\uC790) \u2014 \uD14D\uC2A4\uD2B8 \uB808\uC774\uC5B4\uAC00 \uC5C6\uC5B4 OCR\uC774 \uD544\uC694\uD569\uB2C8\uB2E4. ocr: true (CLI --ocr) \uB85C \uB2E4\uC2DC \uD30C\uC2F1\uD558\uBA74 \uC77D\uC2B5\uB2C8\uB2E4`,
4114
+ code: "NEEDS_OCR"
4115
+ });
4116
+ }
4117
+ if (!isImageBased) {
4118
+ const OCR_REASON_MESSAGES = {
4119
+ vector_text: "\uAE00\uC790\uB97C \uACE1\uC120(\uBCA1\uD130 \uACBD\uB85C)\uC73C\uB85C \uADF8\uB9B0 \uD398\uC774\uC9C0 (\uD14D\uC2A4\uD2B8\uCE35\uC5D0 \uAE00\uC790 \uC5C6\uC74C)",
4120
+ low_text: "\uD14D\uC2A4\uD2B8\uAC00 \uAC70\uC758 \uC5C6\uB294 \uD398\uC774\uC9C0 (\uC2A4\uCE94/\uC774\uBBF8\uC9C0 \uCD94\uC815)",
4121
+ high_pua: "\uAE00\uAF34 \uB9E4\uD551 \uC2E4\uD328 (PUA \uBE44\uC728 \uB192\uC74C) \u2014 \uCD94\uCD9C \uD14D\uC2A4\uD2B8 \uC2E0\uB8B0 \uBD88\uAC00",
4122
+ high_control: "\uC81C\uC5B4\uBB38\uC790 \uBE44\uC728 \uB192\uC74C \u2014 \uCD94\uCD9C \uD14D\uC2A4\uD2B8 \uC2E0\uB8B0 \uBD88\uAC00",
4123
+ high_replacement: "\uB300\uCCB4\uBB38\uC790(U+FFFD) \uBE44\uC728 \uB192\uC74C \u2014 \uCD94\uCD9C \uD14D\uC2A4\uD2B8 \uC2E0\uB8B0 \uBD88\uAC00",
4124
+ garbled_hangul: "\uAE00\uAF34 \uB9E4\uD551 \uC2E4\uD328 (\uD55C\uAE00 \uC790\uC18C \uBD84\uD3EC \uC774\uC0C1) \u2014 \uCD94\uCD9C \uD14D\uC2A4\uD2B8\uAC00 \uAE68\uC84C\uC744 \uC218 \uC788\uC74C"
4125
+ };
4126
+ for (const pq of pageQuality) {
4127
+ if (!pq.needsOcr || !pq.ocrReason || pq.ocrApplied) continue;
4128
+ if (pq.ocrReason === "low_text" && !pagesWithLargeImage.has(pq.page)) continue;
4129
+ warnings.push({ page: pq.page, message: `${OCR_REASON_MESSAGES[pq.ocrReason]} \u2014 OCR \uAC80\uD1A0 \uD544\uC694 (ocr: true / CLI --ocr \uB85C \uB2E4\uC2DC \uD30C\uC2F1)`, code: "NEEDS_OCR" });
4130
+ }
4131
+ }
4132
+ if (!isImageBased) {
4133
+ for (const [page, count] of [...skippedImagePages.entries()].sort((a, b) => a[0] - b[0])) {
4134
+ if (ocrDone.has(page)) continue;
4135
+ warnings.push({ page, message: `${count}\uAC1C \uC774\uBBF8\uC9C0 \uC601\uC5ED\uC5D0 \uCD94\uCD9C \uAC00\uB2A5\uD55C \uD14D\uC2A4\uD2B8 \uC5C6\uC74C (\uADF8\uB9BC/\uCC28\uD2B8/\uB3C4\uC7A5 \uB0B4\uC6A9 \uB204\uB77D \uAC00\uB2A5 \u2014 \uADF8\uB9BC \uC18D \uAE00\uC740 ocr: true / CLI --ocr \uB85C \uC77D\uC2B5\uB2C8\uB2E4)`, code: "SKIPPED_IMAGE" });
4136
+ }
4137
+ }
4138
+ if (options?.removeHeaderFooter !== false && (parsedPageCount >= 3 || headerContext.length)) {
4139
+ const removed = removeHeaderFooterBlocks(blocks, pageHeights, warnings, noteMarks, false, headerContext);
4140
+ const running = runningLinePatterns(removed.map((ri) => blocks[ri]), pageHeights);
4141
+ for (let ri = removed.length - 1; ri >= 0; ri--) {
4142
+ blocks.splice(removed[ri], 1);
4143
+ }
4144
+ const stripped = stripAbsorbedRunningLines(blocks, pageHeights, running);
4145
+ if (stripped !== blocks) {
4146
+ blocks.length = 0;
4147
+ blocks.push(...stripped);
4148
+ }
4149
+ const kept = removeSideTabs(blocks, pageWidths);
4150
+ if (kept !== blocks) {
4151
+ blocks.length = 0;
4152
+ blocks.push(...kept);
4153
+ }
4154
+ }
4155
+ mergeContinuedCells(blocks, pageHeights);
4156
+ mergeCrossPageTables(blocks, pageHeights, wrapLexicon);
4157
+ if (options?.removeHeaderFooter !== false && parsedPageCount >= 3) {
4158
+ const boxes = removeHeaderFooterBlocks(blocks, pageHeights, warnings, noteMarks, true);
4159
+ for (let ri = boxes.length - 1; ri >= 0; ri--) blocks.splice(boxes[ri], 1);
4160
+ }
4161
+ splitContactTables(blocks);
4162
+ if (!options?.keepTrailingEmptyCols) trimTrailingEmptyTableCols(blocks);
4163
+ joinPageBreakWraps(blocks, wrapLexicon);
4164
+ await flushPdfImages(imageState, warnings, pageImageBlocks, extractedImages);
4165
+ injectPageImageBlocks(blocks, pageImageBlocks);
4166
+ if (options?.formulaOcr && formulaBuffer) {
4167
+ try {
4168
+ await applyFormulaOcr(formulaBuffer, blocks, pageFilter, effectivePageCount, warnings, options.onProgress);
4169
+ } catch (e) {
4170
+ warnings.push({
4171
+ message: `\uC218\uC2DD OCR \uC2E4\uD328: ${e instanceof Error ? e.message : String(e)}`,
4172
+ code: "PARTIAL_PARSE"
4173
+ });
4174
+ }
4175
+ }
4176
+ const medianFontSize = computeMedianFontSizeFromFreq(fontSizeFreq);
4177
+ if (medianFontSize > 0) {
4178
+ detectHeadings(blocks, medianFontSize);
4179
+ }
4180
+ detectDocumentStyleHeadings(blocks);
4181
+ detectTypographyHeadings(blocks);
4182
+ detectSiblingStyleHeadings(blocks);
4183
+ detectRepeatedPageLabels(blocks);
4184
+ detectPageLeadHeadings(blocks);
4185
+ mergeStackedHeadingLines(blocks, medianFontSize);
4186
+ refineDocumentStyleHeadings(blocks);
4187
+ detectMarkerHeadings(blocks);
4188
+ demoteNonHeadingRoles(blocks, pageHeights, faceNames);
4189
+ detectTableCaptions(blocks);
4190
+ detectKoreanListBlocks(blocks);
4191
+ sanitizeBlockControlChars(blocks);
4192
+ if (options?.imagePlacement === "flow") moveImagesInFlow(blocks);
4193
+ let outBlocks = splitSingleCellTables(blocks);
4194
+ if (options?.layoutTables !== "keep") {
4195
+ blocks.length = 0;
4196
+ for (const block of outBlocks) blocks.push(block);
4197
+ }
4198
+ outBlocks = inlineFootnotes(outBlocks, noteMarks);
4199
+ outBlocks = relocateEndnotes(outBlocks);
4200
+ if (options?.removeHeaderFooter !== false) outBlocks = outBlocks.filter((b) => {
4201
+ if (b.type !== "paragraph" || !/^\s*\d{1,4}\s*$/.test(b.text ?? "")) return true;
4202
+ const h = pageHeights.get(b.pageNumber ?? 0);
4203
+ if (!b.bbox || !h) return false;
4204
+ return b.bbox.y > h * 0.1 && b.bbox.y + b.bbox.height < h * 0.9;
4205
+ });
4206
+ joinLatinCellWraps(outBlocks);
4207
+ if (options?.layoutTables !== "keep") {
4208
+ const hancom = isHancomPdf(info);
4209
+ const shown = /* @__PURE__ */ new Map();
4210
+ const markContent = (bs) => {
4211
+ for (const b of bs ?? []) if (b.table) for (const row of b.table.cells) for (const c of row) {
4212
+ if (IMAGE_CELLS.has(c)) CONTENT_CELLS.add(c);
4213
+ const lines = CELL_LINES.get(c);
4214
+ if (lines) CELL_BASELINES.set(c, lines.map((l) => l.y));
4215
+ markContent(c.blocks);
4216
+ }
4217
+ };
4218
+ const visual = (bs) => bs.flatMap((b) => {
4219
+ if (b.type !== "table") return [b];
4220
+ if (!hancom && b.table && CLIP_TABLES.has(b.table)) return [b];
4221
+ let v = shown.get(b);
4222
+ if (!v) {
4223
+ markContent([b]);
4224
+ shown.set(b, v = unframeLayoutTables([b], !!options?.keepTrailingEmptyCols));
4225
+ }
4226
+ return v;
4227
+ });
4228
+ outBlocks = visual(outBlocks);
4229
+ const kept = visual(blocks);
4230
+ blocks.length = 0;
4231
+ for (const b of kept) blocks.push(b);
4232
+ }
4233
+ const finishMarkdown = (bs) => mergeLinkRuns(cleanPdfText(blocksToMarkdown(bs, { tableFormat: options?.tableFormat }), { keepLoneNumbers: true }));
4234
+ if (options?.tableFormat === "gfm") assignTableIds(blocks);
4235
+ let markdown = finishMarkdown(outBlocks);
4236
+ const outline = collectPdfOutline(outBlocks);
4237
+ return {
4238
+ markdown,
4239
+ pages: blocksToPages(splitPageTables(splitPageBreakWraps(outBlocks)), finishMarkdown),
4240
+ blocks,
4241
+ metadata,
4242
+ outline: outline.length > 0 ? outline : void 0,
4243
+ warnings: warnings.length > 0 ? warnings : void 0,
4244
+ isImageBased: isImageBased || void 0,
4245
+ pageQuality,
4246
+ qualitySummary: summarizeDocumentQuality(pageQuality),
4247
+ images: extractedImages.length > 0 ? extractedImages : void 0,
4248
+ ...options?.ocrLines ? { ocrLines: [...ocrLinesOut.values()].sort((a, b) => a.pageNumber - b.pageNumber) } : {},
4249
+ ...pageImages ? { pageImages } : {}
4250
+ };
4251
+ } finally {
4252
+ doc.close();
4253
+ }
4254
+ }
4255
+ function extractPdfMetadata(info, metadata) {
4256
+ if (info.Title?.trim()) metadata.title = info.Title.trim();
4257
+ if (info.Author?.trim()) metadata.author = info.Author.trim();
4258
+ if (info.Creator?.trim()) metadata.creator = info.Creator.trim();
4259
+ if (info.Subject?.trim()) metadata.description = info.Subject.trim();
4260
+ if (info.Keywords?.trim()) {
4261
+ metadata.keywords = info.Keywords.split(/[,;]/).map((k) => k.trim()).filter(Boolean);
4262
+ }
4263
+ if (typeof info.CreationDate === "string") metadata.createdAt = parsePdfDate(info.CreationDate);
4264
+ if (typeof info.ModDate === "string") metadata.modifiedAt = parsePdfDate(info.ModDate);
4265
+ }
4266
+ function isHancomPdf(info) {
4267
+ return [info.Producer, info.Creator].some((v) => typeof v === "string" && /^\s*(?:hancom\b|hwp\b)/i.test(v));
4268
+ }
4269
+ function isPreciseGapProducer(info) {
4270
+ return [info.Producer, info.Creator].some((v) => typeof v === "string" && /^\s*(?:microsoft: print to pdf|libreoffice)\b/i.test(v));
4271
+ }
4272
+ function parsePdfDate(dateStr) {
4273
+ const m = dateStr.match(/D:(\d{4})(\d{2})?(\d{2})?(\d{2})?(\d{2})?(\d{2})?/);
4274
+ if (!m) return void 0;
4275
+ const [, year, month = "01", day = "01", hour = "00", min = "00", sec = "00"] = m;
4276
+ return `${year}-${month}-${day}T${hour}:${min}:${sec}`;
4277
+ }
4278
+ async function extractPdfMetadataOnly(buffer) {
4279
+ const doc = await loadPdf(buffer);
4280
+ try {
4281
+ const metadata = { pageCount: doc.pageCount() };
4282
+ extractPdfMetadata(pdfInfo(doc), metadata);
4283
+ return metadata;
4284
+ } finally {
4285
+ doc.close();
4286
+ }
4287
+ }
4288
+ function marginStamp(items) {
4289
+ const rotated = items.filter((it) => it.rotated);
4290
+ if (rotated.length === 0) return [];
4291
+ const flat = items.filter((it) => !it.rotated);
4292
+ if (flat.length < 20) return [];
4293
+ const outside = (it) => {
4294
+ const x1 = it.x - it.fontSize, x2 = it.x + it.w + it.fontSize;
4295
+ const beside = flat.filter((f) => f.y >= it.y && f.y <= it.y + it.rotated);
4296
+ return beside.length >= 5 && (beside.every((f) => f.x >= x2) || beside.every((f) => f.x + f.w <= x1));
4297
+ };
4298
+ return rotated.every(outside) ? rotated : [];
4299
+ }
4300
+ export {
4301
+ cleanPdfText,
4302
+ detectKoreanListBlocks,
4303
+ detectTableCaptions,
4304
+ extractPdfMetadataOnly,
4305
+ isPreciseGapProducer,
4306
+ mergeCrossPageTables,
4307
+ ocrImageRegions,
4308
+ parsePdfDocument,
4309
+ removeHeaderFooterBlocks
4310
+ };