@bendyline/squisq-formats 1.3.0 → 1.4.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 (224) hide show
  1. package/dist/chunk-6M7Z25LA.js +46 -0
  2. package/dist/chunk-6M7Z25LA.js.map +1 -0
  3. package/dist/{chunk-S3Y7H2BK.js → chunk-APSIAEXL.js} +9 -8
  4. package/dist/chunk-APSIAEXL.js.map +1 -0
  5. package/dist/{chunk-UDS45KUJ.js → chunk-BJQIJ4S4.js} +36 -52
  6. package/dist/chunk-BJQIJ4S4.js.map +1 -0
  7. package/dist/{chunk-33YRFXZZ.js → chunk-CRTC6DEX.js} +259 -13
  8. package/dist/chunk-CRTC6DEX.js.map +1 -0
  9. package/dist/chunk-FMOIGA5T.js +201 -0
  10. package/dist/chunk-FMOIGA5T.js.map +1 -0
  11. package/dist/{chunk-VN2KEOYB.js → chunk-I2GFTEOV.js} +321 -91
  12. package/dist/chunk-I2GFTEOV.js.map +1 -0
  13. package/dist/chunk-JBNVE2GV.js +116 -0
  14. package/dist/chunk-JBNVE2GV.js.map +1 -0
  15. package/dist/chunk-L53YIGYS.js +141 -0
  16. package/dist/chunk-L53YIGYS.js.map +1 -0
  17. package/dist/{chunk-ERZ627GR.js → chunk-ON232HJR.js} +11 -26
  18. package/dist/chunk-ON232HJR.js.map +1 -0
  19. package/dist/chunk-PN52A5AA.js +32 -0
  20. package/dist/chunk-PN52A5AA.js.map +1 -0
  21. package/dist/{chunk-7DEUGIOO.js → chunk-QSE7EWE7.js} +12 -87
  22. package/dist/chunk-QSE7EWE7.js.map +1 -0
  23. package/dist/container/index.d.ts +7 -5
  24. package/dist/container/index.js +39 -70
  25. package/dist/container/index.js.map +1 -1
  26. package/dist/csv/index.d.ts +37 -0
  27. package/dist/csv/index.js +13 -0
  28. package/dist/csv/index.js.map +1 -0
  29. package/dist/docx/index.d.ts +128 -15
  30. package/dist/docx/index.js +19 -22
  31. package/dist/docx/index.js.map +1 -1
  32. package/dist/epub/index.d.ts +66 -11
  33. package/dist/epub/index.js +11 -18
  34. package/dist/epub/index.js.map +1 -1
  35. package/dist/html/index.d.ts +315 -15
  36. package/dist/html/index.js +32 -165
  37. package/dist/html/index.js.map +1 -1
  38. package/dist/index.d.ts +10 -38
  39. package/dist/index.js +80 -37
  40. package/dist/index.js.map +1 -1
  41. package/dist/ooxml/index.d.ts +353 -14
  42. package/dist/ooxml/index.js +116 -22
  43. package/dist/ooxml/index.js.map +1 -1
  44. package/dist/pdf/index.d.ts +143 -17
  45. package/dist/pdf/index.js +16 -25
  46. package/dist/pdf/index.js.map +1 -1
  47. package/dist/pptx/index.d.ts +98 -21
  48. package/dist/pptx/index.js +18 -34
  49. package/dist/pptx/index.js.map +1 -1
  50. package/dist/xlsx/index.d.ts +29 -25
  51. package/dist/xlsx/index.js +13 -44
  52. package/dist/xlsx/index.js.map +1 -1
  53. package/package.json +7 -2
  54. package/src/__tests__/csvImport.test.ts +51 -0
  55. package/src/__tests__/exportThemeReconciliation.test.ts +87 -0
  56. package/src/__tests__/htmlImport.test.ts +57 -0
  57. package/src/__tests__/plainHtml.test.ts +31 -0
  58. package/src/__tests__/pptxExport.test.ts +138 -0
  59. package/src/__tests__/pptxImport.test.ts +70 -0
  60. package/src/__tests__/roundTripMatrix.fixtures.ts +86 -0
  61. package/src/__tests__/roundTripMatrix.helpers.ts +154 -0
  62. package/src/__tests__/roundTripMatrix.test.ts +136 -0
  63. package/src/__tests__/xlsxImport.test.ts +80 -0
  64. package/src/csv/index.ts +165 -0
  65. package/src/docx/export.ts +27 -44
  66. package/src/docx/import.ts +1 -2
  67. package/src/epub/export.ts +10 -27
  68. package/src/html/import.ts +297 -0
  69. package/src/html/index.ts +4 -0
  70. package/src/html/plainHtml.ts +66 -16
  71. package/src/index.ts +10 -3
  72. package/src/ooxml/namespaces.ts +3 -0
  73. package/src/pdf/export.ts +10 -5
  74. package/src/pdf/import.ts +1 -1
  75. package/src/pptx/export.ts +225 -85
  76. package/src/pptx/import.ts +156 -0
  77. package/src/pptx/index.ts +10 -28
  78. package/src/shared/inlineRuns.ts +99 -0
  79. package/src/shared/text.ts +41 -0
  80. package/src/xlsx/import.ts +159 -0
  81. package/src/xlsx/index.ts +11 -28
  82. package/dist/__tests__/container.test.d.ts +0 -8
  83. package/dist/__tests__/container.test.d.ts.map +0 -1
  84. package/dist/__tests__/container.test.js +0 -147
  85. package/dist/__tests__/container.test.js.map +0 -1
  86. package/dist/__tests__/docxExport.test.d.ts +0 -8
  87. package/dist/__tests__/docxExport.test.d.ts.map +0 -1
  88. package/dist/__tests__/docxExport.test.js +0 -383
  89. package/dist/__tests__/docxExport.test.js.map +0 -1
  90. package/dist/__tests__/docxImport.test.d.ts +0 -8
  91. package/dist/__tests__/docxImport.test.d.ts.map +0 -1
  92. package/dist/__tests__/docxImport.test.js +0 -309
  93. package/dist/__tests__/docxImport.test.js.map +0 -1
  94. package/dist/__tests__/epub.test.d.ts +0 -8
  95. package/dist/__tests__/epub.test.d.ts.map +0 -1
  96. package/dist/__tests__/epub.test.js +0 -472
  97. package/dist/__tests__/epub.test.js.map +0 -1
  98. package/dist/__tests__/html.test.d.ts +0 -8
  99. package/dist/__tests__/html.test.d.ts.map +0 -1
  100. package/dist/__tests__/html.test.js +0 -317
  101. package/dist/__tests__/html.test.js.map +0 -1
  102. package/dist/__tests__/ooxml.test.d.ts +0 -5
  103. package/dist/__tests__/ooxml.test.d.ts.map +0 -1
  104. package/dist/__tests__/ooxml.test.js +0 -152
  105. package/dist/__tests__/ooxml.test.js.map +0 -1
  106. package/dist/__tests__/pdfExport.test.d.ts +0 -8
  107. package/dist/__tests__/pdfExport.test.d.ts.map +0 -1
  108. package/dist/__tests__/pdfExport.test.js +0 -275
  109. package/dist/__tests__/pdfExport.test.js.map +0 -1
  110. package/dist/__tests__/pdfImport.test.d.ts +0 -11
  111. package/dist/__tests__/pdfImport.test.d.ts.map +0 -1
  112. package/dist/__tests__/pdfImport.test.js +0 -254
  113. package/dist/__tests__/pdfImport.test.js.map +0 -1
  114. package/dist/__tests__/plainHtml.test.d.ts +0 -5
  115. package/dist/__tests__/plainHtml.test.d.ts.map +0 -1
  116. package/dist/__tests__/plainHtml.test.js +0 -327
  117. package/dist/__tests__/plainHtml.test.js.map +0 -1
  118. package/dist/__tests__/plainHtmlBundle.test.d.ts +0 -11
  119. package/dist/__tests__/plainHtmlBundle.test.d.ts.map +0 -1
  120. package/dist/__tests__/plainHtmlBundle.test.js +0 -210
  121. package/dist/__tests__/plainHtmlBundle.test.js.map +0 -1
  122. package/dist/__tests__/roundTrip.test.d.ts +0 -7
  123. package/dist/__tests__/roundTrip.test.d.ts.map +0 -1
  124. package/dist/__tests__/roundTrip.test.js +0 -173
  125. package/dist/__tests__/roundTrip.test.js.map +0 -1
  126. package/dist/chunk-33YRFXZZ.js.map +0 -1
  127. package/dist/chunk-67KIJHV2.js +0 -21
  128. package/dist/chunk-67KIJHV2.js.map +0 -1
  129. package/dist/chunk-7DEUGIOO.js.map +0 -1
  130. package/dist/chunk-ERZ627GR.js.map +0 -1
  131. package/dist/chunk-S3Y7H2BK.js.map +0 -1
  132. package/dist/chunk-UDS45KUJ.js.map +0 -1
  133. package/dist/chunk-VN2KEOYB.js.map +0 -1
  134. package/dist/chunk-YN5HFCEW.js +0 -120
  135. package/dist/chunk-YN5HFCEW.js.map +0 -1
  136. package/dist/container/index.d.ts.map +0 -1
  137. package/dist/docx/export.d.ts +0 -69
  138. package/dist/docx/export.d.ts.map +0 -1
  139. package/dist/docx/export.js +0 -985
  140. package/dist/docx/export.js.map +0 -1
  141. package/dist/docx/import.d.ts +0 -65
  142. package/dist/docx/import.d.ts.map +0 -1
  143. package/dist/docx/import.js +0 -779
  144. package/dist/docx/import.js.map +0 -1
  145. package/dist/docx/index.d.ts.map +0 -1
  146. package/dist/docx/styles.d.ts +0 -68
  147. package/dist/docx/styles.d.ts.map +0 -1
  148. package/dist/docx/styles.js +0 -125
  149. package/dist/docx/styles.js.map +0 -1
  150. package/dist/epub/export.d.ts +0 -72
  151. package/dist/epub/export.d.ts.map +0 -1
  152. package/dist/epub/export.js +0 -698
  153. package/dist/epub/export.js.map +0 -1
  154. package/dist/epub/index.d.ts.map +0 -1
  155. package/dist/html/docsHtmlBundle.d.ts +0 -53
  156. package/dist/html/docsHtmlBundle.d.ts.map +0 -1
  157. package/dist/html/docsHtmlBundle.js +0 -299
  158. package/dist/html/docsHtmlBundle.js.map +0 -1
  159. package/dist/html/htmlTemplate.d.ts +0 -70
  160. package/dist/html/htmlTemplate.d.ts.map +0 -1
  161. package/dist/html/htmlTemplate.js +0 -282
  162. package/dist/html/htmlTemplate.js.map +0 -1
  163. package/dist/html/imageUtils.d.ts +0 -29
  164. package/dist/html/imageUtils.d.ts.map +0 -1
  165. package/dist/html/imageUtils.js +0 -63
  166. package/dist/html/imageUtils.js.map +0 -1
  167. package/dist/html/index.d.ts.map +0 -1
  168. package/dist/html/plainHtml.d.ts +0 -79
  169. package/dist/html/plainHtml.d.ts.map +0 -1
  170. package/dist/html/plainHtml.js +0 -614
  171. package/dist/html/plainHtml.js.map +0 -1
  172. package/dist/html/plainHtmlBundle.d.ts +0 -93
  173. package/dist/html/plainHtmlBundle.d.ts.map +0 -1
  174. package/dist/html/plainHtmlBundle.js +0 -357
  175. package/dist/html/plainHtmlBundle.js.map +0 -1
  176. package/dist/index.d.ts.map +0 -1
  177. package/dist/ooxml/index.d.ts.map +0 -1
  178. package/dist/ooxml/namespaces.d.ts +0 -77
  179. package/dist/ooxml/namespaces.d.ts.map +0 -1
  180. package/dist/ooxml/namespaces.js +0 -104
  181. package/dist/ooxml/namespaces.js.map +0 -1
  182. package/dist/ooxml/reader.d.ts +0 -52
  183. package/dist/ooxml/reader.d.ts.map +0 -1
  184. package/dist/ooxml/reader.js +0 -190
  185. package/dist/ooxml/reader.js.map +0 -1
  186. package/dist/ooxml/types.d.ts +0 -82
  187. package/dist/ooxml/types.d.ts.map +0 -1
  188. package/dist/ooxml/types.js +0 -9
  189. package/dist/ooxml/types.js.map +0 -1
  190. package/dist/ooxml/writer.d.ts +0 -71
  191. package/dist/ooxml/writer.d.ts.map +0 -1
  192. package/dist/ooxml/writer.js +0 -200
  193. package/dist/ooxml/writer.js.map +0 -1
  194. package/dist/ooxml/xmlUtils.d.ts +0 -76
  195. package/dist/ooxml/xmlUtils.d.ts.map +0 -1
  196. package/dist/ooxml/xmlUtils.js +0 -108
  197. package/dist/ooxml/xmlUtils.js.map +0 -1
  198. package/dist/pdf/export.d.ts +0 -56
  199. package/dist/pdf/export.d.ts.map +0 -1
  200. package/dist/pdf/export.js +0 -768
  201. package/dist/pdf/export.js.map +0 -1
  202. package/dist/pdf/import.d.ts +0 -94
  203. package/dist/pdf/import.d.ts.map +0 -1
  204. package/dist/pdf/import.js +0 -796
  205. package/dist/pdf/import.js.map +0 -1
  206. package/dist/pdf/index.d.ts.map +0 -1
  207. package/dist/pdf/styles.d.ts +0 -142
  208. package/dist/pdf/styles.d.ts.map +0 -1
  209. package/dist/pdf/styles.js +0 -145
  210. package/dist/pdf/styles.js.map +0 -1
  211. package/dist/pptx/export.d.ts +0 -75
  212. package/dist/pptx/export.d.ts.map +0 -1
  213. package/dist/pptx/export.js +0 -724
  214. package/dist/pptx/export.js.map +0 -1
  215. package/dist/pptx/index.d.ts.map +0 -1
  216. package/dist/pptx/styles.d.ts +0 -54
  217. package/dist/pptx/styles.d.ts.map +0 -1
  218. package/dist/pptx/styles.js +0 -73
  219. package/dist/pptx/styles.js.map +0 -1
  220. package/dist/pptx/templates.d.ts +0 -24
  221. package/dist/pptx/templates.d.ts.map +0 -1
  222. package/dist/pptx/templates.js +0 -158
  223. package/dist/pptx/templates.js.map +0 -1
  224. package/dist/xlsx/index.d.ts.map +0 -1
@@ -1,779 +0,0 @@
1
- /**
2
- * DOCX Import
3
- *
4
- * Parses a .docx file (Office Open XML WordprocessingML) and converts
5
- * its content into a squisq MarkdownDocument (or Doc).
6
- *
7
- * Uses JSZip + DOMParser to read the archive and parse the XML — no
8
- * third-party docx library. Handles headings, paragraphs, inline
9
- * formatting (bold, italic, strikethrough), hyperlinks, lists, tables,
10
- * blockquotes, code blocks, images, and footnotes.
11
- *
12
- * @example
13
- * ```ts
14
- * import { docxToMarkdownDoc } from '@bendyline/squisq-formats/docx';
15
- *
16
- * const response = await fetch('document.docx');
17
- * const data = await response.arrayBuffer();
18
- * const doc = await docxToMarkdownDoc(data);
19
- * ```
20
- */
21
- import { markdownToDoc } from '@bendyline/squisq/doc';
22
- import { openPackage, getPartXml, getPartBinary, getPartRelationships } from '../ooxml/reader.js';
23
- import { NS_WML, NS_R } from '../ooxml/namespaces.js';
24
- import { MemoryContentContainer } from '@bendyline/squisq/storage';
25
- import { HEADING_STYLE_MAP, QUOTE_STYLE_IDS, CODE_STYLE_IDS, INLINE_CODE_STYLE_IDS, BULLET_NUM_FORMATS, } from './styles.js';
26
- /**
27
- * Convert a .docx file to a MarkdownDocument.
28
- *
29
- * @param data - The raw .docx file as ArrayBuffer or Blob
30
- * @param options - Import options
31
- * @returns A MarkdownDocument representing the document content
32
- */
33
- export async function docxToMarkdownDoc(data, options = {}) {
34
- const pkg = await openPackage(data);
35
- const ctx = await buildImportContext(pkg, options);
36
- const documentXml = await getPartXml(pkg, 'word/document.xml');
37
- if (!documentXml) {
38
- return { type: 'document', children: [] };
39
- }
40
- const body = getFirstElement(documentXml, 'body');
41
- if (!body) {
42
- return { type: 'document', children: [] };
43
- }
44
- const blocks = await convertBody(body, ctx);
45
- return { type: 'document', children: blocks };
46
- }
47
- /**
48
- * Convert a .docx file to a squisq Doc.
49
- *
50
- * Convenience wrapper: DOCX → MarkdownDocument → Doc.
51
- *
52
- * @param data - The raw .docx file as ArrayBuffer or Blob
53
- * @param options - Import options
54
- * @returns A squisq Doc
55
- */
56
- export async function docxToDoc(data, options = {}) {
57
- const markdownDoc = await docxToMarkdownDoc(data, options);
58
- return markdownToDoc(markdownDoc);
59
- }
60
- /**
61
- * Convert a .docx file to a ContentContainer with markdown + extracted images.
62
- *
63
- * The container will contain:
64
- * - The primary markdown document (index.md)
65
- * - Any embedded images under images/ (e.g., images/image1.png)
66
- *
67
- * @param data - The raw .docx file as ArrayBuffer or Blob
68
- * @param options - Import options
69
- * @returns A ContentContainer with the document and its media
70
- */
71
- export async function docxToContainer(data, options = {}) {
72
- const pkg = await openPackage(data);
73
- const ctx = await buildImportContext(pkg, { ...options, extractImages: true });
74
- const documentXml = await getPartXml(pkg, 'word/document.xml');
75
- if (!documentXml) {
76
- const container = new MemoryContentContainer();
77
- await container.writeDocument('');
78
- return container;
79
- }
80
- const body = getFirstElement(documentXml, 'body');
81
- if (!body) {
82
- const container = new MemoryContentContainer();
83
- await container.writeDocument('');
84
- return container;
85
- }
86
- const blocks = await convertBody(body, ctx);
87
- const markdownDoc = { type: 'document', children: blocks };
88
- // Serialize to markdown
89
- const { stringifyMarkdown } = await import('@bendyline/squisq/markdown');
90
- const markdown = stringifyMarkdown(markdownDoc);
91
- // Build container with markdown + images
92
- const container = new MemoryContentContainer();
93
- await container.writeDocument(markdown);
94
- for (const [path, { data: imageData, mimeType }] of ctx.extractedImages) {
95
- await container.writeFile(path, new Uint8Array(imageData), mimeType);
96
- }
97
- return container;
98
- }
99
- async function buildImportContext(pkg, options) {
100
- const ctx = {
101
- headingStyles: new Map(),
102
- quoteStyles: new Set(),
103
- codeStyles: new Set(),
104
- inlineCodeStyles: new Set(),
105
- documentRels: new Map(),
106
- numbering: new Map(),
107
- footnotes: new Map(),
108
- pkg,
109
- options,
110
- extractedImages: new Map(),
111
- imageCounter: 0,
112
- };
113
- // Initialize with built-in defaults
114
- for (const [id, depth] of Object.entries(HEADING_STYLE_MAP)) {
115
- ctx.headingStyles.set(id, depth);
116
- }
117
- for (const id of QUOTE_STYLE_IDS) {
118
- ctx.quoteStyles.add(id);
119
- }
120
- for (const id of CODE_STYLE_IDS) {
121
- ctx.codeStyles.add(id);
122
- }
123
- for (const id of INLINE_CODE_STYLE_IDS) {
124
- ctx.inlineCodeStyles.add(id);
125
- }
126
- // Parse styles.xml for custom heading/quote/code mappings
127
- await parseStyles(pkg, ctx);
128
- // Parse document relationships
129
- const rels = await getPartRelationships(pkg, 'word/document.xml');
130
- for (const rel of rels) {
131
- ctx.documentRels.set(rel.id, rel);
132
- }
133
- // Parse numbering.xml
134
- await parseNumbering(pkg, ctx);
135
- // Parse footnotes.xml
136
- await parseFootnotes(pkg, ctx);
137
- return ctx;
138
- }
139
- // ============================================
140
- // Styles Parsing
141
- // ============================================
142
- async function parseStyles(pkg, ctx) {
143
- const doc = await getPartXml(pkg, 'word/styles.xml');
144
- if (!doc)
145
- return;
146
- const styles = doc.getElementsByTagNameNS(NS_WML, 'style');
147
- // Fallback for documents that don't use namespace prefixes properly
148
- const stylesList = styles.length > 0 ? styles : doc.getElementsByTagName('style');
149
- for (let i = 0; i < stylesList.length; i++) {
150
- const style = stylesList[i];
151
- const styleId = style.getAttributeNS(NS_WML, 'styleId') ?? style.getAttribute('w:styleId');
152
- if (!styleId)
153
- continue;
154
- const nameEl = getFirstChildElement(style, 'name');
155
- const styleName = nameEl?.getAttributeNS(NS_WML, 'val') ?? nameEl?.getAttribute('w:val') ?? '';
156
- // Check if this is a heading style by name
157
- const headingMatch = styleName.match(/^heading\s+(\d+)$/i);
158
- if (headingMatch) {
159
- const depth = parseInt(headingMatch[1], 10);
160
- if (depth >= 1 && depth <= 6) {
161
- ctx.headingStyles.set(styleId, depth);
162
- }
163
- }
164
- // Check pPr > outlineLvl for heading detection
165
- const pPr = getFirstChildElement(style, 'pPr');
166
- if (pPr) {
167
- const outlineLvl = getFirstChildElement(pPr, 'outlineLvl');
168
- if (outlineLvl) {
169
- const val = outlineLvl.getAttributeNS(NS_WML, 'val') ?? outlineLvl.getAttribute('w:val');
170
- if (val !== null) {
171
- const depth = parseInt(val, 10) + 1;
172
- if (depth >= 1 && depth <= 6) {
173
- ctx.headingStyles.set(styleId, depth);
174
- }
175
- }
176
- }
177
- }
178
- }
179
- }
180
- // ============================================
181
- // Numbering Parsing
182
- // ============================================
183
- async function parseNumbering(pkg, ctx) {
184
- const doc = await getPartXml(pkg, 'word/numbering.xml');
185
- if (!doc)
186
- return;
187
- // Parse abstract numbering definitions
188
- const abstractNums = new Map(); // abstractNumId → levels(ilvl → isOrdered)
189
- const abstractNumEls = getAllElements(doc, 'abstractNum');
190
- for (const absNum of abstractNumEls) {
191
- const absId = getAttr(absNum, 'abstractNumId');
192
- if (!absId)
193
- continue;
194
- const levels = new Map();
195
- const lvlEls = getAllChildElements(absNum, 'lvl');
196
- for (const lvl of lvlEls) {
197
- const ilvlStr = getAttr(lvl, 'ilvl');
198
- if (ilvlStr === null)
199
- continue;
200
- const ilvl = parseInt(ilvlStr, 10);
201
- const numFmtEl = getFirstChildElement(lvl, 'numFmt');
202
- const numFmt = numFmtEl ? getAttr(numFmtEl, 'val') : null;
203
- const isOrdered = numFmt !== null && !BULLET_NUM_FORMATS.has(numFmt);
204
- levels.set(ilvl, isOrdered);
205
- }
206
- abstractNums.set(absId, levels);
207
- }
208
- // Parse concrete num → abstractNum mappings
209
- const numEls = getAllElements(doc, 'num');
210
- for (const num of numEls) {
211
- const numId = getAttr(num, 'numId');
212
- if (!numId)
213
- continue;
214
- const abstractNumIdEl = getFirstChildElement(num, 'abstractNumId');
215
- const absId = abstractNumIdEl ? getAttr(abstractNumIdEl, 'val') : null;
216
- if (!absId)
217
- continue;
218
- const levels = abstractNums.get(absId);
219
- if (levels) {
220
- ctx.numbering.set(numId, { levels });
221
- }
222
- }
223
- }
224
- // ============================================
225
- // Footnotes Parsing
226
- // ============================================
227
- async function parseFootnotes(pkg, ctx) {
228
- const doc = await getPartXml(pkg, 'word/footnotes.xml');
229
- if (!doc)
230
- return;
231
- const footnoteEls = getAllElements(doc, 'footnote');
232
- for (const fn of footnoteEls) {
233
- const id = getAttr(fn, 'id');
234
- const type = getAttr(fn, 'type');
235
- // Skip separator and continuation separator footnotes
236
- if (!id || type === 'separator' || type === 'continuationSeparator')
237
- continue;
238
- ctx.footnotes.set(id, fn);
239
- }
240
- }
241
- // ============================================
242
- // Body Conversion
243
- // ============================================
244
- async function convertBody(body, ctx) {
245
- const result = [];
246
- const children = Array.from(body.children);
247
- let i = 0;
248
- while (i < children.length) {
249
- const el = children[i];
250
- const localName = el.localName;
251
- if (localName === 'p') {
252
- // Check if this is part of a list
253
- const numPr = getNumPr(el);
254
- if (numPr) {
255
- // Collect consecutive list paragraphs
256
- const { node, consumed } = await collectList(children, i, ctx);
257
- result.push(node);
258
- i += consumed;
259
- continue;
260
- }
261
- const block = await convertParagraph(el, ctx);
262
- if (block) {
263
- result.push(block);
264
- }
265
- i++;
266
- }
267
- else if (localName === 'tbl') {
268
- const table = await convertTable(el, ctx);
269
- if (table)
270
- result.push(table);
271
- i++;
272
- }
273
- else {
274
- // Skip unknown elements (sectPr, bookmarkStart, etc.)
275
- i++;
276
- }
277
- }
278
- // Append footnote definitions at the end
279
- const footnoteNodes = await convertFootnoteDefinitions(ctx);
280
- result.push(...footnoteNodes);
281
- return result;
282
- }
283
- // ============================================
284
- // Paragraph Conversion
285
- // ============================================
286
- async function convertParagraph(el, ctx) {
287
- const pPr = getFirstChildElement(el, 'pPr');
288
- const styleId = getParagraphStyleId(pPr);
289
- // Check for heading
290
- if (styleId && ctx.headingStyles.has(styleId)) {
291
- const depth = ctx.headingStyles.get(styleId);
292
- const inlines = await convertRuns(el, ctx);
293
- if (inlines.length === 0)
294
- return null;
295
- return {
296
- type: 'heading',
297
- depth: Math.min(Math.max(depth, 1), 6),
298
- children: inlines,
299
- };
300
- }
301
- // Check for blockquote
302
- if (styleId && ctx.quoteStyles.has(styleId)) {
303
- const inlines = await convertRuns(el, ctx);
304
- if (inlines.length === 0)
305
- return null;
306
- const paragraph = { type: 'paragraph', children: inlines };
307
- return { type: 'blockquote', children: [paragraph] };
308
- }
309
- // Check for code block
310
- if (styleId && ctx.codeStyles.has(styleId)) {
311
- const text = getElementTextContent(el);
312
- return { type: 'code', value: text };
313
- }
314
- // Regular paragraph
315
- const inlines = await convertRuns(el, ctx);
316
- if (inlines.length === 0)
317
- return null;
318
- return { type: 'paragraph', children: inlines };
319
- }
320
- // ============================================
321
- // Run (Inline) Conversion
322
- // ============================================
323
- async function convertRuns(paragraphEl, ctx) {
324
- const result = [];
325
- const children = Array.from(paragraphEl.children);
326
- for (const child of children) {
327
- const localName = child.localName;
328
- if (localName === 'r') {
329
- const inlines = await convertRun(child, ctx);
330
- result.push(...inlines);
331
- }
332
- else if (localName === 'hyperlink') {
333
- const link = await convertHyperlink(child, ctx);
334
- if (link)
335
- result.push(link);
336
- }
337
- // Skip pPr, bookmarkStart, bookmarkEnd, etc.
338
- }
339
- return mergeAdjacentText(result);
340
- }
341
- async function convertRun(runEl, ctx) {
342
- const result = [];
343
- const rPr = getFirstChildElement(runEl, 'rPr');
344
- const format = parseRunFormat(rPr, ctx);
345
- for (const child of Array.from(runEl.children)) {
346
- const localName = child.localName;
347
- if (localName === 't') {
348
- const text = child.textContent ?? '';
349
- if (!text)
350
- continue;
351
- if (format.code) {
352
- result.push({ type: 'inlineCode', value: text });
353
- }
354
- else {
355
- let node = { type: 'text', value: text };
356
- if (format.strike) {
357
- node = { type: 'delete', children: [node] };
358
- }
359
- if (format.italic) {
360
- node = { type: 'emphasis', children: [node] };
361
- }
362
- if (format.bold) {
363
- node = { type: 'strong', children: [node] };
364
- }
365
- result.push(node);
366
- }
367
- }
368
- else if (localName === 'br') {
369
- result.push({ type: 'break' });
370
- }
371
- else if (localName === 'footnoteReference') {
372
- const fnId = getAttr(child, 'id');
373
- if (fnId && fnId !== '0' && fnId !== '-1') {
374
- result.push({
375
- type: 'footnoteReference',
376
- identifier: `fn${fnId}`,
377
- });
378
- }
379
- }
380
- else if (localName === 'drawing' || localName === 'pict') {
381
- const img = await extractImage(child, ctx);
382
- if (img)
383
- result.push(img);
384
- }
385
- }
386
- return result;
387
- }
388
- function parseRunFormat(rPr, ctx) {
389
- if (!rPr)
390
- return { bold: false, italic: false, strike: false, code: false };
391
- const bold = hasChildElement(rPr, 'b') && !isFalseToggle(getFirstChildElement(rPr, 'b'));
392
- const italic = hasChildElement(rPr, 'i') && !isFalseToggle(getFirstChildElement(rPr, 'i'));
393
- const strike = hasChildElement(rPr, 'strike') && !isFalseToggle(getFirstChildElement(rPr, 'strike'));
394
- // Check for inline code via character style
395
- const rStyle = getFirstChildElement(rPr, 'rStyle');
396
- const charStyleId = rStyle ? getAttr(rStyle, 'val') : null;
397
- const isCodeStyle = charStyleId ? ctx.inlineCodeStyles.has(charStyleId) : false;
398
- // Check for monospace font as a code indicator
399
- const rFonts = getFirstChildElement(rPr, 'rFonts');
400
- const fontName = rFonts ? (getAttr(rFonts, 'ascii') ?? getAttr(rFonts, 'hAnsi') ?? '') : '';
401
- const isMonospace = /consolas|courier|mono/i.test(fontName);
402
- return { bold, italic, strike, code: isCodeStyle || isMonospace };
403
- }
404
- function isFalseToggle(el) {
405
- const val = getAttr(el, 'val');
406
- return val === '0' || val === 'false';
407
- }
408
- // ============================================
409
- // Hyperlink Conversion
410
- // ============================================
411
- async function convertHyperlink(el, ctx) {
412
- const rId = el.getAttributeNS(NS_R, 'id') ?? el.getAttribute('r:id');
413
- let url = '';
414
- if (rId) {
415
- const rel = ctx.documentRels.get(rId);
416
- if (rel)
417
- url = rel.target;
418
- }
419
- // Also check for w:anchor (internal bookmarks)
420
- if (!url) {
421
- const anchor = el.getAttributeNS(NS_WML, 'anchor') ?? el.getAttribute('w:anchor');
422
- if (anchor)
423
- url = `#${anchor}`;
424
- }
425
- const inlines = [];
426
- for (const child of Array.from(el.children)) {
427
- if (child.localName === 'r') {
428
- inlines.push(...(await convertRun(child, ctx)));
429
- }
430
- }
431
- if (inlines.length === 0)
432
- return null;
433
- return {
434
- type: 'link',
435
- url,
436
- children: mergeAdjacentText(inlines),
437
- };
438
- }
439
- // ============================================
440
- // Image Extraction
441
- // ============================================
442
- async function extractImage(el, ctx) {
443
- // Find <a:blip r:embed="rIdX"/> anywhere in the drawing tree
444
- const blip = findDescendant(el, 'blip');
445
- if (!blip) {
446
- return { type: 'image', url: '', alt: 'Image' };
447
- }
448
- const rId = blip.getAttributeNS(NS_R, 'embed') ?? blip.getAttribute('r:embed');
449
- if (!rId) {
450
- return { type: 'image', url: '', alt: 'Image' };
451
- }
452
- const rel = ctx.documentRels.get(rId);
453
- if (!rel) {
454
- return { type: 'image', url: '', alt: 'Image' };
455
- }
456
- // Resolve the target path relative to word/
457
- const target = rel.target.startsWith('/') ? rel.target.slice(1) : `word/${rel.target}`;
458
- // Extract binary data from the zip
459
- const data = await getPartBinary(ctx.pkg, target);
460
- if (!data) {
461
- return { type: 'image', url: '', alt: 'Image' };
462
- }
463
- // Determine extension and MIME type
464
- const dot = target.lastIndexOf('.');
465
- const ext = dot !== -1 ? target.slice(dot).toLowerCase() : '.png';
466
- const mimeType = IMAGE_MIME_MAP[ext] ?? 'application/octet-stream';
467
- // Generate a unique image path
468
- ctx.imageCounter++;
469
- const imagePath = `images/image${ctx.imageCounter}${ext}`;
470
- // Store the extracted image data
471
- ctx.extractedImages.set(imagePath, { data, mimeType });
472
- // Try to extract alt text from the drawing's docPr element
473
- const docPr = findDescendant(el, 'docPr');
474
- const alt = docPr?.getAttribute('descr') || docPr?.getAttribute('title') || 'Image';
475
- return {
476
- type: 'image',
477
- url: imagePath,
478
- alt,
479
- };
480
- }
481
- const IMAGE_MIME_MAP = {
482
- '.png': 'image/png',
483
- '.jpg': 'image/jpeg',
484
- '.jpeg': 'image/jpeg',
485
- '.gif': 'image/gif',
486
- '.bmp': 'image/bmp',
487
- '.tiff': 'image/tiff',
488
- '.tif': 'image/tiff',
489
- '.svg': 'image/svg+xml',
490
- '.webp': 'image/webp',
491
- '.emf': 'image/emf',
492
- '.wmf': 'image/wmf',
493
- };
494
- /** Recursively find the first descendant element with the given local name. */
495
- function findDescendant(el, localName) {
496
- for (const child of Array.from(el.children)) {
497
- if (child.localName === localName)
498
- return child;
499
- const found = findDescendant(child, localName);
500
- if (found)
501
- return found;
502
- }
503
- return null;
504
- }
505
- async function collectList(elements, startIdx, ctx) {
506
- const firstNumPr = getNumPr(elements[startIdx]);
507
- const { numId } = firstNumPr;
508
- // Determine if ordered from numbering definition
509
- const numInfo = ctx.numbering.get(numId);
510
- const isOrdered = numInfo?.levels.get(0) ?? false;
511
- const items = [];
512
- let consumed = 0;
513
- let i = startIdx;
514
- while (i < elements.length) {
515
- const el = elements[i];
516
- if (el.localName !== 'p')
517
- break;
518
- const numPr = getNumPr(el);
519
- if (!numPr || numPr.numId !== numId)
520
- break;
521
- // Convert this paragraph's inline content
522
- const inlines = await convertRuns(el, ctx);
523
- if (inlines.length > 0) {
524
- const paragraph = { type: 'paragraph', children: inlines };
525
- // Check if this is a nested list item
526
- if (numPr.ilvl > firstNumPr.ilvl) {
527
- // Collect nested list items
528
- const nested = await collectNestedList(elements, i, ctx, firstNumPr.ilvl);
529
- if (items.length > 0) {
530
- // Attach nested list to the last item
531
- const lastItem = items[items.length - 1];
532
- const nestedIsOrdered = numInfo?.levels.get(numPr.ilvl) ?? false;
533
- const nestedList = {
534
- type: 'list',
535
- ordered: nestedIsOrdered,
536
- children: nested.items,
537
- };
538
- lastItem.children.push(nestedList);
539
- }
540
- i += nested.consumed;
541
- consumed += nested.consumed;
542
- continue;
543
- }
544
- items.push({
545
- type: 'listItem',
546
- children: [paragraph],
547
- });
548
- }
549
- i++;
550
- consumed++;
551
- }
552
- return {
553
- node: {
554
- type: 'list',
555
- ordered: isOrdered,
556
- children: items,
557
- },
558
- consumed,
559
- };
560
- }
561
- async function collectNestedList(elements, startIdx, ctx, parentIlvl) {
562
- const items = [];
563
- let consumed = 0;
564
- let i = startIdx;
565
- while (i < elements.length) {
566
- const el = elements[i];
567
- if (el.localName !== 'p')
568
- break;
569
- const numPr = getNumPr(el);
570
- if (!numPr)
571
- break;
572
- if (numPr.ilvl <= parentIlvl)
573
- break;
574
- const inlines = await convertRuns(el, ctx);
575
- if (inlines.length > 0) {
576
- const paragraph = { type: 'paragraph', children: inlines };
577
- items.push({ type: 'listItem', children: [paragraph] });
578
- }
579
- i++;
580
- consumed++;
581
- }
582
- return { items, consumed };
583
- }
584
- function getNumPr(el) {
585
- const pPr = getFirstChildElement(el, 'pPr');
586
- if (!pPr)
587
- return null;
588
- const numPr = getFirstChildElement(pPr, 'numPr');
589
- if (!numPr)
590
- return null;
591
- const ilvlEl = getFirstChildElement(numPr, 'ilvl');
592
- const numIdEl = getFirstChildElement(numPr, 'numId');
593
- const ilvlVal = ilvlEl ? getAttr(ilvlEl, 'val') : null;
594
- const numIdVal = numIdEl ? getAttr(numIdEl, 'val') : null;
595
- if (!numIdVal || numIdVal === '0')
596
- return null; // numId 0 means "no list"
597
- return {
598
- numId: numIdVal,
599
- ilvl: ilvlVal ? parseInt(ilvlVal, 10) : 0,
600
- };
601
- }
602
- // ============================================
603
- // Table Conversion
604
- // ============================================
605
- async function convertTable(tblEl, ctx) {
606
- const rows = [];
607
- const trEls = getAllChildElements(tblEl, 'tr');
608
- for (let ri = 0; ri < trEls.length; ri++) {
609
- const row = await convertTableRow(trEls[ri], ctx, ri === 0);
610
- rows.push(row);
611
- }
612
- if (rows.length === 0)
613
- return null;
614
- // If first row isn't explicitly a header, treat it as one anyway
615
- // (Markdown tables require a header row)
616
- return {
617
- type: 'table',
618
- children: rows,
619
- };
620
- }
621
- async function convertTableRow(trEl, ctx, isHeader) {
622
- const cells = [];
623
- const tcEls = getAllChildElements(trEl, 'tc');
624
- for (const tc of tcEls) {
625
- const cell = await convertTableCell(tc, ctx, isHeader);
626
- cells.push(cell);
627
- }
628
- return { type: 'tableRow', children: cells };
629
- }
630
- async function convertTableCell(tcEl, ctx, isHeader) {
631
- const inlines = [];
632
- // A cell can contain multiple paragraphs; flatten them with breaks
633
- const paragraphs = getAllChildElements(tcEl, 'p');
634
- for (let pi = 0; pi < paragraphs.length; pi++) {
635
- if (pi > 0) {
636
- inlines.push({ type: 'break' });
637
- }
638
- const runs = await convertRuns(paragraphs[pi], ctx);
639
- inlines.push(...runs);
640
- }
641
- return {
642
- type: 'tableCell',
643
- isHeader,
644
- children: mergeAdjacentText(inlines),
645
- };
646
- }
647
- // ============================================
648
- // Footnote Definition Conversion
649
- // ============================================
650
- async function convertFootnoteDefinitions(ctx) {
651
- const results = [];
652
- for (const [id, el] of ctx.footnotes) {
653
- const children = [];
654
- const paragraphs = getAllChildElements(el, 'p');
655
- for (const p of paragraphs) {
656
- const inlines = await convertRuns(p, ctx);
657
- if (inlines.length > 0) {
658
- children.push({
659
- type: 'paragraph',
660
- children: inlines,
661
- });
662
- }
663
- }
664
- if (children.length > 0) {
665
- results.push({
666
- type: 'footnoteDefinition',
667
- identifier: `fn${id}`,
668
- children,
669
- });
670
- }
671
- }
672
- return results;
673
- }
674
- // ============================================
675
- // XML Helper Utilities
676
- // ============================================
677
- /**
678
- * Get the first element child with a given local name.
679
- * Handles both namespaced and non-namespaced elements.
680
- */
681
- function getFirstChildElement(parent, localName) {
682
- for (const child of Array.from(parent.children ?? [])) {
683
- if (child.localName === localName)
684
- return child;
685
- }
686
- return null;
687
- }
688
- /**
689
- * Get all direct child elements with a given local name.
690
- */
691
- function getAllChildElements(parent, localName) {
692
- const result = [];
693
- for (const child of Array.from(parent.children)) {
694
- if (child.localName === localName)
695
- result.push(child);
696
- }
697
- return result;
698
- }
699
- /**
700
- * Get all elements with a given local name in the document.
701
- */
702
- function getAllElements(doc, localName) {
703
- // Try namespace-aware first
704
- const nsEls = 'getElementsByTagNameNS' in doc ? doc.getElementsByTagNameNS(NS_WML, localName) : null;
705
- if (nsEls && nsEls.length > 0)
706
- return Array.from(nsEls);
707
- // Fallback: try with w: prefix
708
- const prefixed = doc.getElementsByTagName(`w:${localName}`);
709
- if (prefixed.length > 0)
710
- return Array.from(prefixed);
711
- // Final fallback: bare name
712
- return Array.from(doc.getElementsByTagName(localName));
713
- }
714
- /**
715
- * Get the first element with given local name in the document or subtree.
716
- */
717
- function getFirstElement(doc, localName) {
718
- const els = getAllElements(doc, localName);
719
- return els.length > 0 ? els[0] : null;
720
- }
721
- /**
722
- * Get a w:-prefixed attribute, trying namespace-aware first then fallback.
723
- */
724
- function getAttr(el, localName) {
725
- return el.getAttributeNS(NS_WML, localName) || el.getAttribute(`w:${localName}`) || null;
726
- }
727
- /**
728
- * Check if an element has a direct child with the given local name.
729
- */
730
- function hasChildElement(parent, localName) {
731
- return getFirstChildElement(parent, localName) !== null;
732
- }
733
- /**
734
- * Get the paragraph style ID from a pPr element.
735
- */
736
- function getParagraphStyleId(pPr) {
737
- if (!pPr)
738
- return null;
739
- const pStyle = getFirstChildElement(pPr, 'pStyle');
740
- if (!pStyle)
741
- return null;
742
- return getAttr(pStyle, 'val');
743
- }
744
- /**
745
- * Get all text content from an element (concatenating all w:t descendants).
746
- */
747
- function getElementTextContent(el) {
748
- const parts = [];
749
- function walk(node) {
750
- if (node.localName === 't') {
751
- parts.push(node.textContent ?? '');
752
- }
753
- for (const child of Array.from(node.children)) {
754
- walk(child);
755
- }
756
- }
757
- walk(el);
758
- return parts.join('');
759
- }
760
- /**
761
- * Merge adjacent MarkdownText nodes to reduce fragmentation.
762
- */
763
- function mergeAdjacentText(nodes) {
764
- if (nodes.length <= 1)
765
- return nodes;
766
- const result = [];
767
- for (const node of nodes) {
768
- const prev = result[result.length - 1];
769
- if (node.type === 'text' && prev?.type === 'text') {
770
- // Merge into previous text node
771
- prev.value += node.value;
772
- }
773
- else {
774
- result.push(node);
775
- }
776
- }
777
- return result;
778
- }
779
- //# sourceMappingURL=import.js.map