@bendyline/squisq-formats 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.
- package/dist/chunk-532L4D5D.js +21 -0
- package/dist/chunk-532L4D5D.js.map +1 -0
- package/dist/chunk-67KIJHV2.js +21 -0
- package/dist/chunk-67KIJHV2.js.map +1 -0
- package/dist/chunk-KAK4V57E.js +387 -0
- package/dist/chunk-KAK4V57E.js.map +1 -0
- package/dist/chunk-MQHCXI56.js +1035 -0
- package/dist/chunk-MQHCXI56.js.map +1 -0
- package/dist/chunk-TBPD5PCU.js +1136 -0
- package/dist/chunk-TBPD5PCU.js.map +1 -0
- package/dist/chunk-ULLIPBEJ.js +271 -0
- package/dist/chunk-ULLIPBEJ.js.map +1 -0
- package/dist/docx/index.d.ts +108 -0
- package/dist/docx/index.js +14 -0
- package/dist/docx/index.js.map +1 -0
- package/dist/html/index.d.ts +166 -0
- package/dist/html/index.js +17 -0
- package/dist/html/index.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +54 -0
- package/dist/index.js.map +1 -0
- package/dist/ooxml/index.d.ts +351 -0
- package/dist/ooxml/index.js +99 -0
- package/dist/ooxml/index.js.map +1 -0
- package/dist/pdf/index.d.ts +130 -0
- package/dist/pdf/index.js +15 -0
- package/dist/pdf/index.js.map +1 -0
- package/dist/pptx/index.d.ts +58 -0
- package/dist/pptx/index.js +13 -0
- package/dist/pptx/index.js.map +1 -0
- package/dist/xlsx/index.d.ts +58 -0
- package/dist/xlsx/index.js +13 -0
- package/dist/xlsx/index.js.map +1 -0
- package/package.json +85 -0
- package/src/__tests__/docxExport.test.ts +457 -0
- package/src/__tests__/docxImport.test.ts +410 -0
- package/src/__tests__/html.test.ts +295 -0
- package/src/__tests__/ooxml.test.ts +197 -0
- package/src/__tests__/pdfExport.test.ts +322 -0
- package/src/__tests__/pdfImport.test.ts +290 -0
- package/src/__tests__/roundTrip.test.ts +201 -0
- package/src/docx/export.ts +978 -0
- package/src/docx/import.ts +909 -0
- package/src/docx/index.ts +26 -0
- package/src/docx/styles.ts +145 -0
- package/src/html/htmlTemplate.ts +307 -0
- package/src/html/imageUtils.ts +66 -0
- package/src/html/index.ts +168 -0
- package/src/index.ts +51 -0
- package/src/ooxml/index.ts +87 -0
- package/src/ooxml/namespaces.ts +160 -0
- package/src/ooxml/reader.ts +218 -0
- package/src/ooxml/types.ts +104 -0
- package/src/ooxml/writer.ts +321 -0
- package/src/ooxml/xmlUtils.ts +123 -0
- package/src/pdf/export.ts +1029 -0
- package/src/pdf/import.ts +835 -0
- package/src/pdf/index.ts +29 -0
- package/src/pdf/styles.ts +180 -0
- package/src/pptx/index.ts +78 -0
- package/src/xlsx/index.ts +78 -0
|
@@ -0,0 +1,835 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PDF Import
|
|
3
|
+
*
|
|
4
|
+
* Parses a PDF file and converts its content into a squisq
|
|
5
|
+
* MarkdownDocument (or Doc) using heuristic detection of headings,
|
|
6
|
+
* lists, code blocks, tables, blockquotes, and hyperlinks.
|
|
7
|
+
*
|
|
8
|
+
* Uses pdfjs-dist (Mozilla pdf.js) for text extraction — a battle-tested,
|
|
9
|
+
* browser-compatible PDF parser. Since PDFs encode positioned glyphs
|
|
10
|
+
* rather than semantic structure, all structure detection is inherently
|
|
11
|
+
* heuristic and works best on simply-formatted documents.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* import { pdfToMarkdownDoc } from '@bendyline/squisq-formats/pdf';
|
|
16
|
+
*
|
|
17
|
+
* const response = await fetch('document.pdf');
|
|
18
|
+
* const data = await response.arrayBuffer();
|
|
19
|
+
* const doc = await pdfToMarkdownDoc(data);
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import type { Doc } from '@bendyline/squisq/schemas';
|
|
24
|
+
import { markdownToDoc } from '@bendyline/squisq/doc';
|
|
25
|
+
import type {
|
|
26
|
+
MarkdownDocument,
|
|
27
|
+
MarkdownBlockNode,
|
|
28
|
+
MarkdownInlineNode,
|
|
29
|
+
MarkdownHeading,
|
|
30
|
+
MarkdownParagraph,
|
|
31
|
+
MarkdownBlockquote,
|
|
32
|
+
MarkdownList,
|
|
33
|
+
MarkdownListItem,
|
|
34
|
+
MarkdownCodeBlock,
|
|
35
|
+
MarkdownTable,
|
|
36
|
+
MarkdownTableRow,
|
|
37
|
+
MarkdownTableCell,
|
|
38
|
+
MarkdownText,
|
|
39
|
+
MarkdownEmphasis,
|
|
40
|
+
MarkdownStrong,
|
|
41
|
+
MarkdownInlineCode,
|
|
42
|
+
MarkdownLink,
|
|
43
|
+
} from '@bendyline/squisq/markdown';
|
|
44
|
+
|
|
45
|
+
import {
|
|
46
|
+
DEFAULT_FONT_SIZE,
|
|
47
|
+
IMPORT_HEADING_MIN_SIZE,
|
|
48
|
+
IMPORT_HEADING_SIZE_RANGES,
|
|
49
|
+
IMPORT_PARAGRAPH_GAP,
|
|
50
|
+
IMPORT_BULLET_CHARS,
|
|
51
|
+
IMPORT_ORDERED_PREFIX,
|
|
52
|
+
IMPORT_COLUMN_TOLERANCE,
|
|
53
|
+
IMPORT_TABLE_MIN_ROWS,
|
|
54
|
+
IMPORT_URL_PATTERN,
|
|
55
|
+
} from './styles.js';
|
|
56
|
+
|
|
57
|
+
// ============================================
|
|
58
|
+
// Public API
|
|
59
|
+
// ============================================
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Options for PDF import.
|
|
63
|
+
*/
|
|
64
|
+
export interface PdfImportOptions {
|
|
65
|
+
/**
|
|
66
|
+
* Hint for the body font size used in the PDF (in points).
|
|
67
|
+
* Text items larger than this are considered headings.
|
|
68
|
+
* If not provided, the importer detects the most common font size.
|
|
69
|
+
*/
|
|
70
|
+
bodyFontSize?: number;
|
|
71
|
+
|
|
72
|
+
/** Whether to detect tables from column-aligned text. Default: true. */
|
|
73
|
+
detectTables?: boolean;
|
|
74
|
+
|
|
75
|
+
/** Whether to detect code blocks from monospace fonts. Default: true. */
|
|
76
|
+
detectCodeBlocks?: boolean;
|
|
77
|
+
|
|
78
|
+
/** Whether to detect blockquotes from indentation. Default: true. */
|
|
79
|
+
detectBlockquotes?: boolean;
|
|
80
|
+
|
|
81
|
+
/** Whether to detect URLs in text and convert to links. Default: true. */
|
|
82
|
+
detectLinks?: boolean;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Convert a PDF file to a MarkdownDocument.
|
|
87
|
+
*
|
|
88
|
+
* Structure detection is heuristic — results are best-effort.
|
|
89
|
+
*
|
|
90
|
+
* @param data - The raw PDF file as ArrayBuffer, Uint8Array, or Blob
|
|
91
|
+
* @param options - Import options
|
|
92
|
+
* @returns A MarkdownDocument representing the detected content
|
|
93
|
+
*/
|
|
94
|
+
export async function pdfToMarkdownDoc(
|
|
95
|
+
data: ArrayBuffer | Uint8Array | Blob,
|
|
96
|
+
options: PdfImportOptions = {},
|
|
97
|
+
): Promise<MarkdownDocument> {
|
|
98
|
+
const bytes =
|
|
99
|
+
data instanceof Blob
|
|
100
|
+
? new Uint8Array(await data.arrayBuffer())
|
|
101
|
+
: data instanceof ArrayBuffer
|
|
102
|
+
? new Uint8Array(data)
|
|
103
|
+
: data;
|
|
104
|
+
|
|
105
|
+
const textLines = await extractTextLines(bytes);
|
|
106
|
+
|
|
107
|
+
if (textLines.length === 0) {
|
|
108
|
+
return { type: 'document', children: [] };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const bodySize = options.bodyFontSize ?? detectBodyFontSize(textLines);
|
|
112
|
+
const blocks = classifyLines(textLines, bodySize, options);
|
|
113
|
+
|
|
114
|
+
return { type: 'document', children: blocks };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Convert a PDF file to a squisq Doc.
|
|
119
|
+
*
|
|
120
|
+
* Convenience wrapper: PDF → MarkdownDocument → Doc.
|
|
121
|
+
*/
|
|
122
|
+
export async function pdfToDoc(
|
|
123
|
+
data: ArrayBuffer | Uint8Array | Blob,
|
|
124
|
+
options: PdfImportOptions = {},
|
|
125
|
+
): Promise<Doc> {
|
|
126
|
+
const markdownDoc = await pdfToMarkdownDoc(data, options);
|
|
127
|
+
return markdownToDoc(markdownDoc);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// ============================================
|
|
131
|
+
// Internal Types
|
|
132
|
+
// ============================================
|
|
133
|
+
|
|
134
|
+
/** A single text item extracted from pdfjs. */
|
|
135
|
+
interface TextItem {
|
|
136
|
+
str: string;
|
|
137
|
+
x: number;
|
|
138
|
+
y: number;
|
|
139
|
+
width: number;
|
|
140
|
+
height: number;
|
|
141
|
+
/** Internal font ID from pdfjs (e.g. "g_d0_f1") */
|
|
142
|
+
fontName: string;
|
|
143
|
+
/** Resolved font family from pdfjs styles (e.g. "sans-serif", "monospace") */
|
|
144
|
+
fontFamily: string;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** A logical line: text items at roughly the same y-coordinate. */
|
|
148
|
+
interface TextLine {
|
|
149
|
+
items: TextItem[];
|
|
150
|
+
y: number;
|
|
151
|
+
/** The page this line is on (0-based). */
|
|
152
|
+
page: number;
|
|
153
|
+
/** The predominant font size on this line. */
|
|
154
|
+
fontSize: number;
|
|
155
|
+
/** The predominant font family on this line. */
|
|
156
|
+
fontFamily: string;
|
|
157
|
+
/** The predominant font ID on this line (may contain bold/italic hints for embedded fonts). */
|
|
158
|
+
fontName: string;
|
|
159
|
+
/** The minimum x position (left edge). */
|
|
160
|
+
minX: number;
|
|
161
|
+
/** Full concatenated text. */
|
|
162
|
+
text: string;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// ============================================
|
|
166
|
+
// PDF Text Extraction (pdfjs-dist)
|
|
167
|
+
// ============================================
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Configure the pdfjs-dist PDF worker source URL.
|
|
171
|
+
*
|
|
172
|
+
* pdfjs-dist requires a worker for PDF parsing. In the **browser**, bundlers
|
|
173
|
+
* (Vite, webpack) typically handle this automatically, or you can point to a
|
|
174
|
+
* CDN-hosted worker script. In **Node.js / SSR / test** environments, call
|
|
175
|
+
* this with a `file://` URL to the worker module **before** any import call.
|
|
176
|
+
*
|
|
177
|
+
* @example
|
|
178
|
+
* ```ts
|
|
179
|
+
* // Browser — CDN
|
|
180
|
+
* configurePdfWorker('https://cdn.jsdelivr.net/npm/pdfjs-dist@4/legacy/build/pdf.worker.min.mjs');
|
|
181
|
+
*
|
|
182
|
+
* // Node / vitest — file URL
|
|
183
|
+
* import { pathToFileURL } from 'url';
|
|
184
|
+
* configurePdfWorker(pathToFileURL(require.resolve('pdfjs-dist/legacy/build/pdf.worker.mjs')).href);
|
|
185
|
+
* ```
|
|
186
|
+
*/
|
|
187
|
+
export function configurePdfWorker(workerSrc: string): void {
|
|
188
|
+
_workerSrc = workerSrc;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Module-level storage for the worker source URL. */
|
|
192
|
+
let _workerSrc: string | undefined;
|
|
193
|
+
|
|
194
|
+
/** Minimal typed surface of the pdfjs-dist library used by the import path. */
|
|
195
|
+
interface PdfjsLib {
|
|
196
|
+
GlobalWorkerOptions?: { workerSrc?: string };
|
|
197
|
+
getDocument(params: { data: Uint8Array; isEvalSupported?: boolean; useSystemFonts?: boolean }): {
|
|
198
|
+
promise: Promise<PdfjsDocument>;
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
interface PdfjsDocument {
|
|
203
|
+
numPages: number;
|
|
204
|
+
getPage(pageNum: number): Promise<PdfjsPage>;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
interface PdfjsPage {
|
|
208
|
+
getTextContent(): Promise<{
|
|
209
|
+
items: Array<{
|
|
210
|
+
str: string;
|
|
211
|
+
transform: number[];
|
|
212
|
+
height: number;
|
|
213
|
+
width?: number;
|
|
214
|
+
fontName?: string;
|
|
215
|
+
}>;
|
|
216
|
+
styles?: Record<string, { fontFamily?: string }>;
|
|
217
|
+
}>;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async function applyWorkerConfig(pdfjsLib: PdfjsLib): Promise<void> {
|
|
221
|
+
if (!pdfjsLib.GlobalWorkerOptions) return;
|
|
222
|
+
if (pdfjsLib.GlobalWorkerOptions.workerSrc) return;
|
|
223
|
+
|
|
224
|
+
if (_workerSrc) {
|
|
225
|
+
pdfjsLib.GlobalWorkerOptions.workerSrc = _workerSrc;
|
|
226
|
+
}
|
|
227
|
+
// If no workerSrc is set, pdfjs-dist's legacy build will attempt its
|
|
228
|
+
// built-in fake-worker fallback. In browsers this usually works; in
|
|
229
|
+
// Node.js the caller must have called configurePdfWorker() first.
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function extractTextLines(data: Uint8Array): Promise<TextLine[]> {
|
|
233
|
+
// Dynamic import — the legacy build bundles a fake-worker fallback
|
|
234
|
+
// that avoids a real Web Worker in environments that don't support it.
|
|
235
|
+
let pdfjsLib: PdfjsLib;
|
|
236
|
+
try {
|
|
237
|
+
pdfjsLib = (await import('pdfjs-dist/legacy/build/pdf.mjs')) as unknown as PdfjsLib;
|
|
238
|
+
} catch {
|
|
239
|
+
pdfjsLib = (await import('pdfjs-dist')) as unknown as PdfjsLib;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
await applyWorkerConfig(pdfjsLib);
|
|
243
|
+
|
|
244
|
+
const loadingTask = pdfjsLib.getDocument({
|
|
245
|
+
data,
|
|
246
|
+
isEvalSupported: false,
|
|
247
|
+
useSystemFonts: true,
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
const pdf = await loadingTask.promise;
|
|
251
|
+
const allLines: TextLine[] = [];
|
|
252
|
+
|
|
253
|
+
for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
|
|
254
|
+
const page = await pdf.getPage(pageNum);
|
|
255
|
+
const content = await page.getTextContent();
|
|
256
|
+
|
|
257
|
+
// Build a fontName → fontFamily lookup from pdfjs styles
|
|
258
|
+
const styleMap = content.styles || {};
|
|
259
|
+
|
|
260
|
+
// Group text items into lines by y-coordinate
|
|
261
|
+
const items: TextItem[] = [];
|
|
262
|
+
for (const item of content.items) {
|
|
263
|
+
if (!item.str || item.str.trim().length === 0) continue;
|
|
264
|
+
const transform = item.transform || [1, 0, 0, 1, 0, 0];
|
|
265
|
+
const x = transform[4];
|
|
266
|
+
const y = transform[5];
|
|
267
|
+
const height = Math.abs(transform[3]) || item.height || 12;
|
|
268
|
+
const width = item.width || 0;
|
|
269
|
+
const fontName = item.fontName || '';
|
|
270
|
+
const fontFamily = styleMap[fontName]?.fontFamily || '';
|
|
271
|
+
items.push({ str: item.str, x, y, width, height, fontName, fontFamily });
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// Group into lines (items within 2pt of same y are same line)
|
|
275
|
+
const lineMap = new Map<number, TextItem[]>();
|
|
276
|
+
for (const item of items) {
|
|
277
|
+
const roundedY = Math.round(item.y * 2) / 2;
|
|
278
|
+
let foundKey: number | undefined;
|
|
279
|
+
for (const key of lineMap.keys()) {
|
|
280
|
+
if (Math.abs(key - roundedY) < 2) {
|
|
281
|
+
foundKey = key;
|
|
282
|
+
break;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if (foundKey !== undefined) {
|
|
286
|
+
lineMap.get(foundKey)!.push(item);
|
|
287
|
+
} else {
|
|
288
|
+
lineMap.set(roundedY, [item]);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Sort lines top-to-bottom (highest y first), items left-to-right
|
|
293
|
+
const sortedKeys = [...lineMap.keys()].sort((a, b) => b - a);
|
|
294
|
+
for (const key of sortedKeys) {
|
|
295
|
+
const lineItems = lineMap.get(key)!.sort((a, b) => a.x - b.x);
|
|
296
|
+
|
|
297
|
+
const fontSizes = lineItems.map((i) => i.height);
|
|
298
|
+
const fontSize = mode(fontSizes) || 12;
|
|
299
|
+
const fontFamilies = lineItems.map((i) => i.fontFamily);
|
|
300
|
+
const fontFamily = modeStr(fontFamilies) || '';
|
|
301
|
+
const fontNames = lineItems.map((i) => i.fontName);
|
|
302
|
+
const fontName = modeStr(fontNames) || '';
|
|
303
|
+
const minX = Math.min(...lineItems.map((i) => i.x));
|
|
304
|
+
const text = lineItems.map((i) => i.str).join(' ');
|
|
305
|
+
|
|
306
|
+
allLines.push({
|
|
307
|
+
items: lineItems,
|
|
308
|
+
y: key,
|
|
309
|
+
page: pageNum - 1,
|
|
310
|
+
fontSize,
|
|
311
|
+
fontFamily,
|
|
312
|
+
fontName,
|
|
313
|
+
minX,
|
|
314
|
+
text,
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
return allLines;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// ============================================
|
|
323
|
+
// Font Size Detection
|
|
324
|
+
// ============================================
|
|
325
|
+
|
|
326
|
+
function detectBodyFontSize(lines: TextLine[]): number {
|
|
327
|
+
const sizes = lines.map((l) => Math.round(l.fontSize * 2) / 2);
|
|
328
|
+
return mode(sizes) || DEFAULT_FONT_SIZE;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function mode(arr: number[]): number {
|
|
332
|
+
const freq = new Map<number, number>();
|
|
333
|
+
for (const v of arr) freq.set(v, (freq.get(v) || 0) + 1);
|
|
334
|
+
let maxCount = 0;
|
|
335
|
+
let maxVal = 0;
|
|
336
|
+
for (const [v, c] of freq) {
|
|
337
|
+
if (c > maxCount) {
|
|
338
|
+
maxCount = c;
|
|
339
|
+
maxVal = v;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return maxVal;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function modeStr(arr: string[]): string {
|
|
346
|
+
const freq = new Map<string, number>();
|
|
347
|
+
for (const v of arr) freq.set(v, (freq.get(v) || 0) + 1);
|
|
348
|
+
let maxCount = 0;
|
|
349
|
+
let maxVal = '';
|
|
350
|
+
for (const [v, c] of freq) {
|
|
351
|
+
if (c > maxCount) {
|
|
352
|
+
maxCount = c;
|
|
353
|
+
maxVal = v;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
return maxVal;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// ============================================
|
|
360
|
+
// Line Classification → MarkdownBlockNode[]
|
|
361
|
+
// ============================================
|
|
362
|
+
|
|
363
|
+
function classifyLines(
|
|
364
|
+
lines: TextLine[],
|
|
365
|
+
bodySize: number,
|
|
366
|
+
options: PdfImportOptions,
|
|
367
|
+
): MarkdownBlockNode[] {
|
|
368
|
+
const blocks: MarkdownBlockNode[] = [];
|
|
369
|
+
const detectTables = options.detectTables !== false;
|
|
370
|
+
const detectCodeBlocks = options.detectCodeBlocks !== false;
|
|
371
|
+
const detectBlockquotes = options.detectBlockquotes !== false;
|
|
372
|
+
const _detectLinks = options.detectLinks !== false;
|
|
373
|
+
|
|
374
|
+
// Determine typical left margin (most common minX)
|
|
375
|
+
const leftMargins = lines.map((l) => Math.round(l.minX));
|
|
376
|
+
const typicalLeftMargin = mode(leftMargins) || 72;
|
|
377
|
+
|
|
378
|
+
let i = 0;
|
|
379
|
+
while (i < lines.length) {
|
|
380
|
+
const line = lines[i];
|
|
381
|
+
|
|
382
|
+
// --- Heading detection ---
|
|
383
|
+
if (line.fontSize >= IMPORT_HEADING_MIN_SIZE && line.fontSize > bodySize + 1) {
|
|
384
|
+
const depth = sizeToHeadingDepth(line.fontSize);
|
|
385
|
+
blocks.push({
|
|
386
|
+
type: 'heading',
|
|
387
|
+
depth,
|
|
388
|
+
children: buildInlineNodes(line, options),
|
|
389
|
+
} as MarkdownHeading);
|
|
390
|
+
i++;
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// --- Code block detection (monospace font runs) ---
|
|
395
|
+
if (detectCodeBlocks && isMonospaceLine(line)) {
|
|
396
|
+
const codeLines: string[] = [];
|
|
397
|
+
while (i < lines.length && isMonospaceLine(lines[i])) {
|
|
398
|
+
codeLines.push(lines[i].text);
|
|
399
|
+
i++;
|
|
400
|
+
}
|
|
401
|
+
blocks.push({
|
|
402
|
+
type: 'code',
|
|
403
|
+
value: codeLines.join('\n'),
|
|
404
|
+
} as MarkdownCodeBlock);
|
|
405
|
+
continue;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// --- Table detection (column-aligned consecutive lines) ---
|
|
409
|
+
if (detectTables && i + 1 < lines.length) {
|
|
410
|
+
const tableLines = tryDetectTable(lines, i, typicalLeftMargin);
|
|
411
|
+
if (tableLines > 0) {
|
|
412
|
+
const table = buildTable(lines.slice(i, i + tableLines), options);
|
|
413
|
+
if (table) {
|
|
414
|
+
blocks.push(table);
|
|
415
|
+
i += tableLines;
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// --- List detection ---
|
|
422
|
+
const bulletMatch = tryMatchBullet(line.text);
|
|
423
|
+
const orderedMatch = line.text.match(IMPORT_ORDERED_PREFIX);
|
|
424
|
+
if (bulletMatch || orderedMatch) {
|
|
425
|
+
const listResult = consumeList(lines, i, typicalLeftMargin, bodySize, options);
|
|
426
|
+
blocks.push(listResult.list);
|
|
427
|
+
i = listResult.nextIndex;
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// --- Blockquote detection (indented text) ---
|
|
432
|
+
if (detectBlockquotes && line.minX > typicalLeftMargin + 20) {
|
|
433
|
+
const quoteLines: TextLine[] = [];
|
|
434
|
+
while (
|
|
435
|
+
i < lines.length &&
|
|
436
|
+
lines[i].minX > typicalLeftMargin + 20 &&
|
|
437
|
+
!isMonospaceLine(lines[i]) &&
|
|
438
|
+
lines[i].fontSize <= bodySize + 1
|
|
439
|
+
) {
|
|
440
|
+
quoteLines.push(lines[i]);
|
|
441
|
+
i++;
|
|
442
|
+
}
|
|
443
|
+
const quoteBlocks: MarkdownBlockNode[] = quoteLines.map(
|
|
444
|
+
(ql) =>
|
|
445
|
+
({
|
|
446
|
+
type: 'paragraph',
|
|
447
|
+
children: buildInlineNodes(ql, options),
|
|
448
|
+
}) as MarkdownParagraph,
|
|
449
|
+
);
|
|
450
|
+
blocks.push({
|
|
451
|
+
type: 'blockquote',
|
|
452
|
+
children: quoteBlocks,
|
|
453
|
+
} as MarkdownBlockquote);
|
|
454
|
+
continue;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// --- Regular paragraph ---
|
|
458
|
+
// Merge consecutive body-sized lines on the same page with small y-gaps
|
|
459
|
+
const paraLines: TextLine[] = [line];
|
|
460
|
+
i++;
|
|
461
|
+
while (i < lines.length) {
|
|
462
|
+
const next = lines[i];
|
|
463
|
+
// Same page, same-ish font size, close y (within line-height gap), not bullet/heading
|
|
464
|
+
if (
|
|
465
|
+
next.page === line.page &&
|
|
466
|
+
Math.abs(next.fontSize - bodySize) <= 1 &&
|
|
467
|
+
!isMonospaceLine(next) &&
|
|
468
|
+
next.minX <= typicalLeftMargin + 15 &&
|
|
469
|
+
!tryMatchBullet(next.text) &&
|
|
470
|
+
!next.text.match(IMPORT_ORDERED_PREFIX)
|
|
471
|
+
) {
|
|
472
|
+
// Check y-gap: lines are sorted top-to-bottom so y decreases
|
|
473
|
+
const yGap = paraLines[paraLines.length - 1].y - next.y;
|
|
474
|
+
const lineHeight = bodySize * 1.6;
|
|
475
|
+
if (yGap > 0 && yGap < lineHeight + IMPORT_PARAGRAPH_GAP) {
|
|
476
|
+
paraLines.push(next);
|
|
477
|
+
i++;
|
|
478
|
+
} else {
|
|
479
|
+
break;
|
|
480
|
+
}
|
|
481
|
+
} else {
|
|
482
|
+
break;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// Build paragraph from merged lines
|
|
487
|
+
const allInlines: MarkdownInlineNode[] = [];
|
|
488
|
+
for (let j = 0; j < paraLines.length; j++) {
|
|
489
|
+
if (j > 0) {
|
|
490
|
+
allInlines.push({ type: 'text', value: ' ' } as MarkdownText);
|
|
491
|
+
}
|
|
492
|
+
allInlines.push(...buildInlineNodes(paraLines[j], options));
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
if (allInlines.length > 0) {
|
|
496
|
+
blocks.push({
|
|
497
|
+
type: 'paragraph',
|
|
498
|
+
children: mergeAdjacentText(allInlines),
|
|
499
|
+
} as MarkdownParagraph);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
return blocks;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// ============================================
|
|
507
|
+
// Heading Depth Mapping
|
|
508
|
+
// ============================================
|
|
509
|
+
|
|
510
|
+
function sizeToHeadingDepth(fontSize: number): 1 | 2 | 3 | 4 | 5 | 6 {
|
|
511
|
+
for (const range of IMPORT_HEADING_SIZE_RANGES) {
|
|
512
|
+
if (fontSize >= range.min) return range.depth as 1 | 2 | 3 | 4 | 5 | 6;
|
|
513
|
+
}
|
|
514
|
+
return 6;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// ============================================
|
|
518
|
+
// Font Heuristics
|
|
519
|
+
// ============================================
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* Check if a line is predominantly monospace.
|
|
523
|
+
* Uses the resolved fontFamily from pdfjs styles first,
|
|
524
|
+
* falls back to fontName pattern matching for embedded fonts.
|
|
525
|
+
*/
|
|
526
|
+
function isMonospaceLine(line: TextLine): boolean {
|
|
527
|
+
return isMonospaceFamily(line.fontFamily) || isMonospaceName(line.fontName);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Check if a text item is monospace.
|
|
532
|
+
*/
|
|
533
|
+
function isMonospaceItem(item: TextItem): boolean {
|
|
534
|
+
return isMonospaceFamily(item.fontFamily) || isMonospaceName(item.fontName);
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function isMonospaceFamily(fontFamily: string): boolean {
|
|
538
|
+
const lower = fontFamily.toLowerCase();
|
|
539
|
+
return lower === 'monospace' || lower.includes('monospace');
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
function isMonospaceName(fontName: string): boolean {
|
|
543
|
+
const lower = fontName.toLowerCase();
|
|
544
|
+
return (
|
|
545
|
+
lower.includes('courier') ||
|
|
546
|
+
lower.includes('mono') ||
|
|
547
|
+
lower.includes('consolas') ||
|
|
548
|
+
lower.includes('menlo') ||
|
|
549
|
+
lower.includes('inconsolata') ||
|
|
550
|
+
lower.includes('firacode') ||
|
|
551
|
+
lower.includes('source code') ||
|
|
552
|
+
lower.includes('dejavu sans mono')
|
|
553
|
+
);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
function isBoldFont(fontName: string): boolean {
|
|
557
|
+
const lower = fontName.toLowerCase();
|
|
558
|
+
return lower.includes('bold') || lower.includes('black') || lower.includes('heavy');
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function isItalicFont(fontName: string): boolean {
|
|
562
|
+
const lower = fontName.toLowerCase();
|
|
563
|
+
return lower.includes('italic') || lower.includes('oblique') || lower.includes('slanted');
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// ============================================
|
|
567
|
+
// Inline Node Construction
|
|
568
|
+
// ============================================
|
|
569
|
+
|
|
570
|
+
function buildInlineNodes(line: TextLine, options: PdfImportOptions): MarkdownInlineNode[] {
|
|
571
|
+
const nodes: MarkdownInlineNode[] = [];
|
|
572
|
+
const detectLinksOpt = options.detectLinks !== false;
|
|
573
|
+
|
|
574
|
+
for (const item of line.items) {
|
|
575
|
+
const text = item.str;
|
|
576
|
+
if (!text || text.trim().length === 0) continue;
|
|
577
|
+
|
|
578
|
+
const bold = isBoldFont(item.fontName);
|
|
579
|
+
const italic = isItalicFont(item.fontName);
|
|
580
|
+
const mono = isMonospaceItem(item);
|
|
581
|
+
|
|
582
|
+
let inlineNodes: MarkdownInlineNode[];
|
|
583
|
+
|
|
584
|
+
if (mono) {
|
|
585
|
+
inlineNodes = [{ type: 'inlineCode', value: text } as MarkdownInlineCode];
|
|
586
|
+
} else if (detectLinksOpt) {
|
|
587
|
+
inlineNodes = splitTextWithLinks(text);
|
|
588
|
+
} else {
|
|
589
|
+
inlineNodes = [{ type: 'text', value: text } as MarkdownText];
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// Wrap in formatting
|
|
593
|
+
for (const node of inlineNodes) {
|
|
594
|
+
let wrapped: MarkdownInlineNode = node;
|
|
595
|
+
if (italic) {
|
|
596
|
+
wrapped = { type: 'emphasis', children: [wrapped] } as MarkdownEmphasis;
|
|
597
|
+
}
|
|
598
|
+
if (bold) {
|
|
599
|
+
wrapped = { type: 'strong', children: [wrapped] } as MarkdownStrong;
|
|
600
|
+
}
|
|
601
|
+
nodes.push(wrapped);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
return nodes;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Split a text string into text nodes and link nodes wherever
|
|
610
|
+
* URL patterns are found.
|
|
611
|
+
*/
|
|
612
|
+
function splitTextWithLinks(text: string): MarkdownInlineNode[] {
|
|
613
|
+
const nodes: MarkdownInlineNode[] = [];
|
|
614
|
+
let lastIndex = 0;
|
|
615
|
+
|
|
616
|
+
// Reset regex state
|
|
617
|
+
IMPORT_URL_PATTERN.lastIndex = 0;
|
|
618
|
+
let match: RegExpExecArray | null;
|
|
619
|
+
|
|
620
|
+
while ((match = IMPORT_URL_PATTERN.exec(text)) !== null) {
|
|
621
|
+
// Text before URL
|
|
622
|
+
if (match.index > lastIndex) {
|
|
623
|
+
nodes.push({ type: 'text', value: text.slice(lastIndex, match.index) } as MarkdownText);
|
|
624
|
+
}
|
|
625
|
+
// URL as link
|
|
626
|
+
const url = match[0];
|
|
627
|
+
nodes.push({
|
|
628
|
+
type: 'link',
|
|
629
|
+
url,
|
|
630
|
+
children: [{ type: 'text', value: url } as MarkdownText],
|
|
631
|
+
} as MarkdownLink);
|
|
632
|
+
lastIndex = match.index + url.length;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
// Remaining text
|
|
636
|
+
if (lastIndex < text.length) {
|
|
637
|
+
nodes.push({ type: 'text', value: text.slice(lastIndex) } as MarkdownText);
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
return nodes.length > 0 ? nodes : [{ type: 'text', value: text } as MarkdownText];
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// ============================================
|
|
644
|
+
// List Detection
|
|
645
|
+
// ============================================
|
|
646
|
+
|
|
647
|
+
function tryMatchBullet(text: string): boolean {
|
|
648
|
+
if (text.length === 0) return false;
|
|
649
|
+
return IMPORT_BULLET_CHARS.has(text[0]) || IMPORT_BULLET_CHARS.has(text.trimStart()[0]);
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
function stripBullet(text: string): string {
|
|
653
|
+
const trimmed = text.trimStart();
|
|
654
|
+
if (IMPORT_BULLET_CHARS.has(trimmed[0])) {
|
|
655
|
+
return trimmed.slice(1).trimStart();
|
|
656
|
+
}
|
|
657
|
+
return text;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
function stripOrderedPrefix(text: string): string {
|
|
661
|
+
return text.replace(IMPORT_ORDERED_PREFIX, '');
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
interface ListResult {
|
|
665
|
+
list: MarkdownList;
|
|
666
|
+
nextIndex: number;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
function consumeList(
|
|
670
|
+
lines: TextLine[],
|
|
671
|
+
startIdx: number,
|
|
672
|
+
_typicalLeftMargin: number,
|
|
673
|
+
_bodySize: number,
|
|
674
|
+
_options: PdfImportOptions,
|
|
675
|
+
): ListResult {
|
|
676
|
+
const firstLine = lines[startIdx];
|
|
677
|
+
const isOrdered = !!firstLine.text.match(IMPORT_ORDERED_PREFIX);
|
|
678
|
+
const items: MarkdownListItem[] = [];
|
|
679
|
+
let i = startIdx;
|
|
680
|
+
|
|
681
|
+
while (i < lines.length) {
|
|
682
|
+
const line = lines[i];
|
|
683
|
+
const isBullet = tryMatchBullet(line.text);
|
|
684
|
+
const isOrd = !!line.text.match(IMPORT_ORDERED_PREFIX);
|
|
685
|
+
|
|
686
|
+
if (!isBullet && !isOrd) break;
|
|
687
|
+
// All items in one list should be same type
|
|
688
|
+
if (isOrdered && !isOrd) break;
|
|
689
|
+
if (!isOrdered && !isBullet) break;
|
|
690
|
+
|
|
691
|
+
const cleanText = isOrdered ? stripOrderedPrefix(line.text) : stripBullet(line.text);
|
|
692
|
+
const para: MarkdownParagraph = {
|
|
693
|
+
type: 'paragraph',
|
|
694
|
+
children: splitTextWithLinks(cleanText),
|
|
695
|
+
};
|
|
696
|
+
items.push({
|
|
697
|
+
type: 'listItem',
|
|
698
|
+
children: [para],
|
|
699
|
+
} as MarkdownListItem);
|
|
700
|
+
i++;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
return {
|
|
704
|
+
list: {
|
|
705
|
+
type: 'list',
|
|
706
|
+
ordered: isOrdered,
|
|
707
|
+
children: items,
|
|
708
|
+
} as MarkdownList,
|
|
709
|
+
nextIndex: i,
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// ============================================
|
|
714
|
+
// Table Detection
|
|
715
|
+
// ============================================
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* Look ahead from index `start` and return the number of consecutive
|
|
719
|
+
* lines that form an aligned table, or 0 if no table detected.
|
|
720
|
+
*/
|
|
721
|
+
function tryDetectTable(lines: TextLine[], start: number, _typicalLeftMargin: number): number {
|
|
722
|
+
// A table needs multiple items per line (columns) on consecutive lines
|
|
723
|
+
// with roughly the same x-alignment pattern.
|
|
724
|
+
|
|
725
|
+
const firstLine = lines[start];
|
|
726
|
+
if (firstLine.items.length < 2) return 0;
|
|
727
|
+
|
|
728
|
+
const cols = getColumnPositions(firstLine);
|
|
729
|
+
if (cols.length < 2) return 0;
|
|
730
|
+
|
|
731
|
+
let count = 1;
|
|
732
|
+
for (let i = start + 1; i < lines.length; i++) {
|
|
733
|
+
const line = lines[i];
|
|
734
|
+
if (line.items.length < 2) break;
|
|
735
|
+
|
|
736
|
+
// Check if this line's columns align with the first line's
|
|
737
|
+
const lineCols = getColumnPositions(line);
|
|
738
|
+
if (lineCols.length !== cols.length) break;
|
|
739
|
+
|
|
740
|
+
let aligned = true;
|
|
741
|
+
for (let c = 0; c < cols.length; c++) {
|
|
742
|
+
if (Math.abs(lineCols[c] - cols[c]) > IMPORT_COLUMN_TOLERANCE) {
|
|
743
|
+
aligned = false;
|
|
744
|
+
break;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
if (!aligned) break;
|
|
748
|
+
count++;
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
return count >= IMPORT_TABLE_MIN_ROWS ? count : 0;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
function getColumnPositions(line: TextLine): number[] {
|
|
755
|
+
// Cluster item x-positions
|
|
756
|
+
const positions: number[] = [];
|
|
757
|
+
for (const item of line.items) {
|
|
758
|
+
const x = Math.round(item.x);
|
|
759
|
+
// Check if this x is close to an existing column
|
|
760
|
+
let found = false;
|
|
761
|
+
for (const p of positions) {
|
|
762
|
+
if (Math.abs(p - x) < IMPORT_COLUMN_TOLERANCE) {
|
|
763
|
+
found = true;
|
|
764
|
+
break;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
if (!found) positions.push(x);
|
|
768
|
+
}
|
|
769
|
+
return positions.sort((a, b) => a - b);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
function buildTable(lines: TextLine[], _options: PdfImportOptions): MarkdownTable | null {
|
|
773
|
+
if (lines.length === 0) return null;
|
|
774
|
+
|
|
775
|
+
// Use the first line's column positions as anchors
|
|
776
|
+
const cols = getColumnPositions(lines[0]);
|
|
777
|
+
if (cols.length < 2) return null;
|
|
778
|
+
|
|
779
|
+
const rows: MarkdownTableRow[] = [];
|
|
780
|
+
|
|
781
|
+
for (let ri = 0; ri < lines.length; ri++) {
|
|
782
|
+
const line = lines[ri];
|
|
783
|
+
const cells: MarkdownTableCell[] = [];
|
|
784
|
+
|
|
785
|
+
for (let ci = 0; ci < cols.length; ci++) {
|
|
786
|
+
const colLeft = cols[ci] - IMPORT_COLUMN_TOLERANCE;
|
|
787
|
+
const colRight = ci + 1 < cols.length ? cols[ci + 1] - IMPORT_COLUMN_TOLERANCE : Infinity;
|
|
788
|
+
|
|
789
|
+
// Collect items in this column
|
|
790
|
+
const cellItems = line.items.filter((item) => item.x >= colLeft && item.x < colRight);
|
|
791
|
+
const text = cellItems
|
|
792
|
+
.map((i) => i.str)
|
|
793
|
+
.join(' ')
|
|
794
|
+
.trim();
|
|
795
|
+
|
|
796
|
+
cells.push({
|
|
797
|
+
type: 'tableCell',
|
|
798
|
+
isHeader: ri === 0,
|
|
799
|
+
children: text.length > 0 ? [{ type: 'text', value: text } as MarkdownText] : [],
|
|
800
|
+
} as MarkdownTableCell);
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
rows.push({
|
|
804
|
+
type: 'tableRow',
|
|
805
|
+
children: cells,
|
|
806
|
+
} as MarkdownTableRow);
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
return {
|
|
810
|
+
type: 'table',
|
|
811
|
+
children: rows,
|
|
812
|
+
} as MarkdownTable;
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
// ============================================
|
|
816
|
+
// Text Merging
|
|
817
|
+
// ============================================
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* Merge adjacent text nodes to reduce fragmentation.
|
|
821
|
+
*/
|
|
822
|
+
function mergeAdjacentText(nodes: MarkdownInlineNode[]): MarkdownInlineNode[] {
|
|
823
|
+
if (nodes.length <= 1) return nodes;
|
|
824
|
+
|
|
825
|
+
const result: MarkdownInlineNode[] = [];
|
|
826
|
+
for (const node of nodes) {
|
|
827
|
+
const prev = result[result.length - 1];
|
|
828
|
+
if (prev && prev.type === 'text' && node.type === 'text') {
|
|
829
|
+
(prev as MarkdownText).value += (node as MarkdownText).value;
|
|
830
|
+
} else {
|
|
831
|
+
result.push(node);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
return result;
|
|
835
|
+
}
|