@docen/import-docx 0.0.9 → 0.0.11

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/README.md CHANGED
@@ -1,290 +1,290 @@
1
- # @docen/import-docx
2
-
3
- ![npm version](https://img.shields.io/npm/v/@docen/import-docx)
4
- ![npm downloads](https://img.shields.io/npm/dw/@docen/import-docx)
5
- ![npm license](https://img.shields.io/npm/l/@docen/import-docx)
6
-
7
- > Import Microsoft Word DOCX files to TipTap/ProseMirror content.
8
-
9
- ## Features
10
-
11
- - 📝 **Rich Text Parsing** - Accurate parsing of headings, paragraphs, and blockquotes with formatting
12
- - 🖼️ **Image Extraction** - Automatic image extraction with base64 conversion and cropping support
13
- - 📊 **Table Support** - Complete table structure with colspan/rowspan detection algorithm
14
- - ✅ **Lists & Tasks** - Bullet lists, numbered lists with start number extraction, and task lists with checkbox detection
15
- - 🎨 **Text Formatting** - Bold, italic, underline, strikethrough, subscript, superscript, and highlights
16
- - 🎯 **Text Styles** - Comprehensive style support including colors, backgrounds, fonts, sizes, and line heights
17
- - 🔗 **Links** - Hyperlink extraction with href preservation
18
- - 💻 **Code Blocks** - Code block detection with language attribute extraction
19
- - 🌐 **Cross-Platform** - Works in both browser and Node.js environments
20
- - ✂️ **Image Cropping** - Automatic cropping of images based on DOCX crop metadata
21
- - 🧠 **Smart Parsing** - DOCX XML parsing with proper element grouping and structure reconstruction
22
- - ⚡ **Fast Processing** - Uses fflate for ultra-fast ZIP decompression
23
-
24
- ## Installation
25
-
26
- ```bash
27
- # Install with npm
28
- $ npm install @docen/import-docx
29
-
30
- # Install with yarn
31
- $ yarn add @docen/import-docx
32
-
33
- # Install with pnpm
34
- $ pnpm add @docen/import-docx
35
- ```
36
-
37
- ## Quick Start
38
-
39
- ```typescript
40
- import { parseDOCX } from "@docen/import-docx";
41
- import { readFileSync } from "node:fs";
42
-
43
- // Read DOCX file
44
- const buffer = readFileSync("document.docx");
45
-
46
- // Parse DOCX to TipTap JSON
47
- const content = await parseDOCX(buffer);
48
-
49
- // Use in TipTap editor
50
- editor.commands.setContent(content);
51
- ```
52
-
53
- ## API Reference
54
-
55
- ### `parseDOCX(input, options?)`
56
-
57
- Parses a DOCX file and converts it to TipTap/ProseMirror JSON content.
58
-
59
- **Parameters:**
60
-
61
- - `input: Buffer | ArrayBuffer | Uint8Array` - DOCX file data
62
- - `options?: DocxImportOptions` - Optional import configuration
63
-
64
- **Returns:** `Promise<JSONContent>` - TipTap/ProseMirror document content with images embedded
65
-
66
- **Options:**
67
-
68
- ```typescript
69
- interface DocxImportOptions {
70
- /** Custom image converter (default: embed as base64) */
71
- convertImage?: (image: DocxImageInfo) => Promise<DocxImageResult>;
72
-
73
- /** Whether to ignore empty paragraphs (default: false).
74
- * Empty paragraphs are those without text content or images.
75
- * Paragraphs containing only whitespace or images are not considered empty. */
76
- ignoreEmptyParagraphs?: boolean;
77
-
78
- /**
79
- * Dynamic import function for @napi-rs/canvas
80
- * Required for image cropping in Node.js environment, ignored in browser
81
- *
82
- * @example
83
- * import { parseDOCX } from '@docen/import-docx';
84
- * const content = await parseDOCX(buffer, {
85
- * canvasImport: () => import('@napi-rs/canvas')
86
- * });
87
- */
88
- canvasImport?: () => Promise<typeof import("@napi-rs/canvas")>;
89
-
90
- /**
91
- * Enable or disable image cropping during import
92
- * When true, images with crop information in DOCX will be cropped
93
- * When false (default), crop information is ignored and full image is used
94
- *
95
- * @default false
96
- */
97
- enableImageCrop?: boolean;
98
- }
99
- ```
100
-
101
- **Default Image Converter:**
102
-
103
- The package exports `defaultImageConverter` which embeds images as base64 data URLs:
104
-
105
- ```typescript
106
- import { defaultImageConverter } from "@docen/import-docx";
107
-
108
- // Use in custom converter
109
- await parseDOCX(buffer, {
110
- convertImage: async (image) => {
111
- if (shouldUploadToCDN) {
112
- return uploadToCDN(image.data);
113
- }
114
- return defaultImageConverter(image);
115
- },
116
- });
117
- ```
118
-
119
- ## Supported Content Types
120
-
121
- ### Text Formatting
122
-
123
- - **Bold**, _Italic_, <u>Underline</u>, ~~Strikethrough~~
124
- - ^Superscript^ and ~Subscript~
125
- - Text highlights
126
- - Text colors and background colors
127
- - Font families and sizes
128
- - Line heights
129
-
130
- ### Block Elements
131
-
132
- - **Headings** (H1-H6) with proper level detection
133
- - **Paragraphs** with text alignment (left, right, center, justify)
134
- - **Blockquotes** (Detected by indentation + left border formatting)
135
- - **Horizontal Rules** (Detected as page breaks in DOCX)
136
- - **Code Blocks** with language attribute support
137
-
138
- ### Lists
139
-
140
- - **Bullet Lists** with proper nesting and structure
141
- - **Numbered Lists** with custom start number extraction
142
- - **Task Lists** with checked/unchecked state detection (☐/☑ symbols)
143
-
144
- ### Tables
145
-
146
- - Complete table structure parsing
147
- - **Table Cells** with colspan detection using grid-based algorithm
148
- - **Table Cells** with rowspan detection using vMerge tracking
149
- - Cell alignment and formatting preservation
150
- - Merged cell handling (both horizontal and vertical)
151
-
152
- ### Media & Embeds
153
-
154
- - **Images** with automatic base64 conversion
155
- - **Grouped Images** (DOCX image groups) support
156
- - **Links** (hyperlinks) with href extraction
157
-
158
- ## Parsing Algorithm
159
-
160
- ### Document Structure
161
-
162
- The parser follows a structured workflow:
163
-
164
- 1. **Extract Relationships** - Parse `_rels/document.xml.rels` for hyperlinks and images
165
- 2. **Parse Numbering** - Extract list definitions from `numbering.xml` (abstractNum → numFmt)
166
- 3. **Process Document Body** - Iterate through document.xml elements:
167
- - Detect content types (tables, lists, paragraphs, code blocks, etc.)
168
- - Group consecutive elements into proper containers
169
- - Convert XML nodes to TipTap JSON nodes
170
-
171
- ### Table Processing
172
-
173
- Tables use specialized algorithms:
174
-
175
- - **Colspan Detection** - Grid-based algorithm tracks cell positions and detects horizontal merges
176
- - **Rowspan Detection** - Vertical merge (vMerge) tracking across rows with proper cell skipping
177
- - **Cell Content** - Recursive parsing of nested paragraphs and formatting
178
- - **Hyperlink Support** - Proper handling of links within table cells
179
-
180
- ### List Processing
181
-
182
- Lists utilize the DOCX numbering system:
183
-
184
- - **Numbering ID Mapping** - Maps abstractNum to formatting (bullet vs decimal)
185
- - **Start Value Extraction** - Extracts and preserves start numbers for ordered lists
186
- - **Nesting Preservation** - Maintains proper list hierarchy
187
- - **Consecutive Grouping** - Groups consecutive list items into list containers
188
-
189
- ## Examples
190
-
191
- ### Basic Usage
192
-
193
- ```typescript
194
- import { parseDOCX } from "@docen/import-docx";
195
-
196
- const buffer = readFileSync("example.docx");
197
- const { content } = await parseDOCX(buffer);
198
-
199
- console.log(JSON.stringify(content, null, 2));
200
- ```
201
-
202
- ### Use with TipTap Editor
203
-
204
- ```typescript
205
- import { Editor } from "@tiptap/core";
206
- import { parseDOCX } from "@docen/import-docx";
207
-
208
- const editor = new Editor({
209
- extensions: [...],
210
- content: "",
211
- });
212
-
213
- // Import DOCX file
214
- async function importDocx(file: File) {
215
- const buffer = await file.arrayBuffer();
216
- const content = await parseDOCX(buffer);
217
- editor.commands.setContent(content);
218
- }
219
- ```
220
-
221
- ### Node.js Environment with Image Cropping
222
-
223
- To enable image cropping in Node.js environment, you need to provide `@napi-rs/canvas`:
224
-
225
- ```typescript
226
- import { parseDOCX } from "@docen/import-docx";
227
- import { readFileSync } from "node:fs";
228
-
229
- // Install @napi-rs/canvas first: pnpm add @napi-rs/canvas
230
- const buffer = readFileSync("document.docx");
231
-
232
- const content = await parseDOCX(buffer, {
233
- canvasImport: () => import("@napi-rs/canvas"),
234
- enableImageCrop: true, // Enable cropping (default is false)
235
- });
236
- ```
237
-
238
- **Note:** By default, image cropping is disabled. Images are imported in full size, ignoring crop information in DOCX.
239
-
240
- ### Disable Image Cropping
241
-
242
- If you want to explicitly ignore crop information in DOCX and use full images (this is the default behavior):
243
-
244
- ```typescript
245
- const content = await parseDOCX(buffer, {
246
- enableImageCrop: false,
247
- });
248
- ```
249
-
250
- ## Known Limitations
251
-
252
- ### Blockquote Detection
253
-
254
- DOCX does not have a semantic blockquote structure. Blockquotes are detected by:
255
-
256
- - Left indentation ≥ 720 twips (0.5 inch)
257
- - Presence of left border (single line)
258
-
259
- This detection method may produce false positives for documents with custom indentation similar to blockquotes.
260
-
261
- ### Code Marks
262
-
263
- The `code` mark is NOT automatically detected from monospace fonts (Consolas, Courier New, etc.). This is intentional to avoid false positives. Code marks should be explicitly added in the source document or through editor UI.
264
-
265
- ### Color Format
266
-
267
- All colors are imported as hex values (e.g., "#FF0000", "#008000"). Color names from the original document are not preserved.
268
-
269
- ### Image Limitations
270
-
271
- - Only embedded images are supported (external image links are not fetched)
272
- - Image dimensions and title are extracted from DOCX metadata
273
- - **Image Cropping**: By default, images are imported in full size (crop information is ignored)
274
- - To enable cropping, set `enableImageCrop: true` in options
275
- - In browser environments, cropping works natively with Canvas API
276
- - In Node.js, you must also provide `canvasImport` option with dynamic import of `@napi-rs/canvas`
277
- - If `@napi-rs/canvas` is not available in Node.js, images will be imported without cropping (graceful degradation)
278
- - Some DOCX image features (like advanced positioning or text wrapping) have limited support
279
-
280
- ### Table Cell Types
281
-
282
- DOCX format does not distinguish between header and body cells at a semantic level. All cells are imported as `tableCell` type for consistency. This is a DOCX format limitation.
283
-
284
- ## Contributing
285
-
286
- Contributions are welcome! Please read our [Contributor Covenant](https://www.contributor-covenant.org/version/2/1/code_of_conduct/) and submit pull requests to the [main repository](https://github.com/DemoMacro/docen).
287
-
288
- ## License
289
-
290
- - [MIT](LICENSE) &copy; [Demo Macro](https://imst.xyz/)
1
+ # @docen/import-docx
2
+
3
+ ![npm version](https://img.shields.io/npm/v/@docen/import-docx)
4
+ ![npm downloads](https://img.shields.io/npm/dw/@docen/import-docx)
5
+ ![npm license](https://img.shields.io/npm/l/@docen/import-docx)
6
+
7
+ > Import Microsoft Word DOCX files to TipTap/ProseMirror content.
8
+
9
+ ## Features
10
+
11
+ - 📝 **Rich Text Parsing** - Accurate parsing of headings, paragraphs, and blockquotes with formatting
12
+ - 🖼️ **Image Extraction** - Automatic image extraction with base64 conversion and cropping support
13
+ - 📊 **Table Support** - Complete table structure with colspan/rowspan detection algorithm
14
+ - ✅ **Lists & Tasks** - Bullet lists, numbered lists with start number extraction, and task lists with checkbox detection
15
+ - 🎨 **Text Formatting** - Bold, italic, underline, strikethrough, subscript, superscript, and highlights
16
+ - 🎯 **Text Styles** - Comprehensive style support including colors, backgrounds, fonts, sizes, and line heights
17
+ - 🔗 **Links** - Hyperlink extraction with href preservation
18
+ - 💻 **Code Blocks** - Code block detection with language attribute extraction
19
+ - 🌐 **Cross-Platform** - Works in both browser and Node.js environments
20
+ - ✂️ **Image Cropping** - Automatic cropping of images based on DOCX crop metadata
21
+ - 🧠 **Smart Parsing** - DOCX XML parsing with proper element grouping and structure reconstruction
22
+ - ⚡ **Fast Processing** - Uses fflate for ultra-fast ZIP decompression
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ # Install with npm
28
+ $ npm install @docen/import-docx
29
+
30
+ # Install with yarn
31
+ $ yarn add @docen/import-docx
32
+
33
+ # Install with pnpm
34
+ $ pnpm add @docen/import-docx
35
+ ```
36
+
37
+ ## Quick Start
38
+
39
+ ```typescript
40
+ import { parseDOCX } from "@docen/import-docx";
41
+ import { readFileSync } from "node:fs";
42
+
43
+ // Read DOCX file
44
+ const buffer = readFileSync("document.docx");
45
+
46
+ // Parse DOCX to TipTap JSON
47
+ const content = await parseDOCX(buffer);
48
+
49
+ // Use in TipTap editor
50
+ editor.commands.setContent(content);
51
+ ```
52
+
53
+ ## API Reference
54
+
55
+ ### `parseDOCX(input, options?)`
56
+
57
+ Parses a DOCX file and converts it to TipTap/ProseMirror JSON content.
58
+
59
+ **Parameters:**
60
+
61
+ - `input: Buffer | ArrayBuffer | Uint8Array` - DOCX file data
62
+ - `options?: DocxImportOptions` - Optional import configuration
63
+
64
+ **Returns:** `Promise<JSONContent>` - TipTap/ProseMirror document content with images embedded
65
+
66
+ **Options:**
67
+
68
+ ```typescript
69
+ interface DocxImportOptions {
70
+ /** Custom image converter (default: embed as base64) */
71
+ convertImage?: (image: DocxImageInfo) => Promise<DocxImageResult>;
72
+
73
+ /** Whether to ignore empty paragraphs (default: false).
74
+ * Empty paragraphs are those without text content or images.
75
+ * Paragraphs containing only whitespace or images are not considered empty. */
76
+ ignoreEmptyParagraphs?: boolean;
77
+
78
+ /**
79
+ * Dynamic import function for @napi-rs/canvas
80
+ * Required for image cropping in Node.js environment, ignored in browser
81
+ *
82
+ * @example
83
+ * import { parseDOCX } from '@docen/import-docx';
84
+ * const content = await parseDOCX(buffer, {
85
+ * canvasImport: () => import('@napi-rs/canvas')
86
+ * });
87
+ */
88
+ canvasImport?: () => Promise<typeof import("@napi-rs/canvas")>;
89
+
90
+ /**
91
+ * Enable or disable image cropping during import
92
+ * When true, images with crop information in DOCX will be cropped
93
+ * When false (default), crop information is ignored and full image is used
94
+ *
95
+ * @default false
96
+ */
97
+ enableImageCrop?: boolean;
98
+ }
99
+ ```
100
+
101
+ **Default Image Converter:**
102
+
103
+ The package exports `defaultImageConverter` which embeds images as base64 data URLs:
104
+
105
+ ```typescript
106
+ import { defaultImageConverter } from "@docen/import-docx";
107
+
108
+ // Use in custom converter
109
+ await parseDOCX(buffer, {
110
+ convertImage: async (image) => {
111
+ if (shouldUploadToCDN) {
112
+ return uploadToCDN(image.data);
113
+ }
114
+ return defaultImageConverter(image);
115
+ },
116
+ });
117
+ ```
118
+
119
+ ## Supported Content Types
120
+
121
+ ### Text Formatting
122
+
123
+ - **Bold**, _Italic_, <u>Underline</u>, ~~Strikethrough~~
124
+ - ^Superscript^ and ~Subscript~
125
+ - Text highlights
126
+ - Text colors and background colors
127
+ - Font families and sizes
128
+ - Line heights
129
+
130
+ ### Block Elements
131
+
132
+ - **Headings** (H1-H6) with proper level detection
133
+ - **Paragraphs** with text alignment (left, right, center, justify)
134
+ - **Blockquotes** (Detected by indentation + left border formatting)
135
+ - **Horizontal Rules** (Detected as page breaks in DOCX)
136
+ - **Code Blocks** with language attribute support
137
+
138
+ ### Lists
139
+
140
+ - **Bullet Lists** with proper nesting and structure
141
+ - **Numbered Lists** with custom start number extraction
142
+ - **Task Lists** with checked/unchecked state detection (☐/☑ symbols)
143
+
144
+ ### Tables
145
+
146
+ - Complete table structure parsing
147
+ - **Table Cells** with colspan detection using grid-based algorithm
148
+ - **Table Cells** with rowspan detection using vMerge tracking
149
+ - Cell alignment and formatting preservation
150
+ - Merged cell handling (both horizontal and vertical)
151
+
152
+ ### Media & Embeds
153
+
154
+ - **Images** with automatic base64 conversion
155
+ - **Grouped Images** (DOCX image groups) support
156
+ - **Links** (hyperlinks) with href extraction
157
+
158
+ ## Parsing Algorithm
159
+
160
+ ### Document Structure
161
+
162
+ The parser follows a structured workflow:
163
+
164
+ 1. **Extract Relationships** - Parse `_rels/document.xml.rels` for hyperlinks and images
165
+ 2. **Parse Numbering** - Extract list definitions from `numbering.xml` (abstractNum → numFmt)
166
+ 3. **Process Document Body** - Iterate through document.xml elements:
167
+ - Detect content types (tables, lists, paragraphs, code blocks, etc.)
168
+ - Group consecutive elements into proper containers
169
+ - Convert XML nodes to TipTap JSON nodes
170
+
171
+ ### Table Processing
172
+
173
+ Tables use specialized algorithms:
174
+
175
+ - **Colspan Detection** - Grid-based algorithm tracks cell positions and detects horizontal merges
176
+ - **Rowspan Detection** - Vertical merge (vMerge) tracking across rows with proper cell skipping
177
+ - **Cell Content** - Recursive parsing of nested paragraphs and formatting
178
+ - **Hyperlink Support** - Proper handling of links within table cells
179
+
180
+ ### List Processing
181
+
182
+ Lists utilize the DOCX numbering system:
183
+
184
+ - **Numbering ID Mapping** - Maps abstractNum to formatting (bullet vs decimal)
185
+ - **Start Value Extraction** - Extracts and preserves start numbers for ordered lists
186
+ - **Nesting Preservation** - Maintains proper list hierarchy
187
+ - **Consecutive Grouping** - Groups consecutive list items into list containers
188
+
189
+ ## Examples
190
+
191
+ ### Basic Usage
192
+
193
+ ```typescript
194
+ import { parseDOCX } from "@docen/import-docx";
195
+
196
+ const buffer = readFileSync("example.docx");
197
+ const { content } = await parseDOCX(buffer);
198
+
199
+ console.log(JSON.stringify(content, null, 2));
200
+ ```
201
+
202
+ ### Use with TipTap Editor
203
+
204
+ ```typescript
205
+ import { Editor } from "@tiptap/core";
206
+ import { parseDOCX } from "@docen/import-docx";
207
+
208
+ const editor = new Editor({
209
+ extensions: [...],
210
+ content: "",
211
+ });
212
+
213
+ // Import DOCX file
214
+ async function importDocx(file: File) {
215
+ const buffer = await file.arrayBuffer();
216
+ const content = await parseDOCX(buffer);
217
+ editor.commands.setContent(content);
218
+ }
219
+ ```
220
+
221
+ ### Node.js Environment with Image Cropping
222
+
223
+ To enable image cropping in Node.js environment, you need to provide `@napi-rs/canvas`:
224
+
225
+ ```typescript
226
+ import { parseDOCX } from "@docen/import-docx";
227
+ import { readFileSync } from "node:fs";
228
+
229
+ // Install @napi-rs/canvas first: pnpm add @napi-rs/canvas
230
+ const buffer = readFileSync("document.docx");
231
+
232
+ const content = await parseDOCX(buffer, {
233
+ canvasImport: () => import("@napi-rs/canvas"),
234
+ enableImageCrop: true, // Enable cropping (default is false)
235
+ });
236
+ ```
237
+
238
+ **Note:** By default, image cropping is disabled. Images are imported in full size, ignoring crop information in DOCX.
239
+
240
+ ### Disable Image Cropping
241
+
242
+ If you want to explicitly ignore crop information in DOCX and use full images (this is the default behavior):
243
+
244
+ ```typescript
245
+ const content = await parseDOCX(buffer, {
246
+ enableImageCrop: false,
247
+ });
248
+ ```
249
+
250
+ ## Known Limitations
251
+
252
+ ### Blockquote Detection
253
+
254
+ DOCX does not have a semantic blockquote structure. Blockquotes are detected by:
255
+
256
+ - Left indentation ≥ 720 twips (0.5 inch)
257
+ - Presence of left border (single line)
258
+
259
+ This detection method may produce false positives for documents with custom indentation similar to blockquotes.
260
+
261
+ ### Code Marks
262
+
263
+ The `code` mark is NOT automatically detected from monospace fonts (Consolas, Courier New, etc.). This is intentional to avoid false positives. Code marks should be explicitly added in the source document or through editor UI.
264
+
265
+ ### Color Format
266
+
267
+ All colors are imported as hex values (e.g., "#FF0000", "#008000"). Color names from the original document are not preserved.
268
+
269
+ ### Image Limitations
270
+
271
+ - Only embedded images are supported (external image links are not fetched)
272
+ - Image dimensions and title are extracted from DOCX metadata
273
+ - **Image Cropping**: By default, images are imported in full size (crop information is ignored)
274
+ - To enable cropping, set `enableImageCrop: true` in options
275
+ - In browser environments, cropping works natively with Canvas API
276
+ - In Node.js, you must also provide `canvasImport` option with dynamic import of `@napi-rs/canvas`
277
+ - If `@napi-rs/canvas` is not available in Node.js, images will be imported without cropping (graceful degradation)
278
+ - Some DOCX image features (like advanced positioning or text wrapping) have limited support
279
+
280
+ ### Table Cell Types
281
+
282
+ DOCX format does not distinguish between header and body cells at a semantic level. All cells are imported as `tableCell` type for consistency. This is a DOCX format limitation.
283
+
284
+ ## Contributing
285
+
286
+ Contributions are welcome! Please read our [Contributor Covenant](https://www.contributor-covenant.org/version/2/1/code_of_conduct/) and submit pull requests to the [main repository](https://github.com/DemoMacro/docen).
287
+
288
+ ## License
289
+
290
+ - [MIT](LICENSE) &copy; [Demo Macro](https://imst.xyz/)