@gmickel/gno 1.45.1 → 2.0.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 (236) hide show
  1. package/README.md +1 -1
  2. package/THIRD_PARTY_NOTICES.md +46 -0
  3. package/assets/skill/SKILL.md +7 -6
  4. package/assets/skill/cli-reference.md +14 -6
  5. package/assets/skill/mcp-reference.md +4 -1
  6. package/assets/spa-production.json.gz +0 -0
  7. package/browser-extension/artifacts/gno-browser-clipper-v2.0.0.zip +0 -0
  8. package/browser-extension/artifacts/gno-browser-clipper-v2.0.0.zip.sha256 +1 -0
  9. package/browser-extension/dist/chunk-4tc9v0ja.js +74 -0
  10. package/browser-extension/dist/manifest.json +1 -1
  11. package/browser-extension/dist/preview.html +1 -1
  12. package/browser-extension/dist/service-worker.js +32 -33
  13. package/bunfig.toml +2 -0
  14. package/package.json +40 -26
  15. package/spec/cli.md +30 -11
  16. package/spec/db/schema.sql +146 -1
  17. package/spec/mcp.md +26 -0
  18. package/src/app/context-runtime-types.ts +3 -0
  19. package/src/app/context-runtime.ts +2 -0
  20. package/src/cli/commands/ask.ts +6 -1
  21. package/src/cli/commands/daemon.ts +21 -8
  22. package/src/cli/commands/embed.ts +77 -41
  23. package/src/cli/commands/mcp/install.ts +20 -0
  24. package/src/cli/commands/mcp/paths.ts +25 -0
  25. package/src/cli/commands/mcp/status.ts +6 -0
  26. package/src/cli/detach.ts +3 -2
  27. package/src/cli/program.ts +6 -0
  28. package/src/config/types.ts +3 -3
  29. package/src/converters/adapters/markitdownTs/adapter.ts +1 -2
  30. package/src/converters/adapters/officeparser/adapter.ts +1 -2
  31. package/src/converters/versions.ts +6 -8
  32. package/src/core/context-evidence.ts +8 -4
  33. package/src/core/job-manager.ts +95 -13
  34. package/src/core/network-boundary-inventory.ts +10 -0
  35. package/src/core/shutdown-budget.ts +45 -0
  36. package/src/embed/backlog.ts +107 -4
  37. package/src/embed/batch.ts +42 -2
  38. package/src/embed/fingerprint.ts +16 -0
  39. package/src/embed/retry.ts +113 -5
  40. package/src/embed/variant-backlog.ts +105 -0
  41. package/src/embed/variant-plan.ts +62 -0
  42. package/src/embed/variant-retry.ts +113 -0
  43. package/src/ingestion/graph-reconciliation.ts +327 -0
  44. package/src/ingestion/sync.ts +9 -272
  45. package/src/llm/http-inference.ts +6 -0
  46. package/src/llm/httpEmbedding.ts +37 -6
  47. package/src/llm/httpGeneration.ts +18 -3
  48. package/src/llm/httpRerank.ts +23 -5
  49. package/src/llm/inference-cancellation.ts +168 -0
  50. package/src/llm/inference-scope.ts +202 -0
  51. package/src/llm/lazy-ports.ts +115 -0
  52. package/src/llm/native-worker/client.ts +541 -0
  53. package/src/llm/native-worker/dispatcher.ts +228 -0
  54. package/src/llm/native-worker/embedding-identity.ts +33 -0
  55. package/src/llm/native-worker/entry.ts +173 -0
  56. package/src/llm/native-worker/errors.ts +32 -0
  57. package/src/llm/native-worker/evaluation.ts +16 -0
  58. package/src/llm/native-worker/owned-exit.ts +108 -0
  59. package/src/llm/native-worker/owner.ts +141 -0
  60. package/src/llm/native-worker/ports.ts +317 -0
  61. package/src/llm/native-worker/protocol.ts +442 -0
  62. package/src/llm/native-worker/runtime-config.ts +92 -0
  63. package/src/llm/nodeLlamaCpp/adapter.ts +77 -20
  64. package/src/llm/nodeLlamaCpp/embedding.ts +130 -46
  65. package/src/llm/nodeLlamaCpp/generation.ts +34 -5
  66. package/src/llm/nodeLlamaCpp/lifecycle-options.ts +99 -0
  67. package/src/llm/nodeLlamaCpp/lifecycle.ts +209 -204
  68. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +111 -0
  69. package/src/llm/nodeLlamaCpp/rerank.ts +118 -27
  70. package/src/llm/nodeLlamaCpp/simulator-handle.ts +73 -0
  71. package/src/llm/nodeLlamaCpp/simulator-install.ts +124 -0
  72. package/src/llm/nodeLlamaCpp/simulator-session.ts +240 -0
  73. package/src/llm/nodeLlamaCpp/simulator-types.ts +80 -0
  74. package/src/llm/types.ts +35 -5
  75. package/src/mcp/context.ts +27 -0
  76. package/src/mcp/http-transport.ts +12 -10
  77. package/src/mcp/server.ts +3 -0
  78. package/src/mcp/tool-profile.ts +30 -8
  79. package/src/mcp/tools/context.ts +8 -11
  80. package/src/mcp/tools/embed.ts +1 -1
  81. package/src/mcp/tools/index-cmd.ts +1 -1
  82. package/src/mcp/tools/index.ts +10 -8
  83. package/src/mcp/tools/query.ts +14 -30
  84. package/src/mcp/tools/vsearch.ts +1 -1
  85. package/src/pipeline/answer.ts +23 -3
  86. package/src/pipeline/claim-verifier.ts +6 -0
  87. package/src/pipeline/expansion.ts +43 -40
  88. package/src/pipeline/explain.ts +6 -2
  89. package/src/pipeline/filters.ts +63 -0
  90. package/src/pipeline/fusion.ts +29 -9
  91. package/src/pipeline/graph-retrieval.ts +29 -9
  92. package/src/pipeline/hybrid.ts +198 -55
  93. package/src/pipeline/hydration.ts +161 -0
  94. package/src/pipeline/owner-fusion.ts +87 -0
  95. package/src/pipeline/rerank.ts +35 -11
  96. package/src/pipeline/search.ts +13 -2
  97. package/src/pipeline/types.ts +5 -3
  98. package/src/pipeline/vsearch.ts +87 -7
  99. package/src/sdk/client.ts +47 -3
  100. package/src/sdk/embed.ts +63 -39
  101. package/src/serve/background-runtime.ts +1 -1
  102. package/src/serve/context.ts +41 -56
  103. package/src/serve/embed-scheduler.ts +58 -35
  104. package/src/serve/public/components/IndexingProgress.tsx +46 -60
  105. package/src/serve/public/globals.built.css +1 -1
  106. package/src/serve/public/lib/shiki-language-ids.ts +14 -0
  107. package/src/serve/resident-admission.ts +36 -36
  108. package/src/serve/resident-background-work.ts +20 -2
  109. package/src/serve/resident-request.ts +11 -5
  110. package/src/serve/resident-runtime.ts +97 -61
  111. package/src/serve/resident-shutdown.ts +153 -0
  112. package/src/serve/routes/api.ts +3 -1
  113. package/src/serve/server.ts +47 -26
  114. package/src/store/migrations/028-vector-variants.ts +54 -0
  115. package/src/store/migrations/029-graph-reference-state.ts +77 -0
  116. package/src/store/migrations/index.ts +4 -0
  117. package/src/store/sqlite/adapter.ts +251 -183
  118. package/src/store/sqlite/eligibility.ts +174 -0
  119. package/src/store/sqlite/graph-edge-application.ts +66 -0
  120. package/src/store/sqlite/graph-reference-state.ts +194 -0
  121. package/src/store/sqlite/legacy-vector-ownership.ts +79 -0
  122. package/src/store/types.ts +80 -12
  123. package/src/store/vector/eligibility.ts +36 -0
  124. package/src/store/vector/freshness.ts +33 -6
  125. package/src/store/vector/lazy.ts +81 -0
  126. package/src/store/vector/sqlite-vec.ts +106 -54
  127. package/src/store/vector/stats.ts +14 -3
  128. package/src/store/vector/types.ts +35 -2
  129. package/src/store/vector/variant-search.ts +192 -0
  130. package/src/store/vector/variants.ts +451 -0
  131. package/vendor/converters/markitdown-ts/LICENSE +21 -0
  132. package/vendor/converters/markitdown-ts/dist/index.cjs +1180 -0
  133. package/vendor/converters/markitdown-ts/dist/index.d.cts +46 -0
  134. package/vendor/converters/markitdown-ts/dist/index.d.mts +46 -0
  135. package/vendor/converters/markitdown-ts/dist/index.d.ts +46 -0
  136. package/vendor/converters/markitdown-ts/dist/index.mjs +1152 -0
  137. package/vendor/converters/markitdown-ts/package.json +77 -0
  138. package/vendor/converters/officeparser/LICENSE +21 -0
  139. package/vendor/converters/officeparser/dist/OfficeConverter.d.ts +47 -0
  140. package/vendor/converters/officeparser/dist/OfficeConverter.js +76 -0
  141. package/vendor/converters/officeparser/dist/OfficeGenerator.d.ts +23 -0
  142. package/vendor/converters/officeparser/dist/OfficeGenerator.js +73 -0
  143. package/vendor/converters/officeparser/dist/OfficeParser.d.ts +106 -0
  144. package/vendor/converters/officeparser/dist/OfficeParser.js +332 -0
  145. package/vendor/converters/officeparser/dist/cli.d.ts +28 -0
  146. package/vendor/converters/officeparser/dist/cli.js +381 -0
  147. package/vendor/converters/officeparser/dist/defaults.d.ts +41 -0
  148. package/vendor/converters/officeparser/dist/defaults.js +218 -0
  149. package/vendor/converters/officeparser/dist/generators/BaseGenerator.d.ts +107 -0
  150. package/vendor/converters/officeparser/dist/generators/BaseGenerator.js +248 -0
  151. package/vendor/converters/officeparser/dist/generators/ChunkingGenerator.d.ts +82 -0
  152. package/vendor/converters/officeparser/dist/generators/ChunkingGenerator.js +797 -0
  153. package/vendor/converters/officeparser/dist/generators/CsvGenerator.d.ts +38 -0
  154. package/vendor/converters/officeparser/dist/generators/CsvGenerator.js +245 -0
  155. package/vendor/converters/officeparser/dist/generators/EpubGenerator.d.ts +43 -0
  156. package/vendor/converters/officeparser/dist/generators/EpubGenerator.js +315 -0
  157. package/vendor/converters/officeparser/dist/generators/HtmlGenerator.d.ts +59 -0
  158. package/vendor/converters/officeparser/dist/generators/HtmlGenerator.js +1942 -0
  159. package/vendor/converters/officeparser/dist/generators/MarkdownGenerator.d.ts +96 -0
  160. package/vendor/converters/officeparser/dist/generators/MarkdownGenerator.js +1175 -0
  161. package/vendor/converters/officeparser/dist/generators/PdfGenerator.d.ts +22 -0
  162. package/vendor/converters/officeparser/dist/generators/PdfGenerator.js +194 -0
  163. package/vendor/converters/officeparser/dist/generators/RtfGenerator.d.ts +29 -0
  164. package/vendor/converters/officeparser/dist/generators/RtfGenerator.js +316 -0
  165. package/vendor/converters/officeparser/dist/generators/TextGenerator.d.ts +13 -0
  166. package/vendor/converters/officeparser/dist/generators/TextGenerator.js +201 -0
  167. package/vendor/converters/officeparser/dist/index.d.ts +60 -0
  168. package/vendor/converters/officeparser/dist/index.js +72 -0
  169. package/vendor/converters/officeparser/dist/index.mjs +18 -0
  170. package/vendor/converters/officeparser/dist/officeparser.browser.d.ts +2621 -0
  171. package/vendor/converters/officeparser/dist/officeparser.browser.iife.js +1336 -0
  172. package/vendor/converters/officeparser/dist/officeparser.browser.mjs +1335 -0
  173. package/vendor/converters/officeparser/dist/officeparser.browser.slim.d.ts +2621 -0
  174. package/vendor/converters/officeparser/dist/officeparser.browser.slim.iife.js +1336 -0
  175. package/vendor/converters/officeparser/dist/officeparser.browser.slim.mjs +1335 -0
  176. package/vendor/converters/officeparser/dist/parsers/CsvParser.d.ts +9 -0
  177. package/vendor/converters/officeparser/dist/parsers/CsvParser.js +115 -0
  178. package/vendor/converters/officeparser/dist/parsers/EpubParser.d.ts +8 -0
  179. package/vendor/converters/officeparser/dist/parsers/EpubParser.js +217 -0
  180. package/vendor/converters/officeparser/dist/parsers/ExcelParser.d.ts +32 -0
  181. package/vendor/converters/officeparser/dist/parsers/ExcelParser.js +736 -0
  182. package/vendor/converters/officeparser/dist/parsers/HtmlParser.d.ts +2 -0
  183. package/vendor/converters/officeparser/dist/parsers/HtmlParser.js +1287 -0
  184. package/vendor/converters/officeparser/dist/parsers/MarkdownParser.d.ts +2 -0
  185. package/vendor/converters/officeparser/dist/parsers/MarkdownParser.js +1272 -0
  186. package/vendor/converters/officeparser/dist/parsers/OpenOfficeParser.d.ts +31 -0
  187. package/vendor/converters/officeparser/dist/parsers/OpenOfficeParser.js +1819 -0
  188. package/vendor/converters/officeparser/dist/parsers/PdfParser.d.ts +67 -0
  189. package/vendor/converters/officeparser/dist/parsers/PdfParser.js +848 -0
  190. package/vendor/converters/officeparser/dist/parsers/PowerPointParser.d.ts +32 -0
  191. package/vendor/converters/officeparser/dist/parsers/PowerPointParser.js +950 -0
  192. package/vendor/converters/officeparser/dist/parsers/RtfParser.d.ts +187 -0
  193. package/vendor/converters/officeparser/dist/parsers/RtfParser.js +1801 -0
  194. package/vendor/converters/officeparser/dist/parsers/WordParser.d.ts +79 -0
  195. package/vendor/converters/officeparser/dist/parsers/WordParser.js +1177 -0
  196. package/vendor/converters/officeparser/dist/sbom.cdx.json +1763 -0
  197. package/vendor/converters/officeparser/dist/types.d.ts +2507 -0
  198. package/vendor/converters/officeparser/dist/types.js +107 -0
  199. package/vendor/converters/officeparser/dist/utils/astUtils.d.ts +16 -0
  200. package/vendor/converters/officeparser/dist/utils/astUtils.js +33 -0
  201. package/vendor/converters/officeparser/dist/utils/chartUtils.d.ts +6 -0
  202. package/vendor/converters/officeparser/dist/utils/chartUtils.js +257 -0
  203. package/vendor/converters/officeparser/dist/utils/configUtils.d.ts +44 -0
  204. package/vendor/converters/officeparser/dist/utils/configUtils.js +315 -0
  205. package/vendor/converters/officeparser/dist/utils/dateUtils.d.ts +17 -0
  206. package/vendor/converters/officeparser/dist/utils/dateUtils.js +69 -0
  207. package/vendor/converters/officeparser/dist/utils/envUtils.d.ts +29 -0
  208. package/vendor/converters/officeparser/dist/utils/envUtils.js +152 -0
  209. package/vendor/converters/officeparser/dist/utils/errorUtils.d.ts +72 -0
  210. package/vendor/converters/officeparser/dist/utils/errorUtils.js +245 -0
  211. package/vendor/converters/officeparser/dist/utils/imageUtils.d.ts +66 -0
  212. package/vendor/converters/officeparser/dist/utils/imageUtils.js +133 -0
  213. package/vendor/converters/officeparser/dist/utils/mathUtils.d.ts +42 -0
  214. package/vendor/converters/officeparser/dist/utils/mathUtils.js +385 -0
  215. package/vendor/converters/officeparser/dist/utils/moduleLoader.d.ts +18 -0
  216. package/vendor/converters/officeparser/dist/utils/moduleLoader.js +106 -0
  217. package/vendor/converters/officeparser/dist/utils/ocrUtils.d.ts +42 -0
  218. package/vendor/converters/officeparser/dist/utils/ocrUtils.js +428 -0
  219. package/vendor/converters/officeparser/dist/utils/sanitize.d.ts +148 -0
  220. package/vendor/converters/officeparser/dist/utils/sanitize.js +344 -0
  221. package/vendor/converters/officeparser/dist/utils/sheetUtils.d.ts +7 -0
  222. package/vendor/converters/officeparser/dist/utils/sheetUtils.js +35 -0
  223. package/vendor/converters/officeparser/dist/utils/styleMapper.d.ts +36 -0
  224. package/vendor/converters/officeparser/dist/utils/styleMapper.js +224 -0
  225. package/vendor/converters/officeparser/dist/utils/xmlUtils.d.ts +163 -0
  226. package/vendor/converters/officeparser/dist/utils/xmlUtils.js +461 -0
  227. package/vendor/converters/officeparser/dist/utils/zipUtils.d.ts +134 -0
  228. package/vendor/converters/officeparser/dist/utils/zipUtils.js +337 -0
  229. package/vendor/converters/officeparser/package.json +147 -0
  230. package/vendor/converters/upstream-manifest.json +124 -0
  231. package/vendor/dependency-fixes/README.md +77 -0
  232. package/vendor/dependency-fixes/vendor-converters.py +83 -0
  233. package/browser-extension/artifacts/gno-browser-clipper-v1.45.1.zip +0 -0
  234. package/browser-extension/artifacts/gno-browser-clipper-v1.45.1.zip.sha256 +0 -1
  235. package/browser-extension/dist/chunk-627emwpj.js +0 -75
  236. /package/browser-extension/dist/{chunk-ydfx5d7p.css → chunk-z74y8n8c.css} +0 -0
@@ -0,0 +1,2621 @@
1
+ // Generated by dts-bundle-generator v9.5.1
2
+
3
+ /**
4
+ * Standard error types for OfficeParser.
5
+ * Use these to identify the kind of error being reported.
6
+ */
7
+ export declare enum OfficeErrorType {
8
+ /** Unsupported file extension */
9
+ EXTENSION_UNSUPPORTED = "EXTENSION_UNSUPPORTED",
10
+ /** Unsupported output generator format */
11
+ FORMAT_UNSUPPORTED = "FORMAT_UNSUPPORTED",
12
+ /** File appears to be corrupted or malformed */
13
+ FILE_CORRUPTED = "FILE_CORRUPTED",
14
+ /** File could not be found at the specified path */
15
+ FILE_DOES_NOT_EXIST = "FILE_DOES_NOT_EXIST",
16
+ /** Specified location/directory is not reachable or is a directory */
17
+ LOCATION_NOT_FOUND = "LOCATION_NOT_FOUND",
18
+ /** Arguments passed to the function are missing or invalid */
19
+ IMPROPER_ARGUMENTS = "IMPROPER_ARGUMENTS",
20
+ /** Error occurred while reading or processing file buffers */
21
+ IMPROPER_BUFFERS = "IMPROPER_BUFFERS",
22
+ /** Input type is not a supported type (string, Buffer, ArrayBuffer, Uint8Array) */
23
+ INVALID_INPUT = "INVALID_INPUT",
24
+ /** PDF worker source is missing (required in browser) */
25
+ PDF_WORKER_MISSING = "PDF_WORKER_MISSING",
26
+ /** Attempted to use Node.js-only features in a browser environment */
27
+ FEATURE_NOT_SUPPORTED_IN_BROWSER = "FEATURE_NOT_SUPPORTED_IN_BROWSER",
28
+ /** Style mapping string is malformed */
29
+ INVALID_STYLE_MAPPING = "INVALID_STYLE_MAPPING",
30
+ /** Selector in style mapping is invalid */
31
+ INVALID_SELECTOR = "INVALID_SELECTOR",
32
+ /** Output mapping in style mapping is invalid */
33
+ INVALID_OUTPUT_MAPPING = "INVALID_OUTPUT_MAPPING",
34
+ /** Semantic chunking strategy is selected but no embedding function is provided */
35
+ MISSING_EMBEDDING_FUNCTION = "MISSING_EMBEDDING_FUNCTION",
36
+ /** The operation was aborted */
37
+ OPERATION_ABORTED = "OPERATION_ABORTED",
38
+ /** ZIP entry count exceeds limit */
39
+ ZIP_ENTRY_COUNT_LIMIT_EXCEEDED = "ZIP_ENTRY_COUNT_LIMIT_EXCEEDED",
40
+ /** ZIP entry missing a valid declared size */
41
+ ZIP_ENTRY_INVALID_SIZE = "ZIP_ENTRY_INVALID_SIZE",
42
+ /** ZIP uncompressed size limit exceeded */
43
+ ZIP_SIZE_LIMIT_EXCEEDED = "ZIP_SIZE_LIMIT_EXCEEDED",
44
+ /** ZIP data yielded no readable entries (corrupt, truncated, or not a ZIP archive) */
45
+ ZIP_NO_ENTRIES_FOUND = "ZIP_NO_ENTRIES_FOUND",
46
+ /** ZIP data is truncated: the End of Central Directory record is absent */
47
+ ZIP_TRUNCATED = "ZIP_TRUNCATED",
48
+ /** A readable ZIP archive is missing the part its document format requires */
49
+ REQUIRED_PART_MISSING = "REQUIRED_PART_MISSING",
50
+ /** Document element/structure nesting exceeded the safe recursion depth */
51
+ MAX_NESTING_DEPTH_EXCEEDED = "MAX_NESTING_DEPTH_EXCEEDED",
52
+ /** Embedding call timed out */
53
+ EMBEDDING_TIMEOUT = "EMBEDDING_TIMEOUT"
54
+ }
55
+ /**
56
+ * Standard warning types for OfficeParser.
57
+ * Use these for reporting non-fatal issues or performance tips.
58
+ */
59
+ export declare enum OfficeWarningType {
60
+ /** Performance advice (e.g., Rosetta translation on Mac) */
61
+ PERFORMANCE_TIP = "PERFORMANCE_TIP",
62
+ /** OCR processing failed for an attachment */
63
+ OCR_FAILED = "OCR_FAILED",
64
+ /** Extraction of structured chart data failed */
65
+ CHART_DATA_EXTRACTION_FAILED = "CHART_DATA_EXTRACTION_FAILED",
66
+ /** Automatic worker path failed, falling back to CDN */
67
+ PDF_WORKER_FALLBACK = "PDF_WORKER_FALLBACK",
68
+ /** General attachment extraction failure */
69
+ ATTACHMENT_EXTRACTION_FAILED = "ATTACHMENT_EXTRACTION_FAILED",
70
+ /** Failed to load a specific page in a multi-page document */
71
+ PAGE_LOAD_FAILED = "PAGE_LOAD_FAILED",
72
+ /** Failed to load a required dynamic dependency */
73
+ DEPENDENCY_LOAD_FAILED = "DEPENDENCY_LOAD_FAILED",
74
+ /** Failed to extract images from a source */
75
+ IMAGE_EXTRACTION_FAILED = "IMAGE_EXTRACTION_FAILED",
76
+ /** Failed to extract annotations from a document */
77
+ ANNOTATION_EXTRACTION_FAILED = "ANNOTATION_EXTRACTION_FAILED",
78
+ /** Failed to process an extracted image bitmap */
79
+ IMAGE_PROCESSING_FAILED = "IMAGE_PROCESSING_FAILED",
80
+ /** Warning about limitations of browser-based generation */
81
+ BROWSER_GENERATION_LIMITATION = "BROWSER_GENERATION_LIMITATION",
82
+ /** Specified sheet range in Excel/ODS export was not found */
83
+ SHEET_RANGE_NOT_FOUND = "SHEET_RANGE_NOT_FOUND",
84
+ /** Buffer content type does not match the provided or expected file extension */
85
+ BUFFER_TYPE_MISMATCH = "BUFFER_TYPE_MISMATCH",
86
+ /** Failed to detect file type from buffer due to library error or incompatibility */
87
+ FILE_TYPE_DETECTION_FAILED = "FILE_TYPE_DETECTION_FAILED",
88
+ /** No chunks were generated for the document given the current strategy */
89
+ EMPTY_CHUNK_GENERATED = "EMPTY_CHUNK_GENERATED",
90
+ /** A node was skipped because it only contained whitespace */
91
+ WHITESPACE_NODE_SKIPPED = "WHITESPACE_NODE_SKIPPED",
92
+ /** The HTML generator containerWidth option is invalid */
93
+ INVALID_CONTAINER_WIDTH = "INVALID_CONTAINER_WIDTH",
94
+ /** A document's repeated-cell expansion hit the configured cell limit and was truncated */
95
+ TABLE_CELL_LIMIT_EXCEEDED = "TABLE_CELL_LIMIT_EXCEEDED",
96
+ /** A metadata override could not be represented in the destination format's vocabulary */
97
+ METADATA_NOT_REPRESENTABLE = "METADATA_NOT_REPRESENTABLE",
98
+ /** A styleMap output.tag was not an allowed element name and was ignored */
99
+ INVALID_STYLE_MAP_TAG = "INVALID_STYLE_MAP_TAG",
100
+ /** A workbook archive contains no worksheet parts (chartsheet-only workbooks are legitimate) */
101
+ NO_WORKSHEETS_FOUND = "NO_WORKSHEETS_FOUND",
102
+ /** A presentation archive contains no slides (a zero-slide presentation is legitimate) */
103
+ NO_SLIDES_FOUND = "NO_SLIDES_FOUND"
104
+ }
105
+ /**
106
+ * Consolidated timeout settings for OCR operations.
107
+ * Preferred over the individual flat timeout properties on {@link OcrConfig},
108
+ * which are now deprecated.
109
+ *
110
+ * If a key is present here, it takes priority over the corresponding deprecated
111
+ * flat property (e.g. `timeout.autoTerminate` wins over `autoTerminateTimeout`).
112
+ * Set any value to `0` to disable that specific timeout.
113
+ */
114
+ export interface OcrTimeoutConfig {
115
+ /**
116
+ * Timeout in milliseconds of inactivity before the OCR worker pool is
117
+ * automatically terminated and freed.
118
+ *
119
+ * The timer resets every time a new OCR job is enqueued. When the last
120
+ * job completes and this duration passes without a new one, the entire
121
+ * worker pool is torn down so that no background threads keep the Node.js
122
+ * process alive unnecessarily.
123
+ *
124
+ * Set to `0` to keep workers alive indefinitely (useful when you want to
125
+ * call {@link terminateOcr} manually at shutdown time).
126
+ * Default is 10,000 ms (10 seconds).
127
+ */
128
+ autoTerminate?: number;
129
+ /**
130
+ * Timeout in milliseconds for initializing a Tesseract worker
131
+ * (loading the JS runtime, downloading or loading the `.traineddata`
132
+ * language file) or for re-initializing an existing worker with a
133
+ * different language.
134
+ *
135
+ * Multi-language combinations (e.g. `'por+eng+spa'`) must download a
136
+ * separate `.traineddata` file for each language and are therefore
137
+ * particularly susceptible to slow networks. Tune this value upward if
138
+ * your OCR environment has high network latency or if you are loading
139
+ * languages from disk in a large container image.
140
+ *
141
+ * When the timeout fires, the failed job is rejected with a non-fatal
142
+ * {@link OfficeWarningType.OCR_FAILED} warning and parsing continues
143
+ * without OCR output for that image. The stalled worker is terminated
144
+ * and removed from the pool to prevent thread leaks.
145
+ *
146
+ * Set to `0` to wait indefinitely (not recommended for production; a hung
147
+ * network request will block the entire OCR queue for that language).
148
+ * Default is 60,000 ms (60 seconds).
149
+ */
150
+ workerLoad?: number;
151
+ /**
152
+ * Timeout in milliseconds for the actual OCR text-recognition call
153
+ * (`worker.recognize(image)`) on an already-initialized Tesseract worker.
154
+ *
155
+ * Recognition time scales with image resolution and the number of active
156
+ * languages. Very high-resolution scans or unusual character sets can
157
+ * exceed the default. If this timeout fires, the job is rejected with a
158
+ * non-fatal {@link OfficeWarningType.OCR_FAILED} warning; the worker is
159
+ * terminated and evicted from the pool because its internal state after a
160
+ * mid-recognition timeout is undefined.
161
+ *
162
+ * Set to `0` to wait indefinitely.
163
+ * Default is 30,000 ms (30 seconds).
164
+ */
165
+ recognition?: number;
166
+ }
167
+ /**
168
+ * Configuration options for OCR.
169
+ */
170
+ export interface OcrConfig {
171
+ /**
172
+ * Language for OCR.
173
+ * Default is 'eng'.
174
+ *
175
+ * You can provide multiple languages separated by a `+` sign (e.g., 'eng+fra' for English and French).
176
+ * The OCR engine will then attempt to recognize text in any of the specified languages.
177
+ *
178
+ * See the list of supported languages and their codes here:
179
+ * https://tesseract-ocr.github.io/tessdoc/Data-Files#data-files-for-version-400-november-29-2016
180
+ */
181
+ language?: string;
182
+ /**
183
+ * Path to the Tesseract worker script.
184
+ * Primarily used for offline/air-gapped environments.
185
+ * Default is ''.
186
+ */
187
+ workerPath?: string;
188
+ /**
189
+ * Path to the Tesseract core script.
190
+ * Primarily used for offline/air-gapped environments.
191
+ * Default is ''.
192
+ */
193
+ corePath?: string;
194
+ /**
195
+ * Path for Tesseract language files (traineddata).
196
+ * Primarily used for offline/air-gapped environments.
197
+ * Default is ''.
198
+ */
199
+ langPath?: string;
200
+ /**
201
+ * Consolidated timeout settings for all OCR operations.
202
+ *
203
+ * Prefer this over the deprecated flat timeout properties.
204
+ * If `timeout.autoTerminate` is set, it takes priority over the deprecated `autoTerminateTimeout`.
205
+ */
206
+ timeout?: OcrTimeoutConfig;
207
+ /**
208
+ * @deprecated Use `timeout.autoTerminate` instead.
209
+ *
210
+ * Timeout in milliseconds of inactivity before the OCR worker pool is automatically terminated.
211
+ * Set to 0 to disable auto-termination.
212
+ * Default is 10,000 (10 seconds).
213
+ *
214
+ * If `timeout.autoTerminate` is also set, that value takes priority over this one.
215
+ */
216
+ autoTerminateTimeout?: number;
217
+ /**
218
+ * An optional AbortSignal propagated from the main parser configuration to abort active OCR jobs.
219
+ * If the signal is aborted:
220
+ * 1. Any pending OCR jobs in the scheduler queue are rejected immediately.
221
+ * 2. Any active OCR job running on a Tesseract worker will reject, the worker will be
222
+ * terminated, and it will be removed from the pool to avoid hanging worker threads.
223
+ *
224
+ * Developers should prefer passing this at the top level of `parseOffice` (as `config.abortSignal`),
225
+ * which automatically propagates here.
226
+ */
227
+ abortSignal?: AbortSignal | null;
228
+ }
229
+ /**
230
+ * Configuration options shared across every input format.
231
+ */
232
+ export interface CommonOfficeParserConfig {
233
+ /**
234
+ * @deprecated Use `onWarning` instead.
235
+ * Flag to show all the logs to console in case of an error irrespective of your own handling.
236
+ * Default is false.
237
+ */
238
+ outputErrorToConsole?: boolean;
239
+ /**
240
+ * Callback for warnings or non-fatal errors encountered during parsing.
241
+ * Allows you to capture issues like OCR failures or attachment extraction errors
242
+ * without stopping the parsing process.
243
+ */
244
+ onWarning?: (issue: OfficeIssue) => void;
245
+ /**
246
+ * The delimiter used for every new line in places that allow multiline text like word.
247
+ * Default is \n.
248
+ */
249
+ newlineDelimiter?: string;
250
+ /**
251
+ * Flag to ignore notes from parsing in files like powerpoint.
252
+ * Default is false. It includes notes in the parsed text by default.
253
+ */
254
+ ignoreNotes?: boolean;
255
+ /**
256
+ * Flag to ignore comments from parsing.
257
+ * Default is false.
258
+ */
259
+ ignoreComments?: boolean;
260
+ /**
261
+ * Flag to ignore headers and footers from parsing.
262
+ * Default is false.
263
+ */
264
+ ignoreHeadersAndFooters?: boolean;
265
+ /**
266
+ * Flag to ignore slide masters from parsing in PowerPoint.
267
+ * Default is false.
268
+ */
269
+ ignoreSlideMasters?: boolean;
270
+ /**
271
+ * @deprecated Notes are now structurally attached to the specific nodes they belong to via `node.notes`.
272
+ * This option is now completely ignored by all parsers.
273
+ */
274
+ putNotesAtLast?: boolean;
275
+ /**
276
+ * Flag to extract attachments like images, charts, etc.
277
+ * Default is false.
278
+ */
279
+ extractAttachments?: boolean;
280
+ /**
281
+ * Flag to include raw content (XML for XML-based formats, RTF for RTF) in the AST.
282
+ * Default is false.
283
+ */
284
+ includeRawContent?: boolean;
285
+ /**
286
+ * Flag to enable OCR for images.
287
+ * Default is false.
288
+ */
289
+ ocr?: boolean;
290
+ /**
291
+ * @deprecated Use `ocrConfig.language` instead.
292
+ * Language for OCR.
293
+ * Default is 'eng'.
294
+ *
295
+ * You can provide multiple languages separated by a `+` sign (e.g., 'eng+fra' for English and French).
296
+ * The OCR engine will then attempt to recognize text in any of the specified languages.
297
+ *
298
+ * See the list of supported languages and their codes here:
299
+ * https://tesseract-ocr.github.io/tessdoc/Data-Files#data-files-for-version-400-november-29-2016
300
+ */
301
+ ocrLanguage?: string;
302
+ /**
303
+ * Shared OCR configuration for worker pooling and offline support.
304
+ * If provided, `ocrLanguage` will be ignored in favor of `ocrConfig.language`.
305
+ */
306
+ ocrConfig?: OcrConfig;
307
+ /**
308
+ * An optional AbortSignal to cancel the parsing operation.
309
+ * When aborted, the parser immediately rejects with a standard AbortError (DOMException).
310
+ *
311
+ * ### Format-Specific Abort Behavior:
312
+ * - **PDF**: Checked between page loads and before individual image OCR operations.
313
+ * - **RTF**: Checked before parsing/traversal and before running OCR on image attachments.
314
+ * - **DOCX/XLSX/PPTX/ODF**: Checked during zip decompression before loading and parsing XML files.
315
+ * - **CSV/MD/HTML**: Checked at the start of the parsing phase.
316
+ *
317
+ * Note: If an OCR operation is currently running on a Tesseract worker when aborted,
318
+ * the worker will be terminated and removed from the worker pool automatically to prevent leaks.
319
+ */
320
+ abortSignal?: AbortSignal | null;
321
+ /**
322
+ * Flag to serialize raw content (XML) as clean, formatted strings.
323
+ * Only relevant when `includeRawContent` is true.
324
+ * Default is true.
325
+ *
326
+ * If false, the parser will attempt to extract the original raw substring from the
327
+ * source document instead of re-serializing the DOM node.
328
+ */
329
+ serializeRawContent?: boolean;
330
+ /**
331
+ * Flag to preserve original XML whitespace and line endings when serializing.
332
+ * Only relevant when `includeRawContent` is true and `serializeRawContent` is true.
333
+ * Default is false.
334
+ */
335
+ preserveXmlWhitespace?: boolean;
336
+ /**
337
+ * The URL/path to the PDF.js worker script.
338
+ *
339
+ * **Mandatory** when using PDF parsing in browser environments to avoid worker configuration errors.
340
+ * If not provided, it defaults to `https://cdn.jsdelivr.net/npm/pdfjs-dist@6.1.200/build/pdf.worker.min.mjs`.
341
+ * You can override this with your own local path or a different CDN link.
342
+ */
343
+ pdfWorkerSrc?: string;
344
+ /**
345
+ * Flag to include break nodes in the AST.
346
+ * This is currently only supported for Word documents. (w:br nodes)
347
+ *
348
+ * Default is false
349
+ */
350
+ includeBreakNodes?: boolean;
351
+ /**
352
+ * Flag to ignore all internal (anchor) links during parsing.
353
+ * When true, all bookmarks, cross-references, and internal document jumps are stripped
354
+ * from the AST. Only external URLs will be preserved.
355
+ *
356
+ * Use this if you want a "flat" document without any internal interactivity.
357
+ *
358
+ * Default is false.
359
+ */
360
+ ignoreInternalLinks?: boolean;
361
+ /**
362
+ * Optional hint for the file format.
363
+ * When a Buffer or ArrayBuffer is passed, the parser relies on magic bytes to detect the file type.
364
+ * Text-based formats like 'md', 'html', and 'csv' lack reliable magic bytes.
365
+ * If you are parsing these formats from a Buffer, you must provide this fileType hint.
366
+ *
367
+ * This is authoritative and is used to determine the file type, so it should be accurate.
368
+ * If provided, this bypasses the magic bytes detection and the file extension-based detection either way.
369
+ *
370
+ * Default is null.
371
+ */
372
+ fileType?: SupportedFileType | null;
373
+ /**
374
+ * Custom delimiter for CSV files.
375
+ * Defaults to ',' but can be overridden (e.g., ';', '\t').
376
+ */
377
+ csvDelimiter?: string;
378
+ /**
379
+ * Limits and checks applied during ZIP extraction to protect against excessive
380
+ * memory and resource usage.
381
+ */
382
+ decompressionLimits?: DecompressionLimits;
383
+ }
384
+ /**
385
+ * Format-specific options for HTML (and XHTML/EPUB, which parse through the same code path).
386
+ *
387
+ * Note there is deliberately no `MdParserConfig`: the Markdown parser populates its
388
+ * dialect-provenance metadata (e.g. `AdmonitionMetadata.sourceSyntax`) unconditionally because
389
+ * doing so costs nothing and changes no existing field's value, so it has nothing to configure.
390
+ * An empty placeholder interface would be worse than useless here - `interface X {}` accepts any
391
+ * non-nullish value in TypeScript, so `mdParserConfig: 5` would type-check.
392
+ */
393
+ export interface HtmlParserConfig {
394
+ /**
395
+ * Preserve source HTML attributes that no typed metadata field consumed, on
396
+ * `OfficeContentNode.htmlAttributes`, so they can be replayed on generation.
397
+ *
398
+ * Off by default: with it off nothing is populated, so the AST is byte-identical to previous
399
+ * releases, and the attribute-replay surface stays something a consumer opts into rather than
400
+ * something switched on for every existing caller. Captured values are sanitized on the way in
401
+ * *and* on the way out - see `BaseContentNode.htmlAttributes`.
402
+ *
403
+ * Defaults to false.
404
+ */
405
+ preserveAttributes?: boolean;
406
+ /**
407
+ * Preserve `<iframe>` embeds that aren't recognized as a known provider (YouTube is always
408
+ * recognized). By default every non-YouTube iframe is dropped, which is a deliberate security
409
+ * posture other consumers rely on; set this to opt back in. `true` preserves any iframe; an
410
+ * array is a hostname allowlist (an entry matches the src's host exactly or as a `.`-suffix,
411
+ * so `"vimeo.com"` also matches `player.vimeo.com`). Preserved iframes become `embed` nodes
412
+ * with `embedType: 'iframe'`; on generation the `src` is still scheme-checked (only http/https
413
+ * survive). This also governs a raw `<iframe>` block encountered in Markdown input.
414
+ *
415
+ * Defaults to false.
416
+ */
417
+ preserveIframes?: boolean | string[];
418
+ /**
419
+ * Import ambiguous "folk" embed forms in Markdown as embeds: a standalone Obsidian-style image
420
+ * whose URL is a YouTube link (`![](https://youtube.com/watch?v=ID)`), and the clickable
421
+ * thumbnail-link (`[![alt](https://img.youtube.com/vi/ID/…)](watch-url)`). Both become a
422
+ * `embedType: 'youtube'` embed (rendered from the validated id, so it is safe). Off by default:
423
+ * auto-upgrading an image/link to an embed is a heuristic that could mangle a genuinely-intended
424
+ * image link, so a consumer opts in. The unambiguous forms (`<div data-youtube-video>`, a bare
425
+ * YouTube `<iframe>`, the `::youtube` directive) are always recognized, independent of this flag.
426
+ *
427
+ * Defaults to false.
428
+ */
429
+ embedFolkForms?: boolean;
430
+ }
431
+ /**
432
+ * Maps an input format string to its corresponding format-specific parser configuration, mirroring
433
+ * `GeneratorSpecificConfig<D>` on the generator side. Unlike the generator side, the input format is
434
+ * usually runtime-detected rather than known statically at the `parseOffice()` call site, so this
435
+ * mainly exists for internal typing/extensibility rather than compile-time narrowing per call.
436
+ */
437
+ export type ParserSpecificConfig<F extends string> = F extends "html" | "epub" ? {
438
+ htmlParserConfig?: HtmlParserConfig;
439
+ } : Partial<{
440
+ htmlParserConfig: HtmlParserConfig;
441
+ }>;
442
+ /**
443
+ * Configuration options for the OfficeParser.
444
+ */
445
+ export type OfficeParserConfig<F extends string = string> = CommonOfficeParserConfig & ParserSpecificConfig<F>;
446
+ /**
447
+ * Limits applied to ZIP archive decompression.
448
+ */
449
+ export interface DecompressionLimits {
450
+ /**
451
+ * Maximum allowed total uncompressed size (in bytes) of files extracted from a ZIP archive.
452
+ * Applies to OOXML (DOCX, XLSX, PPTX) and ODF (ODT, ODP, ODS) formats.
453
+ * Default is 536870912 (512 MB).
454
+ */
455
+ maxUncompressedBytes?: number;
456
+ /**
457
+ * Maximum allowed number of entries (files and directories) in a ZIP archive.
458
+ * Applies to OOXML (DOCX, XLSX, PPTX) and ODF (ODT, ODP, ODS) formats.
459
+ * Default is 10000.
460
+ */
461
+ maxZipEntries?: number;
462
+ /**
463
+ * Maximum number of table cells materialized from a single document.
464
+ *
465
+ * ODF encodes runs of identical cells and rows with `table:number-columns-repeated` and
466
+ * `table:number-rows-repeated` rather than repeating the markup, so a few hundred bytes of XML
467
+ * can ask the parser to build an arbitrary number of nodes - and because the two multiply, a
468
+ * row repeat times a column repeat compounds it. The ZIP limits above cannot catch this: the
469
+ * XML is tiny before decompression and the expansion happens afterwards, while building the
470
+ * AST.
471
+ *
472
+ * Real documents are nowhere near this. The repeat counts LibreOffice writes are large
473
+ * (`number-rows-repeated="1048566"` is routine) but they sit on *empty* trailing runs, which
474
+ * are skipped for spreadsheets; the bundled fixtures top out around 350 cells.
475
+ *
476
+ * On reaching the limit the parser stops materializing further cells, emits a
477
+ * `TABLE_CELL_LIMIT_EXCEEDED` warning, and returns what it has rather than throwing, so a
478
+ * genuinely enormous sheet still yields usable output. Raise it if you routinely process
479
+ * spreadsheets larger than this; note the memory cost scales with it.
480
+ *
481
+ * Default is 1000000.
482
+ */
483
+ maxTableCells?: number;
484
+ }
485
+ /**
486
+ * Represents a single issue (warning, error, or info) generated during document processing.
487
+ */
488
+ export interface OfficeIssue {
489
+ /** The severity of the issue. */
490
+ type: "warning" | "info" | "error";
491
+ /** Human-readable message text. */
492
+ message: string;
493
+ /** The specific AST node that triggered this issue, if applicable. */
494
+ node?: OfficeContentNode;
495
+ /** A unique error code for programmatic handling. */
496
+ code: OfficeWarningType | OfficeErrorType;
497
+ /** Optional additional context or original error object. */
498
+ details?: any;
499
+ }
500
+ /**
501
+ * An Error thrown by OfficeParser, carrying the structured issue that produced it.
502
+ *
503
+ * Catching code can branch on `error.officeIssue.code`, the same stable enum used for warnings,
504
+ * instead of matching against message text. Errors that originate outside the library (and
505
+ * `AbortError`, which is deliberately re-thrown untouched so cancellation stays detectable via
506
+ * `error.name`) do not carry this property, hence the optional marker.
507
+ *
508
+ * @example
509
+ * ```typescript
510
+ * try {
511
+ * await parseOffice(buffer, { fileType: 'docx' });
512
+ * } catch (err) {
513
+ * if ((err as OfficeError).officeIssue?.code === OfficeErrorType.REQUIRED_PART_MISSING) {
514
+ * // the archive is readable, but it is not a docx
515
+ * }
516
+ * }
517
+ * ```
518
+ */
519
+ export interface OfficeError extends Error {
520
+ /** The structured issue this error was created from. */
521
+ officeIssue?: OfficeIssue;
522
+ }
523
+ /**
524
+ * The result of a document conversion operation.
525
+ */
526
+ export type ConversionValue<D extends UniversalGeneratorFormat> = D extends "pdf" ? Uint8Array | string : D extends "chunks" ? OfficeChunk[] : D extends "csv" ? string | Uint8Array : D extends "epub" ? Uint8Array : string;
527
+ export interface ConversionResult<D extends UniversalGeneratorFormat> {
528
+ /** The actual generated content (HTML, Markdown, Text, OfficeChunk[], etc.). */
529
+ value: ConversionValue<D>;
530
+ /** A collection of issues (warnings/infos) generated during the process. */
531
+ messages: OfficeIssue[];
532
+ }
533
+ /**
534
+ * Universal formats supported by all source types for generation.
535
+ */
536
+ export type UniversalGeneratorFormat = "text" | "md" | "html" | "pdf" | "csv" | "rtf" | "chunks" | "epub";
537
+ /**
538
+ * Allowed destination formats for a given source type.
539
+ * Currently, all generators are universal across all source formats.
540
+ */
541
+ export type SupportedDestination<_T extends SupportedFileType = SupportedFileType> = UniversalGeneratorFormat;
542
+ /**
543
+ * Configuration options for the OfficeGenerator.
544
+ */
545
+ /**
546
+ * Common configuration options for all generators.
547
+ */
548
+ /**
549
+ * Per-field overrides for the metadata written into generated output.
550
+ *
551
+ * Field names mirror `OfficeMetadata` so the same vocabulary describes what was parsed and what
552
+ * gets written. Only the fields generators can actually represent are listed; arbitrary
553
+ * caller-defined entries go in `custom`.
554
+ *
555
+ * **Not every format can represent every field.** HTML (`<meta>`) and Markdown (YAML frontmatter)
556
+ * accept anything; EPUB's OPF is a closed Dublin Core vocabulary and RTF's `\info` group has a
557
+ * fixed set of control words, so a `custom` entry has nowhere to go in those. Rather than
558
+ * silently dropping it, generators report the loss through `onWarning`
559
+ * (`OfficeWarningType.MetadataNotRepresentable`) and continue.
560
+ */
561
+ export interface MetadataOverrides {
562
+ /** Document title. */
563
+ title?: string;
564
+ /** Document author. */
565
+ author?: string;
566
+ /** Description/comments. */
567
+ description?: string;
568
+ /** Subject/topic. */
569
+ subject?: string;
570
+ /** Keywords. */
571
+ keywords?: string;
572
+ /** User who last modified the document. */
573
+ lastModifiedBy?: string;
574
+ /** Creation date. */
575
+ created?: Date;
576
+ /**
577
+ * Last modification date.
578
+ *
579
+ * EPUB writes it as the required `dcterms:modified` property and as the mtime on every zip
580
+ * entry. When unset, the source document's own `metadata.modified` is used, falling back to
581
+ * the current time only if the document has none.
582
+ */
583
+ modified?: Date;
584
+ /**
585
+ * Language tag (e.g. `'en'`, `'de-DE'`). Written as EPUB `dc:language` and HTML `lang`.
586
+ */
587
+ language?: string;
588
+ /**
589
+ * Arbitrary caller-defined key/value pairs, kept in their own bucket rather than mixed in
590
+ * beside the named fields above: with a bare index signature a typo like `titel` would
591
+ * silently become a custom entry instead of a compile error.
592
+ *
593
+ * Written where the format allows it (HTML `<meta name="custom:KEY">`, Markdown frontmatter);
594
+ * reported via `onWarning` where it does not (EPUB, RTF).
595
+ */
596
+ custom?: Record<string, string | number | boolean | Date>;
597
+ }
598
+ export interface CommonGeneratorConfig {
599
+ /**
600
+ * Callback called for every node during generation.
601
+ * Allows users to modify nodes before processing, completely override rendering, or filter them out.
602
+ *
603
+ * #### Callback Capabilities:
604
+ * 1. **Filter/Remove Nodes**: Return `false` to skip a node and all its children.
605
+ * 2. **Override Rendering**: Return a `string` to use that exact text as the output, bypassing default logic and recursion.
606
+ * 3. **Mutate Nodes**: Modify the `node` object directly (e.g., changing `node.text`) and return `void` to let the generator proceed with your changes.
607
+ * 4. **Async Support**: The callback can be `async`, allowing you to load external data or perform complex logic during generation.
608
+ */
609
+ onNode?: (node: OfficeContentNode) => string | false | Promise<string | false | void> | void;
610
+ /**
611
+ * Callback for warnings, non-fatal errors, or issues encountered during generation.
612
+ * Allows the process to continue while reporting skipping or approximation of content.
613
+ */
614
+ onWarning?: (issue: OfficeIssue) => void;
615
+ /**
616
+ * Map document styles (e.g., 'Heading 1', 'Intense Quote') to specific semantic elements.
617
+ *
618
+ * DESIGN PHILOSOPHY:
619
+ * This is the primary way to customize how the library interprets the visual
620
+ * structure of your source documents.
621
+ *
622
+ * To disable all semantic translation and use raw AST types only,
623
+ * set `ignoreDefaultStyleMap: true` and leave `styleMap` empty.
624
+ *
625
+ * It supports two formats:
626
+ *
627
+ * 1. LEGACY STRING DSL:
628
+ * Simple "selector => output" syntax. Highly compatible with mammoth.js style maps.
629
+ * @example ["p[style-name='Heading 1'] => h1"]
630
+ * @example ["p[style='Quote'] => blockquote"]
631
+ *
632
+ * 2. STRUCTURED OBJECTS (Recommended):
633
+ * More powerful and strictly typed. Ideal for complex logic or when you
634
+ * need to apply specific classes/attributes for the HTML generator.
635
+ * @example
636
+ * [
637
+ * {
638
+ * selector: { nodeType: 'paragraph', attributes: { style: 'Heading 1' } },
639
+ * output: { tag: 'h1', classes: ['main-title'], attributes: { id: 'top' } }
640
+ * }
641
+ * ]
642
+ *
643
+ * Note: This property works in conjunction with `ignoreDefaultStyleMap`.
644
+ * Defaults to a robust built-in map that covers common standard Office styles.
645
+ */
646
+ styleMap?: string[] | StructuredStyleMapping[];
647
+ /**
648
+ * Whether to include visual formatting like font size, font family, and colors in the output.
649
+ * Set to false for clean, semantic output.
650
+ * Defaults to true.
651
+ */
652
+ includeFormatting?: boolean;
653
+ /**
654
+ * Whether to automatically generate unique slug-based IDs for headings.
655
+ * Useful for table-of-contents and anchor links.
656
+ * Defaults to true.
657
+ */
658
+ generateIds?: boolean;
659
+ /**
660
+ * Whether to render document metadata (title, author, etc.) as visible content
661
+ * in the generated output (e.g., a header block in HTML or plain text).
662
+ * Structural metadata (HTML <meta> tags, Markdown YAML frontmatter) is always included.
663
+ * Defaults to false.
664
+ */
665
+ renderMetadata?: boolean;
666
+ /**
667
+ * Overrides for the document metadata written into the generated output, applied on top of
668
+ * `ast.metadata`.
669
+ *
670
+ * Merged **per field**, so setting only `modified` leaves the parsed title, author, and
671
+ * everything else intact. Every field is optional; an omitted field keeps the source
672
+ * document's value.
673
+ *
674
+ * These are output overrides only - `ast.metadata` itself is never mutated, so the same AST
675
+ * can be generated repeatedly with different metadata.
676
+ *
677
+ * @example Set the modification date written into the output
678
+ * ```typescript
679
+ * await ast.to('epub', { metadataOverrides: { modified: new Date('2024-01-01T00:00:00Z') } });
680
+ * ```
681
+ * @example Rebrand the output without touching the parsed document
682
+ * ```typescript
683
+ * await ast.to('html', {
684
+ * metadataOverrides: { title: 'Q4 Report', author: 'Acme Inc', custom: { department: 'Finance' } },
685
+ * });
686
+ * ```
687
+ */
688
+ metadataOverrides?: MetadataOverrides;
689
+ /**
690
+ * Whether to ignore the built-in default style mappings (e.g. "Heading 1" -> h1).
691
+ * Set to true if you want full control over style mapping.
692
+ * Defaults to false.
693
+ */
694
+ ignoreDefaultStyleMap?: boolean;
695
+ /**
696
+ * Whether to include images in the generated output.
697
+ * Defaults to true.
698
+ */
699
+ includeImages?: boolean;
700
+ /**
701
+ * Whether to include interactive charts in the generated output (HTML only).
702
+ * Defaults to true.
703
+ */
704
+ includeCharts?: boolean;
705
+ /**
706
+ * Whether to ignore all internal (anchor) links and anchor IDs during generation.
707
+ * When true, all bookmarks, cross-references, and internal document jumps are stripped.
708
+ * Specifically for Markdown, this removes the {#id} block from headings.
709
+ * Defaults to false.
710
+ */
711
+ ignoreInternalLinks?: boolean;
712
+ /**
713
+ * An optional AbortSignal to cancel the generation operation.
714
+ * When aborted, the generator immediately rejects with a standard AbortError.
715
+ * Currently supported by PdfGenerator and ChunkingGenerator.
716
+ */
717
+ abortSignal?: AbortSignal | null;
718
+ }
719
+ /**
720
+ * Destination-aware generator configuration.
721
+ * Restricts format-specific configurations to their respective destinations.
722
+ */
723
+ /**
724
+ * Maps a destination format string to its corresponding specific configuration object type.
725
+ */
726
+ export type GeneratorSpecificConfig<D extends string> = D extends "html" ? {
727
+ htmlConfig?: HtmlGeneratorConfig;
728
+ } : D extends "md" ? {
729
+ mdConfig?: MdGeneratorConfig;
730
+ } : D extends "pdf" ? {
731
+ pdfConfig?: PdfGeneratorConfig;
732
+ } : D extends "csv" ? {
733
+ csvConfig?: CsvGeneratorConfig;
734
+ } : D extends "text" ? {
735
+ textConfig?: TextGeneratorConfig;
736
+ } : D extends "rtf" ? {
737
+ rtfConfig?: RtfGeneratorConfig;
738
+ } : D extends "chunks" ? {
739
+ chunksConfig?: ChunkingConfig;
740
+ } : Partial<{
741
+ htmlConfig: HtmlGeneratorConfig;
742
+ mdConfig: MdGeneratorConfig;
743
+ pdfConfig: PdfGeneratorConfig;
744
+ csvConfig: CsvGeneratorConfig;
745
+ textConfig: TextGeneratorConfig;
746
+ rtfConfig: RtfGeneratorConfig;
747
+ chunksConfig: ChunkingConfig;
748
+ }>;
749
+ /**
750
+ * Configuration options for document generators.
751
+ *
752
+ * This interface is designed to be format-aware. When you specify a destination format
753
+ * (e.g., `OfficeGenerator.generate(ast, 'html', config)`), the generic parameter `D`
754
+ * ensures that only the relevant sub-configuration (e.g., `htmlConfig`) is available
755
+ * for type checking.
756
+ *
757
+ * @template D The destination format string. Defaults to `string` for a general configuration.
758
+ */
759
+ export type GeneratorConfig<D extends string = string> = CommonGeneratorConfig & GeneratorSpecificConfig<D>;
760
+ /**
761
+ * Configuration options for the OfficeConverter.
762
+ * Combines relevant parser and generator settings for a seamless one-step conversion.
763
+ *
764
+ * @template D The destination format string.
765
+ */
766
+ /**
767
+ * Configuration options for the OfficeConverter.
768
+ * Combines general generator settings with a specific subset of parser settings.
769
+ *
770
+ * @template D The destination format string.
771
+ * @template T The source file type.
772
+ */
773
+ export type OfficeConverterConfig<D extends string = string, T extends SupportedFileType = SupportedFileType> = {
774
+ /**
775
+ * Specific configuration for the source parsing phase.
776
+ */
777
+ parseConfig?: OfficeParserConfig & {
778
+ fileType?: T;
779
+ };
780
+ /**
781
+ * Specific configuration for the destination generation phase.
782
+ */
783
+ generatorConfig?: GeneratorConfig<D>;
784
+ /**
785
+ * Callback for warnings or non-fatal errors encountered during the entire conversion process.
786
+ * This is passed to both the parser and the generator.
787
+ * If provided, this takes precedence over callbacks inside parseConfig or generatorConfig.
788
+ */
789
+ onWarning?: (issue: OfficeIssue) => void;
790
+ };
791
+ /**
792
+ * Configuration options for granular raw HTML injections.
793
+ */
794
+ export interface HtmlInjectionConfig {
795
+ /** Raw HTML injected immediately after the opening <head> tag */
796
+ headStart?: string;
797
+ /** Raw HTML injected immediately before the closing </head> tag */
798
+ headEnd?: string;
799
+ /** Raw HTML injected immediately after the opening <body> tag */
800
+ bodyStart?: string;
801
+ /** Raw HTML injected immediately before the closing </body> tag */
802
+ bodyEnd?: string;
803
+ }
804
+ /**
805
+ * Granular control over which parts of the full HTML "document envelope" are emitted.
806
+ * Shorthand: `standalone: true` == every part on (a complete document); `standalone: false` ==
807
+ * every part off (a bare content fragment). When an object is passed, any field you omit
808
+ * defaults to its "on" (standalone) value.
809
+ */
810
+ export interface StandaloneConfig {
811
+ /**
812
+ * Wrap the output in `<!DOCTYPE html><html><head>…</head><body>…</body></html>`.
813
+ * When false, only the inner content fragment is emitted. Defaults to true.
814
+ */
815
+ document?: boolean;
816
+ /**
817
+ * Emit `<title>` and `<meta>` tags (author, description, dates, custom properties) in the head.
818
+ * Only meaningful when `document` is true. Defaults to true.
819
+ */
820
+ metaTags?: boolean;
821
+ /**
822
+ * How the library's built-in CSS is delivered:
823
+ * - `'full'` — the complete premium stylesheet using global selectors (`body`, `h1`, `table`, …).
824
+ * This is what `standalone: true` has always emitted.
825
+ * - `'scoped'` — the same styling, scoped under the fragment's container via CSS `@scope` so it
826
+ * cannot leak into a host page's own styles. Requires a modern browser engine (Chrome 118+,
827
+ * Safari 17.4+, Firefox 128+).
828
+ * - `'none'` — no stylesheet is emitted; the host page (or EPUB reader, or rich-text editor)
829
+ * supplies its own styling.
830
+ * The boolean shorthand for `standalone` maps `true` → `'full'`, `false` → `'none'`.
831
+ * Defaults to `'full'`.
832
+ */
833
+ styles?: "full" | "scoped" | "none";
834
+ /**
835
+ * Emit injected `<script>` tags: the Chart.js loader (when `includeCharts` is true and charts
836
+ * are present) and the spreadsheet interactivity script. Defaults to true.
837
+ */
838
+ scripts?: boolean;
839
+ /**
840
+ * Apply `injections.headStart` / `injections.headEnd`. Only meaningful when `document` is true
841
+ * (there is no `<head>` to inject into otherwise). Defaults to true.
842
+ */
843
+ headInjections?: boolean;
844
+ /**
845
+ * Apply `injections.bodyStart` / `injections.bodyEnd`. Applies even when generating a bare
846
+ * fragment (`document: false`), since these wrap body *content*, not the document shell.
847
+ * Defaults to true.
848
+ */
849
+ bodyInjections?: boolean;
850
+ }
851
+ /**
852
+ * Configuration options for HTML generation.
853
+ */
854
+ export interface HtmlGeneratorConfig {
855
+ /**
856
+ * Whether to wrap the output in a full HTML document structure (e.g., <html>, <head>, etc.).
857
+ * Pass an object instead of a boolean for granular control over individual parts of the
858
+ * envelope (document shell, meta tags, styles, scripts, injections) - see `StandaloneConfig`.
859
+ * Defaults to true.
860
+ */
861
+ standalone?: boolean | StandaloneConfig;
862
+ /**
863
+ * URL for the Chart.js library to use when 'includeCharts' is true.
864
+ * Defaults to 'https://cdn.jsdelivr.net/npm/chart.js'.
865
+ */
866
+ chartJsSrc?: string;
867
+ /**
868
+ * Custom container width for the generated HTML.
869
+ * Can be a number (pixels) or string (e.g., '900px', '100%').
870
+ * If not specified or set to 'auto', it defaults based on the content type:
871
+ * - Spreadsheet: '100%'
872
+ * - Presentation/Slides: '1100px'
873
+ * - Standard Document (PDF/DOCX/RTF/etc.): '900px'
874
+ */
875
+ containerWidth?: string | number;
876
+ /**
877
+ * Custom CSS to append to the generated HTML document.
878
+ * This CSS will be included in the `<style>` block and can be used to style
879
+ * custom classes added during AST manipulation or override default styles.
880
+ */
881
+ customCss?: string;
882
+ /**
883
+ * Granular injection points for custom HTML, scripts, and styles.
884
+ */
885
+ injections?: HtmlInjectionConfig;
886
+ /**
887
+ * Carry each rich node's raw source in a `data-*` attribute, with undelimited text content,
888
+ * so attribute-driven structured consumers (rich-text editors, custom viewers) can rehydrate
889
+ * the node from the markup rather than re-parsing the display text. Affects wikilinks
890
+ * (adds `data-wikilink`/`data-target`/`data-alias`), citations (a `<span class="citation">`
891
+ * carrying `data-key` instead of `<cite>`), math (the LaTeX in `data-math`, undelimited) and
892
+ * mermaid (a `<div class="mermaid" data-mermaid>` instead of `<pre><code>`).
893
+ *
894
+ * Off by default; the default output is byte-identical to previous releases. The widened
895
+ * `HtmlParser` reads every shape this emits, so output stays self-round-trippable.
896
+ */
897
+ sourceAttributes?: boolean;
898
+ /**
899
+ * Emit a generic (non-YouTube) iframe embed as a gated placeholder,
900
+ * `<div data-embed-gated data-embed-src="…" …>`, instead of a live `<iframe>`. The gated shape
901
+ * never auto-loads its src: an editor renders a click-to-load placeholder from it, and
902
+ * `HtmlParser` reads it back to the same `embed` node. The src is scheme-checked (`sanitizeUrl`)
903
+ * on emit. Off by default; the default output (a live `<iframe>`) is unchanged. YouTube embeds
904
+ * are unaffected (they already render from a validated id).
905
+ */
906
+ gatedEmbeds?: boolean;
907
+ }
908
+ /**
909
+ * Configuration options for PDF generation.
910
+ * Maps closely to Puppeteer's PDF options.
911
+ */
912
+ export interface PdfGeneratorConfig {
913
+ /** Paper format. Defaults to 'A4'. */
914
+ format?: "letter" | "legal" | "tabloid" | "ledger" | "a0" | "a1" | "a2" | "a3" | "a4" | "a5" | "a6" | "Letter" | "Legal" | "Tabloid" | "Ledger" | "A0" | "A1" | "A2" | "A3" | "A4" | "A5" | "A6";
915
+ /** Paper width, accepts values labeled with units (e.g., '5in', '3cm') or numbers (in pixels). */
916
+ width?: string | number;
917
+ /** Paper height, accepts values labeled with units (e.g., '5in', '3cm') or numbers (in pixels). */
918
+ height?: string | number;
919
+ /** Whether to print in landscape orientation. Defaults to false. */
920
+ landscape?: boolean;
921
+ /** Whether to print background graphics. Defaults to true. */
922
+ printBackground?: boolean;
923
+ /** Scale of the webpage rendering. Defaults to 1. */
924
+ scale?: number;
925
+ /** Paper margins. */
926
+ margin?: {
927
+ top?: string | number;
928
+ right?: string | number;
929
+ bottom?: string | number;
930
+ left?: string | number;
931
+ };
932
+ /** Whether to display header and footer. Defaults to false. */
933
+ displayHeaderFooter?: boolean;
934
+ /** HTML template for the print header. */
935
+ headerTemplate?: string;
936
+ /** HTML template for the print footer. */
937
+ footerTemplate?: string;
938
+ /**
939
+ * Optional Puppeteer launch options for Node.js environment.
940
+ * Useful for setting custom executable paths or args in CI/CD.
941
+ */
942
+ launchOptions?: any;
943
+ /**
944
+ * Timeout in milliseconds for PDF generation.
945
+ * Limits the time spent waiting for Puppeteer to launch, load content, and render PDF.
946
+ * Defaults to 30000 ms (30 seconds). Set to 0 to disable.
947
+ */
948
+ timeout?: number;
949
+ }
950
+ /**
951
+ * Structured style mapping definition for the StyleMapper.
952
+ *
953
+ * DESIGN PHILOSOPHY: "Semantic Translation"
954
+ * -----------------------------------------
955
+ * Office documents (Word, RTF, PPTX) often use custom or localized style names
956
+ * (e.g., "Heading 1" in English vs "Titre 1" in French, or "MyCompany-Quote").
957
+ *
958
+ * This interface allows you to create a "semantic bridge" between these arbitrary
959
+ * source styles and a universal vocabulary of document elements.
960
+ *
961
+ * WHY USE HTML TAGS FOR NON-HTML OUTPUT?
962
+ * --------------------------------------
963
+ * We use HTML tags (`h1`, `blockquote`, `code`, `pre`) as a "Universal Intermediate
964
+ * Language". By mapping a custom Word style to `blockquote`, you are defining its
965
+ * SEMANTIC MEANING rather than its physical appearance.
966
+ *
967
+ * Each generator then interprets this meaning natively:
968
+ * - HTML Generator: Directly renders the `<blockquote>` tag with your classes.
969
+ * - Markdown Generator: Sees 'blockquote' and renders the standard `> ` prefix.
970
+ * - Text Generator: Sees 'blockquote' and applies appropriate structural indentation.
971
+ */
972
+ export interface StructuredStyleMapping {
973
+ /**
974
+ * The criteria used to identify which AST nodes should be transformed.
975
+ * Think of this as the "Source Filter".
976
+ */
977
+ selector: {
978
+ /**
979
+ * The structural type of the node (e.g., 'paragraph', 'heading', 'text').
980
+ * Most style mappings target 'paragraph' nodes to convert them into headers or blocks.
981
+ */
982
+ nodeType?: OfficeContentNodeType;
983
+ /**
984
+ * A dictionary of attributes to match on the node.
985
+ *
986
+ * The most common use case is matching the 'style' attribute from
987
+ * Word documents (e.g., { style: 'Intense Quote' }).
988
+ *
989
+ * Matchers:
990
+ * - Literal: `style: 'Heading 1'` matches exactly.
991
+ * - Operator: `{ value: 'Title', operator: '~=' }` matches if the word 'Title'
992
+ * is found within the style name.
993
+ */
994
+ attributes?: Record<string, string | number | boolean | {
995
+ value: string | number | boolean;
996
+ operator: "=" | "~=";
997
+ }>;
998
+ };
999
+ /**
1000
+ * The target representation for the matched node.
1001
+ * Think of this as the "Semantic Meaning" you want to assign to the match.
1002
+ */
1003
+ output: {
1004
+ /**
1005
+ * The universal semantic tag (e.g., 'h1', 'h2', 'blockquote', 'code', 'pre', 'u').
1006
+ * All generators use this tag to decide their native output syntax.
1007
+ */
1008
+ tag: string;
1009
+ /**
1010
+ * CSS classes to apply to the output.
1011
+ * This is utilized by the HTML generator to allow for downstream CSS styling.
1012
+ */
1013
+ classes?: string[];
1014
+ /**
1015
+ * Key-value pair of HTML attributes (like 'id', 'data-*', or 'style') to apply.
1016
+ * Primarily used by the HTML generator for high-fidelity conversion.
1017
+ */
1018
+ attributes?: Record<string, string>;
1019
+ /**
1020
+ * If true, prevents the generator from collapsing this element into
1021
+ * adjacent elements of the same type.
1022
+ *
1023
+ * For example, multiple paragraphs mapped to 'blockquote' normally merge into
1024
+ * one big blockquote. Setting `fresh: true` forces them to be separate blocks.
1025
+ */
1026
+ fresh?: boolean;
1027
+ };
1028
+ }
1029
+ /**
1030
+ * Configuration options for RTF generation.
1031
+ */
1032
+ export interface RtfGeneratorConfig {
1033
+ }
1034
+ /**
1035
+ * Configuration options for CSV generation.
1036
+ */
1037
+ export interface CsvGeneratorConfig {
1038
+ /**
1039
+ * Range of sheets to export.
1040
+ * Supports formats like "1", "1-3", "1,2", "1,3-5,7".
1041
+ * 1-based indexing.
1042
+ * Default is '' (all sheets).
1043
+ */
1044
+ sheets?: string;
1045
+ /**
1046
+ * Whether to merge all selected sheets into a single CSV.
1047
+ * If false, returns a ZIP archive containing individual CSV files.
1048
+ * Defaults to true.
1049
+ */
1050
+ mergeSheets?: boolean;
1051
+ /**
1052
+ * Custom delimiter for CSV files.
1053
+ * Defaults to ','.
1054
+ */
1055
+ columnDelimiter?: string;
1056
+ }
1057
+ /**
1058
+ * Named Markdown dialect presets for `MarkdownDialectConfig`/`MdGeneratorConfig.dialect`.
1059
+ * `'extended'` is officeParser's own kitchen-sink default and reproduces this library's
1060
+ * historical output exactly (every feature on, GitHub-style admonitions).
1061
+ */
1062
+ export type MarkdownDialectPreset = "extended" | "github" | "gitlab" | "obsidian" | "pandoc" | "commonmark";
1063
+ /** Admonition syntax: `'blockquote'` = GitHub `> [!NOTE]`, `'fence'` = GitLab `:::note`,
1064
+ * `'fence-attribute'` = Pandoc `::: {.note}`, `'none'` = plain bold-labeled blockquote. */
1065
+ export type AdmonitionSyntax = "blockquote" | "fence" | "fence-attribute" | "none";
1066
+ /** `==text==` highlight (`'equals'`), or `'none'` to disable. */
1067
+ export type HighlightSyntax = "equals" | "none";
1068
+ /** GFM `~~text~~` strikethrough (`'tilde'`), or `'none'`. */
1069
+ export type StrikethroughSyntax = "tilde" | "none";
1070
+ /** `Term`/`: Description` definition lists (`'colon'`), or `'none'`. */
1071
+ export type DefinitionListSyntax = "colon" | "none";
1072
+ /** `[^id]` footnotes (`'caret'`), or `'none'`. */
1073
+ export type FootnoteSyntax = "caret" | "none";
1074
+ /** `[@citekey]` citations (`'at'`), or `'none'`. */
1075
+ export type CitationSyntax = "at" | "none";
1076
+ /** `[[Page]]` wikilinks (`'double-bracket'`), or `'none'`. */
1077
+ export type WikilinkSyntax = "double-bracket" | "none";
1078
+ /** `{width=50%}` attribute lists (`'brace'`), or `'none'`. */
1079
+ export type AttributeListSyntax = "brace" | "none";
1080
+ /**
1081
+ * How an `embed` node is written to Markdown:
1082
+ * - `'html'` (default): the single-line `<div data-youtube-video="ID">` / `<iframe src=...>` block
1083
+ * this library has always emitted. Round-trips through officeParser, but renders as an invisible
1084
+ * empty box on GitHub.
1085
+ * - `'directive'`: a remark-directive leaf, `::youtube[Label]{id=... width=... align=...}` /
1086
+ * `::embed[Label]{src=... width=... height=... align=...}`. Round-trips within an editor that
1087
+ * understands it; renders verbatim (not just the label) on GitHub, so it is an editor format, not
1088
+ * a GitHub-interop one.
1089
+ * - `'link'`: a plain `[YouTube](url)` / `[Embed](url)`.
1090
+ * - `'thumbnail'`: a YouTube-only clickable thumbnail `[![Label](.../vi/ID/hqdefault.jpg)](watch)`,
1091
+ * the best GitHub degrade; a non-YouTube embed falls back to `'link'`.
1092
+ */
1093
+ export type EmbedSyntax = "html" | "directive" | "link" | "thumbnail";
1094
+ /**
1095
+ * @deprecated Legacy flavor names for `MarkdownDialectConfig.admonitions`. Use the syntax names
1096
+ * instead: `'github'` -> `'blockquote'`, `'gitlab'` -> `'fence'`, `'pandoc'` -> `'fence-attribute'`.
1097
+ * These aliases still resolve to the same output and will be removed in the next major version.
1098
+ */
1099
+ export type DeprecatedAdmonitionFlavor = "github" | "gitlab" | "pandoc";
1100
+ /**
1101
+ * @deprecated Boolean toggles for dialect capability fields are deprecated in favor of the
1102
+ * syntax-name unions: `true` maps to that field's on-value (e.g. `'tilde'`), `false` maps to
1103
+ * `'none'`. Booleans keep working via coercion and will be removed in the next major version.
1104
+ */
1105
+ export type DeprecatedDialectToggle = boolean;
1106
+ /**
1107
+ * Granular control over which native Markdown syntax the generator emits for constructs that
1108
+ * differ across real-world dialects (e.g. GitHub's `> [!NOTE]` vs GitLab's `:::note` vs Pandoc's
1109
+ * `::: {.note}` admonitions). Shorthand: pass a `MarkdownDialectPreset` string for a named target;
1110
+ * pass an object for granular control. Any field you omit from the object form falls back to the
1111
+ * preset named by `extends` (default `'extended'`) - **not** to whatever preset may have been
1112
+ * ambient before, since config merging replaces the whole field rather than layering on top of it.
1113
+ */
1114
+ export interface MarkdownDialectConfig {
1115
+ /** Base preset any omitted field inherits from. Defaults to 'extended'. */
1116
+ extends?: MarkdownDialectPreset;
1117
+ /**
1118
+ * Admonition syntax: `'blockquote'` = GitHub `> [!NOTE]`, `'fence'` = GitLab `:::note`,
1119
+ * `'fence-attribute'` = Pandoc `::: {.note}`, `'none'` = a plain bold-labeled blockquote with no
1120
+ * special marker. Omit to inherit from the `extends` preset. The legacy flavor names
1121
+ * `'github'`/`'gitlab'`/`'pandoc'` are accepted as deprecated aliases (see
1122
+ * `DeprecatedAdmonitionFlavor`) and will be removed in the next major version.
1123
+ */
1124
+ admonitions?: AdmonitionSyntax | DeprecatedAdmonitionFlavor;
1125
+ /**
1126
+ * Markdown Extra/Pandoc-style `Term`/`: Description` definition lists (`'colon'`), or `'none'`
1127
+ * to render terms and descriptions as plain paragraphs. Omit to inherit from `extends`. Passing
1128
+ * a boolean is deprecated: `true` = `'colon'`, `false` = `'none'` (removed next major).
1129
+ */
1130
+ definitionLists?: DefinitionListSyntax | DeprecatedDialectToggle;
1131
+ /**
1132
+ * `[^id]` footnote references/definitions (`'caret'`), or `'none'` to inline note content as a
1133
+ * parenthetical right at the reference point. Omit to inherit from `extends`. Passing a boolean
1134
+ * is deprecated: `true` = `'caret'`, `false` = `'none'` (removed next major).
1135
+ */
1136
+ footnotes?: FootnoteSyntax | DeprecatedDialectToggle;
1137
+ /**
1138
+ * Pandoc-style `[@citekey]` citations (`'at'`), or `'none'` to emit `[citekey]` (brackets, no
1139
+ * `@`). Omit to inherit from `extends`. Passing a boolean is deprecated: `true` = `'at'`,
1140
+ * `false` = `'none'` (removed next major).
1141
+ */
1142
+ citations?: CitationSyntax | DeprecatedDialectToggle;
1143
+ /**
1144
+ * Obsidian-style `[[Page]]`/`[[Page|Alias]]` wikilinks (`'double-bracket'`), or `'none'` to fall
1145
+ * back to a plain `[text](url)` link using the same target. Omit to inherit from `extends`.
1146
+ * Passing a boolean is deprecated: `true` = `'double-bracket'`, `false` = `'none'` (removed next major).
1147
+ */
1148
+ wikilinks?: WikilinkSyntax | DeprecatedDialectToggle;
1149
+ /** Inline `$...$`/block `$$...$$` math delimiters (`'dollar'`), or `'none'` for bare LaTeX text. */
1150
+ math?: "dollar" | "none";
1151
+ /**
1152
+ * Pandoc-style `{width=50% .centered}` attribute lists after images/tables (`'brace'`), or
1153
+ * `'none'`. Omit to inherit from `extends`. Passing a boolean is deprecated: `true` = `'brace'`,
1154
+ * `false` = `'none'` (removed next major).
1155
+ */
1156
+ attributeLists?: AttributeListSyntax | DeprecatedDialectToggle;
1157
+ /**
1158
+ * GFM `~~text~~` strikethrough (`'tilde'`; not part of base CommonMark), or `'none'`. Omit to
1159
+ * inherit from `extends`. Passing a boolean is deprecated: `true` = `'tilde'`, `false` = `'none'`
1160
+ * (removed next major).
1161
+ */
1162
+ strikethrough?: StrikethroughSyntax | DeprecatedDialectToggle;
1163
+ /**
1164
+ * `==text==` highlight (`'equals'`; Obsidian/extended flavors, NOT GFM or CommonMark where `==`
1165
+ * is literal text), or `'none'`. When `'equals'`, a highlighted run round-trips as `==text==`
1166
+ * and `==text==` is read back as a highlight; when `'none'`, a highlight falls back to an HTML
1167
+ * `<mark>`/`<span>` per `fallbackToHtml.inlineFormatting`, and `==text==` stays literal on parse.
1168
+ * Omit to inherit from `extends`.
1169
+ */
1170
+ highlight?: HighlightSyntax;
1171
+ /** Unordered list bullet character. */
1172
+ bulletListMarker?: "-" | "*" | "+";
1173
+ /** Ordered list marker punctuation. */
1174
+ orderedListMarker?: "." | ")";
1175
+ /** Emphasis delimiter style for bold/italic. */
1176
+ emphasisMarker?: "asterisk" | "underscore";
1177
+ /** Table syntax: native GFM pipe tables, or forced HTML `<table>` (required for strict
1178
+ * CommonMark, which has no table syntax of its own). */
1179
+ tables?: "native" | "html";
1180
+ /**
1181
+ * How an `embed` node is written to Markdown (`'html'` | `'directive'` | `'link'` |
1182
+ * `'thumbnail'`; see `EmbedSyntax`). This is the authority for embed form. When omitted, the
1183
+ * deprecated `fallbackToHtml.embeds` boolean is honored (`true`/unset maps to `'html'`, `false`
1184
+ * to `'link'`), then the default `'html'`.
1185
+ */
1186
+ embeds?: EmbedSyntax;
1187
+ }
1188
+ /**
1189
+ * Granular control over when the Markdown generator falls back to raw HTML tags for features
1190
+ * standard Markdown can't express natively. Shorthand: `true`/`false` (via
1191
+ * `MdGeneratorConfig.fallbackToHtml`) turns every part on/off at once; pass an object instead to
1192
+ * control them independently. Omitted object fields default to on, matching the boolean shorthand.
1193
+ */
1194
+ export interface FallbackToHtmlConfig {
1195
+ /** Underline/subscript/superscript via `<u>`/`<sub>`/`<sup>`. */
1196
+ textFormatting?: boolean;
1197
+ /** Heading/paragraph text alignment via `<div style="text-align:...">`. */
1198
+ alignment?: boolean;
1199
+ /** Internal-link/heading `<a id>`/`<a name>` anchor tags. */
1200
+ anchors?: boolean;
1201
+ /** Nested-table and merged-cell (colspan/rowspan) HTML `<table>` fallback. */
1202
+ tables?: boolean;
1203
+ /**
1204
+ * YouTube embed `<div data-youtube-video>` vs. a plain link.
1205
+ * @deprecated Use `mdConfig.dialect.embeds` (`EmbedSyntax`) instead, which also selects the
1206
+ * `'directive'` and `'thumbnail'` forms. When `dialect.embeds` is unset this boolean is still
1207
+ * honored (`true` maps to `'html'`, `false` to `'link'`); it will be removed in the next major.
1208
+ */
1209
+ embeds?: boolean;
1210
+ /** Multi-line table cell content joined with `<br>` instead of a space. */
1211
+ cellLineBreaks?: boolean;
1212
+ /**
1213
+ * Multi-paragraph list-item content (an HTML `<li>` with several `<p>` children) joined with
1214
+ * `<br>` instead of a space, so it stays on the item's single Markdown line. Block children of
1215
+ * an item (a code fence or table inside `<li>`) degrade under this join, the same way they do
1216
+ * inside a table cell under `cellLineBreaks`.
1217
+ */
1218
+ itemLineBreaks?: boolean;
1219
+ /**
1220
+ * Inline text color, highlight, and font size via a `<span style="color:...;background-color:...;
1221
+ * font-size:...">` run, which the Markdown parser reads back. These have no Markdown syntax and
1222
+ * are silently lost otherwise. Unlike the other fields this is **off by default even when
1223
+ * `fallbackToHtml` is `true`**, because it changes default output; enable it explicitly with
1224
+ * `fallbackToHtml: { inlineFormatting: true }`.
1225
+ */
1226
+ inlineFormatting?: boolean;
1227
+ }
1228
+ /**
1229
+ * Configuration options for Markdown generation.
1230
+ */
1231
+ export interface MdGeneratorConfig {
1232
+ /**
1233
+ * Whether to fallback to HTML tags for features not supported by standard Markdown.
1234
+ * Pass an object instead of a boolean for granular control over individual parts (text
1235
+ * formatting, alignment, anchors, tables, embeds, cell line breaks) - see
1236
+ * `FallbackToHtmlConfig`. Omitted object fields default to on, matching `true`.
1237
+ *
1238
+ * Markdown has limited support for complex document structures. This flag controls how
1239
+ * the generator handles features that cannot be represented in pure Markdown:
1240
+ *
1241
+ * 1. If a feature is NOT supported natively by Markdown (e.g., nested tables, text alignment,
1242
+ * underline, subscript/superscript):
1243
+ * - If true: The generator will use HTML tags (<u>, <sub>, <div>, <table>, etc.) to
1244
+ * maintain high fidelity.
1245
+ * - If false: The generator will skip or simplify the feature (e.g., ignoring alignment,
1246
+ * skipping underline, or hoisting nested tables out of their cells).
1247
+ *
1248
+ * 2. If a feature IS supported by Markdown but a higher quality version is possible
1249
+ * via HTML (e.g., tables with merged cells):
1250
+ * - If true: Use HTML for better fidelity.
1251
+ * - If false: Use native Markdown syntax (e.g., a standard GFM table grid).
1252
+ *
1253
+ * Defaults to true.
1254
+ */
1255
+ fallbackToHtml?: boolean | FallbackToHtmlConfig;
1256
+ /**
1257
+ * Target Markdown dialect for generation - which native syntax to emit for constructs that
1258
+ * differ across real-world targets (GitHub/GitLab/Obsidian/Pandoc/strict CommonMark). See
1259
+ * `MarkdownDialectConfig` for the full per-feature field list. Defaults to `'extended'`
1260
+ * (officeParser's own historical kitchen-sink behavior, unchanged from prior versions).
1261
+ */
1262
+ dialect?: MarkdownDialectPreset | MarkdownDialectConfig;
1263
+ }
1264
+ /**
1265
+ * Configuration options for plain text generation.
1266
+ */
1267
+ export interface TextGeneratorConfig {
1268
+ /**
1269
+ * The delimiter used for every new line.
1270
+ * Defaults to '\n'.
1271
+ */
1272
+ newlineDelimiter?: string;
1273
+ /**
1274
+ * Whether to attempt to preserve the original document layout.
1275
+ * If true, tables are rendered with separators and aligned columns, and list items get their
1276
+ * markers and indentation.
1277
+ * If false, output is a flat stream of text nodes (cells are tab-separated).
1278
+ * Defaults to **true**.
1279
+ */
1280
+ preserveLayout?: boolean;
1281
+ /**
1282
+ * Whether to append the collected footnotes/endnotes as a trailing `--- Notes ---` section.
1283
+ * Set false to omit it when you want only the document body; the notes are still parsed and
1284
+ * remain available on the AST, they are simply not rendered into the text output.
1285
+ *
1286
+ * Note this differs from the parser's `ignoreNotes`, which discards notes at parse time so they
1287
+ * never reach the AST at all. Use this when you want the AST to keep them but the text output
1288
+ * to leave them out.
1289
+ *
1290
+ * Defaults to true.
1291
+ */
1292
+ renderNotes?: boolean;
1293
+ }
1294
+ /**
1295
+ * The strategy used for chunking a document for RAG pipelines.
1296
+ * - 'fixed-size': Traditional character/token count based splitting.
1297
+ * - 'document-structure': Leverages the AST to split at natural document boundaries.
1298
+ * - 'semantic': Uses embedding similarity to find natural topic breakpoints.
1299
+ */
1300
+ export type ChunkingStrategy = "fixed-size" | "document-structure" | "semantic";
1301
+ /**
1302
+ * Base configuration applicable to all chunking strategies.
1303
+ */
1304
+ export interface BaseChunkingConfig {
1305
+ /**
1306
+ * The strategy used for chunking.
1307
+ * Default is 'document-structure'.
1308
+ */
1309
+ strategy?: ChunkingStrategy;
1310
+ /**
1311
+ * A function that measures the size of a text string.
1312
+ * Defaults to character count: `(text) => text.length`.
1313
+ * Override with a token counter (e.g., `tiktoken`) for strict LLM context window adherence.
1314
+ */
1315
+ lengthFunction?: (text: string) => number;
1316
+ /**
1317
+ * Whether to strip leading/trailing whitespace from each chunk.
1318
+ * Default is true.
1319
+ */
1320
+ stripWhitespace?: boolean;
1321
+ /**
1322
+ * Whether to include rich AST metadata (page number, slide number, heading, etc.)
1323
+ * in the generated chunk objects.
1324
+ * Default is true.
1325
+ */
1326
+ includeMetadata?: boolean;
1327
+ /**
1328
+ * Whether to include the starting character index of each chunk
1329
+ * relative to the whole document. Useful for UI text highlighting.
1330
+ * Default is false.
1331
+ */
1332
+ addStartIndex?: boolean;
1333
+ /**
1334
+ * Optional custom regex (as string or RegExp object) to identify sentence boundaries.
1335
+ * Use this for languages or specific document types that require custom splitting logic.
1336
+ * If provided, it overrides or augments the default segmenter.
1337
+ * @example /[。?!]/
1338
+ */
1339
+ sentenceBoundaryRegex?: string | RegExp;
1340
+ /**
1341
+ * Optional list of abbreviations to ignore when splitting text into sentences.
1342
+ * These words, if followed by a period, will not be treated as sentence boundaries.
1343
+ * Use this to handle language-specific or domain-specific abbreviations.
1344
+ * @example ["Inc", "Ltd", "approx"]
1345
+ */
1346
+ abbreviations?: string[];
1347
+ }
1348
+ /**
1349
+ * Configuration for Fixed-Size Chunking.
1350
+ * Cuts text based on a maximum size limit with an optional overlap.
1351
+ * This is equivalent to LangChain's `RecursiveCharacterTextSplitter`.
1352
+ */
1353
+ export interface FixedSizeChunkingConfig extends BaseChunkingConfig {
1354
+ strategy: "fixed-size";
1355
+ /**
1356
+ * Maximum size of the chunk, measured by `lengthFunction`.
1357
+ * Default is 1000 characters.
1358
+ */
1359
+ chunkSize?: number;
1360
+ /**
1361
+ * Number of characters/tokens to overlap between consecutive chunks
1362
+ * to avoid losing context at boundaries.
1363
+ * Rule of thumb: ~10–20% of `chunkSize`.
1364
+ * Default is 200.
1365
+ */
1366
+ chunkOverlap?: number;
1367
+ /**
1368
+ * Ordered list of separators to try when splitting.
1369
+ * The chunker tries each in order; if a split would exceed `chunkSize`,
1370
+ * it tries the next separator.
1371
+ * Default is ['\n\n', '\n', ' ', ''].
1372
+ */
1373
+ separators?: string[];
1374
+ }
1375
+ /**
1376
+ * Configuration for Document-Structure Chunking.
1377
+ * Uses the officeParser AST to split at natural document boundaries like
1378
+ * headings, paragraphs, slides, or pages. This is the recommended strategy
1379
+ * as it preserves semantic context from the document's own structure.
1380
+ */
1381
+ export interface DocumentStructureChunkingConfig extends BaseChunkingConfig {
1382
+ strategy: "document-structure";
1383
+ /**
1384
+ * The primary structural element at which to force a chunk boundary.
1385
+ * - 'paragraph': Never cross a paragraph boundary (finest-grained, most precise).
1386
+ * - 'heading': Split at every heading change.
1387
+ * - 'page': Chunks never span multiple pages (PDF only).
1388
+ * - 'slide': Chunks never span multiple slides (PPTX/ODP only).
1389
+ * - 'sheet': Chunks never span multiple sheets (XLSX/ODS only).
1390
+ * Default is 'paragraph'.
1391
+ */
1392
+ splitBy?: "page" | "slide" | "sheet" | "heading" | "paragraph";
1393
+ /**
1394
+ * Maximum size of a chunk (measured by `lengthFunction`).
1395
+ * If a single structural unit (e.g., one paragraph) exceeds this limit,
1396
+ * it will be further split using a recursive character splitter.
1397
+ * Default is 1000 characters.
1398
+ */
1399
+ maxChunkSize?: number;
1400
+ /**
1401
+ * How to handle table nodes when splitting.
1402
+ * - 'row': Split by rows, REPEATING the header row in every chunk so the LLM
1403
+ * always understands what the columns mean. (Highly recommended for RAG)
1404
+ * - 'flatten': Convert the table to plain text and split like a regular block.
1405
+ * Default is 'row'.
1406
+ */
1407
+ tableSplitStrategy?: "row" | "flatten";
1408
+ }
1409
+ /**
1410
+ * Configuration for Semantic Chunking.
1411
+ * Uses an embedding model to detect topic shifts and create boundaries
1412
+ * where content meaning naturally changes. Computationally expensive but
1413
+ * produces the highest quality chunks.
1414
+ */
1415
+ export interface SemanticChunkingConfig extends BaseChunkingConfig {
1416
+ strategy: "semantic";
1417
+ /**
1418
+ * A user-provided async function to generate vector embeddings for a text string.
1419
+ * Required. Example: a wrapper around OpenAI's `text-embedding-3-small`.
1420
+ * @example async (text) => await openai.embeddings.create({ input: text, model: 'text-embedding-3-small' }).then(r => r.data[0].embedding)
1421
+ */
1422
+ embeddingFunction: (text: string) => Promise<number[]>;
1423
+ /**
1424
+ * The cosine similarity threshold below which a chunk boundary is created.
1425
+ * When the similarity between two adjacent sentences drops below this value,
1426
+ * a new chunk starts. Higher = more splits, smaller chunks.
1427
+ * Default is 0.8.
1428
+ */
1429
+ similarityThreshold?: number;
1430
+ /**
1431
+ * Maximum size of a chunk even if semantic similarity remains high.
1432
+ * Prevents runaway chunks when an entire document is on one topic.
1433
+ * Default is 2000 characters.
1434
+ */
1435
+ maxChunkSize?: number;
1436
+ /**
1437
+ * Number of surrounding sentences to include when computing similarity
1438
+ * for a sentence. A larger window reduces noise from single odd sentences.
1439
+ * Default is 1.
1440
+ */
1441
+ bufferSize?: number;
1442
+ /**
1443
+ * Number of sentences to process in a single batch when calling the embedding function.
1444
+ * Higher values are faster but may trigger API rate limits.
1445
+ * Default is 50.
1446
+ */
1447
+ embeddingBatchSize?: number;
1448
+ /**
1449
+ * Timeout in milliseconds for individual embedding API calls.
1450
+ * Defaults to 10000 ms (10 seconds). Set to 0 to disable.
1451
+ */
1452
+ timeout?: number;
1453
+ }
1454
+ /**
1455
+ * Discriminated union of all chunking strategy configurations.
1456
+ */
1457
+ export type ChunkingConfig = FixedSizeChunkingConfig | DocumentStructureChunkingConfig | SemanticChunkingConfig;
1458
+ /**
1459
+ * Represents a single document chunk ready for a RAG (Retrieval-Augmented Generation) pipeline.
1460
+ *
1461
+ * Chunks are the result of splitting a document into smaller, semantically coherent
1462
+ * pieces that fit within the context window of an LLM. Each chunk includes the
1463
+ * extracted text and rich AST-derived metadata for citations and filtered retrieval.
1464
+ */
1465
+ export interface OfficeChunk {
1466
+ /** The text content of this chunk. This is what gets embedded. */
1467
+ text: string;
1468
+ /**
1469
+ * Rich contextual metadata extracted from the AST.
1470
+ * Use this to populate vector DB metadata fields for filtered retrieval
1471
+ * and for LLM citations.
1472
+ */
1473
+ metadata: {
1474
+ /** The source file format (e.g., 'docx', 'pptx', 'pdf'). */
1475
+ sourceType: SupportedFileType;
1476
+ /** Page number (1-based), if available (PDF). */
1477
+ pageNumber?: number;
1478
+ /** Slide number (1-based), if available (PPTX/ODP). */
1479
+ slideNumber?: number;
1480
+ /** Sheet name, if available (XLSX/ODS). */
1481
+ sheetName?: string;
1482
+ /** The text of the nearest heading above this chunk in the document. */
1483
+ closestHeading?: string;
1484
+ /** True if this chunk is part of a table split. */
1485
+ isTableChunk?: boolean;
1486
+ /** Extensible for user-defined metadata. */
1487
+ [key: string]: any;
1488
+ };
1489
+ /** The start character index of this chunk in the full document text. Only set when `addStartIndex` is true. */
1490
+ startIndex?: number;
1491
+ /** The end character index of this chunk in the full document text. Only set when `addStartIndex` is true. */
1492
+ endIndex?: number;
1493
+ }
1494
+ /**
1495
+ * Supported file types for parsing.
1496
+ */
1497
+ export type SupportedFileType = "docx" | "pptx" | "xlsx" | "odt" | "odp" | "ods" | "pdf" | "rtf" | "md" | "html" | "csv" | "epub";
1498
+ /**
1499
+ * A structural stand-in for the web `Blob`/`File` so `parseOffice`/`convert` accept them in the
1500
+ * browser without pulling the DOM lib into this package's types. Any object with an
1501
+ * `arrayBuffer()` method qualifies. When `name` is present (as on a `File`) it is used only for
1502
+ * extension-based type detection, never as a filesystem path.
1503
+ */
1504
+ export interface BlobLike {
1505
+ arrayBuffer(): Promise<ArrayBuffer>;
1506
+ name?: string;
1507
+ }
1508
+ /**
1509
+ * Types of content nodes in the AST.
1510
+ */
1511
+ export type OfficeContentNodeType = "paragraph" | "heading" | "table" | "list" | "text" | "image" | "chart" | "drawing" | "slide" | "note" | "sheet" | "row" | "cell" | "page" | "break" | "code" | "comment" | "header" | "footer" | "slideMaster" | "embed" | "admonition" | "definitionList" | "definitionTerm" | "definitionDescription";
1512
+ /**
1513
+ * Supported MIME types for attachments.
1514
+ */
1515
+ export type OfficeMimeType = "image/jpeg" | "image/png" | "image/gif" | "image/bmp" | "image/tiff" | "image/svg+xml" | "application/pdf" | "application/vnd.openxmlformats-officedocument.wordprocessingml.document" | "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | "application/vnd.openxmlformats-officedocument.presentationml.presentation" | "application/vnd.oasis.opendocument.chart" | "application/vnd.oasis.opendocument.spreadsheet" | "application/vnd.oasis.opendocument.text" | "application/vnd.oasis.opendocument.presentation" | "application/rtf" | "text/csv" | "text/markdown" | "text/html";
1516
+ /**
1517
+ * Text alignment options.
1518
+ * Common in spreadsheet cells, paragraph styles, and text elements.
1519
+ */
1520
+ export type TextAlignment = "left" | "center" | "right" | "justify";
1521
+ /**
1522
+ * Text formatting options available for text content.
1523
+ * Represents common formatting attributes found in office documents (DOCX, RTF, PPTX, etc.).
1524
+ * All properties are optional and only present when the formatting is explicitly applied.
1525
+ */
1526
+ export interface TextFormatting {
1527
+ /**
1528
+ * Whether the text is bold.
1529
+ * Corresponds to `<w:b/>` in OOXML, `\b` in RTF.
1530
+ * @example true for **bold text**, false or undefined for normal weight
1531
+ */
1532
+ bold?: boolean;
1533
+ /**
1534
+ * Whether the text is italic.
1535
+ * Corresponds to `<w:i/>` in OOXML, `\i` in RTF.
1536
+ * @example true for *italic text*, false or undefined for normal style
1537
+ */
1538
+ italic?: boolean;
1539
+ /**
1540
+ * Whether the text is underlined.
1541
+ * Corresponds to `<w:u/>` in OOXML, `\ul` in RTF.
1542
+ * @example true for underlined text, false or undefined for no underline
1543
+ */
1544
+ underline?: boolean;
1545
+ /**
1546
+ * Whether the text has a strikethrough.
1547
+ * Corresponds to `<w:strike/>` in OOXML, `\strike` in RTF.
1548
+ * @example true for ~~struck through~~ text
1549
+ */
1550
+ strikethrough?: boolean;
1551
+ /**
1552
+ * Text color in hex format (#RRGGBB).
1553
+ * Extracted from color tables in RTF or XML color attributes in OOXML.
1554
+ * @example "#ff0000" for red, "#00ff00" for green, "#0000ff" for blue
1555
+ */
1556
+ color?: string;
1557
+ /**
1558
+ * Background/highlight color in hex format (#RRGGBB).
1559
+ * Represents the background color or text highlighting.
1560
+ * @example "#ffff00" for yellow highlight, "#d3d3d3" for light gray
1561
+ */
1562
+ backgroundColor?: string;
1563
+ /**
1564
+ * Font size with units.
1565
+ * Most parsers append 'pt' (points), but ODF may use other units like 'in' (inches) or 'cm'.
1566
+ * @example "12pt" for 12pt, "14pt" for 14pt, "0.5in" for 0.5 inches
1567
+ */
1568
+ size?: string;
1569
+ /**
1570
+ * Font family/typeface name.
1571
+ * Extracted from font tables in RTF or font definitions in OOXML.
1572
+ * @example "Arial", "Times New Roman", "Calibri", "Ubuntu Mono"
1573
+ */
1574
+ font?: string;
1575
+ /**
1576
+ * Whether the text is subscript (e.g., H₂O).
1577
+ * Corresponds to `\sub` in RTF, `<w:vertAlign w:val="subscript"/>` in OOXML.
1578
+ * Mutually exclusive with superscript.
1579
+ * @example true for subscript text like H₂O
1580
+ */
1581
+ subscript?: boolean;
1582
+ /**
1583
+ * Whether the text is superscript (e.g., E=mc²).
1584
+ * Corresponds to `\super` in RTF, `<w:vertAlign w:val="superscript"/>` in OOXML.
1585
+ * Mutually exclusive with subscript.
1586
+ * @example true for superscript text like x²
1587
+ */
1588
+ superscript?: boolean;
1589
+ /**
1590
+ * The alignment of the text.
1591
+ * Common in spreadsheet cells or paragraph styles.
1592
+ * @example "center", "right"
1593
+ */
1594
+ alignment?: TextAlignment;
1595
+ }
1596
+ /**
1597
+ * Metadata for a slide in PowerPoint.
1598
+ */
1599
+ export interface SlideMetadata {
1600
+ /** The slide number (1-based). */
1601
+ slideNumber: number;
1602
+ /**
1603
+ * The unique ID of the note associated with this slide (if any).
1604
+ * @example "slide-note-1"
1605
+ */
1606
+ noteId?: string;
1607
+ /** The style of the slide. */
1608
+ style?: string;
1609
+ /** Unique anchor IDs for internal linking. */
1610
+ anchorIds?: string[];
1611
+ }
1612
+ /**
1613
+ * Metadata for a sheet in Excel.
1614
+ */
1615
+ export interface SheetMetadata {
1616
+ /** The name of the sheet. */
1617
+ sheetName: string;
1618
+ /** The style of the sheet. */
1619
+ style?: string;
1620
+ /** Unique anchor IDs for internal linking. */
1621
+ anchorIds?: string[];
1622
+ }
1623
+ /**
1624
+ * Detailed indentation information for paragraphs and headings.
1625
+ * Values are typically in twentieths of a point (twips) in OOXML.
1626
+ */
1627
+ export interface IndentationMetadata {
1628
+ /** Left indentation. */
1629
+ left?: number;
1630
+ /** Right indentation. */
1631
+ right?: number;
1632
+ /** First line indentation. */
1633
+ firstLine?: number;
1634
+ /** Hanging indentation. */
1635
+ hanging?: number;
1636
+ }
1637
+ /**
1638
+ * Metadata for a heading.
1639
+ */
1640
+ export interface HeadingMetadata {
1641
+ /** The heading level (e.g., 1 for H1). */
1642
+ level: number;
1643
+ /** The alignment of the heading. */
1644
+ alignment?: TextAlignment;
1645
+ /** The style of the heading. */
1646
+ style?: string;
1647
+ /** Detailed indentation information. */
1648
+ paragraphIndentation?: IndentationMetadata;
1649
+ /** Unique anchor IDs for internal linking. */
1650
+ anchorIds?: string[];
1651
+ }
1652
+ /**
1653
+ * Metadata for a paragraph.
1654
+ */
1655
+ export interface ParagraphMetadata {
1656
+ /** The alignment of the paragraph. */
1657
+ alignment?: TextAlignment;
1658
+ /** The style of the paragraph. */
1659
+ style?: string;
1660
+ /** Detailed indentation information. */
1661
+ paragraphIndentation?: IndentationMetadata;
1662
+ /** Unique anchor IDs for internal linking. */
1663
+ anchorIds?: string[];
1664
+ }
1665
+ /**
1666
+ * Metadata for a list item.
1667
+ */
1668
+ export interface ListMetadata {
1669
+ /**
1670
+ * The type of list: 'ordered' (numbered) or 'unordered' (bulleted).
1671
+ * @example 'ordered' for numbered lists, 'unordered' for bulleted lists
1672
+ */
1673
+ listType: "ordered" | "unordered";
1674
+ /**
1675
+ * The nesting level (indent level) of the list item, starting from 0.
1676
+ * @example 0 for top-level items, 1 for first nested level
1677
+ */
1678
+ indentation: number;
1679
+ /** Detailed indentation information. */
1680
+ paragraphIndentation?: IndentationMetadata;
1681
+ /**
1682
+ * Text alignment of the list item.
1683
+ * @example 'left', 'center', 'right', 'justify'
1684
+ */
1685
+ alignment: TextAlignment;
1686
+ /**
1687
+ * The list ID from the Word document's numbering definition.
1688
+ * Used to identify which list definition this item belongs to.
1689
+ * @example '1', '2' for different list definitions
1690
+ */
1691
+ listId: string;
1692
+ /**
1693
+ * The zero-based index of this item within its list.
1694
+ * Continues incrementing even across paragraph interruptions for the same listId.
1695
+ * @example 0, 1, 2, 3 for sequential list items
1696
+ */
1697
+ itemIndex: number;
1698
+ /**
1699
+ * The style name of the list item.
1700
+ * @example "ListParagraph"
1701
+ */
1702
+ style?: string;
1703
+ /** Unique anchor IDs for internal linking. */
1704
+ anchorIds?: string[];
1705
+ /** True when this list item is a GFM task-list item (checkbox), regardless of checked state. */
1706
+ isTask?: boolean;
1707
+ /** Checked state for a task-list item. Only meaningful when isTask is true. */
1708
+ checked?: boolean;
1709
+ }
1710
+ /**
1711
+ * Metadata for a table cell (primarily used in Excel/spreadsheet parsing).
1712
+ * Contains positional information about where the cell appears in the table.
1713
+ */
1714
+ export interface CellMetadata {
1715
+ /**
1716
+ * The row index of the cell (0-based).
1717
+ * @example 0 for the first row, 1 for the second row, etc.
1718
+ */
1719
+ row: number;
1720
+ /**
1721
+ * The column index of the cell (0-based).
1722
+ * @example 0 for column A, 1 for column B, etc.
1723
+ */
1724
+ col: number;
1725
+ /**
1726
+ * Text alignment for this cell's column, from the GFM pipe-table separator row
1727
+ * (`:---` left, `:---:` center, `---:` right). All cells in a column carry the same value;
1728
+ * the Markdown generator reads it from the header row to emit the separator.
1729
+ */
1730
+ align?: "left" | "center" | "right";
1731
+ /**
1732
+ * The number of rows this cell spans (merges).
1733
+ * @example 2 if the cell is merged with the one below it.
1734
+ */
1735
+ rowSpan?: number;
1736
+ /**
1737
+ * The number of columns this cell spans (merges).
1738
+ * @example 2 if the cell is merged with the one to its right.
1739
+ */
1740
+ colSpan?: number;
1741
+ /** The style of the cell. */
1742
+ style?: string;
1743
+ /** Unique anchor IDs for internal linking. */
1744
+ anchorIds?: string[];
1745
+ /** Background color for this cell in hex format (e.g. #FFFFFF). */
1746
+ backgroundColor?: string;
1747
+ }
1748
+ /**
1749
+ * Metadata for a table.
1750
+ */
1751
+ export interface TableMetadata {
1752
+ /** Unique anchor IDs for internal linking. */
1753
+ anchorIds?: string[];
1754
+ /**
1755
+ * Layout alignment of the table on the page (e.g. an editor's custom table node).
1756
+ * @example 'center'
1757
+ */
1758
+ align?: "left" | "center" | "right";
1759
+ }
1760
+ /**
1761
+ * Metadata for a chart node in the document.
1762
+ * Links the chart node to its corresponding attachment in the attachments array.
1763
+ */
1764
+ export interface ChartMetadata {
1765
+ /**
1766
+ * The name of the attachment that contains the actual chart data.
1767
+ * Use this to look up the full chart data from the attachments array.
1768
+ * @example "chart1.xml"
1769
+ */
1770
+ attachmentName: string;
1771
+ /** Unique anchor IDs for internal linking. */
1772
+ anchorIds?: string[];
1773
+ }
1774
+ /**
1775
+ * Metadata for an image node in the document.
1776
+ * Links the image node to its corresponding attachment in the attachments array.
1777
+ */
1778
+ export interface ImageMetadata {
1779
+ /**
1780
+ * The name of the attachment that contains the actual image data.
1781
+ * Use this to look up the full image data from the attachments array.
1782
+ * @example "image1.png"
1783
+ */
1784
+ attachmentName: string;
1785
+ /**
1786
+ * Alt text (alternative text) describing the image.
1787
+ * Extracted from image properties in the document.
1788
+ * @example "Company logo"
1789
+ */
1790
+ altText?: string;
1791
+ /**
1792
+ * URL of the image if it is an external link.
1793
+ * Typical for HTML or Markdown images that point to remote servers.
1794
+ * @example "https://example.com/image.png"
1795
+ */
1796
+ url?: string;
1797
+ /** Unique anchor IDs for internal linking. */
1798
+ anchorIds?: string[];
1799
+ /**
1800
+ * Display width of the image (e.g. an editor's custom image node), as a CSS length or percentage.
1801
+ * @example "50%"
1802
+ */
1803
+ width?: string;
1804
+ /**
1805
+ * Layout alignment of the image (e.g. an editor's custom image node).
1806
+ * @example 'center'
1807
+ */
1808
+ align?: "left" | "center" | "right";
1809
+ /** Advisory image title (Markdown `![alt](url "title")`, HTML `<img title>`), if any. */
1810
+ title?: string;
1811
+ }
1812
+ /**
1813
+ * Metadata for an embedded external media node (e.g. a YouTube video).
1814
+ * Markdown has no native syntax for this - see `MarkdownGenerator`'s `embed` case.
1815
+ */
1816
+ export interface EmbedMetadata {
1817
+ /**
1818
+ * The kind of embed. 'youtube' is recognized from a `data-youtube-video` wrapper or a YouTube
1819
+ * iframe; 'iframe' is a generic preserved iframe (opt-in via `HtmlParserConfig.preserveIframes`).
1820
+ */
1821
+ embedType: "youtube" | "iframe";
1822
+ /** The provider-specific video ID (e.g. the 11-character YouTube video ID). Absent for generic iframes. */
1823
+ videoId?: string;
1824
+ /** The original/canonical URL of the embedded media, if known. For a generic iframe, its `src`. */
1825
+ url?: string;
1826
+ /** Display width, as a CSS length or percentage. */
1827
+ width?: string;
1828
+ /** Display height, as a CSS length or percentage. */
1829
+ height?: string;
1830
+ /** Layout alignment of the embed. */
1831
+ align?: "left" | "center" | "right";
1832
+ /** Human-readable label for the embed (e.g. the `[Label]` of a `::youtube[Label]{...}` leaf
1833
+ * directive, or a gated embed's caption). Purely descriptive; never a trust or render input. */
1834
+ label?: string;
1835
+ }
1836
+ /**
1837
+ * Metadata for an admonition/alert node (e.g. GitHub's `> [!NOTE]` or GLFM's `:::note`).
1838
+ * `MarkdownParser` accepts both syntaxes (and generates either, plus Pandoc's `::: {.note}`,
1839
+ * depending on `MdGeneratorConfig.dialect`). Children are block content (paragraphs) wrapped by
1840
+ * the admonition.
1841
+ */
1842
+ export interface AdmonitionMetadata {
1843
+ admonitionType: "note" | "tip" | "important" | "warning" | "caution";
1844
+ /** Optional custom title; falls back to the type label. */
1845
+ title?: string;
1846
+ /** Which concrete input syntax produced this node. Always populated by the parser. */
1847
+ sourceSyntax?: "github" | "gitlab";
1848
+ }
1849
+ /**
1850
+ * Metadata for PDF page nodes.
1851
+ * Indicates which page of the PDF this content came from.
1852
+ */
1853
+ export interface PageMetadata {
1854
+ /**
1855
+ * The page number (1-based) from the PDF document.
1856
+ * @example 1 for the first page, 2 for the second page, etc.
1857
+ */
1858
+ pageNumber: number;
1859
+ }
1860
+ /**
1861
+ * Metadata for text nodes that contain hyperlinks.
1862
+ * Used to track hyperlinks in text runs.
1863
+ */
1864
+ export interface TextMetadata {
1865
+ /** Style name of the text */
1866
+ style?: string;
1867
+ /**
1868
+ * The hyperlink URL (for external links) or anchor reference (for internal links).
1869
+ * @example "https://example.com" or "#_Toc123456"
1870
+ */
1871
+ link?: string;
1872
+ /**
1873
+ * Type of hyperlink.
1874
+ * - 'internal': Link to a bookmark/anchor within the same document
1875
+ * - 'external': Link to an external URL
1876
+ */
1877
+ linkType?: "internal" | "external";
1878
+ /**
1879
+ * When set, this text is an abbreviation and this is its full-form expansion,
1880
+ * rendered as `<abbr title="...">`. Populated from Markdown Extra's
1881
+ * `*[HTML]: Hypertext Markup Language` syntax or an HTML `<abbr>` tag.
1882
+ */
1883
+ abbreviationTitle?: string;
1884
+ /**
1885
+ * When set, this text is a Pandoc/MultiMarkdown-style citation reference
1886
+ * (`[@citekey]`), and this is the bare citekey (e.g. "smith2024"). Bibliography
1887
+ * resolution (author/year display, .bib management) is left to the consuming app.
1888
+ */
1889
+ citationKey?: string;
1890
+ /**
1891
+ * True when this is an Obsidian-style wikilink (`[[page]]` / `[[page|alias]]`).
1892
+ * `link` holds the bare page name and `linkType` is always 'internal'; the
1893
+ * per-workspace enable/disable toggle lives in markdownwriter, not here -
1894
+ * officeParser always parses/generates the syntax.
1895
+ */
1896
+ wikilink?: boolean;
1897
+ /** Advisory link title (Markdown `[text](url "title")`, HTML `<a title>`), if any. */
1898
+ title?: string;
1899
+ }
1900
+ /**
1901
+ * Metadata for note nodes (footnotes/endnotes).
1902
+ * Used in ODT and DOCX files to track notes.
1903
+ */
1904
+ export interface NoteMetadata {
1905
+ /**
1906
+ * Type of note: 'footnote' or 'endnote'.
1907
+ */
1908
+ noteType?: "footnote" | "endnote";
1909
+ /**
1910
+ * The unique ID of the note from the source document.
1911
+ * @example "1", "2"
1912
+ */
1913
+ noteId?: string;
1914
+ /** Unique anchor IDs for internal linking. */
1915
+ anchorIds?: string[];
1916
+ /** The slide number this note is associated with (used in PowerPoint). */
1917
+ slideNumber?: number;
1918
+ /**
1919
+ * True for a footnote/endnote definition that no reference points at (an "orphan").
1920
+ * The Markdown parser sets this when it recovers a `[^id]: ...` definition with no matching
1921
+ * `[^id]` reference so the definition is preserved rather than dropped. Generators route such
1922
+ * notes into their footnotes section without a citation marker, and the HTML generator omits
1923
+ * the (otherwise dangling) back-link.
1924
+ */
1925
+ unreferenced?: boolean;
1926
+ }
1927
+ /**
1928
+ * Metadata for break nodes.
1929
+ * Used in DOCX files to track line and page breaks.
1930
+ */
1931
+ export interface BreakMetadata {
1932
+ /**
1933
+ * Type of break. The break type determines the next location where
1934
+ * text shall be placed.
1935
+ * - 'column': The next text will be placed in the next column.
1936
+ * - 'page': The next text will be placed on the next page.
1937
+ * - 'lastRenderedPage': The editing application has inserted a soft break on the last save.
1938
+ * - 'textWrapping' (default, assumed when not specified): The next text will be placed on the next line.
1939
+ * - 'carriageReturn': An explicit carriage return (w:cr) equivalent to a hard line break.
1940
+ * - 'thematic': A thematic break (Markdown `---`/`***`/`___`, HTML `<hr>`) - a horizontal
1941
+ * rule separating sections, distinct from a page break. Emitted as `---` in Markdown and
1942
+ * `<hr>` in HTML.
1943
+ */
1944
+ breakType: "column" | "page" | "lastRenderedPage" | "textWrapping" | "carriageReturn" | "thematic";
1945
+ /**
1946
+ * Specifies the location which shall be used as the next available line when breakType
1947
+ * has a value of 'textWrapping'. Should be ignored for other break types.
1948
+ * - 'all': text wrapping break shall advance the text to the next line which spans the full width of the line
1949
+ * - 'left': text wrapping break shall restart in next text region unblocked on the left
1950
+ * - 'none': text wrapping break shall advance the text to the next line regardless of any floating objects
1951
+ * - 'right': text wrapping break shall restart in next text region unblocked on the right
1952
+ */
1953
+ clear?: "all" | "left" | "none" | "right";
1954
+ }
1955
+ /**
1956
+ * Metadata for a code block.
1957
+ */
1958
+ export interface CodeMetadata {
1959
+ /** The programming language of the code block (e.g., 'typescript', 'python') */
1960
+ language?: string;
1961
+ /** Unique anchor IDs for internal linking. */
1962
+ anchorIds?: string[];
1963
+ /**
1964
+ * When set, this node is a LaTeX math expression rather than a code block. `node.text`
1965
+ * holds the bare LaTeX (delimiters excluded); 'inline' round-trips as `$...$`,
1966
+ * 'block' as `$$...$$`. Matches attribute-driven editors' math nodes.
1967
+ */
1968
+ math?: "inline" | "block";
1969
+ }
1970
+ /**
1971
+ * Metadata for a comment/annotation.
1972
+ */
1973
+ export interface CommentMetadata {
1974
+ author?: string;
1975
+ initials?: string;
1976
+ date?: string;
1977
+ commentId?: string;
1978
+ }
1979
+ /**
1980
+ * Metadata for a header or footer.
1981
+ */
1982
+ export interface HeaderFooterMetadata {
1983
+ type: "default" | "first" | "even" | string;
1984
+ }
1985
+ /**
1986
+ * Union type for content metadata.
1987
+ */
1988
+ export type ContentMetadata = SlideMetadata | SheetMetadata | HeadingMetadata | ListMetadata | CellMetadata | ImageMetadata | ChartMetadata | PageMetadata | ParagraphMetadata | TextMetadata | NoteMetadata | BreakMetadata | CodeMetadata | CommentMetadata | HeaderFooterMetadata | TableMetadata | EmbedMetadata | AdmonitionMetadata | undefined;
1989
+ /**
1990
+ * Represents a node in the document content tree.
1991
+ * This is the core building block of the parsed document structure.
1992
+ * Content nodes can be nested to represent hierarchical document structures
1993
+ * (e.g., paragraphs containing text runs, tables containing rows, rows containing cells).
1994
+ *
1995
+ * @example
1996
+ * // A simple paragraph with formatted text
1997
+ * {
1998
+ * type: 'paragraph',
1999
+ * text: 'Hello world',
2000
+ * children: [
2001
+ * { type: 'text', text: 'Hello ', formatting: { bold: true } },
2002
+ * { type: 'text', text: 'world', formatting: { italic: true } }
2003
+ * ]
2004
+ * }
2005
+ *
2006
+ * @example
2007
+ * // A heading with metadata
2008
+ * {
2009
+ * type: 'heading',
2010
+ * text: 'Chapter 1',
2011
+ * metadata: { level: 1 },
2012
+ * children: [...]
2013
+ * }
2014
+ */
2015
+ /**
2016
+ * Shared properties available on all document content nodes.
2017
+ */
2018
+ export interface BaseContentNode {
2019
+ /**
2020
+ * The complete text content of the node and all its children combined.
2021
+ * For container nodes (paragraph, heading), this is the concatenation of all child text.
2022
+ * For leaf nodes (text), this is the actual text content.
2023
+ * @example "Hello world" for a paragraph containing "Hello " and "world"
2024
+ */
2025
+ text?: string;
2026
+ /**
2027
+ * Child nodes that make up this node's content.
2028
+ * Used for hierarchical structures:
2029
+ * - Paragraphs contain text runs with different formatting
2030
+ * - Tables contain rows
2031
+ * - Rows contain cells
2032
+ * - Cells contain paragraphs
2033
+ * @example [{ type: 'text', text: 'Hello', formatting: { bold: true } }]
2034
+ */
2035
+ children?: OfficeContentNode[];
2036
+ /**
2037
+ * Comments attached to this specific node.
2038
+ * Keeps annotations completely separate from the actual content flow.
2039
+ */
2040
+ comments?: OfficeContentNode[];
2041
+ /**
2042
+ * Notes (like footnotes or slide notes) attached to this specific node.
2043
+ * Keeps notes separate from the actual structural children.
2044
+ */
2045
+ notes?: OfficeContentNode[];
2046
+ /**
2047
+ * Text formatting applied to this node.
2048
+ * Only applicable to text-containing nodes.
2049
+ * For container nodes like paragraphs, formatting typically appears on child text nodes.
2050
+ * @example { bold: true, size: "12", font: "Arial" }
2051
+ */
2052
+ formatting?: TextFormatting;
2053
+ /**
2054
+ * The raw source content for this node.
2055
+ * - For XML-based formats (DOCX, XLSX, PPTX): contains the raw XML
2056
+ * - For RTF: contains the raw RTF markup
2057
+ * - For PDF: typically not available
2058
+ * Only populated when `config.includeRawContent` is true.
2059
+ * Useful for debugging or when you need access to format-specific features.
2060
+ * @example "<w:p><w:r><w:t>Hello</w:t></w:r></w:p>" for DOCX
2061
+ */
2062
+ rawContent?: string;
2063
+ /**
2064
+ * Source HTML attributes that no typed metadata field consumed, preserved for round-trip
2065
+ * fidelity (e.g. a `data-*` attribute an editor round-trips through officeParser).
2066
+ *
2067
+ * Only populated by the HTML/XHTML parser, only for elements it recognises, and only when
2068
+ * `htmlParserConfig.preserveAttributes` is enabled - so by default this is always absent.
2069
+ *
2070
+ * Sanitized on both legs, since an AST can also be constructed programmatically rather than
2071
+ * parsed: event handlers (`on*`) and `srcdoc` are never carried, URL-bearing attributes go
2072
+ * through the same URL sanitizer as typed fields, and every value is escaped on output. A
2073
+ * typed field always wins over a same-named entry here.
2074
+ *
2075
+ * Ignored by the non-HTML generators (Markdown, RTF, CSV, text, chunking) by design - these
2076
+ * are HTML attributes and have no meaning in those targets.
2077
+ * @example { 'data-tracking-id': 'abc123', 'class': 'lead' }
2078
+ */
2079
+ htmlAttributes?: Record<string, string>;
2080
+ }
2081
+ /**
2082
+ * Represents a node in the document content tree.
2083
+ * This is the core building block of the parsed document structure.
2084
+ * Content nodes can be nested to represent hierarchical document structures
2085
+ * (e.g., paragraphs containing text runs, tables containing rows, rows containing cells).
2086
+ *
2087
+ * @example
2088
+ * // A simple paragraph with formatted text
2089
+ * {
2090
+ * type: 'paragraph',
2091
+ * text: 'Hello world',
2092
+ * children: [
2093
+ * { type: 'text', text: 'Hello ', formatting: { bold: true } },
2094
+ * { type: 'text', text: 'world', formatting: { italic: true } }
2095
+ * ]
2096
+ * }
2097
+ *
2098
+ * @example
2099
+ * // A heading with metadata
2100
+ * {
2101
+ * type: 'heading',
2102
+ * text: 'Chapter 1',
2103
+ * metadata: { level: 1 },
2104
+ * children: [...]
2105
+ * }
2106
+ */
2107
+ export type OfficeContentNode = BaseContentNode & ({
2108
+ type: "slide";
2109
+ metadata?: SlideMetadata;
2110
+ } | {
2111
+ type: "sheet";
2112
+ metadata?: SheetMetadata;
2113
+ } | {
2114
+ type: "heading";
2115
+ metadata?: HeadingMetadata;
2116
+ } | {
2117
+ type: "list";
2118
+ metadata?: ListMetadata;
2119
+ } | {
2120
+ type: "cell";
2121
+ metadata?: CellMetadata;
2122
+ } | {
2123
+ type: "image";
2124
+ metadata?: ImageMetadata;
2125
+ } | {
2126
+ type: "chart";
2127
+ metadata?: ChartMetadata;
2128
+ } | {
2129
+ type: "page";
2130
+ metadata?: PageMetadata;
2131
+ } | {
2132
+ type: "paragraph";
2133
+ metadata?: ParagraphMetadata;
2134
+ } | {
2135
+ type: "text";
2136
+ metadata?: TextMetadata;
2137
+ } | {
2138
+ type: "note";
2139
+ metadata?: NoteMetadata;
2140
+ } | {
2141
+ type: "break";
2142
+ metadata?: BreakMetadata;
2143
+ } | {
2144
+ type: "code";
2145
+ metadata?: CodeMetadata;
2146
+ } | {
2147
+ type: "comment";
2148
+ metadata?: CommentMetadata;
2149
+ } | {
2150
+ type: "header";
2151
+ metadata?: HeaderFooterMetadata;
2152
+ } | {
2153
+ type: "footer";
2154
+ metadata?: HeaderFooterMetadata;
2155
+ } | {
2156
+ type: "table";
2157
+ metadata?: TableMetadata;
2158
+ } | {
2159
+ type: "row";
2160
+ metadata?: undefined;
2161
+ } | {
2162
+ type: "drawing";
2163
+ metadata?: undefined;
2164
+ } | {
2165
+ type: "slideMaster";
2166
+ metadata?: SlideMetadata;
2167
+ } | {
2168
+ type: "embed";
2169
+ metadata?: EmbedMetadata;
2170
+ } | {
2171
+ type: "admonition";
2172
+ metadata?: AdmonitionMetadata;
2173
+ } | {
2174
+ type: "definitionList";
2175
+ metadata?: undefined;
2176
+ } | {
2177
+ type: "definitionTerm";
2178
+ metadata?: undefined;
2179
+ } | {
2180
+ type: "definitionDescription";
2181
+ metadata?: undefined;
2182
+ });
2183
+ /**
2184
+ * Structured information extracted from a chart.
2185
+ */
2186
+ export interface ChartData {
2187
+ /** Chart title (if any) */
2188
+ title?: string;
2189
+ /** X-axis title (for continuous or categorical axes) */
2190
+ xAxisTitle?: string;
2191
+ /** Y-axis title (for value or continuous axes) */
2192
+ yAxisTitle?: string;
2193
+ /**
2194
+ * Collections of data points.
2195
+ * For bar/line charts, each dataset is one 'line' or group of bars.
2196
+ * For pie charts, there is typically only one dataset.
2197
+ */
2198
+ dataSets: {
2199
+ /** Name of this data group (e.g., 'Sales 2023') */
2200
+ name?: string;
2201
+ /** Actual numeric or string values for this group */
2202
+ values: string[];
2203
+ /** Specific labels for each point in this dataset (if defined per point) */
2204
+ pointLabels: string[];
2205
+ }[];
2206
+ /**
2207
+ * Labels for the chart facets (e.g., 'Jan', 'Feb', 'Mar' on X-axis).
2208
+ * These typically correspond to the data points in each dataSet.
2209
+ */
2210
+ labels: string[];
2211
+ /** Every text node discovered in the chart XML (for keyword search/raw extraction) */
2212
+ rawTexts: string[];
2213
+ }
2214
+ /**
2215
+ * Represents an attachment extracted from the document (image, chart, etc.).
2216
+ * Attachments are binary resources embedded in the document.
2217
+ * Only populated when `config.extractAttachments` is true.
2218
+ *
2219
+ * @example
2220
+ * ```typescript
2221
+ * {
2222
+ * type: 'image',
2223
+ * mimeType: 'image/png',
2224
+ * data: 'iVBORw0KGgoAAAANSUhEUgAA...', // Base64
2225
+ * name: 'chart1.png',
2226
+ * extension: 'png',
2227
+ * ocrText: 'Sales Chart Q4 2024' // If OCR was enabled
2228
+ * }
2229
+ * ```
2230
+ */
2231
+ export interface OfficeAttachment {
2232
+ /**
2233
+ * The category of the attachment.
2234
+ * Helps identify what kind of content this represents.
2235
+ * @example 'image' for photos and diagrams, 'chart' for embedded charts
2236
+ */
2237
+ type: "image" | "chart";
2238
+ /**
2239
+ * The MIME type of the attachment data.
2240
+ * Indicates the file format and how the data should be interpreted.
2241
+ * @example 'image/png', 'image/jpeg', 'image/svg+xml'
2242
+ */
2243
+ mimeType: OfficeMimeType;
2244
+ /**
2245
+ * The attachment content encoded as Base64.
2246
+ * This is the actual binary data of the image/chart/etc. encoded for text transmission.
2247
+ * Can be used directly in HTML img tags with data URIs or decoded to binary.
2248
+ * @example "iVBORw0KGgoAAAANSUhEUgAA..." (truncated)
2249
+ */
2250
+ data: string;
2251
+ /**
2252
+ * A unique name for this attachment file.
2253
+ * May be derived from the source file or auto-generated.
2254
+ * Used to link `ImageMetadata` nodes to their corresponding attachments.
2255
+ * @example "image1.png", "chart2.emf", "picture3.jpg"
2256
+ */
2257
+ name: string;
2258
+ /**
2259
+ * The file extension (without the dot).
2260
+ * Derived from the MIME type or original filename.
2261
+ * @example "png", "jpg", "svg"
2262
+ */
2263
+ extension: string;
2264
+ /**
2265
+ * Text extracted from the image using Optical Character Recognition (OCR).
2266
+ * Only present when:
2267
+ * - `config.ocr` is true
2268
+ * - `config.extractAttachments` is true
2269
+ * - The attachment is an image containing text
2270
+ * Uses Tesseract.js with the language specified in `config.ocrLanguage`.
2271
+ * @example "Annual Revenue: $1.2M"
2272
+ */
2273
+ ocrText?: string;
2274
+ /**
2275
+ * Alt text or description associated with the image in the document.
2276
+ * Extracted from the document markup (e.g., wp:docPr descr attribute in DOCX).
2277
+ * @example "A chart showing sales growth"
2278
+ */
2279
+ altText?: string;
2280
+ /**
2281
+ * Structured data extracted from a chart attachment.
2282
+ * Only present if the attachment is a chart and data extraction was successful.
2283
+ * Contains series names, values, labels, and titles.
2284
+ * @example { title: "Sales Chart", series: [...], categories: [...] }
2285
+ */
2286
+ chartData?: ChartData;
2287
+ }
2288
+ /**
2289
+ * Metadata for the parsed file.
2290
+ */
2291
+ export interface OfficeMetadata {
2292
+ /** The title of the document. */
2293
+ title?: string;
2294
+ /** The author of the document. */
2295
+ author?: string;
2296
+ /** User who last modified the document. */
2297
+ lastModifiedBy?: string;
2298
+ /** Creation date. */
2299
+ created?: Date;
2300
+ /** Last modification date. */
2301
+ modified?: Date;
2302
+ /** Description/Comments. */
2303
+ description?: string;
2304
+ /** Subject/Topic. */
2305
+ subject?: string;
2306
+ /** Number of pages (if available). */
2307
+ pages?: number;
2308
+ /** Document-wide default formatting settings (font, size, color). */
2309
+ formatting?: Partial<TextFormatting>;
2310
+ /** Style map for styles in the document. */
2311
+ styleMap?: Record<string, Partial<TextFormatting>>;
2312
+ /**
2313
+ * User-defined custom properties embedded in the document.
2314
+ * Sources by format:
2315
+ * - DOCX/XLSX/PPTX: `docProps/custom.xml` (Office custom document properties)
2316
+ * - ODT/ODP/ODS: `meta:user-defined` elements in `meta.xml`
2317
+ * - PDF: non-standard entries in the PDF Info dictionary
2318
+ * RTF does not support custom properties; the `\info` group is not extracted.
2319
+ * Values are typed as string, number, boolean, or Date where the source format provides type information.
2320
+ */
2321
+ customProperties?: Record<string, string | number | boolean | Date>;
2322
+ /** Keywords associated with the document. */
2323
+ keywords?: string;
2324
+ /**
2325
+ * Contains all format-specific metadata fields extracted verbatim.
2326
+ * Consumers can use this to access properties not mapped to the standard OfficeMetadata fields.
2327
+ * Examples: all <meta> tags in HTML, app.xml properties in DOCX, XMP dicts in PDF.
2328
+ */
2329
+ nativeProperties?: Record<string, any>;
2330
+ }
2331
+ /**
2332
+ * Contains out-of-band layout elements and templates that are not part of the main document flow.
2333
+ */
2334
+ export interface OfficeAuxiliaryContent {
2335
+ /** Headers extracted from the document. */
2336
+ headers?: OfficeContentNode[];
2337
+ /** Footers extracted from the document. */
2338
+ footers?: OfficeContentNode[];
2339
+ /** Slide Masters extracted from presentations. */
2340
+ slideMasters?: OfficeContentNode[];
2341
+ }
2342
+ /**
2343
+ * The Root Abstract Syntax Tree (AST) representing a parsed Office Document.
2344
+ * This is the ultimate output of `OfficeParser.parseOffice()`.
2345
+ *
2346
+ * DESIGN PHILOSOPHY:
2347
+ * The AST is designed to be a universal, format-agnostic representation of document content.
2348
+ * Whether the input was a PDF, DOCX, XLSX, Markdown, or HTML file, the resulting AST
2349
+ * uses the same consistent structure (`OfficeContentNode` trees).
2350
+ *
2351
+ * ### Key Top-Level Properties:
2352
+ * - `metadata`: Document-level properties (author, title, stats).
2353
+ * - `content`: The main sequential flow of the document (paragraphs, tables, slides, sheets).
2354
+ * - `attachments`: Extracted binary assets (images, embedded files).
2355
+ * - `auxiliary`: Out-of-band layout/template elements (headers, footers, slide masters).
2356
+ *
2357
+ * @example
2358
+ * ```typescript
2359
+ * const ast = await OfficeParser.parseOffice('document.docx', {
2360
+ * extractAttachments: true,
2361
+ * includeRawContent: false
2362
+ * });
2363
+ *
2364
+ * console.log(ast.type); // 'docx'
2365
+ * console.log(ast.metadata.author); // 'John Doe'
2366
+ * console.log(ast.content.length); // Number of top-level content nodes
2367
+ * console.log(ast.toText()); // Plain text representation
2368
+ * console.log((await ast.to('md')).value); // Markdown representation
2369
+ * console.log((await ast.to('html')).value); // HTML representation
2370
+ * console.log((await ast.to('rtf')).value); // RTF representation
2371
+ * console.log((await ast.to('csv')).value); // CSV representation
2372
+ * console.log((await ast.to('chunks')).value); // Chunks representation
2373
+ * ```
2374
+ */
2375
+ export interface OfficeParserAST {
2376
+ /**
2377
+ * The original configuration used to parse this document.
2378
+ * This includes options like OCR settings, delimiter choices, and filtering flags.
2379
+ */
2380
+ config: OfficeParserConfig;
2381
+ /**
2382
+ * The type of the parsed file.
2383
+ * Indicates which parser was used and what format the input was in.
2384
+ * @example 'docx', 'xlsx', 'pptx', 'rtf', 'pdf', 'odt', 'odp', 'ods'
2385
+ */
2386
+ type: SupportedFileType;
2387
+ /**
2388
+ * Document metadata extracted from the file properties.
2389
+ * Includes information like author, title, creation date, etc.
2390
+ * Availability depends on the file format and whether metadata was present in the source.
2391
+ * @example { author: 'John Smith', title: 'Annual Report', created: new Date('2024-01-01') }
2392
+ */
2393
+ metadata: OfficeMetadata;
2394
+ /**
2395
+ * The hierarchical content structure of the document.
2396
+ * This is an array of top-level content nodes. Each node can have children, creating a tree.
2397
+ * For different file types:
2398
+ * - DOCX: Array of paragraphs, headings, tables, etc.
2399
+ * - XLSX: Array of sheets, each containing rows
2400
+ * - PPTX: Array of slides, each containing content nodes
2401
+ * - PDF: Array of pages, each containing paragraphs
2402
+ * @example [{ type: 'paragraph', text: 'Hello' }, { type: 'heading', text: 'Chapter 1' }]
2403
+ */
2404
+ content: OfficeContentNode[];
2405
+ /**
2406
+ * Out-of-band layout and template elements that are not part of the main text flow.
2407
+ * Extracted only if the respective `ignore...` config flags are false.
2408
+ * Contains elements like `headers`, `footers`, and `slideMasters`.
2409
+ */
2410
+ auxiliary?: OfficeAuxiliaryContent;
2411
+ /**
2412
+ * Attachments extracted from the document (images, charts, embedded files).
2413
+ * Only populated when `config.extractAttachments` is true.
2414
+ * Each attachment includes:
2415
+ * - Base64-encoded data
2416
+ * - MIME type
2417
+ * - Optional OCR text (if `config.ocr` is true)
2418
+ * @example [{ type: 'image', mimeType: 'image/png', data: 'base64...', name: 'image1.png' }]
2419
+ */
2420
+ attachments: OfficeAttachment[];
2421
+ /** Any warnings or non-fatal issues encountered during parsing. */
2422
+ warnings: OfficeIssue[];
2423
+ /**
2424
+ * @deprecated Use `.to('text')` instead. This method is the older renderer and takes no
2425
+ * configuration; `.to('text')` produces the same content and lets you configure the rest.
2426
+ *
2427
+ * Converts the entire AST to plain text, flattening the document structure and stripping all
2428
+ * formatting, metadata, and structure. Text is joined using `config.newlineDelimiter`
2429
+ * (default: `'\n'`).
2430
+ *
2431
+ * **Migrating.** `.to('text')` is asynchronous and configurable. At its defaults it emits
2432
+ * everything this method emits, verified across every bundled fixture in all 12 supported
2433
+ * formats in both layout modes: no word produced here is missing there. It also renders merged
2434
+ * table cells correctly, where this method glues them (`OneThree` vs `One Three`).
2435
+ *
2436
+ * Where the two differ is configuration, not capability. Notes and image placeholders are
2437
+ * emitted by default but are switchable; this method emits neither and offers no way to ask
2438
+ * for them. Layout is likewise a knob rather than a fixed behavior:
2439
+ *
2440
+ * ```typescript
2441
+ * // Default: aligned table grids, list markers, notes, image placeholders.
2442
+ * const { value } = await ast.to('text');
2443
+ *
2444
+ * // Deliberate opt-out - closest to this method's shape.
2445
+ * const { value } = await ast.to('text', {
2446
+ * includeImages: false,
2447
+ * textConfig: { preserveLayout: false, renderNotes: false },
2448
+ * });
2449
+ * ```
2450
+ *
2451
+ * Spreadsheets (CSV/ODS/XLSX) are unaffected by `preserveLayout`, since it governs
2452
+ * `table`/`list` nodes rather than `sheet`/`row`/`cell`; there the default aligned grid is the
2453
+ * most faithful rendering.
2454
+ *
2455
+ * @returns A plain text representation of the document
2456
+ * @example
2457
+ * ```typescript
2458
+ * const text = ast.toText();
2459
+ * console.log(text); // "Hello world\nChapter 1\n..."
2460
+ * ```
2461
+ */
2462
+ toText(): string;
2463
+ /**
2464
+ * Converts this AST to the specified destination format.
2465
+ * This is the recommended way to convert the AST to different formats.
2466
+ *
2467
+ * @param destination The target format (e.g., 'text', 'md', 'html', 'pdf').
2468
+ * @param config Optional configuration for the generator.
2469
+ * @returns A promise resolving to the generated content (string or Buffer).
2470
+ * @example
2471
+ * ```typescript
2472
+ * const html = await ast.to('html', { includeFormatting: false });
2473
+ * const md = await ast.to('md');
2474
+ * ```
2475
+ */
2476
+ to<T extends this, D extends SupportedDestination<T["type"]>>(this: T, destination: D, config?: GeneratorConfig<D>): Promise<ConversionResult<D>>;
2477
+ }
2478
+ /**
2479
+ * Main parser class providing office document parsing functionality.
2480
+ *
2481
+ * This class contains a single static method `parseOffice` that serves as the
2482
+ * universal entry point for parsing any supported office document format.
2483
+ */
2484
+ export declare class OfficeParser {
2485
+ /**
2486
+ * Parses an office document and returns a structured AST.
2487
+ *
2488
+ * This method:
2489
+ * 1. Accepts a file path, Buffer, or ArrayBuffer
2490
+ * 2. Detects the file type (from extension or content)
2491
+ * 3. Routes to the appropriate format-specific parser
2492
+ * 4. Returns a unified AST structure
2493
+ *
2494
+ * **File Type Detection:**
2495
+ * - If a file path is provided, uses the file extension
2496
+ * - If a Buffer is provided, uses magic bytes detection (file-type library)
2497
+ *
2498
+ * **Supported Formats and Routes:**
2499
+ * - `.docx` → WordParser (OOXML)
2500
+ * - `.xlsx` → ExcelParser (OOXML)
2501
+ * - `.pptx` → PowerPointParser (OOXML)
2502
+ * - `.odt`, `.odp`, `.ods` → OpenOfficeParser (ODF)
2503
+ * - `.pdf` → PdfParser (PDF.js)
2504
+ * - `.rtf` → RtfParser (custom RTF parser)
2505
+ * - `.csv` → CsvParser
2506
+ * - `.md` → MarkdownParser
2507
+ * - `.html` → HtmlParser
2508
+ * - `.epub` → EpubParser
2509
+ *
2510
+ * @param file - File path (string), Buffer, or ArrayBuffer containing the document
2511
+ * @param config - Optional configuration object (defaults applied for all omitted options)
2512
+ * @returns A promise resolving to the parsed OfficeParserAST
2513
+ * @throws {Error} If file doesn't exist, format is unsupported, or parsing fails
2514
+ *
2515
+ * @example
2516
+ * ```typescript
2517
+ * // Parse a DOCX file
2518
+ * const ast = await OfficeParser.parseOffice('report.docx', {
2519
+ * extractAttachments: true,
2520
+ * includeRawContent: false
2521
+ * });
2522
+ *
2523
+ * // Parse a Buffer with OCR enabled
2524
+ * const buffer = await retrieveData('document.pdf').then(r => r.arrayBuffer());
2525
+ * const ast = await OfficeParser.parseOffice(buffer, {
2526
+ * ocr: true,
2527
+ * ocrLanguage: 'eng+fra'
2528
+ * });
2529
+ *
2530
+ * // Extract text
2531
+ * const text = ast.toText();
2532
+ * ```
2533
+ */
2534
+ static parseOffice(file: string | Buffer | ArrayBuffer | Uint8Array | BlobLike, configOrCallback?: OfficeParserConfig | ((ast: OfficeParserAST, err?: any) => void), config?: OfficeParserConfig): Promise<OfficeParserAST>;
2535
+ /**
2536
+ * Terminates all active OCR workers and cleans up resources.
2537
+ *
2538
+ * This should be called when the application is shutting down or when OCR
2539
+ * is no longer needed to prevent memory leaks and orphaned worker processes.
2540
+ *
2541
+ * @returns A promise that resolves when all workers have been terminated
2542
+ */
2543
+ static terminateOcr(): Promise<void>;
2544
+ }
2545
+ /**
2546
+ * Main generator class providing document conversion functionality.
2547
+ */
2548
+ export declare class OfficeGenerator {
2549
+ /**
2550
+ * Normalizes format aliases (e.g., 'txt' to 'text', 'markdown' to 'md') to standard internal formats.
2551
+ */
2552
+ static normalizeDestination(dest: string): UniversalGeneratorFormat;
2553
+ /**
2554
+ * Generates a file of the specified type from an AST.
2555
+ * This is the single source of truth for generation logic.
2556
+ *
2557
+ * @param ast - The OfficeParserAST to generate from
2558
+ * @param destination - The target format (e.g., 'text', 'md', 'html', 'pdf')
2559
+ * @param config - Optional configuration for the generator
2560
+ * @returns A promise resolving to the ConversionResult containing the value and messages
2561
+ * @throws {Error} If the destination format is unsupported
2562
+ */
2563
+ static generate<T extends SupportedFileType, D extends SupportedDestination<T>>(ast: OfficeParserAST & {
2564
+ type: T;
2565
+ }, destination: D, config?: GeneratorConfig<D>): Promise<ConversionResult<D>>;
2566
+ }
2567
+ /**
2568
+ * Utility type to infer the file type from a file path string literal.
2569
+ */
2570
+ export type InferFileTypeFromPath<T> = T extends `${string}.${infer E}` ? (Lowercase<E> extends SupportedFileType ? Lowercase<E> : SupportedFileType) : SupportedFileType;
2571
+ /**
2572
+ * Main converter class providing a streamlined one-step API for document conversion.
2573
+ *
2574
+ * This class coordinates the `OfficeParser` and `OfficeGenerator` to transform
2575
+ * documents from one format to another (e.g., DOCX to Markdown, PDF to HTML).
2576
+ */
2577
+ export declare class OfficeConverter {
2578
+ /**
2579
+ * Converts an office document from its source format to a specified destination format.
2580
+ *
2581
+ * This method:
2582
+ * 1. Detects the source file type and parses it into a unified AST using `OfficeParser`.
2583
+ * 2. Automatically configures the parser based on the generator requirements (e.g., enabling
2584
+ * attachment extraction if images are requested in the output).
2585
+ * 3. Generates the destination document from the AST using `OfficeGenerator`.
2586
+ *
2587
+ * @template F The inferred type of the input file (path string or buffer).
2588
+ * @template T The authoritative source file type (inferred from path or config).
2589
+ *
2590
+ * @param file - File path (string), Buffer, or ArrayBuffer containing the source document.
2591
+ * @param destination - The target format (e.g., 'md', 'html', 'pdf', 'text', 'chunks').
2592
+ * @param config - Optional unified configuration for both the parser and generator phases.
2593
+ *
2594
+ * @returns A promise resolving to the ConversionResult containing the value and messages.
2595
+ * @throws {Error} If the source format is unsupported or parsing/generation fails.
2596
+ *
2597
+ * @example
2598
+ * ```typescript
2599
+ * // Convert Word to Markdown with a single call
2600
+ * const { value: markdown } = await OfficeConverter.convert('report.docx', 'md');
2601
+ *
2602
+ * // Convert PDF to HTML (Note: OCR is disabled in this one-step API)
2603
+ * const { value: html } = await OfficeConverter.convert(buffer, 'html', {
2604
+ * generatorConfig: {
2605
+ * includeImages: true
2606
+ * }
2607
+ * });
2608
+ * ```
2609
+ */
2610
+ static convert<F extends string | Buffer | ArrayBuffer | Uint8Array | BlobLike, T extends SupportedFileType = InferFileTypeFromPath<F>, D extends SupportedDestination<T> = SupportedDestination<T>>(file: F, destination: D, config?: OfficeConverterConfig<D, T>): Promise<ConversionResult<D>>;
2611
+ }
2612
+ export declare const parseOffice: typeof OfficeParser.parseOffice;
2613
+ export declare const terminateOcr: typeof OfficeParser.terminateOcr;
2614
+ export declare const convert: typeof OfficeConverter.convert;
2615
+ export declare const generate: typeof OfficeGenerator.generate;
2616
+
2617
+ export {
2618
+ OfficeParser as default,
2619
+ };
2620
+
2621
+ export {};