").strip() == "# Smoke"; print("Distribution and import OK")'
- name: Test structured documents and PDF layout
run: python -m unittest discover -s crates/markkit-python/tests -p 'test_*.py'
+ - name: Verify type stubs ship in the wheel
+ run: python -c 'import pathlib, markkit; d = pathlib.Path(markkit.__file__).parent; assert (d / "__init__.pyi").is_file() and (d / "py.typed").is_file(), "markkit.pyi/py.typed missing from wheel"'
+ - name: Run Python examples
+ run: for ex in examples/python/*.py; do echo "── $ex"; python "$ex"; done
diff --git a/CHANGELOG.md b/CHANGELOG.md
index caf37f7..b3b784d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,10 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+
+- Runnable examples for every surface, run in CI: Rust `documents`, `convert`
+ (DOCX/XLSX/PDF or your own files), `main_content` and `limits`; Python
+ `examples/python/`, Node.js `examples/node/` and WASM `examples/wasm/`,
+ sharing sample files in `examples/data/`. Index: `examples/README.md`.
+- Python type stubs: the wheel ships `markkit/__init__.pyi` and `py.typed`, with
+ typed `Limits` and `Extraction` results; PyPI metadata gains classifiers,
+ `requires-python` and project URLs.
+- `docs/pdf.md`: PDF text, tables, layout geometry, OCR and limits in one guide.
+
### Changed
-- Rewrote the PyPI README (formats, document dict, async, limits, links) and added
- PyPI project links, keywords and classifiers.
+- Docs overhaul: rewritten root, PyPI, npm and WASM READMEs (API tables,
+ result fields, options, limits, errors); getting-started guide rewritten.
+ Rust snippets in the README and guides are now compiled as doctests.
+- docs.rs builds with every format, `http_client`, `tool` and `json-schema`
+ enabled and shows feature badges; crate docs cover configuration, limits,
+ the IR pipeline and features. Node.js `index.d.ts` documents every option and
+ result field.
- Releases now publish PyPI and npm (native + WASM) together with crates.io.
### Fixed
diff --git a/README.md b/README.md
index 2630593..d398370 100644
--- a/README.md
+++ b/README.md
@@ -6,336 +6,283 @@
[](https://docs.rs/markkit)
[](https://pypi.org/project/markkit/)
[](https://www.npmjs.com/package/@everruns/markkit)
+[](https://www.npmjs.com/package/@everruns/markkit-wasm)
[](https://github.com/everruns/markkit/blob/main/AGENTS.md)
-Extract clean markdown from any format. Written in Rust.
-
-Markkit converts HTML, Word documents and spreadsheets into well-structured
-markdown, built for feeding untrusted documents to LLMs and agents. It ships as
-a Rust library, a CLI, native bindings for Python and Node.js, and a WebAssembly
-package for browsers and edge runtimes.
-
-## Features
-
-- **HTML** – Web pages and HTML documents; nav, header, footer, scripts, styles and forms stripped by default
-- **DOCX** – Headings, lists, tables, links, emphasis
-- **PPTX** – One section per slide: titles, bullets, tables, links, speaker notes
-- **ODT** – OpenDocument text: headings, lists, tables, links, emphasis
-- **EPUB** – E-book chapters in reading order, title from the package metadata
-- **Spreadsheets** – XLSX/XLSM, XLSB, XLS and ODS workbooks to markdown tables, one section per sheet
-- **Email (EML)** – Subject, sender, recipients, date, body (plain preferred, HTML converted), attachment list
-- **Jupyter notebooks** – Markdown cells, code cells with language, text outputs and tracebacks
-- **CSV / TSV** – One markdown table; `;` and `|` delimiters detected, RFC 4180 quoting
-- **Plain text / Markdown** – Text to paragraphs; Markdown normalized through the same IR (raw HTML never passed through)
-- **Format detection** – Content type, then file extension, then magic bytes
-- **URL fetching** – Fetch and extract in one call (`http_client` feature)
-- **Configurable** – CSS include/exclude selectors, link/image preservation, resource limits
-- **Safe by default** – No code execution (scripts, macros, formulas), bounded decompression,
- depth and size limits, [threat model](knowledge/security/threat-model.md) with a test per mitigation
-- **PDF** – Text/layout, columns and tables; optional native OCR (encrypted PDFs rejected)
-
-| Format | Status | Feature |
-|---|---|---|
-| HTML / XHTML | Supported | `html` (default) |
-| DOCX | Supported | `docx` |
-| PPTX, PPTM, PPSX | Supported | `pptx` |
-| ODT | Supported | `odt` |
-| EPUB | Supported | `epub` |
-| XLSX, XLSM, XLSB, XLS, ODS | Supported | `spreadsheet` |
-| Plain text | Supported | always on |
-| CSV, TSV | Supported | always on |
-| Jupyter notebooks (ipynb) | Supported | always on |
-| Email (EML) | Supported | `email` |
-| Markdown | Supported | `markdown` |
-| PDF (text, layout and tables) | Supported | `pdf` |
-| PDF OCR | Supported with Tesseract/language data | `pdf-ocr` |
-| DOC, PPT | Detected, rejected explicitly | – |
-
-### PDF source layout
-
-```rust
-let parsed = markkit::Markkit::builder().pdf_layout(true).build()
- .parse_document_sync(pdf_bytes, markkit::DocumentHint::file_name("report.pdf"))?;
-let layout = parsed.layout.as_ref().unwrap(); // pages, dimensions, positioned text spans
-```
-
-CLI: `markkit extract --file report.pdf --json --layout`.
-Node: `extractDocumentSync(bytes, { fileName: "report.pdf" }, { pdfLayout: true })`.
-WASM: `new Markkit({ pdfLayout: true }).extractDocument(bytes, { fileName: "report.pdf" })`.
-
-Layout v1 includes source runs and words, plus semantic blocks, lines and table
-cells in reading order. Coordinates are display points from the cropped/rotated
-page top-left (x right, y down). Source runs retain drawing order. Each block has
-an ID, type, bounds and source span IDs; table cells include row/column positions,
-rowspan/colspan and bounds. IR `Source.page` + `Source.layout_block` link blocks
-when layout is requested. Font bounds approximate an em box; OCR bounds come from
-the recognizer. Layout is omitted by default, and does not change Markdown.
+**Extract clean Markdown from any document, safely.** Written in Rust.
-PDF extraction reconstructs columns, handles ruled and borderless tables, preserves
-bold/italic and numbered lists, and uses tagged-PDF heading roles and `ActualText`.
-Ambiguous alignments remain prose. Enable repeated margin-header/footer suppression
-with `.pdf_remove_repeated_headers(true)` or CLI `--remove-pdf-headers`.
+Markkit turns web pages, PDFs, Word and PowerPoint files, spreadsheets,
+e-books, email and notebooks into well-structured Markdown that LLMs and agents
+can read. It is built for **untrusted input**: nothing is executed, every
+resource a document can drive is bounded, and the default build has no network
+stack.
-Native OCR uses Rust Hayro rendering for pages without text. Install **Tesseract**
-plus language data. Rust requires the `pdf-ocr` feature; the CLI,
-Node and Python packages compile support in. WASM extracts existing text layers;
-OCR helpers run in native hosts.
+One engine, every runtime:
-```bash
-markkit extract --file scanned.pdf --ocr --ocr-language eng --timeout 300
-```
-
-Rust: `.pdf_ocr(true).pdf_ocr_language("eng+deu")`; Node: `{ pdfOcr: true,
-pdfOcrLanguage: "eng", timeout: 300 }`. Python: `extract_document_sync(data,
-file_name="report.pdf", pdf_layout=True, pdf_ocr=True, limits=Limits(timeout=300))`.
-The same structured Python API returns metadata and table counts for all formats.
+| Surface | Install | Docs |
+|---|---|---|
+| Rust library | `cargo add markkit` | [docs.rs/markkit](https://docs.rs/markkit) |
+| CLI + MCP server | `cargo install markkit-cli` | [CLI](#cli) |
+| Python | `pip install markkit` | [Python README](crates/markkit-python/README.md) |
+| Node.js (native) | `npm install @everruns/markkit` | [Node.js README](crates/markkit-js/README.md) |
+| Browser / edge (WebAssembly) | `npm install @everruns/markkit-wasm` | [WASM README](crates/markkit-wasm/README.md) |
+
+## Why Markkit
+
+- **Many formats, one API.** Bytes in, Markdown out. The format is detected
+ from the content type, file extension or magic bytes.
+- **Safe by default.** No scripts, macros or formulas run. XML entities are
+ never expanded. Archives and PDF streams are decompressed under measured
+ limits. Hidden text (a prompt-injection vector) is dropped. URL fetching
+ refuses private and cloud-metadata addresses. Every mitigation in the
+ [threat model](knowledge/security/threat-model.md) has a test.
+- **Bounded.** Input and output size, time, nesting depth, node count, archive
+ and spreadsheet sizes and PDF streams all have limits. A breach is a typed
+ error, never a hang or an out-of-memory crash.
+- **Agent-ready.** Main-content detection strips sidebars and comment
+ threads. Results carry title, metadata, stats and structured warnings. A
+ built-in LLM tool and an MCP server are included.
+- **Fast.** HTML extracts at 14–22 MiB/s and format detection takes
+ microseconds. See [Performance](#performance).
+
+## Supported formats
+
+| Format | Rust feature | Notes |
+|---|---|---|
+| HTML / XHTML | `html` (default) | Nav, header, footer, scripts, styles, forms stripped; optional main-content detection |
+| PDF | `pdf` | Text layer, reading order, columns, ruled and borderless tables, optional [layout geometry](docs/pdf.md) |
+| PDF OCR | `pdf-ocr` | Textless pages via installed Tesseract; optional Rust `ocrs` backend |
+| DOCX | `docx` | Headings, lists, tables, links, emphasis, footnotes |
+| PPTX, PPTM, PPSX | `pptx` | One section per slide: titles, bullets, tables, links, speaker notes |
+| XLSX, XLSM, XLSB, XLS, ODS | `spreadsheet` | One Markdown table per sheet; hidden sheets skipped |
+| ODT | `odt` | OpenDocument text |
+| EPUB | `epub` | Chapters in reading order, title from package metadata |
+| Email (EML) | `email` | Headers, body (plain preferred, HTML converted), attachment list |
+| Markdown | `markdown` | Normalized through the same IR; raw HTML never passed through |
+| Jupyter notebooks | always on | Markdown and code cells, text outputs, tracebacks |
+| CSV / TSV | always on | `,` `;` `\|` and tab delimiters, RFC 4180 quoting |
+| Plain text | always on | Paragraphs |
+| DOC, PPT (legacy binary) | – | Detected and rejected with a clear error |
+
+`all_formats` enables every format feature. The Python, Node.js and CLI
+packages ship with all formats, OCR and URL fetching. The WASM package covers
+HTML, PDF text and layout, DOCX, spreadsheets, Markdown, CSV/TSV, notebooks and
+text, without URL fetching or OCR.
+
+## Quick start
-For Rust-only OCR, build with the optional `pdf-ocr-ocrs` feature and supply local
-ONNX models. Tesseract remains the default backend:
+### Rust
-```bash
-python3 scripts/prepare_ocr_models.py # verifies pinned model sizes and SHA-256
-cargo build --release -p markkit-cli --features pdf-ocr-ocrs
-target/release/markkit extract --file scanned.pdf --ocr --ocr-backend ocrs \
- --ocr-detection-model target/ocr-models/text-detection.onnx \
- --ocr-recognition-model target/ocr-models/text-recognition.onnx --timeout 300
+```toml
+[dependencies]
+markkit = { version = "0.3", features = ["pdf", "docx", "spreadsheet"] }
```
-Rust: `.pdf_ocr_backend(markkit::PdfOcrBackend::Ocrs)` plus
-`.pdf_ocr_detection_model(path)` and `.pdf_ocr_recognition_model(path)`.
-Extraction never downloads models. The pinned weights are CC-BY-SA 4.0, separate
-from the MIT/Apache library code; the setup script writes their attribution and
-license to `target/ocr-models/NOTICE.json`. The default model supports the Latin
-alphabet; `ocrs` currently accepts `eng` only. Models are trusted deployment
-assets. RTen inference checks deadlines between phases and batches; host quotas
-provide hard CPU/memory limits. `RTEN_NUM_THREADS` and `RAYON_NUM_THREADS` configure
-inference/postprocessing thread pools at process startup. Markkit's WASM binding
-does not yet expose this native OCR path.
-
-PDF geometry/rules count against `max_nodes`; retained geometry and analysis work
-are bounded by `max_pdf_decoded_size`. Table grids obey row/column/grid limits.
-Compact layout JSON and Markdown are independently bounded by `max_output_size`
-(excluding JSON wrapper/pretty-print overhead), including parse-only callers.
-Hayro checks image/raster budgets before rendering and the deadline before/after
-its non-interruptible render step. Tesseract uses private files, output caps and
-a killable deadline; no shell is used. OCR currently supports JPEG, JPEG2000 and
-generic-filter images without DecodeParms. Inline, JBIG2 and CCITT OCR is refused
-until bounded decoding is available. Host isolation provides hard CPU/memory quotas.
-
-## Quick Start
-
-### Rust Library
-
-```rust
-use markkit::Markkit;
-
-let markkit = Markkit::builder().build();
-let md = markkit.extract_html("
Hello
World
").await?;
-```
+```rust,no_run
+use markkit::{DocumentHint, Markkit};
-### Documents from bytes
+fn main() -> Result<(), Box> {
+ let markkit = Markkit::builder().build();
-```rust
-use markkit::{DocumentHint, Markkit};
+ // HTML string to Markdown
+ let md = markkit.extract_html_sync("
Hello
World
")?;
+ assert_eq!(md, "# Hello\n\nWorld\n");
-let markkit = Markkit::builder().build();
-// Detection order: content type, then file extension, then magic bytes.
-let hint = DocumentHint { content_type: Some("application/octet-stream"), file_name: Some("report.docx") };
-// CPU-bound: call the sync variant from `tokio::task::spawn_blocking` in async code.
-let doc = markkit.extract_document_sync(&bytes, hint)?;
-println!("{:?} {:?} {:?}", doc.format, doc.title, doc.warnings);
-println!("{}", doc.markdown);
+ // Any supported file: format, title, warnings and stats come back too
+ let bytes = std::fs::read("report.docx")?;
+ let doc = markkit.extract_document_sync(&bytes, DocumentHint::file_name("report.docx"))?;
+ println!("{} {:?} {:?}", doc.format, doc.title, doc.stats);
+ println!("{}", doc.markdown);
+ Ok(())
+}
```
-`Extraction` carries `markdown`, `title`, `format`, `warnings` (structured: `code` such as
-`WarningCode::TruncatedSheet` plus a human-readable `detail`),
-`stats` (sheets/rows/paragraphs/tables) and, for HTML, `metadata` (description, author,
-published date, language, canonical URL, site name, lead image from ``, Open Graph
-and JSON-LD). `extract_bytes` remains as a Markdown-only shortcut.
+Extraction is CPU-bound. In async code, call the `_sync` methods from
+`tokio::task::spawn_blocking`. Async `extract_html`, `extract_document` and
+`extract_url` (feature `http_client`) are also available.
### CLI
```bash
-# From a URL
-markkit extract https://example.com
-
-# From a file
-markkit extract --file document.html
-
-# With CSS selector filtering
-markkit extract https://example.com --include "article" --exclude "nav,footer"
-
-# JSON output with format, title and page metadata
-markkit extract https://example.com --json
-
-# Keep only the article body (drops sidebars, comments, share bars)
-markkit extract https://example.com/post --main-content
+cargo install markkit-cli
-# Resolve relative links in a saved page
+markkit extract https://example.com # URL
+markkit extract --file report.docx # any supported file
+markkit extract --file report.pdf --json # JSON: markdown, format, title, warnings, stats, metadata
+markkit extract https://example.com/post --main-content # article body only
+markkit extract https://example.com -i article -e .ads # CSS include / exclude
markkit extract --file page.html --base-url https://example.com/blog/
+cat page.html | markkit extract - # stdin
+markkit extract --file scan.pdf --ocr --ocr-language eng --timeout 300
+markkit extract --file page.html --rules rules.json # site-specific element rules
+```
-# From stdin
-cat page.html | markkit extract -
+Every resource limit has a flag (`--max-input-size`, `--timeout`,
+`--max-nodes`, ...); see `markkit extract --help`.
-# Map site-specific markup with element rules (JSON file)
-# [{"selector": ".note", "action": "block_quote", "title": "Note"}, {"selector": ".ad", "action": "skip"}]
-markkit extract --file page.html --rules rules.json
+**MCP server.** `markkit mcp` serves the `markkit` tool over stdio
+(`--no-url` keeps it offline):
-# MCP server (stdio) exposing the `markkit` tool to agents
-markkit mcp # add --no-url to keep it offline
+```json
+{ "mcpServers": { "markkit": { "command": "markkit", "args": ["mcp"] } } }
```
-MCP client config: `{"mcpServers": {"markkit": {"command": "markkit", "args": ["mcp"]}}}`.
-
### Python
```python
import markkit
-markdown = markkit.extract_html_sync("
')); // "# Hello\n"
-### CLI
+const doc = await extractDocument(fs.readFileSync('report.docx'), { fileName: 'report.docx' });
+console.log(doc.format, doc.title, doc.markdown);
-```bash
-cargo install markkit-cli
+const md = await extractUrl('https://example.com', { mainContent: true });
```
-### Python
+TypeScript types included. Full API: [Node.js README](crates/markkit-js/README.md).
-```bash
-pip install markkit
-```
+### Browser and edge (WebAssembly)
-Wheels: Linux x64, CPython 3.12. Other platforms build from the sdist (needs Rust).
+```js
+import { initMarkkit, Markkit } from '@everruns/markkit-wasm';
-### Node.js
+await initMarkkit(); // once
+const mk = new Markkit({ mainContent: true });
+console.log(mk.extractHtml('
Hello
'));
-```bash
-npm install @everruns/markkit
+const res = await fetch('/report.pdf');
+const doc = mk.extractDocument(new Uint8Array(await res.arrayBuffer()), { fileName: 'report.pdf' });
```
-Native binary: Linux x64 (glibc).
+Runs in browsers, Cloudflare Workers, Vercel Edge, Deno, Bun and Node with no
+special headers. Full API: [WASM README](crates/markkit-wasm/README.md).
+
+## Examples
-### Browser / edge (WebAssembly)
+Runnable examples for every surface live in [`examples/`](examples/), use the
+bundled sample DOCX, XLSX and PDF in [`examples/data/`](examples/data/), and run
+in CI on every change.
```bash
-npm install @everruns/markkit-wasm
+cargo run -p markkit --example basic
+cargo run -p markkit --features all_formats --example convert -- path/to/file.pptx
+python examples/python/documents.py
+node examples/node/documents.cjs
+node examples/wasm/quickstart.mjs
```
-Any JS runtime (browsers, Cloudflare Workers, Deno, Bun, Node); no special headers.
-HTML, PDF text/layout, DOCX and spreadsheets; no URL fetching. See
-[`crates/markkit-wasm/README.md`](crates/markkit-wasm/README.md).
+See [examples/README.md](examples/README.md) for the full list.
## Configuration
```rust
+use std::time::Duration;
+use markkit::{Limits, Markkit};
+
let markkit = Markkit::builder()
- .max_input_size(10 * 1024 * 1024) // 10MB limit
- .max_processing_secs(30)
- .preserve_links(true)
+ .main_content(true) // keep the article, drop sidebars and comments
+ .include_selector("article") // CSS selectors to keep
+ .exclude_selector(".newsletter") // and to drop (added to nav/footer/script/...)
+ .base_url("https://example.com/blog/") // resolve relative links and images
.preserve_images(false)
- .include_selector("article")
- .exclude_selector("nav")
- .exclude_selector(".sidebar")
+ .track_sources(true) // per-block provenance in the IR
+ .limits(Limits::default().timeout(Duration::from_secs(10)).max_output_size(8 << 20))
.build();
```
-## Feature Flags
-
-| Feature | Default | Description |
-|---------|---------|-------------|
-| `html` | Yes | HTML parsing and conversion |
-| `http_client` | No | URL fetching via reqwest (`extract_url`) |
-| `docx` | No | DOCX conversion (zip + quick-xml) |
-| `pptx` | No | PPTX conversion (zip + quick-xml) |
-| `spreadsheet` | No | XLSX/XLSM, XLS, ODS conversion (calamine) |
-| `pdf` | No | PDF text/layout, reading order and tables (pure Rust) |
-| `pdf-ocr` | No | Native OCR: Rust Hayro rendering + installed Tesseract/language data |
-| `pdf-ocr-ocrs` | No | Optional Rust OCR via ocrs/RTen and caller-supplied local ONNX models |
-| `markdown` | No | Markdown normalization (pulldown-cmark) |
-| `email` | No | EML conversion (mail-parser) |
-| `odt` | No | ODT conversion (zip + quick-xml) |
-| `epub` | No | EPUB conversion (implies `html`) |
-| `all_formats` | No | `html`, `pdf`, `docx`, `pptx`, `spreadsheet`, `markdown`, `email`, `odt`, `epub` |
-| `tool` | No | `markkit::tool::MarkkitTool` LLM agent tool (Everruns toolkit contract) |
-| `logging` | No | Reserved: pulls in `tracing`, emits no events yet |
-
-`http_client` is opt-in: the default build has no HTTP/TLS stack and no tokio in the dependency
-tree.
-Enable it to get `extract_url` (the CLI and the Python/Node bindings ship with it on):
-
-```toml
-[dependencies]
-markkit = { version = "0.1", features = ["http_client"] }
-# office formats only, no HTML, no network:
-# markkit = { version = "0.1", default-features = false, features = ["docx", "pptx", "spreadsheet"] }
-```
+A built `Markkit` is immutable and can be shared across threads. Bindings use
+the same options: snake_case keyword arguments in Python, flat camelCase keys
+in Node.js and WASM.
### Resource limits
Every resource an input can drive is bounded by `markkit::Limits`. Defaults are
-generous; violations return `Error::ResourceLimit`, whose `LimitKind` (`err.limit_kind()`)
-names the field that was exceeded.
+generous. A breach returns `Error::ResourceLimit`, and `err.limit_kind()` names
+the limit (Python raises `RuntimeError`, JS throws `Error`, with the limit name
+in the message).
| Limit | Default | Bounds |
|-------|---------|--------|
| `max_input_size` | 50 MiB | Input bytes, fetched URL body |
| `max_output_size` | 128 MiB | Markdown output |
-| `timeout` | 60 s | Fetch + parse + render, per call |
+| `timeout` | 60 s | Fetch + parse + render, per call (not enforced in WASM: no clock) |
| `max_nesting_depth` | 256 (hard max 512) | HTML flattens deeper content; deeper DOCX XML is rejected |
-| `max_nodes` | 5 000 000 | HTML DOM nodes, DOCX XML nodes; retained PDF layout pages/runs |
-| `max_archive_entries` | 10 000 | ZIP entries (DOCX/XLSX/ODS) |
+| `max_nodes` | 5 000 000 | HTML DOM nodes, XML nodes, retained PDF layout |
+| `max_archive_entries` | 10 000 | ZIP entries (DOCX/PPTX/XLSX/ODT/EPUB) |
| `max_archive_entry_size` | 64 MiB | Decompressed bytes per ZIP entry |
| `max_archive_total_size` | 256 MiB | Decompressed bytes per ZIP |
| `max_spreadsheet_cells` | 4 000 000 | XLS/ODS grid before parsing |
| `max_sheet_rows` / `max_sheet_cols` | 10 000 / 256 | Rendered per sheet (truncated with a warning) |
| `max_pdf_pages` | 10 000 | PDF pages rendered (truncated with a warning) |
| `max_pdf_stream_size` | 64 MiB | Decoded bytes per PDF stream |
-| `max_pdf_decoded_size` | 256 MiB | Decoded PDF stream bytes in total, and PDF content interpreted |
+| `max_pdf_decoded_size` | 256 MiB | Decoded PDF bytes in total |
| `max_redirects` | 5 | `extract_url` redirects |
-```rust
-use markkit::{Limits, Markkit};
-use std::time::Duration;
+### Cargo features
-let markkit = Markkit::builder()
- .limits(Limits::default().timeout(Duration::from_secs(10)).max_output_size(8 << 20))
- .build();
+| Feature | Default | Description |
+|---------|---------|-------------|
+| `html` | Yes | HTML parsing and conversion |
+| `pdf`, `docx`, `pptx`, `spreadsheet`, `odt`, `epub`, `email`, `markdown` | No | Format support, see [Supported formats](#supported-formats) |
+| `all_formats` | No | All of the above |
+| `pdf-ocr` | No | OCR for textless PDF pages: Hayro rendering + installed Tesseract |
+| `pdf-ocr-ocrs` | No | Rust OCR via ocrs/RTen with caller-supplied local ONNX models |
+| `http_client` | No | `extract_url` / `extract_url_document` via reqwest, with SSRF protection |
+| `tool` | No | `markkit::tool::MarkkitTool` LLM agent tool (Everruns toolkit contract) |
+| `json-schema` | No | `markkit::ir::json_schema()` for the serialized IR |
+| `logging` | No | Reserved: pulls in `tracing`, emits no events yet |
+
+`http_client` is opt-in: the default build has no HTTP/TLS stack and no tokio.
+Office formats only, no HTML, no network:
+
+```toml
+markkit = { version = "0.3", default-features = false, features = ["docx", "pptx", "spreadsheet"] }
```
-Each limit also has a builder setter (`.max_nodes(..)`, `.timeout(..)`, ...), a CLI
-flag (`--max-nodes`, `--timeout`, ...; see `markkit extract --help`), a
-`markkit.Limits(...)` argument in Python and flat option keys in Node.js and WASM.
-Other options: `include_hidden_sheets`, `allow_private_networks`, `allow_host`.
+## PDF
+
+PDF extraction reads the text layer, rebuilds reading order across columns,
+reconstructs ruled and borderless tables (with merged and wrapped cells), keeps
+bold, italic and numbered lists, and uses tagged-PDF headings and
+`ActualText`. Opt-in extras:
+
+- **Layout geometry**: `pdf_layout(true)` / `--layout` / `pdfLayout: true` adds
+ pages, positioned text spans and semantic blocks with bounding boxes.
+- **Repeated headers**: `pdf_remove_repeated_headers(true)` /
+ `--remove-pdf-headers` drops running headers and footers.
+- **OCR**: `pdf_ocr(true)` / `--ocr` recognizes pages without text using
+ installed Tesseract, or the Rust `ocrs` backend with local ONNX models.
+
+Encrypted PDFs are rejected. Details, coordinates, OCR setup and limits:
+[docs/pdf.md](docs/pdf.md).
+
+## Agent tool
+
+With the `tool` feature, `markkit::tool::MarkkitTool` is an LLM tool with
+input/output JSON schemas, an OpenAI-style definition, a system prompt and a
+validated `execute` (also a `tower::Service`). The same tool is available as
+`MarkkitTool` in the WASM package and over MCP via `markkit mcp`. See
+[`examples/agent_tool.rs`](examples/agent_tool.rs) and the
+[tool contract](knowledge/integrations/tool-contract.md).
## Performance
@@ -373,26 +320,31 @@ Takeaways:
## Security
-Markkit treats every input as untrusted. HTML scripts, styles, forms, iframes and
-SVG are stripped; office containers are decompressed under measured byte limits;
-spreadsheet grids are pre-scanned so sparse cells cannot force huge allocations;
-XML entities are never expanded; every PDF stream is decode-checked against size
-limits before parsing; macros and formulas are never executed; hidden
-sheets are skipped by default. `extract_url` accepts only http/https, refuses
-loopback, private, link-local and cloud-metadata addresses (also after DNS
-resolution and on every redirect), caps redirects, and bounds the body by
-`max_input_size` and the fetch by `timeout`. Opt in to internal
-hosts with `allow_private_networks(true)`; restrict hosts with `allow_host(..)`.
+Markkit treats every input as untrusted. HTML scripts, styles, forms, iframes
+and SVG are stripped. Office containers are decompressed under measured byte
+limits. Spreadsheet grids are pre-scanned so sparse cells cannot force huge
+allocations. XML entities are never expanded. Every PDF stream is checked
+against size limits before decoding. Macros and formulas are never executed.
+Hidden sheets and hidden text are skipped by default.
+
+`extract_url` accepts only http and https. It refuses loopback, private,
+link-local and cloud-metadata addresses (also after DNS resolution and on
+every redirect), caps redirects, and bounds the body by `max_input_size` and
+the fetch by `timeout`. Opt in to internal hosts with
+`allow_private_networks(true)`; restrict hosts with `allow_host(..)`.
-See the [threat model](knowledge/security/threat-model.md) and the
-[security policy](SECURITY.md) for reporting vulnerabilities.
+See the [threat model](knowledge/security/threat-model.md). To report a
+vulnerability, follow the [security policy](SECURITY.md).
## Documentation
-- [Getting started](docs/getting-started.md)
+- [Getting started](docs/getting-started.md): install, extract, configure, IR and provenance
+- [PDF guide](docs/pdf.md): layout geometry, tables, OCR
- API reference: [docs.rs/markkit](https://docs.rs/markkit)
+- Bindings: [Python](crates/markkit-python/README.md), [Node.js](crates/markkit-js/README.md), [WASM](crates/markkit-wasm/README.md)
+- [Examples](examples/README.md)
- Design knowledge (architecture, IR, formats, threat model, processes): [`knowledge/`](knowledge/index.md)
-- [Examples](examples/): `cargo run -p markkit --example basic`
+- [Changelog](CHANGELOG.md)
## Development
@@ -400,6 +352,7 @@ See the [threat model](knowledge/security/threat-model.md) and the
just build # Build workspace
just test # Run all tests
just lint # Run clippy
+just examples # Run every Rust example
just check # fmt, clippy, tests, knowledge, examples
just pre-pr # Full pre-PR validation
just bench # Benchmarks, results saved to crates/markkit-bench/results
@@ -417,7 +370,7 @@ Coding agents: start with [AGENTS.md](AGENTS.md).
Bug reports, feature requests and questions are welcome as
[issues](https://github.com/everruns/markkit/issues). For code, see
-[CONTRIBUTING.md](CONTRIBUTING.md).
+[CONTRIBUTING.md](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
## Ecosystem
@@ -426,6 +379,7 @@ Markkit is part of the [Everruns](https://everruns.com) ecosystem, alongside
## License
-MIT License. See [LICENSE](LICENSE) for details. Third-party attributions,
-including data embedded by PDF rendering, are in [NOTICE](NOTICE). Report
-vulnerabilities privately per [SECURITY.md](SECURITY.md).
+MIT License. See [LICENSE](LICENSE). Third-party attributions, including data
+embedded by PDF rendering, are in [NOTICE](NOTICE). Optional OCR model weights
+fetched by `scripts/prepare_ocr_models.py` are separate CC-BY-SA 4.0 assets,
+never bundled. Report vulnerabilities privately per [SECURITY.md](SECURITY.md).
diff --git a/crates/markkit-js/README.md b/crates/markkit-js/README.md
index f13a6dc..839e0dd 100644
--- a/crates/markkit-js/README.md
+++ b/crates/markkit-js/README.md
@@ -1,93 +1,172 @@
# @everruns/markkit
-Native Node.js bindings for Markkit: HTML, PDF, DOCX and spreadsheets to Markdown.
+[](https://www.npmjs.com/package/@everruns/markkit)
+[](https://github.com/everruns/markkit/blob/main/LICENSE)
-This npm release supports **Linux x64 with glibc**. It does not include binaries for
-macOS, Windows, ARM64 or musl Linux. Other platforms require a separate future
-native release; Rust and Python package availability is independent.
+**Extract clean Markdown from any document, safely.** Native Node.js bindings
+for [Markkit](https://github.com/everruns/markkit), written in Rust.
-The package contains its JavaScript loader and native binary. CI verifies a clean
-installation and extraction smoke on Node.js 24.22.1 before publication. Use a
-currently supported Node.js release with its security patches installed.
+Convert HTML, PDF, Word, PowerPoint, Excel/ODS spreadsheets, ODT, EPUB, email
+(EML), Jupyter notebooks, CSV/TSV, Markdown and plain text into well-structured
+Markdown for LLMs, RAG pipelines and agents. Built for untrusted input: nothing
+is executed, and every resource a document can drive is bounded.
-```js
-const { extractHtmlSync } = require('@everruns/markkit');
-console.log(extractHtmlSync('
Hello
'));
-// # Hello
+- One call for every format, detected from file name, content type or bytes
+- Title, metadata, stats and structured warnings with every result
+- Main-content detection for web pages, CSS include/exclude selectors
+- PDF reading order, columns, tables, optional layout geometry and OCR
+- URL fetching with SSRF protection
+- TypeScript declarations included; async functions run off the event loop
+
+## Install
+
+```bash
+npm install @everruns/markkit
```
-## Options
+The package ships a prebuilt native addon for **Linux x64 (glibc)**. macOS,
+Windows, ARM64 and musl are not published yet; for those, or for browsers and
+edge runtimes, use [`@everruns/markkit-wasm`](https://www.npmjs.com/package/@everruns/markkit-wasm).
+CI verifies a clean install and extraction on Node.js 24.
-Every function takes an optional trailing options object:
+## Quick start
```js
-const { extractHtml, extractUrl, extractDocumentSync } = require('@everruns/markkit');
-
-await extractHtml(html, { includeSelectors: ['article'], excludeSelectors: ['.ad'], preserveImages: false });
+const fs = require('node:fs');
+const { extractHtmlSync, extractDocument } = require('@everruns/markkit');
-// URLs: non-public addresses are blocked by default.
-await extractUrl('https://docs.example.com/page', { allowedHosts: ['docs.example.com'], maxRedirects: 2 });
+console.log(extractHtmlSync('
Hello
World
'));
+// # Hello
+//
+// World
-// Documents with metadata (HTML, PDF, DOCX, PPTX, XLSX/XLSB/XLS/ODS). `warnings` are `{ code, detail }`.
-const doc = extractDocumentSync(fs.readFileSync('report.docx'), { fileName: 'report.docx' }, { maxSheetRows: 500 });
-console.log(doc.title, doc.format, doc.warnings, doc.markdown);
+const doc = await extractDocument(fs.readFileSync('report.docx'), { fileName: 'report.docx' });
+console.log(doc.format, doc.title, doc.stats); // docx "Q3 Report" { paragraphs: 7, tables: 1 }
+console.log(doc.markdown);
```
-Fields: `maxInputSize`, `maxOutputSize`, `timeout` (seconds, covers fetch, parsing and
-rendering; `maxProcessingSecs` is the whole-second form), `maxNodes`, `maxNestingDepth`,
-`baseUrl`, `mainContent`, `pdfLayout`, `preserveLinks`, `preserveImages`,
-`includeSelectors`, `excludeSelectors` (added to the defaults), `maxArchiveEntries`,
-`maxArchiveEntrySize`, `maxArchiveTotalSize`, `maxSheetRows`, `maxSheetCols`,
-`maxSpreadsheetCells`, `includeHiddenSheets`, `allowPrivateNetworks` (trusted URLs only),
-`allowedHosts`, `maxRedirects`, `maxPdfPages`, `maxPdfStreamSize`, `maxPdfDecodedSize`.
-
-For browsers and edge runtimes use [`@everruns/markkit-wasm`](https://www.npmjs.com/package/@everruns/markkit-wasm).
+ES modules work too: `import { extractHtml } from '@everruns/markkit';`.
-## PDF layout and tables
+## API
-PDF text extraction reconstructs columns, ruled and conservative borderless tables,
-including merged and wrapped cells. Tagged headings/ActualText, bold/italic and
-numbered lists are preserved. Set `pdfRemoveRepeatedHeaders: true` to suppress
-repeated margin headers/footers.
+Every function takes an optional trailing `options` object.
-`pdfLayout: true` adds `layout: { version: 1, pages }` to document results. Source
-`spans` retain drawing order and include glyph-positioned `words`. Semantic `blocks`
-are in reading order, with `id`, `kind`, `bbox`, `spanIds`, `lines` and table `cells`.
-Cells have row/column positions, rowspan/colspan and source references. Coordinates
-are display points from the cropped/rotated top-left, x right and y down. Font
-bounds approximate an em box. Layout is optional and does not change Markdown.
+| Function | Returns | Use it for |
+|---|---|---|
+| `extractDocument(data: Buffer, hint?, options?)` | `Promise` | Any format, with metadata |
+| `extractDocumentSync(data, hint?, options?)` | `Extraction` | Same, synchronous |
+| `extractHtml(html: string, options?)` | `Promise` | HTML string to Markdown |
+| `extractHtmlSync(html, options?)` | `string` | Same, synchronous |
+| `extractBytes(data: Buffer, contentType?, options?)` | `Promise` | Bytes to Markdown only |
+| `extractUrl(url: string, options?)` | `Promise` | Fetch and convert a URL |
-Node and WASM use camelCase keys. `maxNodes` bounds primitives and geometry;
-`maxPdfDecodedSize` bounds retained geometry and analysis work; table row/column/
-grid limits apply. `maxOutputSize` independently bounds compact layout JSON and
-Markdown, excluding JSON wrapper/pretty-print overhead.
+`hint` is `{ contentType?: string, fileName?: string }`. The format is detected
+from `contentType`, then the extension of `fileName`, then magic bytes. The
+sync variants are CPU-bound and block the event loop while they run.
-Native OCR: install Tesseract plus language data. Use
-`{ pdfOcr: true, pdfOcrLanguage: "eng", timeout: 300 }` on `extractDocumentSync` /
-`extractDocument`. Only textless pages are recognized. OCR word bounds are returned
-in layout; helpers use private files, bounded dimensions/output and the deadline.
+`Extraction`:
-## Optional Rust OCR backend
+| Field | Type | Contents |
+|---|---|---|
+| `markdown` | `string` | The Markdown |
+| `title` | `string \| undefined` | Title when the source declares one |
+| `format` | `string` | `html`, `pdf`, `docx`, `pptx`, `xlsx`, `xlsb`, `xls`, `ods`, `odt`, `epub`, `eml`, `ipynb`, `csv`, `tsv`, `markdown`, `text` |
+| `warnings` | `{ code, detail }[]` | e.g. `{ code: 'truncated_sheet', detail: '...' }`; match on `code` |
+| `stats` | `ExtractionStats` | `pages`, `sheets`, `rows`, `paragraphs`, `tables` |
+| `metadata` | `Metadata` | HTML `description`, `author`, `published`, `language`, `canonicalUrl`, `siteName`, `image` |
+| `layout` | `PdfLayout \| undefined` | PDF geometry, only with `pdfLayout: true` |
-Source builds can enable `markkit-js`'s Cargo feature `pdf-ocr-ocrs`. Default npm
-builds retain Tesseract. Prepare the pinned models from the repository with
-`python3 scripts/prepare_ocr_models.py`, then configure:
+## Options
```js
-extractDocumentSync(bytes, { fileName: "scan.pdf" }, {
- pdfOcr: true, pdfOcrBackend: "ocrs", timeout: 300,
- pdfOcrDetectionModel: "/models/text-detection.onnx",
- pdfOcrRecognitionModel: "/models/text-recognition.onnx"
+const { extractHtml, extractUrl } = require('@everruns/markkit');
+
+await extractHtml(html, {
+ mainContent: true, // keep the article, drop sidebars and comments
+ includeSelectors: ['main'], // keep only matches
+ excludeSelectors: ['.ad'], // drop matches (on top of nav/footer/script/...)
+ baseUrl: 'https://example.com/blog/', // resolve relative links and images
+ preserveImages: false,
});
+
+// URLs: loopback, private, link-local and metadata addresses are refused,
+// also after DNS resolution and on every redirect.
+await extractUrl('https://docs.example.com/page', { allowedHosts: ['docs.example.com'], maxRedirects: 2 });
```
-Models load from explicit local paths only. The pinned weights use CC-BY-SA 4.0
-and carry attribution in the setup script's NOTICE.json. The current Latin
-model accepts `pdfOcrLanguage: "eng"`. Missing build features/models and other
-languages fail explicitly. Model files and inference need trusted deployment
-configuration and host CPU/memory quotas; inference deadlines are cooperative.
+| Option | Default | Meaning |
+|---|---|---|
+| `mainContent` | `false` | Keep only the detected article body |
+| `includeSelectors` / `excludeSelectors` | `[]` | CSS selectors to keep / drop |
+| `baseUrl` | none | Base for relative links and images |
+| `preserveLinks` / `preserveImages` | `true` | Keep `[text](url)` / `` |
+| `includeHiddenSheets` | `false` | Render hidden spreadsheet sheets |
+| `pdfLayout` | `false` | Add `layout` geometry for PDFs |
+| `pdfRemoveRepeatedHeaders` | `false` | Drop running PDF headers/footers |
+| `pdfOcr`, `pdfOcrLanguage` | `false`, `"eng"` | OCR textless PDF pages with Tesseract |
+| `pdfOcrBackend`, `pdfOcrDetectionModel`, `pdfOcrRecognitionModel` | `"tesseract"` | Rust `ocrs` backend (source builds) |
+| `allowPrivateNetworks` | `false` | Let `extractUrl` reach internal hosts (trusted URLs only) |
+| `allowedHosts` | `[]` | Host allowlist for `extractUrl`, checked on every redirect |
+
+### Limits and errors
+
+| Option | Default | Bounds |
+|---|---|---|
+| `maxInputSize` | 50 MiB | Input bytes, fetched body |
+| `maxOutputSize` | 128 MiB | Markdown output bytes |
+| `timeout` | 60 | Seconds per call, fractions allowed (`maxProcessingSecs` is the whole-second form) |
+| `maxNodes` | 5 000 000 | Parsed nodes, retained PDF geometry |
+| `maxNestingDepth` | 256 | Element nesting (hard max 512) |
+| `maxArchiveEntries` | 10 000 | ZIP entries |
+| `maxArchiveEntrySize` / `maxArchiveTotalSize` | 64 / 256 MiB | Decompressed ZIP bytes |
+| `maxSheetRows` / `maxSheetCols` | 10 000 / 256 | Rendered per sheet (truncated with a warning) |
+| `maxSpreadsheetCells` | 4 000 000 | XLS/ODS grid before parsing |
+| `maxRedirects` | 5 | `extractUrl` redirects |
+| `maxPdfPages` | 10 000 | PDF pages (truncated with a warning) |
+| `maxPdfStreamSize` / `maxPdfDecodedSize` | 64 / 256 MiB | Decoded PDF bytes |
+
+Failures throw an `Error` whose message names the cause:
+
+```js
+try {
+ extractDocumentSync(bytes, { fileName: 'big.xlsx' }, { maxOutputSize: 1 << 20, timeout: 10 });
+} catch (err) {
+ console.error(err.message); // "Resource limit exceeded: output exceeds max_output_size 1048576"
+}
+```
+
+## PDF layout and OCR
+
+```js
+const doc = extractDocumentSync(pdfBytes, { fileName: 'report.pdf' }, { pdfLayout: true });
+for (const block of doc.layout.pages[0].blocks) {
+ console.log(block.kind, block.bbox); // reading order; bbox is [left, top, right, bottom]
+}
+```
+
+PDF extraction rebuilds reading order and columns, ruled and borderless tables
+(with merged and wrapped cells), emphasis, numbered lists and tagged headings.
+`layout` is `{ version: 1, pages }`. Each page has source `spans` (text runs
+with `bbox`, `baseline`, `font`, `size`, `words`) and semantic `blocks`
+(`kind`, `bbox`, `spanIds`, `lines`, table `cells`). Coordinates are points
+from the page's top-left, x right and y down. Layout never changes the
+Markdown.
+
+Scanned pages: install Tesseract and language data, then pass
+`{ pdfOcr: true, pdfOcrLanguage: 'eng', timeout: 300 }`. Only pages without
+text are recognized. Source builds can enable the Rust `ocrs` backend (Cargo
+feature `pdf-ocr-ocrs`) with local ONNX model paths; extraction never
+downloads models. See the
+[PDF guide](https://github.com/everruns/markkit/blob/main/docs/pdf.md).
+
+## Examples
+
+Runnable scripts in
+[`examples/node/`](https://github.com/everruns/markkit/tree/main/examples/node):
+`quickstart.cjs` (HTML, options, bytes) and `documents.cjs` (DOCX, XLSX, PDF
+with stats, limits and layout; pass your own files as arguments).
## License
-MIT. See [LICENSE](https://github.com/everruns/markkit/blob/main/LICENSE); third-party notices in
+MIT. See [LICENSE](https://github.com/everruns/markkit/blob/main/LICENSE); third-party notices are in
[NOTICE](https://github.com/everruns/markkit/blob/main/NOTICE).
diff --git a/crates/markkit-js/src/lib.rs b/crates/markkit-js/src/lib.rs
index d6e93ce..8336efc 100644
--- a/crates/markkit-js/src/lib.rs
+++ b/crates/markkit-js/src/lib.rs
@@ -35,24 +35,40 @@ pub struct MarkkitOptions {
pub main_content: Option,
/// Retain PDF page dimensions and positioned text runs in `Extraction.layout`.
pub pdf_layout: Option,
+ /// Drop margin headers/footers repeated across PDF pages (default false).
pub pdf_remove_repeated_headers: Option,
+ /// OCR PDF pages that have no text layer (default false). Needs Tesseract
+ /// and language data installed, or the `ocrs` backend.
pub pdf_ocr: Option,
+ /// Tesseract language codes, e.g. `"eng"` or `"eng+deu"` (default `"eng"`).
pub pdf_ocr_language: Option,
+ /// `"tesseract"` (default) or `"ocrs"` (source builds with `pdf-ocr-ocrs`).
pub pdf_ocr_backend: Option,
+ /// Local ONNX text-detection model path for the `ocrs` backend.
pub pdf_ocr_detection_model: Option,
+ /// Local ONNX text-recognition model path for the `ocrs` backend.
pub pdf_ocr_recognition_model: Option,
+ /// Keep link URLs as `[text](url)` (default true); false keeps the text only.
pub preserve_links: Option,
+ /// Keep images as `` (default true); false drops them.
pub preserve_images: Option,
/// CSS selectors to include (empty = whole document).
pub include_selectors: Option>,
/// CSS selectors to drop, added to nav/footer/header/script/style/noscript.
pub exclude_selectors: Option>,
+ /// Maximum ZIP entries in DOCX/PPTX/XLSX/ODT/EPUB containers (default 10 000).
pub max_archive_entries: Option,
+ /// Maximum decompressed bytes per ZIP entry (default 64 MiB).
pub max_archive_entry_size: Option,
+ /// Maximum decompressed bytes per ZIP container (default 256 MiB).
pub max_archive_total_size: Option,
+ /// Rows rendered per sheet; extra rows are truncated with a warning (default 10 000).
pub max_sheet_rows: Option,
+ /// Columns rendered per sheet; extra columns are truncated with a warning (default 256).
pub max_sheet_cols: Option,
+ /// Maximum XLS/ODS grid cells before parsing (default 4 000 000).
pub max_spreadsheet_cells: Option,
+ /// Render hidden and very hidden sheets (default false: skipped with a warning).
pub include_hidden_sheets: Option,
/// Let `extractUrl` reach loopback/private/link-local addresses. Trusted URLs only.
pub allow_private_networks: Option,
@@ -60,8 +76,11 @@ pub struct MarkkitOptions {
pub allowed_hosts: Option>,
/// Maximum redirects `extractUrl` follows (default 5).
pub max_redirects: Option,
+ /// PDF pages rendered; later pages are truncated with a warning (default 10 000).
pub max_pdf_pages: Option,
+ /// Decoded bytes per PDF stream (default 64 MiB).
pub max_pdf_stream_size: Option,
+ /// Decoded PDF bytes in total, also bounds retained layout geometry (default 256 MiB).
pub max_pdf_decoded_size: Option,
}
@@ -75,24 +94,37 @@ pub struct DocumentHint {
pub file_name: Option,
}
+/// Document counts; a field is absent when it does not apply to the format.
#[napi(object)]
pub struct ExtractionStats {
+ /// PDF pages.
pub pages: Option,
+ /// Rendered spreadsheet sheets.
pub sheets: Option,
+ /// Rendered spreadsheet / CSV data rows.
pub rows: Option,
+ /// Paragraph blocks.
pub paragraphs: Option,
+ /// Tables.
pub tables: Option,
}
/// Document metadata (HTML meta, Open Graph, JSON-LD); fields absent when unknown.
#[napi(object)]
pub struct Metadata {
+ /// Page summary (``, `og:description`, JSON-LD).
pub description: Option,
+ /// Author name.
pub author: Option,
+ /// Publication date as written in the source (usually ISO 8601).
pub published: Option,
+ /// Document language, e.g. `en` (from ``).
pub language: Option,
+ /// Canonical URL (``, `og:url`).
pub canonical_url: Option,
+ /// Site name (`og:site_name`).
pub site_name: Option,
+ /// Lead image URL (`og:image`).
pub image: Option,
}
@@ -105,16 +137,22 @@ pub struct Warning {
pub detail: String,
}
-/// Markdown plus metadata.
+/// Markdown plus metadata, returned by `extractDocument` / `extractDocumentSync`.
#[napi(object)]
pub struct Extraction {
+ /// PDF source geometry; present only with `pdfLayout: true` on PDF input.
pub layout: Option,
+ /// The extracted Markdown.
pub markdown: String,
+ /// Document title when the source declares one (HTML ``, document properties).
pub title: Option,
- /// Detected format (`html`, `docx`, `pptx`, `xlsx`, `xlsb`, `xls`, `ods`, `text`, `markdown`, `csv`, `tsv`, `ipynb`, `eml`, `odt`, `epub`).
+ /// Detected format (`html`, `pdf`, `docx`, `pptx`, `xlsx`, `xlsb`, `xls`, `ods`, `text`, `markdown`, `csv`, `tsv`, `ipynb`, `eml`, `odt`, `epub`).
pub format: String,
+ /// Non-fatal issues: truncation, skipped hidden content, encoding problems.
pub warnings: Vec,
+ /// Page, sheet, row, paragraph and table counts.
pub stats: ExtractionStats,
+ /// HTML page metadata; empty for other formats.
pub metadata: Metadata,
}
@@ -463,7 +501,8 @@ pub async fn extract_url(url: String, options: Option) -> napi::
markkit(options)?.extract_url(&url).await.map_err(err)
}
-/// Extract markdown from a buffer with optional content type.
+/// Extract Markdown from a buffer; the format is detected from `contentType`
+/// and the bytes. Use `extractDocument` for title, warnings and stats.
#[napi]
pub async fn extract_bytes(
data: Buffer,
@@ -476,7 +515,10 @@ pub async fn extract_bytes(
.map_err(err)
}
-/// Convert a document (HTML, DOCX, XLSX/XLS/ODS) with metadata (async).
+/// Convert document bytes (HTML, PDF, DOCX, PPTX, XLSX/XLSB/XLS/ODS, ODT, EPUB,
+/// EML, CSV/TSV, ipynb, Markdown, text) to Markdown plus title, format,
+/// warnings, stats and metadata (async). The format is detected from
+/// `hint.contentType`, then `hint.fileName`'s extension, then magic bytes.
#[napi]
pub async fn extract_document(
data: Buffer,
@@ -486,7 +528,7 @@ pub async fn extract_document(
document(&data, hint, options)
}
-/// Convert a document (HTML, DOCX, XLSX/XLS/ODS) with metadata (synchronous).
+/// Synchronous `extractDocument`. CPU-bound: blocks the event loop while it runs.
#[napi]
pub fn extract_document_sync(
data: Buffer,
diff --git a/crates/markkit-python/README.md b/crates/markkit-python/README.md
index dcda087..0245062 100644
--- a/crates/markkit-python/README.md
+++ b/crates/markkit-python/README.md
@@ -1,59 +1,110 @@
-# markkit
+# markkit for Python
-Extract clean Markdown from HTML, PDF, Office documents, spreadsheets, e-books,
-email and notebooks. Built for feeding untrusted documents to LLMs and agents.
-Native Rust core, no runtime dependencies.
+[](https://pypi.org/project/markkit/)
+[](https://github.com/everruns/markkit/blob/main/LICENSE)
+
+**Extract clean Markdown from any document, safely.** Native Python bindings
+for [Markkit](https://github.com/everruns/markkit), written in Rust.
+
+Convert HTML, PDF, Word, PowerPoint, Excel/ODS spreadsheets, ODT, EPUB, email
+(EML), Jupyter notebooks, CSV/TSV, Markdown and plain text into well-structured
+Markdown for LLMs, RAG pipelines and agents. Markkit is built for untrusted
+input: nothing is executed, and every resource a document can drive (size,
+time, nesting, nodes, archives, PDF streams) is bounded.
+
+- One call for every format, detected from file name, content type or bytes
+- Title, metadata, stats and structured warnings with every result
+- Main-content detection for web pages, CSS include/exclude selectors
+- PDF reading order, columns, tables, optional layout geometry and OCR
+- URL fetching with SSRF protection (private and metadata addresses refused)
+- Fully typed (`.pyi` stubs + `py.typed`), sync and `asyncio` APIs
+
+## Install
```bash
pip install markkit
```
+Wheels: Linux x86_64 (manylinux2014), CPython 3.12. Other platforms install
+from the source distribution, which needs a Rust toolchain (1.99+). OCR additionally needs
+[Tesseract](https://tesseract-ocr.github.io/) and language data installed.
+
+## Quick start
+
```python
import markkit
-markkit.extract_html_sync("
"))
+# # Hello
+#
+# World
-HTML, PDF (text, layout, tables, optional OCR), DOCX, PPTX, ODT, EPUB,
-XLSX/XLSM/XLSB/XLS/ODS, CSV/TSV, Jupyter notebooks, email (EML), Markdown and
-plain text. The format is detected from the content type, then the file name,
-then the bytes.
+with open("report.docx", "rb") as f:
+ result = markkit.extract_document_sync(f.read(), file_name="report.docx")
-## Documents
+print(result["format"]) # "docx"
+print(result["title"]) # "Q3 Report"
+print(result["stats"]) # {"paragraphs": 7, "tables": 1, ...}
+print(result["markdown"])
+```
-`extract_document_sync` takes raw bytes and returns a dict with the Markdown and
-metadata:
+## API
+
+| Function | Returns | Use it for |
+|---|---|---|
+| `extract_document_sync(data, *, file_name=None, content_type=None, pdf_layout=False, pdf_remove_repeated_headers=False, pdf_ocr=False, pdf_ocr_language="eng", pdf_ocr_backend="tesseract", pdf_ocr_detection_model=None, pdf_ocr_recognition_model=None, limits=None)` | `dict` | Any format, with metadata |
+| `extract_html_sync(html, *, limits=None)` | `str` | HTML string to Markdown |
+| `extract_html_sync_with_options(html, *, include_selectors=None, exclude_selectors=None, max_input_size=None, base_url=None, main_content=False, limits=None)` | `str` | HTML with selectors, link resolution, main content |
+| `await extract_html(html, *, limits=None)` | `str` | Async HTML |
+| `await extract_bytes(data, content_type=None, *, limits=None)` | `str` | Async bytes to Markdown only |
+| `await extract_url(url, *, limits=None)` | `str` | Fetch and convert a URL |
+| `Limits(...)` | `Limits` | Resource limits for any call |
+
+### Documents
+
+`extract_document_sync` detects the format from `content_type`, then the
+extension of `file_name`, then magic bytes, and returns a dict:
+
+| Key | Type | Contents |
+|---|---|---|
+| `markdown` | `str` | The Markdown |
+| `title` | `str \| None` | Title when the source declares one |
+| `format` | `str` | `html`, `pdf`, `docx`, `pptx`, `xlsx`, `xlsb`, `xls`, `ods`, `odt`, `epub`, `eml`, `ipynb`, `csv`, `tsv`, `markdown`, `text` |
+| `warnings` | `list[dict]` | `{"code": "truncated_sheet", "detail": "..."}`; match on `code` |
+| `stats` | `dict` | `pages`, `sheets`, `rows`, `paragraphs`, `tables`, ... (`None` when not applicable) |
+| `metadata` | `dict` | HTML `description`, `author`, `published`, `language`, `canonical_url`, `site_name`, `image` |
+| `layout` | `dict` | PDF geometry, only with `pdf_layout=True` |
```python
import markkit
-with open("report.docx", "rb") as f:
- doc = markkit.extract_document_sync(f.read(), file_name="report.docx")
-
-doc["markdown"] # extracted Markdown
-doc["title"] # document title, or None
-doc["format"] # detected format, e.g. "docx"
-doc["warnings"] # list of {"code": ..., "detail": ...}
+def convert(path: str) -> str:
+ with open(path, "rb") as f:
+ result = markkit.extract_document_sync(f.read(), file_name=path)
+ for w in result["warnings"]:
+ print(f"warning [{w['code']}]: {w['detail']}")
+ return result["markdown"]
```
-## HTML options
+From an HTTP response, pass the content type:
+`extract_document_sync(resp.content, content_type=resp.headers["content-type"])`.
+
+### Web pages
```python
-markkit.extract_html_sync_with_options(
+md = markkit.extract_html_sync_with_options(
html,
- include_selectors=["article"], # keep only these
- exclude_selectors=[".ad", "nav"], # drop these (added to the defaults)
- main_content=True, # keep only the detected article body
- base_url="https://example.com/", # resolve relative links and images
+ main_content=True, # keep the article, drop sidebars and comments
+ include_selectors=["main"], # keep only matches
+ exclude_selectors=[".newsletter"], # drop matches (on top of nav/footer/script/...)
+ base_url="https://example.com/blog/", # resolve relative links and images
)
```
-## Async
+### Async
-`extract_html`, `extract_bytes` and `extract_url` are coroutines:
+The async functions return awaitables backed by a native Tokio runtime, so
+they do not block the event loop.
```python
import asyncio
@@ -61,80 +112,97 @@ import markkit
async def main():
md = await markkit.extract_url("https://example.com")
- pdf = await markkit.extract_bytes(open("paper.pdf", "rb").read(), "application/pdf")
+ md2 = await markkit.extract_bytes(b"a,b\n1,2\n", "text/csv")
asyncio.run(main())
```
-`extract_url` blocks private and loopback addresses and bounds redirects, body
-size and time.
-
-## Resource limits
-
-All inputs are treated as untrusted. Every function accepts `limits=`, and every
-limit has a safe default. A breach raises `RuntimeError`.
+`extract_url` accepts only http and https. It refuses loopback, private,
+link-local and cloud-metadata addresses, also after DNS resolution and on every
+redirect.
+
+## Limits and errors
+
+Every function accepts `limits=markkit.Limits(...)`. All fields are optional
+keyword arguments with generous defaults:
+
+| Field | Default | Bounds |
+|---|---|---|
+| `max_input_size` | 50 MiB | Input bytes, fetched body |
+| `max_output_size` | 128 MiB | Markdown output bytes |
+| `timeout` | 60.0 | Seconds per call (fetch + parse + render) |
+| `max_nesting_depth` | 256 | Element nesting (deeper HTML is flattened; hard max 512) |
+| `max_nodes` | 5 000 000 | Parsed nodes, retained PDF geometry |
+| `max_archive_entries` | 10 000 | ZIP entries (DOCX, PPTX, XLSX, ODT, EPUB) |
+| `max_archive_entry_size` / `max_archive_total_size` | 64 / 256 MiB | Decompressed ZIP bytes |
+| `max_sheet_rows` / `max_sheet_cols` | 10 000 / 256 | Rendered per sheet (truncated with a warning) |
+| `max_spreadsheet_cells` | 4 000 000 | XLS/ODS grid before parsing |
+| `max_redirects` | 5 | `extract_url` redirects |
+| `max_pdf_pages` | 10 000 | PDF pages (truncated with a warning) |
+| `max_pdf_stream_size` / `max_pdf_decoded_size` | 64 / 256 MiB | Decoded PDF bytes |
```python
-limits = markkit.Limits(
- timeout=10.0, # seconds
- max_output_size=8 * 1024 * 1024, # bytes
- max_nesting_depth=128,
-)
-markkit.extract_html_sync(html, limits=limits)
+limits = markkit.Limits(max_input_size=10 << 20, max_output_size=1 << 20, timeout=10.0)
+try:
+ md = markkit.extract_html_sync(html, limits=limits)
+except RuntimeError as err:
+ print(err) # "Resource limit exceeded: output exceeds max_output_size 1048576"
```
-Fields: `max_input_size`, `max_output_size`, `timeout`, `max_nesting_depth`,
-`max_nodes`, `max_archive_entries`, `max_archive_entry_size`,
-`max_archive_total_size`, `max_sheet_rows`, `max_sheet_cols`,
-`max_spreadsheet_cells`, `max_redirects`, `max_pdf_pages`,
-`max_pdf_stream_size`, `max_pdf_decoded_size`.
+Errors raise `RuntimeError` with a message naming the cause: an exceeded limit,
+an unsupported format (legacy `.doc`/`.ppt`, encrypted PDF), a parse failure,
+a blocked URL or an HTTP failure. Invalid arguments (for example an unknown OCR
+backend) raise `ValueError`.
## PDF layout and OCR
```python
result = markkit.extract_document_sync(
pdf_bytes, file_name="report.pdf",
- pdf_layout=True, pdf_remove_repeated_headers=True,
+ pdf_layout=True, # add page geometry
+ pdf_remove_repeated_headers=True, # drop running headers/footers
)
-result["markdown"]
-result["layout"]["pages"][0]["blocks"] # positioned blocks, lines and table cells
+page = result["layout"]["pages"][0]
+for block in page["blocks"]: # reading order
+ print(block["kind"], block["bbox"]) # "table", [left, top, right, bottom]
```
-PDF extraction reconstructs reading order, columns and tables (ruled and
-borderless, with merged cells). Layout keys are snake_case; coordinates are
-points from the top-left of the cropped, rotated page.
+PDF extraction rebuilds reading order and columns, ruled and borderless tables
+(with merged and wrapped cells), emphasis, numbered lists and tagged headings.
+Layout adds source `spans` (text runs with `bbox`, `baseline`, `font`, `size`,
+`words`) and semantic `blocks` (`kind`, `bbox`, `span_ids`, `lines`, table
+`cells`). Coordinates are points from the page's top-left, x right and y down.
-For scanned pages, install [Tesseract](https://github.com/tesseract-ocr/tesseract)
-with your language data and pass `pdf_ocr=True`:
+Scanned pages, with Tesseract and language data installed:
```python
-markkit.extract_document_sync(
+result = markkit.extract_document_sync(
pdf_bytes, file_name="scan.pdf",
- pdf_ocr=True, pdf_ocr_language="eng",
+ pdf_ocr=True, pdf_ocr_language="eng+deu",
limits=markkit.Limits(timeout=300),
)
```
-OCR is opt-in, runs locally and only touches pages without text.
+OCR is opt-in and only processes pages without text. Source builds can also
+enable the Rust `ocrs` backend (`maturin build --features pdf-ocr-ocrs`) with
+`pdf_ocr_backend="ocrs"` plus local `pdf_ocr_detection_model` and
+`pdf_ocr_recognition_model` paths; extraction never downloads models. See the
+[PDF guide](https://github.com/everruns/markkit/blob/main/docs/pdf.md).
-
-Rust OCR backend (source builds)
+## Examples
-Build from source with the `pdf-ocr-ocrs` Cargo feature
-(`maturin build --features pdf-ocr-ocrs`), prepare the pinned model pair with
-`python3 scripts/prepare_ocr_models.py`, then pass
-`pdf_ocr_backend="ocrs"`, `pdf_ocr_detection_model=...` and
-`pdf_ocr_recognition_model=...`. Extraction never downloads models. The pinned
-weights are CC-BY-SA 4.0; only `pdf_ocr_language="eng"` is supported. An unknown
-backend raises `ValueError`; a missing feature or model raises `RuntimeError`.
+Runnable scripts in
+[`examples/python/`](https://github.com/everruns/markkit/tree/main/examples/python):
+`quickstart.py` (HTML, options, async), `documents.py` (DOCX, XLSX, PDF with
+stats and layout; pass your own files as arguments) and `limits.py`.
-
+## Packaging
-## Platforms
-
-Wheels are published for **Linux x86_64 (manylinux2014), CPython 3.12**. On other
-platforms pip builds from the source distribution, which needs a Rust toolchain
-(1.99+).
+The PyPI distribution and import are both `markkit`. Wheels are built with
+maturin and published with PyPI Trusted Publishing (OIDC). Before upload, the
+publisher verifies wheel metadata, installs the wheel into a clean virtual
+environment and runs a native extraction. The source distribution keeps the
+full Cargo workspace and lockfile.
## Links
@@ -142,8 +210,12 @@ platforms pip builds from the source distribution, which needs a Rust toolchain
- [Changelog](https://github.com/everruns/markkit/blob/main/CHANGELOG.md)
- [Security model](https://github.com/everruns/markkit/blob/main/knowledge/security/threat-model.md)
- Also available as a [Rust crate](https://crates.io/crates/markkit), a
- [CLI](https://crates.io/crates/markkit-cli) and an
- [npm package](https://www.npmjs.com/package/@everruns/markkit)
+ [CLI](https://crates.io/crates/markkit-cli), a native
+ [npm package](https://www.npmjs.com/package/@everruns/markkit) and a
+ [WebAssembly package](https://www.npmjs.com/package/@everruns/markkit-wasm)
+
+## License
-MIT licensed; see [LICENSE](https://github.com/everruns/markkit/blob/main/LICENSE). Third-party notices are in
-[NOTICE](https://github.com/everruns/markkit/blob/main/NOTICE).
+MIT. See [LICENSE](https://github.com/everruns/markkit/blob/main/LICENSE); third-party notices are in
+[NOTICE](https://github.com/everruns/markkit/blob/main/NOTICE). Optional OCR
+model weights are separate CC-BY-SA 4.0 assets, never bundled.
diff --git a/crates/markkit-python/tests/test_stubs.py b/crates/markkit-python/tests/test_stubs.py
new file mode 100644
index 0000000..fddcf75
--- /dev/null
+++ b/crates/markkit-python/tests/test_stubs.py
@@ -0,0 +1,54 @@
+"""markkit.pyi (shipped in the wheel) must match the native module."""
+import ast
+import inspect
+import pathlib
+import unittest
+
+import markkit
+
+STUB = pathlib.Path(__file__).resolve().parents[3] / "markkit.pyi"
+
+
+def stub_tree():
+ return ast.parse(STUB.read_text())
+
+
+def stub_params(fn):
+ a = fn.args
+ return [p.arg for p in a.posonlyargs + a.args + a.kwonlyargs if p.arg != "self"]
+
+
+class Stubs(unittest.TestCase):
+ def test_functions_match_runtime_signatures(self):
+ stub_fns = {n.name: n for n in stub_tree().body if isinstance(n, ast.FunctionDef)}
+ runtime = {
+ name for name in dir(markkit)
+ if not name.startswith("_") and inspect.isbuiltin(getattr(markkit, name))
+ }
+ self.assertEqual(set(stub_fns), runtime)
+ for name, fn in stub_fns.items():
+ sig = inspect.signature(getattr(markkit, name))
+ self.assertEqual(stub_params(fn), list(sig.parameters), name)
+
+ def test_limits_fields_match_runtime(self):
+ cls = next(n for n in stub_tree().body if isinstance(n, ast.ClassDef) and n.name == "Limits")
+ fields = [n.target.id for n in cls.body if isinstance(n, ast.AnnAssign)]
+ init = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "__init__")
+ self.assertEqual(stub_params(init), fields)
+ self.assertEqual(fields, list(inspect.signature(markkit.Limits).parameters))
+ limits = markkit.Limits()
+ for f in fields:
+ self.assertTrue(hasattr(limits, f), f)
+
+ def test_all_lists_public_names(self):
+ tree = stub_tree()
+ declared = next(
+ ast.literal_eval(n.value) for n in tree.body
+ if isinstance(n, ast.Assign) and n.targets[0].id == "__all__"
+ )
+ defined = {n.name for n in tree.body if isinstance(n, (ast.FunctionDef, ast.ClassDef))}
+ self.assertEqual(set(declared), defined)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/crates/markkit-wasm/README.md b/crates/markkit-wasm/README.md
index 5086c35..ff86302 100644
--- a/crates/markkit-wasm/README.md
+++ b/crates/markkit-wasm/README.md
@@ -1,16 +1,25 @@
# @everruns/markkit-wasm
-Markkit compiled to WebAssembly: extract clean Markdown from HTML, PDF text/layout, DOCX,
-spreadsheets (XLSX/XLSM, XLS, ODS), CSV/TSV, Jupyter notebooks, plain text and
-Markdown in the **browser and any JavaScript runtime**:
-edge workers (Cloudflare Workers, Vercel Edge, Deno Deploy), Node, Deno and Bun.
+[](https://www.npmjs.com/package/@everruns/markkit-wasm)
+[](https://github.com/everruns/markkit/blob/main/LICENSE)
-Single-threaded `wasm-bindgen` build: no `SharedArrayBuffer`, no `COOP`/`COEP`
-headers. For a native Node.js addon use
-[`@everruns/markkit`](https://www.npmjs.com/package/@everruns/markkit).
+**Extract clean Markdown from documents in the browser and at the edge.**
+[Markkit](https://github.com/everruns/markkit) compiled to WebAssembly.
+
+Convert HTML, PDF (text and layout), DOCX, spreadsheets (XLSX/XLSM/XLSB, XLS,
+ODS), CSV/TSV, Jupyter notebooks, Markdown and plain text to Markdown in any
+JavaScript runtime: browsers, Cloudflare Workers, Vercel Edge, Deno Deploy,
+Deno, Bun and Node.js. Includes an LLM agent tool.
-No URL fetching: the host fetches and passes bytes in, so network policy stays
-with the host.
+- Single-threaded `wasm-bindgen` build: no `SharedArrayBuffer`, no
+ `COOP`/`COEP` headers, no bundler required
+- Untrusted input is safe: nothing executes, sizes, nodes and nesting are bounded
+- No network access: the host fetches and passes bytes in, so network policy
+ stays with the host
+- TypeScript declarations included
+
+For a native Node.js addon (all formats, OCR, URL fetching), use
+[`@everruns/markkit`](https://www.npmjs.com/package/@everruns/markkit).
## Install
@@ -23,31 +32,92 @@ npm install @everruns/markkit-wasm
```js
import { initMarkkit, Markkit } from "@everruns/markkit-wasm";
-await initMarkkit(); // once
+await initMarkkit(); // load the .wasm once, before first use
-const mk = new Markkit({ includeSelectors: ["article"], preserveImages: false });
-console.log(mk.extractHtml("
"));
+// # Hello
+//
+// World
const res = await fetch("/report.docx");
const doc = mk.extractDocument(new Uint8Array(await res.arrayBuffer()), {
contentType: res.headers.get("content-type") ?? undefined,
fileName: "report.docx",
});
-console.log(doc.title, doc.format, doc.markdown);
+console.log(doc.format, doc.title, doc.stats, doc.markdown);
+```
+
+### Loading the module
+
+`initMarkkit()` is idempotent. Browsers and edge runtimes fetch
+`markkit_wasm_bg.wasm` next to the module; Node reads it from disk. Pass your
+own source when the bundler or runtime needs it:
+
+```js
+// Cloudflare Workers / bundlers that import .wasm as a module
+import wasm from "@everruns/markkit-wasm/markkit_wasm_bg.wasm";
+await initMarkkit(wasm);
+
+// Or any URL, Response, BufferSource or WebAssembly.Module
+await initMarkkit(new URL("/assets/markkit_wasm_bg.wasm", location.href));
```
+## API
+
+| Member | Returns | Use it for |
+|---|---|---|
+| `initMarkkit(input?)` | `Promise` | Load the module once |
+| `version()` | `string` | Library version |
+| `new Markkit(options?)` | `Markkit` | Extractor with fixed options; reuse it |
+| `mk.extractDocument(bytes: Uint8Array, hint?)` | `Extraction` | Any supported format, with metadata |
+| `mk.extractHtml(html: string)` | `string` | HTML string to Markdown |
+| `mk.extractBytes(bytes, contentType?)` | `string` | Bytes to Markdown only |
+| `mk.free()` | | Release wasm memory early (optional) |
+| `new MarkkitTool(options?)` | `MarkkitTool` | LLM agent tool, see below |
+
+`hint` is `{ contentType?, fileName? }`; detection uses the content type, then
+the file extension, then magic bytes. Methods are synchronous; run them in a
+Web Worker to keep a page responsive on large files.
+
+`Extraction` is `{ markdown, title, format, warnings, stats, metadata, layout? }`.
+`warnings` are `{ code, detail }` with stable codes such as `truncated_sheet`.
+`metadata` holds HTML `description`, `author`, `published`, `language`,
+`canonicalUrl`, `siteName` and `image`.
+
## Options
-`maxInputSize`, `maxOutputSize`, `maxNodes`, `maxNestingDepth`, `baseUrl`, `mainContent`, `preserveLinks`, `preserveImages`, `includeSelectors`,
-`excludeSelectors` (added to the defaults), `maxArchiveEntries`,
-`maxArchiveEntrySize`, `maxArchiveTotalSize`, `maxSheetRows`, `maxSheetCols`,
-`maxSpreadsheetCells`, `includeHiddenSheets`. Unknown keys throw. There is no
-`timeout`: wasm has no clock, so bound time in the host (e.g. a Worker timeout).
+| Option | Default | Meaning |
+|---|---|---|
+| `mainContent` | `false` | Keep only the detected article body of HTML |
+| `includeSelectors` / `excludeSelectors` | `[]` | CSS selectors to keep / drop (drops add to nav/footer/script/...) |
+| `baseUrl` | none | Base for relative links and images |
+| `preserveLinks` / `preserveImages` | `true` | Keep `[text](url)` / `` |
+| `includeHiddenSheets` | `false` | Render hidden spreadsheet sheets |
+| `pdfLayout` | `false` | Add PDF `layout` geometry |
+| `pdfRemoveRepeatedHeaders` | `false` | Drop running PDF headers/footers |
+| `maxInputSize` | 50 MiB | Input bytes |
+| `maxOutputSize` | 128 MiB | Markdown output bytes |
+| `maxNodes` | 5 000 000 | Parsed nodes, retained PDF geometry |
+| `maxNestingDepth` | 256 | Element nesting (hard max 512) |
+| `maxArchiveEntries` | 10 000 | ZIP entries |
+| `maxArchiveEntrySize` / `maxArchiveTotalSize` | 64 / 256 MiB | Decompressed ZIP bytes |
+| `maxSheetRows` / `maxSheetCols` | 10 000 / 256 | Rendered per sheet (truncated with a warning) |
+| `maxSpreadsheetCells` | 4 000 000 | XLS/ODS grid before parsing |
+| `maxPdfPages` | 10 000 | PDF pages (truncated with a warning) |
+| `maxPdfStreamSize` / `maxPdfDecodedSize` | 64 / 256 MiB | Decoded PDF bytes |
+
+Unknown keys throw. There is no `timeout`: WebAssembly has no clock here, so
+bound time in the host (a Worker timeout, an edge CPU limit, or
+`worker.terminate()`). Failures throw an `Error` whose message names the
+cause, for example `Resource limit exceeded: output exceeds max_output_size 8`.
## Agent tool
-`MarkkitTool` follows the Everruns toolkit contract: tool definition, schemas,
-system prompt and a validated `execute`. Sources are `html` or `content_base64`.
+`MarkkitTool` follows the Everruns toolkit contract: name, descriptions, input
+and output JSON schemas, a system prompt, an OpenAI-compatible tool definition
+and a validated `execute`. Sources are `html` or `content_base64` (with an
+optional `file_name` / `content_type`).
```js
import { initMarkkit, MarkkitTool } from "@everruns/markkit-wasm";
@@ -55,6 +125,7 @@ await initMarkkit();
const tool = new MarkkitTool({ maxOutputChars: 20000 });
const tools = [tool.toolDefinition()]; // send with the model request
+const system = tool.systemPrompt();
try {
const result = await tool.execute({ html: "
Title
" });
@@ -64,29 +135,25 @@ try {
}
```
-## License
+## PDF layout
-MIT. See [LICENSE](https://github.com/everruns/markkit/blob/main/LICENSE); third-party notices in
-[NOTICE](https://github.com/everruns/markkit/blob/main/NOTICE).
+`pdfLayout: true` adds `layout: { version: 1, pages }` to PDF results. Each
+page has source `spans` (text runs with `bbox`, `baseline`, `font`, `size`,
+`words`) and semantic `blocks` in reading order (`kind`, `bbox`, `spanIds`,
+`lines`, table `cells` with row/column spans). Coordinates are points from the
+page's top-left, x right and y down. Layout never changes the Markdown.
-## PDF layout and tables
+PDF extraction rebuilds reading order, columns and tables from the text layer.
+OCR for scanned pages runs only in the native Rust, Node.js and Python
+packages. See the [PDF guide](https://github.com/everruns/markkit/blob/main/docs/pdf.md).
-PDF text extraction reconstructs columns, ruled and conservative borderless tables,
-including merged and wrapped cells. Tagged headings/ActualText, bold/italic and
-numbered lists are preserved. Set `pdfRemoveRepeatedHeaders: true` to suppress
-repeated margin headers/footers.
+## Example
-`pdfLayout: true` adds `layout: { version: 1, pages }` to document results. Source
-`spans` retain drawing order and include glyph-positioned `words`. Semantic `blocks`
-are in reading order, with `id`, `kind`, `bbox`, `spanIds`, `lines` and table `cells`.
-Cells have row/column positions, rowspan/colspan and source references. Coordinates
-are display points from the cropped/rotated top-left, x right and y down. Font
-bounds approximate an em box. Layout is optional and does not change Markdown.
+[`examples/wasm/quickstart.mjs`](https://github.com/everruns/markkit/blob/main/examples/wasm/quickstart.mjs)
+converts HTML, DOCX, XLSX and PDF and runs the agent tool; it runs in CI
+against the freshly built package.
-Node and WASM use camelCase keys. `maxNodes` bounds primitives and geometry;
-`maxPdfDecodedSize` bounds retained geometry and analysis work; table row/column/
-grid limits apply. `maxOutputSize` independently bounds compact layout JSON and
-Markdown, excluding JSON wrapper/pretty-print overhead.
+## License
-WASM reads existing PDF text layers. Native process OCR runs through the Rust,
-Node or Python packages with installed Tesseract and language data.
+MIT. See [LICENSE](https://github.com/everruns/markkit/blob/main/LICENSE); third-party notices are in
+[NOTICE](https://github.com/everruns/markkit/blob/main/NOTICE).
diff --git a/crates/markkit-wasm/js/index.d.ts b/crates/markkit-wasm/js/index.d.ts
index 915e9ce..42fa8ea 100644
--- a/crates/markkit-wasm/js/index.d.ts
+++ b/crates/markkit-wasm/js/index.d.ts
@@ -22,22 +22,35 @@ export interface MarkkitOptions {
mainContent?: boolean;
/** Include PDF source geometry in extractDocument results. */
pdfLayout?: boolean;
+ /** Drop margin headers/footers repeated across PDF pages (default false). */
pdfRemoveRepeatedHeaders?: boolean;
+ /** PDF pages rendered; later pages are truncated with a warning (default 10 000). */
maxPdfPages?: number;
+ /** Decoded bytes per PDF stream (default 64 MiB). */
maxPdfStreamSize?: number;
+ /** Decoded PDF bytes in total, also bounds layout geometry (default 256 MiB). */
maxPdfDecodedSize?: number;
+ /** Keep link URLs as `[text](url)` (default true); false keeps the text only. */
preserveLinks?: boolean;
+ /** Keep images as `` (default true); false drops them. */
preserveImages?: boolean;
/** CSS selectors to include (empty = whole document). */
includeSelectors?: string[];
/** CSS selectors to drop, added to nav/footer/header/script/style/noscript. */
excludeSelectors?: string[];
+ /** Maximum ZIP entries in DOCX/XLSX containers (default 10 000). */
maxArchiveEntries?: number;
+ /** Maximum decompressed bytes per ZIP entry (default 64 MiB). */
maxArchiveEntrySize?: number;
+ /** Maximum decompressed bytes per ZIP container (default 256 MiB). */
maxArchiveTotalSize?: number;
+ /** Rows rendered per sheet; extra rows are truncated with a warning (default 10 000). */
maxSheetRows?: number;
+ /** Columns rendered per sheet; extra columns are truncated with a warning (default 256). */
maxSheetCols?: number;
+ /** Maximum XLS/ODS grid cells before parsing (default 4 000 000). */
maxSpreadsheetCells?: number;
+ /** Render hidden and very hidden sheets (default false: skipped with a warning). */
includeHiddenSheets?: boolean;
}
@@ -119,11 +132,25 @@ export interface PdfBlock {
cells?:{row:number;column:number;rowspan:number;colspan:number;bbox:[number,number,number,number];spanIds:number[]}[];
}
+/**
+ * Extractor with fixed options; create once and reuse. Methods are synchronous
+ * and throw an `Error` naming the cause (exceeded limit, unsupported format,
+ * parse failure). Unknown option keys throw in the constructor.
+ */
export class Markkit {
constructor(options?: MarkkitOptions);
+ /** Convert an HTML string to Markdown. */
extractHtml(html: string): string;
+ /**
+ * Convert document bytes (HTML, PDF, DOCX, XLSX/XLSM/XLSB/XLS/ODS, CSV/TSV,
+ * ipynb, Markdown, text) to Markdown plus title, format, warnings, stats and
+ * metadata. Format detection: `hint.contentType`, then `hint.fileName`'s
+ * extension, then magic bytes.
+ */
extractDocument(bytes: Uint8Array, hint?: DocumentHint): Extraction;
+ /** Convert bytes to Markdown only, detected from `contentType` and the bytes. */
extractBytes(bytes: Uint8Array, contentType?: string): string;
+ /** Release the wasm memory now instead of on garbage collection. */
free(): void;
}
diff --git a/crates/markkit/Cargo.toml b/crates/markkit/Cargo.toml
index 3a49378..2fd8f9a 100644
--- a/crates/markkit/Cargo.toml
+++ b/crates/markkit/Cargo.toml
@@ -12,6 +12,15 @@ keywords.workspace = true
categories.workspace = true
description = "Extract clean markdown from any format – HTML, PDF, DOCX, and more"
readme = "../../README.md"
+documentation = "https://docs.rs/markkit"
+homepage = "https://github.com/everruns/markkit"
+
+# docs.rs documents every public API, with "Available on crate feature ..."
+# badges (doc_cfg, nightly-only, so gated on the `docsrs` cfg docs.rs sets).
+# pdf-ocr-ocrs is left out: same public API as pdf-ocr, heavy native ML deps.
+[package.metadata.docs.rs]
+features = ["all_formats", "pdf-ocr", "http_client", "tool", "json-schema"]
+rustdoc-args = ["--cfg", "docsrs"]
[features]
default = ["html"]
@@ -132,6 +141,26 @@ name = "transforms"
path = "../../examples/transforms.rs"
required-features = ["html"]
+[[example]]
+name = "documents"
+path = "../../examples/documents.rs"
+required-features = ["html"]
+
+[[example]]
+name = "main_content"
+path = "../../examples/main_content.rs"
+required-features = ["html"]
+
+[[example]]
+name = "limits"
+path = "../../examples/limits.rs"
+required-features = ["html"]
+
+[[example]]
+name = "convert"
+path = "../../examples/convert.rs"
+required-features = ["docx", "spreadsheet", "pdf"]
+
[[bench]]
name = "extraction"
harness = false
diff --git a/crates/markkit/src/lib.rs b/crates/markkit/src/lib.rs
index b69b174..959f67e 100644
--- a/crates/markkit/src/lib.rs
+++ b/crates/markkit/src/lib.rs
@@ -1,58 +1,155 @@
//! # Markkit
//!
-//! Extract clean markdown from any format.
+//! Extract clean Markdown from any document format, safely.
//!
-//! Markkit is a Rust library for converting HTML, PDF, DOCX, spreadsheets,
-//! and other document formats into clean, well-structured markdown.
+//! Markkit converts HTML, PDF, Word, PowerPoint, spreadsheets, e-books, email,
+//! notebooks and plain-text formats into well-structured Markdown for LLMs and
+//! agents. Every input is treated as untrusted: nothing is executed, every
+//! resource an input can drive is bounded ([`Limits`]), and the default build
+//! has no network stack.
//!
-//! ## Quick Start
+//! The same engine ships as a CLI (`markkit-cli`), Python (`pip install
+//! markkit`), Node.js (`@everruns/markkit`) and WebAssembly
+//! (`@everruns/markkit-wasm`) packages.
//!
-//! ```rust,no_run
-//! use markkit::{DocumentHint, Markkit};
+//! ## Quick start
+//!
+//! ```rust
+//! # #[cfg(feature = "html")] {
+//! use markkit::Markkit;
+//!
+//! let markkit = Markkit::builder().build();
+//! let md = markkit.extract_html_sync("
Hello
World
")?;
+//! assert_eq!(md, "# Hello\n\nWorld\n");
+//! # }
+//! # Ok::<(), markkit::Error>(())
+//! ```
+//!
+//! ## Any format from bytes
+//!
+//! [`Markkit::extract_document_sync`] takes bytes plus an optional
+//! [`DocumentHint`]. The format is detected from the content type, then the
+//! file extension, then magic bytes. The [`Extraction`] carries Markdown,
+//! title, [`Format`], structured [`Warning`]s, [`ExtractionStats`] and HTML
+//! [`Metadata`].
+//!
+//! ```rust
+//! use markkit::{DocumentHint, Format, Markkit};
//!
-//! # async fn example() -> anyhow::Result<()> {
//! let markkit = Markkit::builder().build();
+//! let csv = b"name,stars\nmarkkit,1200\n";
+//! let doc = markkit.extract_document_sync(csv, DocumentHint::file_name("repos.csv"))?;
+//! assert_eq!(doc.format, Format::Csv);
+//! assert!(doc.markdown.contains("| markkit | 1200 |"));
+//!
+//! // Office files work the same way once their feature is enabled:
+//! // let doc = markkit.extract_document_sync(&std::fs::read("report.docx")?,
+//! // DocumentHint::file_name("report.docx"))?;
+//! # Ok::<(), markkit::Error>(())
+//! ```
+//!
+//! Extraction is CPU-bound. The `*_sync` methods are the primitive; the async
+//! methods ([`Markkit::extract_html`], [`Markkit::extract_document`]) run the
+//! same work inline. In async servers call the sync variant from
+//! `tokio::task::spawn_blocking`.
//!
-//! // Extract markdown from HTML
-//! let md = markkit.extract_html("
Hello
World
").await?;
+//! ## Configuration
//!
-//! // Convert any supported document from bytes (format detected from the
-//! // content type, then the file extension, then magic bytes).
-//! let bytes = std::fs::read("report.docx")?;
-//! let doc = markkit.extract_document_sync(&bytes, DocumentHint::file_name("report.docx"))?;
-//! println!("{} ({}): {}", doc.title.unwrap_or_default(), doc.format, doc.markdown);
+//! [`Markkit::builder`] returns a [`MarkkitBuilder`]. A built [`Markkit`] is
+//! immutable, cheap to share across threads, and reusable for many calls.
//!
-//! // Extract from a URL (requires the `http_client` feature)
-//! #[cfg(feature = "http_client")]
-//! let md = markkit.extract_url("https://example.com").await?;
-//! # Ok(())
+//! ```rust
+//! # #[cfg(feature = "html")] {
+//! use markkit::Markkit;
+//!
+//! let markkit = Markkit::builder()
+//! .main_content(true) // keep the article, drop sidebars/comments
+//! .base_url("https://example.com/blog/") // resolve relative links and images
+//! .include_selector("article") // CSS selectors to keep...
+//! .exclude_selector(".newsletter-signup") // ...and to drop
+//! .preserve_images(false)
+//! .build();
+//! let md = markkit.extract_html_sync(
+//! r#"
"#,
+//! )?;
+//! assert_eq!(md, "# Post\n\n[Next](https://example.com/blog/next)\n");
//! # }
+//! # Ok::<(), markkit::Error>(())
//! ```
//!
-//! ## Features
-//!
-//! - **HTML** (`html`, default): Convert HTML to markdown with configurable rules
-//! - **DOCX** (`docx`): Convert Word documents
-//! - **PPTX** (`pptx`): Convert PowerPoint presentations, one section per slide
-//! - **Spreadsheet** (`spreadsheet`): Convert XLSX/XLSM, XLSB, XLS and ODS workbooks to tables
-//! - **Plain text** (always on): `text/plain`, `.txt`
-//! - **EPUB** (`epub`, implies `html`): e-books, chapters in reading order
-//! - **ODT** (`odt`): OpenDocument text documents
-//! - **Email** (`email`): `.eml` / `message/rfc822`, headers, body and attachment list
-//! - **Jupyter notebooks** (always on): `.ipynb`, cells and text outputs
-//! - **CSV / TSV** (always on): `text/csv`, `text/tab-separated-values`, `.csv`, `.tsv`, one table
-//! - **Markdown** (`markdown`): `text/markdown`, `.md`, normalized through the IR
-//! - **PDF** (`pdf`): Text, layout and tables; optional native OCR (`pdf-ocr`)
-//! uses Rust Hayro rendering and installed Tesseract. Encrypted PDFs are
-//! rejected with [`Error::UnsupportedFormat`]
-//! - **URL fetching** (`http_client`, opt-in): Fetch and extract from URLs via reqwest
-//! - **Agent tool** (`tool`): `markkit::tool::MarkkitTool`, an LLM tool following the
-//! Everruns toolkit-library contract (schemas, OpenAI definition, `tower::Service`)
-//! - **JSON Schema** (`json-schema`): `ir::json_schema()` for the serialized IR
-//!
-//! The default build has no network stack; enable `http_client` for
-//! `Markkit::extract_url`. Office formats only, no HTML:
-//! `markkit = { version = "0.1", default-features = false, features = ["docx", "spreadsheet"] }`.
+//! ## Resource limits and errors
+//!
+//! Defaults are generous (50 MiB in, 128 MiB out, 60 s, 5 M nodes, ...).
+//! Breaches return [`Error::ResourceLimit`]; [`Error::limit_kind`] names the
+//! exceeded [`LimitKind`].
+//!
+//! ```rust
+//! use std::time::Duration;
+//! use markkit::{DocumentHint, LimitKind, Limits, Markkit};
+//!
+//! let markkit = Markkit::builder()
+//! .limits(Limits::default().max_output_size(16).timeout(Duration::from_secs(5)))
+//! .build();
+//! let csv = b"city,population\nKyiv,2952301\nLviv,717273\n";
+//! let err = markkit.extract_document_sync(csv, DocumentHint::file_name("cities.csv")).unwrap_err();
+//! assert_eq!(err.limit_kind(), Some(LimitKind::MaxOutputSize));
+//! ```
+//!
+//! ## Pipeline: parse, transform, render
+//!
+//! Every format parses into one intermediate representation ([`ir::Document`]),
+//! optional [`transform`] passes rewrite it, and [`MarkdownRenderer`] renders
+//! it. Use [`Markkit::parse_document_sync`] (or [`Markkit::parse_html`]) to
+//! inspect or chunk the IR yourself; with
+//! [`track_sources(true)`](MarkkitBuilder::track_sources) each block carries a
+//! [`ir::Source`] (HTML XPath, DOCX block index, sheet and cell range, PDF page).
+//! Custom formats plug in through [`registry::FormatParser`], site-specific HTML
+//! markup through [`rules`].
+//!
+//! ## Cargo features
+//!
+//! | Feature | Default | Adds |
+//! |---|---|---|
+//! | `html` | yes | HTML / XHTML |
+//! | `pdf` | | PDF text, reading order, columns and tables (pure Rust); encrypted PDFs are rejected |
+//! | `pdf-ocr` | | OCR of textless PDF pages: Hayro rendering + installed Tesseract |
+//! | `pdf-ocr-ocrs` | | Rust OCR backend with caller-supplied local ONNX models |
+//! | `docx` | | Word `.docx` |
+//! | `pptx` | | PowerPoint `.pptx`, one section per slide |
+//! | `spreadsheet` | | XLSX/XLSM, XLSB, XLS, ODS, one table per sheet |
+//! | `odt` | | OpenDocument text |
+//! | `epub` | | EPUB e-books (implies `html`) |
+//! | `email` | | `.eml` / `message/rfc822` |
+//! | `markdown` | | Markdown normalized through the IR |
+//! | `all_formats` | | All format features above except OCR |
+//! | `http_client` | | [`Markkit::extract_url`] with SSRF protection (reqwest) |
+//! | `tool` | | `tool::MarkkitTool`, an LLM agent tool (Everruns toolkit contract) |
+//! | `json-schema` | | `ir::json_schema()` for the serialized IR |
+//!
+//! Plain text, CSV/TSV and Jupyter notebooks are always available. Legacy
+//! `.doc` and `.ppt` are detected and rejected with [`Error::UnsupportedFormat`].
+//! Office formats only, no HTML, no network:
+//! `markkit = { version = "0.3", default-features = false, features = ["docx", "spreadsheet"] }`.
+//!
+//! ## Examples
+//!
+//! Runnable examples live in
+//! [`examples/`](https://github.com/everruns/markkit/tree/main/examples):
+//! `cargo run -p markkit --example basic`, `documents`, `main_content`,
+//! `limits`, `configuration`, `custom_selectors`, `ir_access`, `transforms`,
+//! `agent_tool` (`--features tool`) and `convert` (`--features all_formats`,
+//! converts DOCX, XLSX and PDF samples or your own files).
+//!
+//! ## Security
+//!
+//! Scripts, macros and formulas are never executed; XML entities are never
+//! expanded; archives and PDF streams are decompressed under measured byte
+//! limits; hidden content (a prompt-injection vector) is dropped by default;
+//! `extract_url` refuses private, loopback and metadata addresses on every
+//! redirect. See the
+//! [threat model](https://github.com/everruns/markkit/blob/main/knowledge/security/threat-model.md).
+
+#![cfg_attr(docsrs, feature(doc_cfg))]
#[cfg(any(
feature = "docx",
@@ -110,6 +207,19 @@ pub mod transform;
#[cfg_attr(not(feature = "docx"), allow(dead_code))] // DOCX uses every helper
mod xml;
+// Compile and run the Rust snippets in the user docs as doctests, so the
+// README and guides cannot drift from the API. Never part of a normal build.
+// The README and guide examples use HTML, so they need the `html` feature.
+#[cfg(all(doctest, feature = "html"))]
+#[doc = include_str!("../../../README.md")]
+struct ReadmeDoctests;
+#[cfg(all(doctest, feature = "html"))]
+#[doc = include_str!("../../../docs/getting-started.md")]
+struct GettingStartedDoctests;
+#[cfg(doctest)]
+#[doc = include_str!("../../../docs/pdf.md")]
+struct PdfGuideDoctests;
+
pub use config::{MarkkitBuilder, PdfOcrBackend};
pub use error::Error;
pub use extract::{
diff --git a/docs/getting-started.md b/docs/getting-started.md
index f96717c..e52dfdc 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -1,125 +1,225 @@
-# Getting Started with Markkit
+# Getting started with Markkit
-## Installation
+This guide takes you from installation to production configuration in Rust.
+Every Rust snippet below is compiled as a doctest, so it matches the current
+API. For Python, Node.js and WebAssembly, see the
+[Python](../crates/markkit-python/README.md),
+[Node.js](../crates/markkit-js/README.md) and
+[WASM](../crates/markkit-wasm/README.md) READMEs.
-Add markkit to your `Cargo.toml`:
+## 1. Install
```toml
[dependencies]
-markkit = "0.1"
+markkit = "0.3" # HTML only, no network stack
```
-For PDF, DOCX, PPTX and spreadsheets:
+Enable the formats you need:
```toml
[dependencies]
-markkit = { version = "0.1", features = ["pdf", "docx", "pptx", "spreadsheet"] }
+markkit = { version = "0.3", features = ["pdf", "docx", "pptx", "spreadsheet"] }
+# or everything: features = ["all_formats", "http_client"]
```
-## Basic Usage
+Plain text, CSV/TSV and Jupyter notebooks are always available. See the
+[feature table](../README.md#cargo-features).
+
+## 2. Extract HTML
```rust
use markkit::Markkit;
-#[tokio::main]
-async fn main() -> anyhow::Result<()> {
- let markkit = Markkit::builder().build();
+let markkit = Markkit::builder().build();
+let html = r#"
Title
Some content here.
"#;
+let markdown = markkit.extract_html_sync(html).unwrap();
+assert_eq!(markdown, "# Title\n\nSome *content* here.\n");
+```
+
+Navigation, headers, footers, scripts, styles and forms are stripped by
+default. `Markkit` is immutable after `build()`: create one and reuse it for
+every call, from any thread.
+
+## 3. Convert any document from bytes
- // Extract from HTML
- let html = "
Title
Some content here.
";
- let markdown = markkit.extract_html(html).await?;
- println!("{markdown}");
+`extract_document_sync` detects the format from the content type, then the
+file extension, then magic bytes, and returns an `Extraction`.
- // Extract from a URL
- let markdown = markkit.extract_url("https://example.com").await?;
- println!("{markdown}");
+```rust
+use markkit::{DocumentHint, Markkit};
+fn convert(path: &str) -> Result<(), Box> {
+ let markkit = Markkit::builder().build();
+ let bytes = std::fs::read(path)?;
+ let doc = markkit.extract_document_sync(&bytes, DocumentHint::file_name(path))?;
+
+ println!("format: {}", doc.format); // docx, pdf, xlsx, html, ...
+ println!("title: {:?}", doc.title);
+ println!("stats: {:?}", doc.stats); // pages, sheets, rows, paragraphs, tables
+ for w in &doc.warnings {
+ println!("warning {}: {}", w.code, w.detail); // e.g. truncated_sheet
+ }
+ println!("{}", doc.markdown);
Ok(())
}
```
-## Documents from bytes
+When the bytes come from an HTTP response, pass the content type too:
+`DocumentHint { content_type: Some("application/pdf"), file_name: Some("a.pdf") }`.
+For HTML, `doc.metadata` holds the description, author, published date,
+language, canonical URL, site name and lead image (from ``, Open Graph
+and JSON-LD).
+
+Try it: `cargo run -p markkit --features all_formats --example convert -- your-file.docx`.
+
+## 4. Async code
+
+Extraction is CPU-bound. The `*_sync` methods are the primitive. In an async
+server, run them on the blocking pool:
+
+```rust
+use markkit::{DocumentHint, Extraction, Markkit};
+use std::sync::Arc;
+
+async fn handle_upload(markkit: Arc, bytes: Vec, name: String) -> Extraction {
+ tokio::task::spawn_blocking(move || {
+ markkit.extract_document_sync(&bytes, DocumentHint::file_name(&name))
+ })
+ .await
+ .expect("extraction task panicked")
+ .expect("extraction failed")
+}
+```
+
+`extract_html(..).await`, `extract_document(..).await` and, with the
+`http_client` feature, `extract_url(..).await` are also available.
+
+## 5. Web pages: main content, selectors, links
```rust
-use markkit::{DocumentHint, Markkit};
+use markkit::Markkit;
-let markkit = Markkit::builder().build();
-let bytes = std::fs::read("report.docx")?;
-let hint = DocumentHint { content_type: None, file_name: Some("report.docx") };
-let doc = markkit.extract_document_sync(&bytes, hint)?;
-println!("{}", doc.markdown);
+let markkit = Markkit::builder()
+ .main_content(true) // keep the article, drop sidebars, comments, share bars
+ .exclude_selector(".newsletter-signup") // drop more, on top of the defaults
+ .base_url("https://example.com/blog/") // resolve relative links and images
+ .build();
+let md = markkit
+ .extract_html_sync(r#"
"#)
+ .unwrap();
+assert_eq!(md, "# Post\n\nSee [next](https://example.com/blog/next).\n");
+```
+
+`include_selector("article")` keeps only matching elements. For site-specific
+markup, `html_rule` maps selectors to IR nodes (callouts, skips, ...); see
+[`markkit::rules`](https://docs.rs/markkit/latest/markkit/rules/).
+
+## 6. Fetch URLs
+
+With the `http_client` feature:
+
+```rust
+#[cfg(feature = "http_client")]
+async fn fetch() -> markkit::Result {
+ let markkit = markkit::Markkit::builder()
+ .allow_host("docs.example.com") // optional allowlist, checked on every redirect
+ .build();
+ markkit.extract_url("https://docs.example.com/guide").await
+}
```
-## PDF source layout
+Only http and https are accepted. Loopback, private, link-local and
+cloud-metadata addresses are refused, also after DNS resolution and on every
+redirect. Opt in to internal hosts with `allow_private_networks(true)` only
+for trusted URLs.
-Enable optional positioned text output with `Markkit::builder().pdf_layout(true)`.
-The parse/extraction result has a `layout` sidecar: page dimensions and text runs
-with approximate bounding boxes, baselines, font names, sizes and angles. Coordinates
-are display points from the cropped/rotated page top-left (x right, y down).
-Layout is optional and does not change Markdown; source runs retain drawing order.
-Semantic blocks/lines/table cells are in reading order and link to IR provenance.
-PDF extraction reconstructs columns and ruled/borderless tables. Native OCR is
-opt-in with the `pdf-ocr` feature and installed Tesseract and language data.
+## 7. Limits and errors
+
+Every resource a document can drive is bounded by `markkit::Limits`, with
+generous defaults. Tighten them for multi-tenant services:
+
+```rust
+use std::time::Duration;
+use markkit::{Error, LimitKind, Limits, Markkit};
+
+let markkit = Markkit::builder()
+ .limits(
+ Limits::default()
+ .max_input_size(10 << 20) // 10 MiB in
+ .max_output_size(1 << 20) // 1 MiB of Markdown out
+ .timeout(Duration::from_secs(10)),
+ )
+ .build();
-```bash
-markkit extract --file report.pdf --json --layout
-markkit extract --file scanned.pdf --ocr --ocr-language eng --timeout 300
+match markkit.extract_html_sync(&"
word
".repeat(200_000)) {
+ Ok(md) => println!("{md}"),
+ Err(err @ Error::ResourceLimit(_)) => {
+ assert_eq!(err.limit_kind(), Some(LimitKind::MaxOutputSize));
+ }
+ Err(err) => panic!("unexpected error: {err}"),
+}
```
-## IR and provenance
+Other errors: `Error::UnsupportedFormat` (legacy `.doc`/`.ppt`, encrypted
+PDF, disabled feature), per-format parse errors (`Error::DocxExtract`, ...),
+`Error::UrlBlocked` and `Error::Http`. The same limits are CLI flags
+(`markkit extract --help`), `markkit.Limits(...)` in Python, and flat option
+keys in Node.js and WASM. Runnable: `cargo run -p markkit --example limits`.
+
+## 8. IR, provenance and transforms
-`parse_document_sync` returns the IR (`markkit::ir::Document`) plus metadata instead of
-Markdown. With `track_sources(true)` every block carries a `Source`: the element XPath
-for HTML, the body block index for DOCX, the sheet and A1 range for spreadsheets. Use it
-to cite where a chunk came from.
+Every format parses into one intermediate representation, `markkit::ir::Document`.
+`parse_document_sync` returns it instead of Markdown. With
+`track_sources(true)`, each block carries a `Source`: the element XPath for
+HTML, the body block index for DOCX, the sheet and A1 range for
+spreadsheets, the page and layout block for PDF. Use it to cite where a chunk
+came from.
```rust
+use markkit::{DocumentHint, Markkit};
+
let markkit = Markkit::builder().track_sources(true).build();
-let parsed = markkit.parse_document_sync(&bytes, hint)?;
+let parsed = markkit
+ .parse_document_sync(b"
").unwrap();
+assert_eq!(md, "# Section\n\n## Sub\n");
```
-Every resource an input can drive (input/output size, time, nesting, node count,
-archives, spreadsheets, redirects) is bounded by `markkit::Limits` with generous
-defaults. The same limits are available as CLI flags (`markkit extract --help`,
-"Limits" section), as `markkit.Limits(...)` in Python and as flat option keys in
-Node.js and WASM.
+See `cargo run -p markkit --example ir_access` and `--example transforms`,
+and the [IR specification](../knowledge/foundations/ir.md).
-## Next Steps
+## 9. PDF
-- [HTML extraction](../knowledge/formats/html-extraction.md): element mapping and stripping rules
-- [Format support](../knowledge/formats/format-support.md): formats, detection, DOCX, spreadsheet and PDF mapping
-- [Threat model](../knowledge/security/threat-model.md): security boundaries and limits
-- [Examples](../examples/): runnable with `cargo run -p markkit --example `
+PDF text, columns and tables work out of the box with the `pdf` feature.
+Layout geometry and OCR for scanned pages are opt-in: see the
+[PDF guide](pdf.md).
-### Optional Rust OCR
+## Output notes
-Build the CLI with `--features pdf-ocr-ocrs`, run
-`python3 scripts/prepare_ocr_models.py`, then select `--ocr --ocr-backend ocrs`
-with `--ocr-detection-model target/ocr-models/text-detection.onnx` and
-`--ocr-recognition-model target/ocr-models/text-recognition.onnx`.
-The default engine remains Tesseract. Extraction is offline; model weights are
-separate CC-BY-SA 4.0 assets and support Latin-alphabet text (`eng`).
-See the [PDF OCR guide](../README.md#pdf-source-layout) for Rust configuration,
-model attribution and resource-limit behavior.
+Task-list bodies render below their checkbox marker. HTML definition lists
+render as a term paragraph followed by an unordered list of definitions. Both
+keep nested code blocks and their literal text safe when the output is
+rendered by a GFM reader; no definition-list extension is required.
-## Lists and code blocks
+## Next steps
-Task-list bodies render below their checkbox marker. HTML definition lists render
-as a term paragraph followed by an unordered list of definitions. Both forms keep
-nested code blocks and their literal text safe when the output is rendered by a
-GFM reader; no definition-list extension is required.
+- [Examples](../examples/README.md): runnable Rust, Python, Node.js and WASM programs
+- [API reference](https://docs.rs/markkit)
+- [HTML extraction](../knowledge/formats/html-extraction.md): element mapping and stripping rules
+- [Format support](../knowledge/formats/format-support.md): detection and per-format mapping
+- [Threat model](../knowledge/security/threat-model.md): security boundaries and limits
diff --git a/docs/pdf.md b/docs/pdf.md
new file mode 100644
index 0000000..2693600
--- /dev/null
+++ b/docs/pdf.md
@@ -0,0 +1,156 @@
+# PDF guide
+
+Markkit's `pdf` feature extracts the text layer of PDF files with a pure-Rust
+parser (Hayro). This guide covers what it reconstructs, the optional layout
+geometry, OCR for scanned pages, and the limits that bound it. The Python,
+Node.js and CLI packages include PDF and OCR support. The WASM package reads
+text layers and layout, but has no OCR.
+
+## Text, reading order and tables
+
+PDF pages are positioned glyphs, not paragraphs. Markkit rebuilds:
+
+- **Reading order** across columns
+- **Tables**: ruled and conservative borderless tables, including merged and
+ wrapped cells. Ambiguous alignments stay prose instead of becoming false
+ tables.
+- **Emphasis and lists**: bold, italic and numbered lists
+- **Headings** from tagged-PDF roles, and `ActualText` replacements
+- **Repeated headers and footers** (opt-in): running margin text repeated on
+ every page is dropped
+
+| Surface | Remove repeated headers |
+|---|---|
+| Rust | `Markkit::builder().pdf_remove_repeated_headers(true)` |
+| CLI | `markkit extract --file report.pdf --remove-pdf-headers` |
+| Python | `extract_document_sync(data, file_name="report.pdf", pdf_remove_repeated_headers=True)` |
+| Node.js / WASM | `{ pdfRemoveRepeatedHeaders: true }` |
+
+Encrypted PDFs are rejected with `Error::UnsupportedFormat`. A page without a
+text layer produces a `pdf_no_text` warning, unless OCR is enabled.
+
+## Layout geometry
+
+Layout is an optional sidecar for citation, highlighting and custom chunking.
+It never changes the Markdown.
+
+```rust
+use markkit::{DocumentHint, Markkit};
+
+fn page_geometry(pdf_bytes: &[u8]) -> markkit::Result<()> {
+ let markkit = Markkit::builder().pdf_layout(true).build();
+ let doc = markkit.extract_document_sync(pdf_bytes, DocumentHint::file_name("report.pdf"))?;
+ let layout = doc.layout.as_ref().expect("PDF input with pdf_layout(true)");
+ for page in &layout.pages {
+ println!("page {}: {}x{} pt", page.page, page.width, page.height);
+ for block in &page.blocks {
+ println!(" {} at {:?}", block.kind, block.bbox); // [left, top, right, bottom]
+ }
+ }
+ Ok(())
+}
+```
+
+| Surface | Enable layout |
+|---|---|
+| Rust | `.pdf_layout(true)`, then `Extraction::layout` / `ParsedDocument::layout` |
+| CLI | `markkit extract --file report.pdf --json --layout` |
+| Python | `extract_document_sync(data, file_name="report.pdf", pdf_layout=True)["layout"]` |
+| Node.js | `extractDocumentSync(bytes, { fileName: "report.pdf" }, { pdfLayout: true }).layout` |
+| WASM | `new Markkit({ pdfLayout: true }).extractDocument(bytes, { fileName: "report.pdf" }).layout` |
+
+Layout v1 (`{ version: 1, pages: [...] }`) has, for each page:
+
+- `page`, `width`, `height`, `rotation`
+- `spans`: source text runs in drawing order, with `id`, `text`, `bbox`
+ (`[left, top, right, bottom]`), `baseline`, `font`, `size`, `angle`, `bold`,
+ `italic`, tagged `role`, an `ocr` flag and glyph-positioned `words`
+- `blocks`: semantic blocks in reading order, with `id`, `kind` (`heading`,
+ `paragraph`, `table`, ...), `bbox`, source `span_ids` (`spanIds` in JS),
+ `lines`, and table `cells` with row/column positions, rowspan/colspan and
+ bounds
+
+Coordinates are display points from the cropped and rotated page's top-left
+corner, x right and y down. Font bounds approximate an em box; OCR bounds come
+from the recognizer. With `track_sources(true)`, IR blocks carry
+`Source.page` and `Source.layout_block`, which link Markdown blocks back to
+layout blocks. Python keys are snake_case; Node.js and WASM keys are camelCase.
+
+Try it on the bundled sample: `python examples/python/documents.py` or
+`node examples/node/documents.cjs` print the block geometry of
+`examples/data/sample.pdf`.
+
+## OCR for scanned pages
+
+OCR is opt-in and only processes pages that have no text layer. Pages are
+rendered in Rust (Hayro) and recognized locally. Extraction never downloads
+anything.
+
+### Tesseract (default)
+
+Install Tesseract and the language data you need (for example
+`apt install tesseract-ocr tesseract-ocr-deu`).
+
+```bash
+markkit extract --file scanned.pdf --ocr --ocr-language eng --timeout 300
+```
+
+| Surface | Enable OCR |
+|---|---|
+| Rust | feature `pdf-ocr`; `.pdf_ocr(true).pdf_ocr_language("eng+deu")` |
+| CLI | `--ocr --ocr-language eng` |
+| Python | `extract_document_sync(data, file_name="scan.pdf", pdf_ocr=True, pdf_ocr_language="eng", limits=markkit.Limits(timeout=300))` |
+| Node.js | `{ pdfOcr: true, pdfOcrLanguage: "eng", timeout: 300 }` |
+
+OCR is slow compared to text extraction: raise `timeout` for scanned
+documents. OCR word bounds are included in layout output.
+
+### Rust `ocrs` backend (optional)
+
+For deployments without Tesseract, build with the `pdf-ocr-ocrs` feature and
+supply local ONNX models. Default packages keep Tesseract.
+
+```bash
+python3 scripts/prepare_ocr_models.py # fetch pinned weights, verify sizes and SHA-256
+cargo build --release -p markkit-cli --features pdf-ocr-ocrs
+target/release/markkit extract --file scanned.pdf --ocr --ocr-backend ocrs \
+ --ocr-detection-model target/ocr-models/text-detection.onnx \
+ --ocr-recognition-model target/ocr-models/text-recognition.onnx --timeout 300
+```
+
+Rust: `.pdf_ocr_backend(markkit::PdfOcrBackend::Ocrs)` plus
+`.pdf_ocr_detection_model(path)` and `.pdf_ocr_recognition_model(path)`.
+Python and Node.js source builds accept the same settings
+(`pdf_ocr_backend="ocrs"` / `pdfOcrBackend: "ocrs"` and model paths).
+
+The pinned weights are CC-BY-SA 4.0, separate from Markkit's MIT code. The
+setup script writes their attribution and license to
+`target/ocr-models/NOTICE.json`. The default model supports the Latin
+alphabet, and `ocrs` currently accepts `eng` only. Models are trusted
+deployment assets. `RTEN_NUM_THREADS` and `RAYON_NUM_THREADS` size the
+inference thread pools at process start.
+
+## Limits
+
+PDF work is bounded like every other format:
+
+| Limit | Default | Bounds |
+|---|---|---|
+| `max_pdf_pages` | 10 000 | Pages rendered; later pages are truncated with a `truncated_pdf` warning |
+| `max_pdf_stream_size` | 64 MiB | Decoded bytes per stream, checked before decoding |
+| `max_pdf_decoded_size` | 256 MiB | Decoded bytes in total, PDF content interpreted, retained geometry and analysis work |
+| `max_nodes` | 5 000 000 | Geometry and rule primitives, retained layout |
+| `max_output_size` | 128 MiB | Markdown and compact layout JSON, each bounded on its own |
+| `timeout` | 60 s | Whole call, including OCR |
+
+Table grids also obey the row, column and grid limits. Hayro checks image and
+raster budgets before rendering, and the deadline before and after its
+non-interruptible render step. Tesseract runs with private temp files, output
+caps and a killable deadline, without a shell. OCR currently supports JPEG,
+JPEG2000 and generic-filter images without DecodeParms. Inline, JBIG2 and CCITT
+images are refused until bounded decoding is available. For hard CPU and
+memory quotas, isolate the host process.
+
+See the [threat model](../knowledge/security/threat-model.md) (T8) and
+[native dependencies](../knowledge/security/native-dependencies.md) for
+provenance and licensing.
diff --git a/examples/README.md b/examples/README.md
new file mode 100644
index 0000000..96e0a1e
--- /dev/null
+++ b/examples/README.md
@@ -0,0 +1,74 @@
+# Examples
+
+Runnable programs for every Markkit surface. They need no network, read only
+inline strings and the sample files in [`data/`](data/), and run in CI on every
+change, so they always match the current API.
+
+## Sample documents
+
+[`data/`](data/) holds a Word report (`report.docx`), a two-sheet workbook
+(`sales.xlsx`) and a one-page PDF (`sample.pdf`). They are tiny, contain no
+macros or external references, and are regenerated byte-for-byte by
+`python3 examples/data/generate.py`.
+
+## Rust
+
+Run from the repository root:
+
+| Example | Command | Shows |
+|---|---|---|
+| [`basic.rs`](basic.rs) | `cargo run -p markkit --example basic` | HTML to Markdown with defaults |
+| [`documents.rs`](documents.rs) | `cargo run -p markkit --example documents` | `extract_document_sync`: format detection, title, metadata, stats, warnings, unsupported formats |
+| [`convert.rs`](convert.rs) | `cargo run -p markkit --features all_formats --example convert [-- FILE...]` | Convert DOCX, XLSX, PDF (or your own files) |
+| [`main_content.rs`](main_content.rs) | `cargo run -p markkit --example main_content` | Article detection, `base_url`, selectors |
+| [`custom_selectors.rs`](custom_selectors.rs) | `cargo run -p markkit --example custom_selectors` | CSS include / exclude selectors |
+| [`configuration.rs`](configuration.rs) | `cargo run -p markkit --example configuration` | How builder options change output |
+| [`limits.rs`](limits.rs) | `cargo run -p markkit --example limits` | `Limits`, `Error::ResourceLimit`, `LimitKind` handling |
+| [`ir_access.rs`](ir_access.rs) | `cargo run -p markkit --example ir_access` | Parse to IR, walk nodes, render separately |
+| [`transforms.rs`](transforms.rs) | `cargo run -p markkit --example transforms` | Built-in and closure IR transforms |
+| [`agent_tool.rs`](agent_tool.rs) | `cargo run -p markkit --features tool --example agent_tool` | LLM tool definition, system prompt, execution |
+
+`just examples` runs them all.
+
+## Python
+
+```bash
+pip install markkit # or, in this repo: maturin develop
+python examples/python/quickstart.py
+```
+
+| Example | Shows |
+|---|---|
+| [`python/quickstart.py`](python/quickstart.py) | HTML, selectors and main content, `asyncio` functions |
+| [`python/documents.py`](python/documents.py) | DOCX, XLSX, PDF with stats and warnings, PDF layout; pass your own files as arguments |
+| [`python/limits.py`](python/limits.py) | `markkit.Limits` and error handling |
+
+## Node.js
+
+```bash
+npm install @everruns/markkit
+node examples/node/quickstart.cjs
+```
+
+Inside this repository, build the binding first
+(`cd crates/markkit-js && npm install && npx napi build --release --platform`)
+and point the examples at it with `MARKKIT_MODULE=$PWD/crates/markkit-js`.
+
+| Example | Shows |
+|---|---|
+| [`node/quickstart.cjs`](node/quickstart.cjs) | HTML sync and async, options, bytes |
+| [`node/documents.cjs`](node/documents.cjs) | DOCX, XLSX, PDF with stats, limits and layout; pass your own files as arguments |
+
+## WebAssembly
+
+```bash
+just wasm # build crates/markkit-wasm/pkg
+node examples/wasm/quickstart.mjs
+```
+
+| Example | Shows |
+|---|---|
+| [`wasm/quickstart.mjs`](wasm/quickstart.mjs) | `initMarkkit`, HTML, DOCX/XLSX/PDF bytes, the agent tool, limit errors |
+
+The same code runs in browsers and edge runtimes; only the file reading
+differs (use `fetch` and `new Uint8Array(await res.arrayBuffer())`).
diff --git a/examples/convert.rs b/examples/convert.rs
new file mode 100644
index 0000000..1804352
--- /dev/null
+++ b/examples/convert.rs
@@ -0,0 +1,55 @@
+// Convert files to Markdown: DOCX, XLSX, PDF and every other enabled format.
+//
+// cargo run -p markkit --features all_formats --example convert
+// cargo run -p markkit --features all_formats --example convert -- path/to/file.pptx
+//
+// With no arguments it converts the bundled samples in examples/data/
+// (a Word report, a two-sheet workbook and a one-page PDF). Pass file paths
+// to convert your own documents; the format is detected from the file name
+// and the bytes. Extraction is CPU-bound and synchronous; in async code call
+// it from `tokio::task::spawn_blocking` or use `extract_document(..).await`.
+
+use std::path::{Path, PathBuf};
+
+use markkit::{DocumentHint, Markkit};
+
+fn main() -> Result<(), Box> {
+ let mut paths: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect();
+ if paths.is_empty() {
+ let data = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples/data");
+ paths = ["report.docx", "sales.xlsx", "sample.pdf"]
+ .iter()
+ .map(|name| data.join(name))
+ .collect();
+ }
+
+ let markkit = Markkit::builder().build();
+ for path in paths {
+ let bytes = std::fs::read(&path)?;
+ let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
+ let doc = markkit.extract_document_sync(&bytes, DocumentHint::file_name(file_name))?;
+
+ println!("=== {file_name} ===");
+ println!("format: {}", doc.format);
+ if let Some(title) = &doc.title {
+ println!("title: {title}");
+ }
+ let stats = &doc.stats;
+ for (label, value) in [
+ ("pages", stats.pages),
+ ("sheets", stats.sheets),
+ ("rows", stats.rows),
+ ("paragraphs", stats.paragraphs),
+ ("tables", stats.tables),
+ ] {
+ if let Some(v) = value {
+ println!("{label}: {v}");
+ }
+ }
+ for w in &doc.warnings {
+ println!("warning [{}]: {}", w.code.as_str(), w.detail);
+ }
+ println!("\n{}", doc.markdown);
+ }
+ Ok(())
+}
diff --git a/examples/data/generate.py b/examples/data/generate.py
new file mode 100644
index 0000000..dff50eb
--- /dev/null
+++ b/examples/data/generate.py
@@ -0,0 +1,225 @@
+#!/usr/bin/env python3
+"""Regenerate the sample documents in examples/data/ (deterministic, stdlib only).
+
+ python3 examples/data/generate.py
+
+The files are tiny, hand-built and contain no macros, scripts or external
+references. Every Rust, Python, Node.js and WASM example reads them, so the
+same inputs exercise every binding.
+"""
+
+import pathlib
+import zipfile
+
+HERE = pathlib.Path(__file__).resolve().parent
+# Fixed timestamp keeps the archives byte-for-byte reproducible.
+STAMP = (2026, 1, 1, 0, 0, 0)
+
+
+def write_zip(name, entries):
+ with zipfile.ZipFile(HERE / name, "w", zipfile.ZIP_DEFLATED) as z:
+ for path, data in entries:
+ info = zipfile.ZipInfo(path, STAMP)
+ info.compress_type = zipfile.ZIP_DEFLATED
+ z.writestr(info, data)
+
+
+W_NS = (
+ 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" '
+ 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"'
+)
+REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
+OFFICE_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
+
+
+def para(text, style=None, num=None):
+ ppr = ""
+ if style or num:
+ ppr = ""
+ if style:
+ ppr += f''
+ if num:
+ ppr += f''
+ ppr += ""
+ return f'{ppr}{text}'
+
+
+def cell(text, bold=False):
+ rpr = "" if bold else ""
+ return f'{rpr}{text}'
+
+
+def docx():
+ body = "".join(
+ [
+ para("Quarterly report", "Heading1"),
+ 'Revenue grew '
+ '18%'
+ ' quarter over quarter. Details on '
+ 'the dashboard'
+ ".",
+ para("Highlights", "Heading2"),
+ para("Two new enterprise customers", num=1),
+ para("Churn below 2%", num=1),
+ para("PDF table extraction shipped", num=1),
+ para("Regional breakdown", "Heading2"),
+ ""
+ "" + cell("Region", True) + cell("Revenue", True) + cell("Growth", True) + ""
+ "" + cell("EMEA") + cell("$1.2M") + cell("21%") + ""
+ "" + cell("Americas") + cell("$2.4M") + cell("16%") + ""
+ "",
+ ]
+ )
+ numbering = (
+ f''
+ ''
+ ''
+ )
+ write_zip(
+ "report.docx",
+ [
+ (
+ "[Content_Types].xml",
+ ''
+ ''
+ ''
+ ''
+ ''
+ "",
+ ),
+ (
+ "_rels/.rels",
+ f''
+ f''
+ f''
+ "",
+ ),
+ (
+ "word/document.xml",
+ f'{body}',
+ ),
+ (
+ "word/_rels/document.xml.rels",
+ f''
+ f''
+ "",
+ ),
+ ("word/numbering.xml", f'{numbering}'),
+ (
+ "docProps/core.xml",
+ 'Q3 Report',
+ ),
+ ],
+ )
+
+
+def col(c):
+ return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[c]
+
+
+def sheet_xml(rows):
+ out = []
+ for r, row in enumerate(rows):
+ cells = []
+ for c, v in enumerate(row):
+ at = f"{col(c)}{r + 1}"
+ if isinstance(v, (int, float)):
+ cells.append(f'{v}')
+ else:
+ cells.append(f'{v}')
+ out.append(f'{"".join(cells)}')
+ return (
+ ''
+ ''
+ f"{''.join(out)}"
+ )
+
+
+def xlsx():
+ sheets = [
+ ("Sales", [["Month", "Units", "Revenue"], ["Jan", 120, 2400], ["Feb", 135, 2700], ["Mar", 160, 3200]]),
+ ("Team", [["Name", "Role"], ["Ada", "Engineering"], ["Grace", "Research"]]),
+ ]
+ ct = (
+ ''
+ ''
+ ''
+ ''
+ ''
+ )
+ wb_sheets, wb_rels, entries = "", "", []
+ for i, (name, rows) in enumerate(sheets, 1):
+ ct += (
+ f''
+ )
+ wb_sheets += f''
+ wb_rels += f''
+ entries.append((f"xl/worksheets/sheet{i}.xml", sheet_xml(rows)))
+ ct += ""
+ write_zip(
+ "sales.xlsx",
+ [
+ ("[Content_Types].xml", ct),
+ (
+ "_rels/.rels",
+ f''
+ f'',
+ ),
+ (
+ "xl/workbook.xml",
+ ''
+ '{wb_sheets}',
+ ),
+ (
+ "xl/_rels/workbook.xml.rels",
+ f'{wb_rels}',
+ ),
+ ]
+ + entries,
+ )
+
+
+def pdf():
+ lines = [
+ ("F2", 20, 72, 720, "Markkit sample PDF"),
+ ("F1", 12, 72, 690, "Markkit reads the text layer of PDF files, rebuilds"),
+ ("F1", 12, 72, 675, "reading order across columns and detects tables."),
+ ("F2", 14, 72, 640, "Why it matters"),
+ ("F1", 12, 72, 615, "Agents get clean Markdown instead of positioned glyphs."),
+ ]
+ text = "".join(f"BT /{f} {s} Tf {x} {y} Td ({t}) Tj ET\n" for f, s, x, y, t in lines)
+ objects = [
+ "<< /Type /Catalog /Pages 2 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
+ "/Resources << /Font << /F1 4 0 R /F2 5 0 R >> >> /Contents 6 0 R >>",
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>",
+ f"<< /Length {len(text)} >>\nstream\n{text}endstream",
+ "<< /Title (Markkit sample) >>",
+ ]
+ out = b"%PDF-1.4\n"
+ offsets = []
+ for i, body in enumerate(objects, 1):
+ offsets.append(len(out))
+ out += f"{i} 0 obj\n{body}\nendobj\n".encode("latin-1")
+ xref = len(out)
+ out += f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode()
+ for off in offsets:
+ out += f"{off:010d} 00000 n \n".encode()
+ out += (
+ f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R /Info 7 0 R >>\n"
+ f"startxref\n{xref}\n%%EOF\n"
+ ).encode()
+ (HERE / "sample.pdf").write_bytes(out)
+
+
+if __name__ == "__main__":
+ docx()
+ xlsx()
+ pdf()
+ print("wrote", ", ".join(p.name for p in sorted(HERE.glob("*.*")) if p.suffix != ".py"))
diff --git a/examples/data/report.docx b/examples/data/report.docx
new file mode 100644
index 0000000..e81ee9c
Binary files /dev/null and b/examples/data/report.docx differ
diff --git a/examples/data/sales.xlsx b/examples/data/sales.xlsx
new file mode 100644
index 0000000..7337627
Binary files /dev/null and b/examples/data/sales.xlsx differ
diff --git a/examples/data/sample.pdf b/examples/data/sample.pdf
new file mode 100644
index 0000000..6df5f71
Binary files /dev/null and b/examples/data/sample.pdf differ
diff --git a/examples/documents.rs b/examples/documents.rs
new file mode 100644
index 0000000..ee98fb2
--- /dev/null
+++ b/examples/documents.rs
@@ -0,0 +1,72 @@
+// Documents from bytes: one entry point for every format.
+//
+// `extract_document_sync` detects the format (content type, then file
+// extension, then magic bytes) and returns an `Extraction` with Markdown,
+// title, format, structured warnings, stats and metadata.
+//
+// Uses the always-on formats (CSV, Jupyter, plain text) and HTML so it runs
+// with default features. DOCX, PDF, XLSX, ... work the same way once their
+// feature is enabled: pass the file bytes and a hint.
+
+use markkit::{DocumentHint, Markkit};
+
+fn main() -> markkit::Result<()> {
+ let markkit = Markkit::builder().build();
+
+ // 1. CSV, detected from the file name. `;` delimiters are sniffed too.
+ let csv = b"name;language;stars\nmarkkit;Rust;1200\nbashkit;Rust;900\n";
+ let doc = markkit.extract_document_sync(csv, DocumentHint::file_name("repos.csv"))?;
+ println!(
+ "--- {} ({} rows) ---",
+ doc.format,
+ doc.stats.rows.unwrap_or(0)
+ );
+ println!("{}", doc.markdown);
+
+ // 2. Jupyter notebook, detected from the content type. Code cells keep
+ // their language; with the `markdown` feature, Markdown cells are
+ // parsed as Markdown (headings, lists, ...) instead of plain text.
+ let notebook = br##"{
+ "nbformat": 4, "nbformat_minor": 5, "metadata": {"language_info": {"name": "python"}},
+ "cells": [
+ {"cell_type": "markdown", "metadata": {}, "source": ["Quick look at the data."]},
+ {"cell_type": "code", "metadata": {}, "execution_count": 1, "source": ["print(1 + 1)"],
+ "outputs": [{"output_type": "stream", "name": "stdout", "text": ["2\n"]}]}
+ ]
+ }"##;
+ let doc = markkit.extract_document_sync(
+ notebook,
+ DocumentHint::content_type("application/x-ipynb+json"),
+ )?;
+ println!("--- {} (title: {:?}) ---", doc.format, doc.title);
+ println!("{}", doc.markdown);
+
+ // 3. HTML with no hint at all: detected from the bytes. Title and page
+ // metadata (meta tags, Open Graph, JSON-LD) come back alongside.
+ let html = br#"
+ Release notes
+
+
+
Release notes
Faster PDF tables.
"#;
+ let doc = markkit.extract_document_sync(html, DocumentHint::default())?;
+ println!("--- {} ---", doc.format);
+ println!("title: {:?}", doc.title);
+ println!("description: {:?}", doc.metadata.description);
+ println!("author: {:?}", doc.metadata.author);
+ println!("language: {:?}", doc.metadata.language);
+ println!("{}", doc.markdown);
+
+ // 4. Structured warnings: hidden sheets, truncation, skipped content, ...
+ // Each has a stable machine code plus a human-readable detail.
+ for warning in &doc.warnings {
+ println!("warning {}: {}", warning.code.as_str(), warning.detail);
+ }
+
+ // 5. Legacy binary formats are detected and rejected explicitly.
+ let doc_bytes = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1, 0, 0, 0, 0];
+ match markkit.extract_document_sync(&doc_bytes, DocumentHint::file_name("old.doc")) {
+ Ok(_) => println!("unexpected success"),
+ Err(e) => println!("--- old.doc ---\nError: {e}"),
+ }
+ Ok(())
+}
diff --git a/examples/limits.rs b/examples/limits.rs
new file mode 100644
index 0000000..21d0955
--- /dev/null
+++ b/examples/limits.rs
@@ -0,0 +1,59 @@
+// Resource limits and error handling.
+//
+// Every resource an input can drive is bounded by `markkit::Limits`
+// (input/output bytes, time, nesting depth, node count, archive and
+// spreadsheet sizes, PDF streams, redirects). Defaults are generous; a breach
+// returns `Error::ResourceLimit` and `err.limit_kind()` names the limit, so a
+// service can map it to "413 Payload Too Large" or a retry with a bigger cap.
+
+use std::time::Duration;
+
+use markkit::{Error, LimitKind, Limits, Markkit};
+
+fn main() {
+ // Tight limits for a multi-tenant service.
+ let limits = Limits::default()
+ .max_input_size(64 * 1024)
+ .max_output_size(256)
+ .max_nodes(1_000)
+ .timeout(Duration::from_secs(5));
+ let markkit = Markkit::builder().limits(limits).build();
+
+ let small = "
Fits
Well under every limit.
";
+ let big = format!(
+ "
Report
{}",
+ "
A paragraph of findings.
".repeat(50)
+ );
+ let noisy = format!("
{}
", "
x
".repeat(2_000));
+
+ for (name, html) in [("small", small.to_string()), ("big", big), ("noisy", noisy)] {
+ match markkit.extract_html_sync(&html) {
+ Ok(md) => println!("{name}: ok, {} bytes of markdown", md.len()),
+ Err(err @ Error::ResourceLimit(_)) => {
+ let kind = err.limit_kind().expect("resource limit has a kind");
+ let hint = match kind {
+ LimitKind::MaxInputSize => "reject upload (413)",
+ LimitKind::MaxOutputSize => "raise max_output_size or chunk the input",
+ LimitKind::MaxNodes | LimitKind::MaxNestingDepth => "likely hostile input",
+ LimitKind::Timeout => "retry off the hot path",
+ _ => "see Limits docs",
+ };
+ println!("{name}: limit {} hit ({err}); {hint}", kind.as_str());
+ }
+ Err(err) => println!("{name}: other error: {err}"),
+ }
+ }
+
+ // Deep HTML does not fail by default: content past max_nesting_depth is
+ // flattened, so the text survives without risking a stack overflow.
+ let deep = format!(
+ "{}still here{}",
+ "
".repeat(5_000),
+ "
".repeat(5_000)
+ );
+ let md = Markkit::builder()
+ .build()
+ .extract_html_sync(&deep)
+ .expect("deep HTML is flattened, not rejected");
+ println!("deep (default limits): {:?}", md.trim());
+}
diff --git a/examples/main_content.rs b/examples/main_content.rs
new file mode 100644
index 0000000..d472b91
--- /dev/null
+++ b/examples/main_content.rs
@@ -0,0 +1,53 @@
+// Main content: keep only the article body of a web page.
+//
+// Navigation, headers, footers, scripts and forms are always stripped.
+// `main_content(true)` goes further: it scores the remaining blocks and keeps
+// the detected article, dropping sidebars, "related posts", comment threads
+// and share bars. `base_url` resolves relative links and images, so the
+// Markdown stays useful outside the original page.
+
+use markkit::Markkit;
+
+const PAGE: &str = r#"
+
+
+
+
+
+
Parsing untrusted documents
+
Every input is hostile until proven otherwise. Markkit bounds input size,
+ output size, nesting depth, node counts and time for each call, and never
+ executes scripts, macros or formulas.
+
Read the threat model for the full list
+ of mitigations, each one backed by a test.
+
+
+
3 comments
First!
+
+
+
+"#;
+
+fn main() -> markkit::Result<()> {
+ let everything = Markkit::builder().build().extract_html_sync(PAGE)?;
+ println!("--- Default (boilerplate tags stripped) ---\n{everything}");
+
+ let article = Markkit::builder()
+ .main_content(true)
+ .base_url("https://example.com/blog/posts/")
+ .build()
+ .extract_html_sync(PAGE)?;
+ println!("--- main_content(true) + base_url ---\n{article}");
+
+ // Explicit selectors win when you know the site's markup.
+ let selected = Markkit::builder()
+ .include_selector("article")
+ .preserve_images(false)
+ .build()
+ .extract_html_sync(PAGE)?;
+ println!("--- include_selector(\"article\"), no images ---\n{selected}");
+ Ok(())
+}
diff --git a/examples/node/documents.cjs b/examples/node/documents.cjs
new file mode 100644
index 0000000..6e0675e
--- /dev/null
+++ b/examples/node/documents.cjs
@@ -0,0 +1,45 @@
+// Convert DOCX, XLSX and PDF files with metadata, stats and warnings.
+//
+// node examples/node/documents.cjs # bundled samples
+// node examples/node/documents.cjs my.pptx my.epub # your own files
+const fs = require('node:fs');
+const path = require('node:path');
+const { extractDocument, extractDocumentSync } = require(
+ process.env.MARKKIT_MODULE ?? '@everruns/markkit',
+);
+
+const data = path.join(__dirname, '..', 'data');
+const files = process.argv.slice(2);
+if (files.length === 0) {
+ files.push(...['report.docx', 'sales.xlsx', 'sample.pdf'].map((f) => path.join(data, f)));
+}
+
+async function main() {
+ for (const file of files) {
+ // Format detection: hint.contentType, then hint.fileName, then magic bytes.
+ const doc = await extractDocument(fs.readFileSync(file), { fileName: path.basename(file) });
+ console.log(`=== ${path.basename(file)} ===`);
+ console.log('format:', doc.format, '| title:', doc.title ?? '(none)');
+ console.log('stats:', JSON.stringify(doc.stats));
+ for (const w of doc.warnings) console.log(`warning [${w.code}]: ${w.detail}`);
+ console.log(`\n${doc.markdown}`);
+ }
+
+ // Limits are option keys too; breaches throw an Error naming the limit.
+ try {
+ extractDocumentSync(fs.readFileSync(path.join(data, 'report.docx')), { fileName: 'report.docx' }, { maxOutputSize: 64 });
+ } catch (err) {
+ console.log('limit:', err.message);
+ }
+
+ // PDF geometry: pages, positioned spans and semantic blocks (camelCase keys).
+ const pdf = extractDocumentSync(fs.readFileSync(path.join(data, 'sample.pdf')), { fileName: 'sample.pdf' }, { pdfLayout: true });
+ const page = pdf.layout.pages[0];
+ console.log(`=== sample.pdf layout: ${page.width}x${page.height} pt ===`);
+ for (const b of page.blocks) console.log(b.kind.padEnd(10), b.bbox.map(Math.round));
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/examples/node/quickstart.cjs b/examples/node/quickstart.cjs
new file mode 100644
index 0000000..20644cb
--- /dev/null
+++ b/examples/node/quickstart.cjs
@@ -0,0 +1,48 @@
+// Markkit quick start for Node.js: HTML to Markdown, sync and async.
+//
+// npm install @everruns/markkit
+// node examples/node/quickstart.cjs
+//
+// Inside this repository the example loads the locally built binding
+// (crates/markkit-js); set MARKKIT_MODULE to point elsewhere.
+const { extractHtml, extractHtmlSync, extractBytes } = require(
+ process.env.MARKKIT_MODULE ?? '@everruns/markkit',
+);
+
+const page = `
+
+
+
+
Getting started
+
Markkit turns untrusted documents into clean Markdown.
+
+
+
+
+"""
+
+# 1. Defaults: nav, header, footer, scripts, styles and forms are stripped.
+print("--- extract_html_sync ---")
+print(markkit.extract_html_sync(PAGE))
+
+# 2. Selectors, main-content detection and link resolution.
+print("--- extract_html_sync_with_options ---")
+print(
+ markkit.extract_html_sync_with_options(
+ PAGE,
+ include_selectors=["article"],
+ exclude_selectors=[".ad"],
+ base_url="https://example.com/docs/",
+ main_content=True,
+ )
+)
+
+
+# 3. Async variants run on a background Tokio runtime and return awaitables.
+# `markkit.extract_url(url)` works the same way (public hosts only by default).
+async def main() -> None:
+ md = await markkit.extract_html("
Async
Non-blocking extraction.
")
+ print("--- await extract_html ---")
+ print(md)
+ md = await markkit.extract_bytes(b"name,score\nada,10\n", "text/csv")
+ print("--- await extract_bytes (CSV) ---")
+ print(md)
+
+
+asyncio.run(main())
diff --git a/examples/wasm/quickstart.mjs b/examples/wasm/quickstart.mjs
new file mode 100644
index 0000000..19a4dca
--- /dev/null
+++ b/examples/wasm/quickstart.mjs
@@ -0,0 +1,49 @@
+// @everruns/markkit-wasm in any JavaScript runtime (browser, edge, Deno, Bun, Node).
+//
+// npm install @everruns/markkit-wasm
+// node examples/wasm/quickstart.mjs
+//
+// Inside this repository, build the package first (`just wasm`); the example
+// then loads crates/markkit-wasm/pkg. Set MARKKIT_WASM_MODULE to override.
+import { readFile } from "node:fs/promises";
+
+const modulePath =
+ process.env.MARKKIT_WASM_MODULE ?? new URL("../../crates/markkit-wasm/pkg/index.js", import.meta.url).href;
+const { initMarkkit, Markkit, MarkkitTool, version } = await import(modulePath);
+
+// Load the .wasm once. Browsers fetch it next to the module; Node reads it from disk.
+await initMarkkit();
+console.log(`markkit-wasm ${version()}`);
+
+// 1. HTML. Options are fixed per instance; reuse it for many calls.
+const mk = new Markkit({ includeSelectors: ["article"], preserveImages: false });
+console.log("--- extractHtml ---");
+console.log(mk.extractHtml('
Hello
From WebAssembly.
'));
+
+// 2. Documents from bytes. In a browser: new Uint8Array(await res.arrayBuffer()).
+// There is no URL fetching in WASM: the host fetches, so network policy stays with it.
+const docs = new Markkit();
+for (const name of ["report.docx", "sales.xlsx", "sample.pdf"]) {
+ const bytes = new Uint8Array(await readFile(new URL(`../data/${name}`, import.meta.url)));
+ const doc = docs.extractDocument(bytes, { fileName: name });
+ console.log(`=== ${name}: ${doc.format}, title ${JSON.stringify(doc.title)} ===`);
+ console.log(doc.markdown);
+}
+
+// 3. Agent tool: an LLM tool definition plus a validated `execute`.
+const tool = new MarkkitTool({ maxOutputChars: 2000 });
+console.log("--- tool definition ---");
+console.log(JSON.stringify(tool.toolDefinition()).slice(0, 120) + "...");
+const result = await tool.execute({ html: "
Tool call
Result for the model.
" });
+console.log("--- tool result ---");
+console.log(result);
+
+// 4. Errors: limits and bad input throw; `userFacing` errors are safe to show a model.
+try {
+ new Markkit({ maxOutputSize: 8 }).extractHtml("
This output is longer than eight bytes.
");
+} catch (err) {
+ console.log("--- limit ---");
+ console.log(err.message);
+}
+mk.free(); // optional: release wasm memory early
+docs.free();
diff --git a/justfile b/justfile
index 6f78767..1dd873f 100644
--- a/justfile
+++ b/justfile
@@ -60,14 +60,7 @@ schema:
# Run every example (CI runs this too)
examples:
- #!/usr/bin/env bash
- set -euo pipefail
- for ex in basic custom_selectors configuration ir_access transforms; do
- echo "── example: $ex"
- cargo run -q -p markkit --example "$ex"
- done
- echo "── example: agent_tool"
- cargo run -q -p markkit --features tool --example agent_tool
+ bash scripts/run-examples.sh
# Build the WASM package and run its Node tests (needs wasm32 target + wasm-bindgen-cli)
wasm:
diff --git a/knowledge/log.md b/knowledge/log.md
index d72d257..e83929d 100644
--- a/knowledge/log.md
+++ b/knowledge/log.md
@@ -5,6 +5,7 @@
* **Registries in sync**: `release.yml` now dispatches the PyPI, npm and npm WASM publishers (real publish) alongside crates.io from the release tag. 0.2.1 and 0.3.0 had reached crates.io only. See [Release Process](operations/release-process.md).
* **Release 0.3.1**: patch release carrying calamine 0.38 (RUSTSEC-2026-0436) and the dependency refresh. No API changes. See `CHANGELOG.md`.
* **calamine 0.38**: RUSTSEC-2026-0436 (calamine CFB/OLE2 panic + OOM, fixed in 0.38) broke downstream `cargo audit`. Bumped calamine, cfb 0.16 and the lockfile; XLS pre-scan + own XLSB reader unchanged. Deferred majors: hayro 0.9 (published 2026-11-02, makes SIMD mandatory against the [Native Dependencies](security/native-dependencies.md) review) and mail-parser 1.0 (full rewrite, MSRV 1.98, new unsafe SIMD code); each needs its own review. See [Threat Model](security/threat-model.md).
+* **Docs and examples**: README, PyPI/npm/WASM READMEs and guides rewritten; Rust snippets in README and `docs/` compiled as doctests; docs.rs builds all features with `doc_cfg`; Python wheel ships `.pyi` stubs (checked against the module); Rust, Python, Node.js and WASM examples share `examples/data/` samples and run in CI. See [Documentation Architecture](operations/documentation.md) and [Examples](operations/examples.md).
* **Licensing and security policy**: every published artifact (crates.io, PyPI, both npm packages) now ships `LICENSE` and `NOTICE`; Python metadata is PEP 639 `License-Expression: MIT`. `NOTICE` reproduces the BSD-3 notices for PDFium/Foxit fonts and Adobe CMaps that hayro embeds under `pdf-ocr`. `SECURITY.md` covers 0.3.x, GitHub private reporting and all packages. `scripts/tests/test_licensing.py` enforces it. See [Native Dependencies](security/native-dependencies.md) and [Release Process](operations/release-process.md).
diff --git a/knowledge/operations/documentation.md b/knowledge/operations/documentation.md
index 97b6d78..be3e798 100644
--- a/knowledge/operations/documentation.md
+++ b/knowledge/operations/documentation.md
@@ -13,21 +13,40 @@ tags:
| Tree | Audience | Holds |
|---|---|---|
-| `README.md` | Users | Pitch, features, quick start per surface, install, feature flags |
-| `docs/` | Users | Guides (`getting-started.md`) |
-| rustdoc (`crates/*/src/lib.rs`) | Rust users | API reference, feature flags, examples |
-| `crates/markkit-python/README.md`, `crates/markkit-js/README.md` | Binding users | Shipped as the PyPI / npm package readme |
+| `README.md` | Users | Pitch, surfaces table, formats, quick start per surface, examples, configuration, limits, features, performance, security |
+| `docs/` | Users | `getting-started.md` (Rust walkthrough), `pdf.md` (PDF text, layout, OCR, limits) |
+| `examples/README.md` | Users | Index of Rust, Python, Node.js and WASM examples |
+| rustdoc (`crates/*/src/lib.rs`) | Rust users | API reference, feature table, examples; docs.rs builds with `[package.metadata.docs.rs]` features |
+| `crates/markkit-python/README.md` | Python users | Shipped as the PyPI readme: install, API table, result keys, limits, errors, PDF |
+| `markkit.pyi` (repo root) | Python users | Type stubs; maturin ships it as `markkit/__init__.pyi` + `py.typed` |
+| `crates/markkit-js/README.md` | Node.js users | Shipped as the npm readme; `index.d.ts` is generated from napi rustdoc in `crates/markkit-js/src/lib.rs` |
+| `crates/markkit-wasm/README.md`, `crates/markkit-wasm/js/index.d.ts` | Browser/edge users | Shipped in the WASM npm package |
| `knowledge/` | Contributors, agents | OKF bundle: design decisions, threats, processes |
| `AGENTS.md` | Coding agents | Commands, rules, knowledge map |
| `CHANGELOG.md` | Everyone | Keep a Changelog, Unreleased section first |
Durable engineering knowledge goes in `knowledge/`, not `docs/`. User-facing guides
-link to GitHub-rendered knowledge only where no user doc exists.
+link to GitHub-rendered knowledge only where no user doc exists. Binding READMEs
+use absolute GitHub links: they render on PyPI and npm, where relative links break.
## Requirements
- All public API items have rustdoc; `cargo doc --workspace --no-deps` with
`RUSTDOCFLAGS=-Dwarnings` is clean (CI lint job)
+- docs.rs: `crates/markkit/Cargo.toml` `[package.metadata.docs.rs]` enables every
+ feature except `pdf-ocr-ocrs` and sets `--cfg docsrs`; `lib.rs` turns on
+ `doc_cfg` under `docsrs` so items show their feature badge
+- Rust snippets in `README.md`, `docs/getting-started.md` and `docs/pdf.md` are
+ doctests (`#[cfg(doctest)]` `include_str!` structs in `crates/markkit/src/lib.rs`).
+ Write them self-contained: wrap `?` and undefined inputs in a `fn`, use
+ `rust,no_run` for file I/O, never hidden `# ` lines (GitHub renders them).
+ The README/getting-started structs need `feature = "html"`; HTML snippets in
+ `lib.rs` wrap in a hidden `#[cfg(feature = "html")]` block (CI also runs
+ `--no-default-features`)
+ Fences without a language tag are compiled as Rust
+- Python stubs match the native module: `crates/markkit-python/tests/test_stubs.py`
+ compares function names, parameter names and `Limits` fields; `python.yml`
+ asserts the wheel contains `__init__.pyi` and `py.typed`
- README feature list, feature-flag table, and binding snippets match the code
- Binding READMEs match exported functions (see [Python Package](../runtimes/python-package.md),
[Node.js Package](../runtimes/node-package.md))
diff --git a/knowledge/operations/examples.md b/knowledge/operations/examples.md
index a4b557c..2e7184d 100644
--- a/knowledge/operations/examples.md
+++ b/knowledge/operations/examples.md
@@ -13,61 +13,78 @@ tags:
```
examples/
+ README.md # Index of every example, per surface
+ data/ # Sample report.docx, sales.xlsx, sample.pdf + generate.py
basic.rs # Default HTML to markdown extraction
+ documents.rs # extract_document_sync: detection, title, metadata, stats, warnings
+ convert.rs # DOCX/XLSX/PDF samples or CLI-supplied files (docx,spreadsheet,pdf)
+ main_content.rs # main_content(true), base_url, include_selector
custom_selectors.rs # include/exclude CSS selectors
configuration.rs # How builder options change output
+ limits.rs # Limits, Error::ResourceLimit, LimitKind dispatch
ir_access.rs # Parse to IR, inspect nodes, render separately
agent_tool.rs # LLM tool definition, system prompt, execution
transforms.rs # Built-in and closure IR transform passes
+ python/ # quickstart.py, documents.py, limits.py (installed markkit wheel)
+ node/ # quickstart.cjs, documents.cjs (MARKKIT_MODULE overrides the package)
+ wasm/ # quickstart.mjs (crates/markkit-wasm/pkg by default)
```
-Examples live at the workspace root and are registered as `[[example]]` targets
-of the `markkit` crate (`crates/markkit/Cargo.toml`, `required-features = ["html"]`).
-Run one with `cargo run -p markkit --example `, all with `just examples`.
-
-## Examples
-
-### basic.rs
-
-- `Markkit::builder().build()` with defaults
-- `extract_html_sync` on an inline HTML string
-- Print the markdown
-
-### custom_selectors.rs
-
-- `include_selector("article")` targets main content
-- `exclude_selector(".sidebar")` strips boilerplate
-- Print the filtered markdown
-
-### configuration.rs
-
-- Compare default output with `preserve_links(false)` and `preserve_images(false)`
-- Show how each option changes the rendered markdown
-
-### ir_access.rs
-
-- `parse_html()` returns the IR `Document` (see [IR Specification](../foundations/ir.md))
-- Walk `Document.nodes`, match on `Node` variants
-- Render with `MarkdownRenderer` to show parse and render are separate stages
-
-### agent_tool.rs
-
-- Needs the `tool` feature (`required-features = ["html", "tool"]`)
-- Prints the OpenAI tool definition and system prompt, then executes model-style
- arguments and prints `ToolOutput::result` (see [Tool Contract](../integrations/tool-contract.md))
-
-### transforms.rs
-
-- `transform(NormalizeHeadings)` shifts `h3`/`h4` to `#`/`##`
-- `transform::from_fn` + `Document::visit_mut` rewrites links in place
-- Prints the pass names (`config().transforms`) and the result
+Rust examples live at the workspace root and are registered as `[[example]]`
+targets of the `markkit` crate (`crates/markkit/Cargo.toml`, `required-features`
+per example). Run one with `cargo run -p markkit --example `, all with
+`just examples` (`scripts/run-examples.sh`).
+
+## Sample data
+
+`examples/data/generate.py` (stdlib only, fixed ZIP timestamps) writes the
+sample DOCX (heading, bold, hyperlink, bullet list, table, `dc:title`), XLSX
+(two sheets, inline strings and numbers) and PDF (one page, Helvetica text,
+`/Title`). Every binding's examples read the same files. Regenerate rather than
+hand-edit; commit the outputs.
+
+## Rust examples
+
+- `basic.rs`: `Markkit::builder().build()`, `extract_html_sync`
+- `documents.rs`: CSV by file name, ipynb by content type, HTML by magic bytes
+ with `Metadata`, warning codes, legacy `.doc` rejection; default features only
+- `convert.rs`: `required-features = ["docx", "spreadsheet", "pdf"]`; with no
+ args converts `examples/data/*`, otherwise each path argument; prints format,
+ title, stats, warnings and Markdown
+- `main_content.rs`: default vs `main_content(true)` + `base_url` vs
+ `include_selector("article")` on one page with nav, sidebar and comments
+- `custom_selectors.rs`: `include_selector("article")`, `exclude_selector(".sidebar")`
+- `configuration.rs`: `preserve_links(false)`, `preserve_images(false)`, limit errors
+- `limits.rs`: tight `Limits`, matches `Error::ResourceLimit` and maps each
+ `LimitKind` to a service response; deep HTML flattens under default limits
+- `ir_access.rs`: `parse_html()` returns the IR `Document` (see
+ [IR Specification](../foundations/ir.md)); `MarkdownRenderer` renders it
+- `agent_tool.rs`: `required-features = ["html", "tool"]`; OpenAI tool
+ definition, system prompt, `ToolOutput::result` (see [Tool Contract](../integrations/tool-contract.md))
+- `transforms.rs`: `transform(NormalizeHeadings)`, `transform::from_fn` + `Document::visit_mut`
+
+## Binding examples
+
+- Python (`examples/python/`): `quickstart.py` (sync, options, asyncio),
+ `documents.py` (dict result, stats, warnings, PDF layout; path args),
+ `limits.py` (`markkit.Limits`, `RuntimeError`)
+- Node.js (`examples/node/`): `quickstart.cjs`, `documents.cjs` (path args,
+ `maxOutputSize` error, `pdfLayout`). `MARKKIT_MODULE` points at the built
+ binding in CI; users `require('@everruns/markkit')`
+- WASM (`examples/wasm/quickstart.mjs`): `initMarkkit`, `Markkit`, documents,
+ `MarkkitTool`, limit error. `MARKKIT_WASM_MODULE` overrides the default
+ `crates/markkit-wasm/pkg/index.js`
## Requirements
-- No network or file access; inline HTML samples only
-- Output to stdout, exit 0 on success
-- CI runs every example (`just examples` in the Test job), so a broken example fails the build
-- A new example is added to `crates/markkit/Cargo.toml`, this document, and the `examples` recipe
+- No network; inline strings and `examples/data/` only (path args optional)
+- Output to stdout, exit 0 on success; an exception or non-zero exit fails CI
+- CI runs every example: Rust in the Test job (`scripts/run-examples.sh`),
+ Python in `python.yml` after the wheel install, Node.js in `js.yml` after the
+ NAPI build, WASM in the `ci.yml` wasm job after the package build
+- A new Rust example is added to `crates/markkit/Cargo.toml`,
+ `scripts/run-examples.sh`, `examples/README.md` and this document; a binding
+ example to its directory (CI globs it), `examples/README.md` and this document
## See also
diff --git a/knowledge/runtimes/node-package.md b/knowledge/runtimes/node-package.md
index 445ff37..abf220f 100644
--- a/knowledge/runtimes/node-package.md
+++ b/knowledge/runtimes/node-package.md
@@ -56,7 +56,10 @@ Errors reject (or throw) with the Rust error's `Display` text as the reason.
Tests: `crates/markkit-js/__test__/*.test.cjs` (`node --test`, run by `js.yml`
after the native build): options on every entry point, limits, invalid numbers,
-`extractDocument`, and URL policy against a local server.
+`extractDocument`, and URL policy against a local server. `js.yml` then runs
+`examples/node/*.cjs` against the built binding (`MARKKIT_MODULE`). Typings:
+`index.d.ts` is generated by `napi build` from the rustdoc on
+`crates/markkit-js/src/lib.rs`, so every option and result field is documented there.
## Build
diff --git a/knowledge/runtimes/python-package.md b/knowledge/runtimes/python-package.md
index 74d9c96..65dd7b2 100644
--- a/knowledge/runtimes/python-package.md
+++ b/knowledge/runtimes/python-package.md
@@ -48,6 +48,17 @@ Invalid values raise `ValueError` / `OverflowError` at construction.
Errors surface as `RuntimeError` carrying the Rust error's `Display` text.
+## Typing
+
+`markkit.pyi` at the repository root (next to `pyproject.toml`, where maturin
+looks for `.pyi` in a pure-Rust project) ships in the wheel as
+`markkit/__init__.pyi` plus a generated `py.typed`. It types `Limits`, every
+function, and the `extract_document_sync` result as `TypedDict`s
+(`Extraction`, `ExtractionStats`, `Metadata`, `Warning`). Docstrings there are
+the Python API reference. `tests/test_stubs.py` fails when a function,
+parameter or `Limits` field is added to the module without the stub;
+`python.yml` asserts the installed wheel contains both files.
+
## Build
`maturin` builds from the workspace root (`pyproject.toml` points at the crate manifest):
@@ -66,8 +77,10 @@ Published to PyPI by `publish-python.yml` from a verified release tag. The Linux
wheel is built in a manylinux2014 container rather than on the moving GitHub host
image; see [Release Process](../operations/release-process.md) for platform scope
and release-retry rules.
-CI: `python.yml` builds and imports the module on changes to `crates/markkit-python/`
-or `crates/markkit/`.
+CI: `python.yml` builds and imports the module, runs `tests/`, checks the stubs
+ship, and runs `examples/python/*.py`, on changes to `crates/markkit-python/`,
+`crates/markkit/`, `examples/python/`, `examples/data/`, `markkit.pyi` or
+`pyproject.toml`.
## Structured documents
diff --git a/knowledge/runtimes/wasm-package.md b/knowledge/runtimes/wasm-package.md
index 23ee3b7..1d5d601 100644
--- a/knowledge/runtimes/wasm-package.md
+++ b/knowledge/runtimes/wasm-package.md
@@ -77,7 +77,9 @@ options and their validation, HTML, bytes, PDF text/layout/tables and limits, DO
(fixtures built by `__test__/zip.mjs`), archive limits, malformed input, version
parity with `package.json`, and the tool (definition, locale, execution,
`userFacing` errors). CI job `wasm` in `ci.yml` also checks the core crate for
-wasm32 and the npm archive contents; it gates `Check`.
+wasm32, runs `examples/wasm/quickstart.mjs` against the built package, and checks
+the npm archive contents; it gates `Check`. `js/index.d.ts` is hand-written:
+keep it in sync with the Rust exports and option keys.
## Distribution
diff --git a/markkit.pyi b/markkit.pyi
new file mode 100644
index 0000000..c5604db
--- /dev/null
+++ b/markkit.pyi
@@ -0,0 +1,210 @@
+"""Extract clean Markdown from any document format, safely.
+
+Markkit converts HTML, PDF, DOCX, PPTX, spreadsheets (XLSX/XLSB/XLS/ODS), ODT,
+EPUB, email (EML), Jupyter notebooks, CSV/TSV, Markdown and plain text into
+well-structured Markdown for LLMs and agents. Every input is treated as
+untrusted: nothing is executed and every resource an input can drive is
+bounded by :class:`Limits`.
+
+Errors: resource-limit breaches, unsupported formats, parse failures and
+blocked URLs raise ``RuntimeError`` with a message naming the cause; invalid
+arguments raise ``ValueError``.
+"""
+
+from typing import Any, Awaitable, Literal, Optional, Sequence, TypedDict
+
+__all__ = [
+ "Limits",
+ "Extraction",
+ "ExtractionStats",
+ "Metadata",
+ "Warning",
+ "extract_document_sync",
+ "extract_html",
+ "extract_html_sync",
+ "extract_html_sync_with_options",
+ "extract_url",
+ "extract_bytes",
+]
+
+class Limits:
+ """Resource limits applied to one call. Every argument is optional and
+ defaults to the library default; pass the object as ``limits=``.
+
+ Breaches raise ``RuntimeError`` naming the limit, e.g.
+ ``"Resource limit exceeded: output exceeds max_output_size 256"``.
+ Spreadsheet rows/columns and PDF pages are truncated with a warning instead.
+ """
+
+ max_input_size: int
+ """Input bytes, and the body of a fetched URL. Default 50 MiB."""
+ max_output_size: int
+ """Markdown output bytes. Default 128 MiB."""
+ timeout: float
+ """Seconds for fetch + parse + render of one call. Default 60."""
+ max_nesting_depth: int
+ """Element nesting; deeper HTML is flattened. Default 256, hard max 512."""
+ max_nodes: int
+ """Parsed HTML DOM / XML nodes and retained PDF geometry. Default 5 000 000."""
+ max_archive_entries: int
+ """ZIP entries in DOCX/PPTX/XLSX/ODT/EPUB containers. Default 10 000."""
+ max_archive_entry_size: int
+ """Decompressed bytes per ZIP entry. Default 64 MiB."""
+ max_archive_total_size: int
+ """Decompressed bytes per ZIP container. Default 256 MiB."""
+ max_sheet_rows: int
+ """Rows rendered per sheet (truncated with a warning). Default 10 000."""
+ max_sheet_cols: int
+ """Columns rendered per sheet (truncated with a warning). Default 256."""
+ max_spreadsheet_cells: int
+ """XLS/ODS grid cells checked before parsing. Default 4 000 000."""
+ max_redirects: int
+ """Redirects followed by :func:`extract_url`. Default 5."""
+ max_pdf_pages: int
+ """PDF pages rendered (truncated with a warning). Default 10 000."""
+ max_pdf_stream_size: int
+ """Decoded bytes per PDF stream. Default 64 MiB."""
+ max_pdf_decoded_size: int
+ """Decoded PDF bytes in total, also bounds layout geometry. Default 256 MiB."""
+
+ def __init__(
+ self,
+ *,
+ max_input_size: Optional[int] = None,
+ max_output_size: Optional[int] = None,
+ timeout: Optional[float] = None,
+ max_nesting_depth: Optional[int] = None,
+ max_nodes: Optional[int] = None,
+ max_archive_entries: Optional[int] = None,
+ max_archive_entry_size: Optional[int] = None,
+ max_archive_total_size: Optional[int] = None,
+ max_sheet_rows: Optional[int] = None,
+ max_sheet_cols: Optional[int] = None,
+ max_spreadsheet_cells: Optional[int] = None,
+ max_redirects: Optional[int] = None,
+ max_pdf_pages: Optional[int] = None,
+ max_pdf_stream_size: Optional[int] = None,
+ max_pdf_decoded_size: Optional[int] = None,
+ ) -> None: ...
+
+class Warning(TypedDict):
+ """A non-fatal extraction issue."""
+
+ code: str
+ """Stable machine code, e.g. ``"truncated_sheet"``, ``"hidden_sheet_skipped"``."""
+ detail: str
+ """Human-readable description."""
+
+class ExtractionStats(TypedDict, total=False):
+ """Counts for the document; a key is ``None`` when it does not apply."""
+
+ pages: Optional[int]
+ sheets: Optional[int]
+ rows: Optional[int]
+ paragraphs: Optional[int]
+ tables: Optional[int]
+ cells: Optional[int]
+ attachments: Optional[int]
+ chapters: Optional[int]
+
+class Metadata(TypedDict, total=False):
+ """HTML page metadata from ````, Open Graph and JSON-LD."""
+
+ description: Optional[str]
+ author: Optional[str]
+ published: Optional[str]
+ language: Optional[str]
+ canonical_url: Optional[str]
+ site_name: Optional[str]
+ image: Optional[str]
+
+class Extraction(TypedDict, total=False):
+ """Result of :func:`extract_document_sync`."""
+
+ markdown: str
+ """The extracted Markdown."""
+ title: Optional[str]
+ """Document title when the source declares one."""
+ format: str
+ """Detected format: ``html``, ``pdf``, ``docx``, ``pptx``, ``xlsx``,
+ ``xlsb``, ``xls``, ``ods``, ``odt``, ``epub``, ``eml``, ``ipynb``,
+ ``csv``, ``tsv``, ``markdown`` or ``text``."""
+ warnings: list[Warning]
+ stats: ExtractionStats
+ metadata: Metadata
+ layout: dict[str, Any]
+ """PDF geometry, only with ``pdf_layout=True`` on PDF input:
+ ``{"version": 1, "pages": [{"page", "width", "height", "rotation",
+ "spans", "blocks"}]}``. Coordinates are points from the top-left."""
+
+def extract_document_sync(
+ data: bytes,
+ *,
+ file_name: Optional[str] = None,
+ content_type: Optional[str] = None,
+ pdf_layout: bool = False,
+ pdf_remove_repeated_headers: bool = False,
+ pdf_ocr: bool = False,
+ pdf_ocr_language: str = "eng",
+ pdf_ocr_backend: Literal["tesseract", "ocrs"] = "tesseract",
+ pdf_ocr_detection_model: Optional[str] = None,
+ pdf_ocr_recognition_model: Optional[str] = None,
+ limits: Optional[Limits] = None,
+) -> Extraction:
+ """Convert document bytes of any supported format to Markdown plus
+ title, format, warnings, stats and metadata.
+
+ The format is detected from ``content_type``, then the extension of
+ ``file_name``, then magic bytes. ``pdf_layout`` adds PDF geometry,
+ ``pdf_remove_repeated_headers`` drops repeated page headers/footers,
+ ``pdf_ocr`` recognizes textless PDF pages (requires Tesseract and
+ language data, e.g. ``pdf_ocr_language="eng+deu"``).
+
+ >>> r = extract_document_sync(b"a,b\\n1,2\\n", file_name="t.csv")
+ >>> r["format"], r["markdown"].splitlines()[0]
+ ('csv', '| a | b |')
+ """
+
+def extract_html_sync(html: str, *, limits: Optional[Limits] = None) -> str:
+ """Convert an HTML string to Markdown. Navigation, headers, footers,
+ scripts, styles and forms are stripped.
+
+ >>> extract_html_sync("
Hello
")
+ '# Hello\\n'
+ """
+
+def extract_html_sync_with_options(
+ html: str,
+ *,
+ include_selectors: Optional[Sequence[str]] = None,
+ exclude_selectors: Optional[Sequence[str]] = None,
+ max_input_size: Optional[int] = None,
+ base_url: Optional[str] = None,
+ main_content: bool = False,
+ limits: Optional[Limits] = None,
+) -> str:
+ """Convert HTML with CSS selector filtering and link resolution.
+
+ ``include_selectors`` keeps only matching elements; ``exclude_selectors``
+ drops matches (added to the defaults); ``base_url`` resolves relative
+ links and images; ``main_content`` keeps only the detected article body;
+ ``max_input_size`` overrides ``limits.max_input_size``.
+ """
+
+def extract_html(html: str, *, limits: Optional[Limits] = None) -> Awaitable[str]:
+ """Async :func:`extract_html_sync`: ``md = await markkit.extract_html(html)``."""
+
+def extract_url(url: str, *, limits: Optional[Limits] = None) -> Awaitable[str]:
+ """Fetch an http(s) URL and convert the response (any supported format).
+
+ Loopback, private, link-local and cloud-metadata addresses are refused,
+ also after DNS resolution and on every redirect. The body is bounded by
+ ``limits.max_input_size`` and the call by ``limits.timeout``.
+ """
+
+def extract_bytes(
+ data: bytes, content_type: Optional[str] = None, *, limits: Optional[Limits] = None
+) -> Awaitable[str]:
+ """Async conversion of bytes to Markdown only; the format is detected
+ from ``content_type`` and the bytes. Use :func:`extract_document_sync`
+ for title, warnings and stats."""
diff --git a/pyproject.toml b/pyproject.toml
index b995f7b..52fc926 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -8,19 +8,25 @@ dynamic = ["version", "description", "authors"]
license = "MIT"
license-files = ["LICENSE", "NOTICE"]
readme = "crates/markkit-python/README.md"
-keywords = ["markdown", "extraction", "html", "pdf", "docx", "llm"]
+requires-python = ">=3.9"
+keywords = ["markdown", "html", "pdf", "docx", "xlsx", "extraction", "llm", "rag", "agents"]
classifiers = [
- "Programming Language :: Rust",
- "Programming Language :: Python :: 3",
+ "Development Status :: 4 - Beta",
+ "Intended Audience :: Developers",
"Operating System :: POSIX :: Linux",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Rust",
+ "Topic :: Text Processing :: Markup :: HTML",
"Topic :: Text Processing :: Markup :: Markdown",
+ "Typing :: Typed",
]
[project.urls]
Homepage = "https://github.com/everruns/markkit"
-Source = "https://github.com/everruns/markkit"
-Issues = "https://github.com/everruns/markkit/issues"
+Documentation = "https://github.com/everruns/markkit/blob/main/crates/markkit-python/README.md"
+Repository = "https://github.com/everruns/markkit"
Changelog = "https://github.com/everruns/markkit/blob/main/CHANGELOG.md"
+Issues = "https://github.com/everruns/markkit/issues"
[tool.maturin]
manifest-path = "crates/markkit-python/Cargo.toml"
diff --git a/scripts/run-examples.sh b/scripts/run-examples.sh
new file mode 100755
index 0000000..caf521c
--- /dev/null
+++ b/scripts/run-examples.sh
@@ -0,0 +1,18 @@
+#!/usr/bin/env bash
+# Run every Rust example (CI Test job and `just examples`). A broken example
+# fails the build. Keep in sync with [[example]] targets in crates/markkit/Cargo.toml
+# and knowledge/operations/examples.md. Binding examples run in python.yml,
+# js.yml and the ci.yml wasm job.
+set -euo pipefail
+cd "$(dirname "${BASH_SOURCE[0]}")/.."
+
+run() {
+ echo "── example: $*"
+ cargo run -q -p markkit "$@"
+}
+
+for ex in basic custom_selectors configuration ir_access transforms documents main_content limits; do
+ run --example "$ex"
+done
+run --features tool --example agent_tool
+run --features docx,spreadsheet,pdf --example convert
3 comments
First!