anydoc

package module
v0.0.0-...-ced922f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 16, 2026 License: MIT Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-anydoc

English | 简体中文

Go bindings for anydoc — convert Word, PowerPoint, Excel, OpenDocument, RTF, EPUB, CSV and text-based PDF to Markdown.

No cgo. No subprocesses. No system dependencies. The Rust library is compiled to WebAssembly and embedded, so a binary using this package is self-contained and cross-compiles wherever Go does:

CGO_ENABLED=0 GOOS=windows GOARCH=arm64 go build ./...

Install

go get github.com/lawkitt/go-anydoc

Requires Go 1.25 or newer, which is what wazy requires.

Usage

c, err := anydoc.New()
if err != nil {
    return err
}
defer c.Close(ctx)

md, err := c.Convert(ctx, docBytes, "docx")

Pass "" as the hint to detect the format from content. CSV has no signature and must be named explicitly.

Errors are matched with errors.Is:

switch {
case errors.Is(err, anydoc.ErrEncrypted):    // password-protected
case errors.Is(err, anydoc.ErrUnsupported):  // not a format anydoc parses
case errors.Is(err, anydoc.ErrInvalid):      // corrupt or missing required part
case errors.Is(err, anydoc.ErrScannedOnly):  // PDF needs OCR
case errors.Is(err, anydoc.ErrResourceLimit): // input, guest, or output limit
}

Design notes

Interpreter by default. wazy can compile the module to native machine code or interpret it instruction by instruction. This package interprets by default: startup stays bounded, no executable pages or persistent compilation cache are required, and the same profile works on every supported architecture. WithCompiler remains an explicit opt-in for callers with a different deployment envelope.

One runtime, not a selector. Wazy is the only production runtime in this module. Keeping two engines or choosing one at runtime would enlarge every downstream binary and split the behavior that the fixture corpus qualifies. The runtime stays behind the Converter interface. FORK.md records the same-guest Linux AMD64 comparison used to accept the hard cut.

AnyDoc 0.1.9. The embedded guest includes the PDF resource caps and text positioning fixes delivered by AnyDoc 0.1.9 and pdf-inspector 1.14.2. Those fixes intentionally change Markdown for documents that exercise the affected PDF and table paths, so upgrades must be diffed against the caller's corpus.

A fresh guest per document. Each Convert instantiates its own linear memory, so a large document cannot leave memory permanently claimed and a malformed one cannot leak state into the next call. Compilation, the expensive part, happens once in New.

A command module, not exported functions. The guest reads stdin and writes stdout, so the Go side never touches linear memory, pointers, or UTF-8 boundaries. The exit code carries the error kind. See rust/src/main.rs — the code table there and in errors.go is a two-language contract.

Sandboxed. WASI is instantiated for stdio and random_get (which HashMap seeding reaches for). No filesystem, no clock, no sockets.

Bounded. Markdown output is capped at 10 MiB and guest diagnostics at 32 KiB. An attempted overflow cancels the guest, returns ErrResourceLimit, and discards all partial Markdown. Context cancellation and deadlines remain the standard context.Canceled and context.DeadlineExceeded errors.

Controlling size

The module is embedded by default so go get and New() just work. Builds that would rather ship it out of band:

go build -tags anydoc_nowasm    # omit the embedded module

embeddedWASM is then nil and New requires WithWASM(r) or WithWASMBytes(b). Useful for container layering, serverless size limits, pinning a different anydoc build, or environments that forbid opaque embedded blobs.

The saving is approximately the size of anydoc.wasm plus Go's embedding machinery.

The build tag affects the compiled binary, not go get: the module is in the Go module either way.

Tuning

anydoc.New(
    anydoc.WithConcurrency(1),        // simultaneous guests; the main memory lever
    anydoc.WithMemoryLimitPages(1024), // 64 MiB per guest
    anydoc.WithMaxInputBytes(20<<20),
    anydoc.WithCompiler(),            // throughput over startup cost; see below
)
WithCompiler

Compiles the module to native code instead of interpreting it. The cost is paid once in New; Convert only instantiates the already-compiled module. It can pay off in a long-lived process that converts large documents and is normally a loss for short-lived processes or small inputs.

It is a request, not a guarantee. The backend needs amd64 or arm64 on a mainstream OS, plus a host that permits mmap'd executable pages. Where that does not hold — riscv64, ppc64le, 386, macOS hardened runtime, some seccomp profiles — wazy falls back to the interpreter silently and the conversion still happens, just at interpreter speed. Cross-compilation is unaffected either way: wazy is pure Go, and this option changes no build constraints.

WithMemoryLimitPages is validated against the module's declared minimum at New time, not at conversion time — setting it too low fails fast with a clear message rather than surfacing later as a mysterious conversion error.

How much a guest actually needs tracks the uncompressed content, not the size of the file on disk — a zip bomb is small on disk and large in memory, which is why the limit exists:

document pages needed
module minimum, converts nothing 64 (4 MiB)
docx, 0.4 MB body 192 (12 MiB)
docx, 2 MB body 576 (36 MiB)
PDF, 7.5 MB file 512–1024 (32–64 MiB)
docx, 5 MB body 1280 (80 MiB)

The default of 1024 pages converts an ordinary 7.5 MB PDF. Raise it if conversions fail on inputs that convert fine elsewhere. Each concurrent guest can claim up to this much, so WithConcurrency multiplied by this value is your real ceiling.

Development

Tasks are run with Task; task --list shows them all.

task test      # builds the wasip1 test stub, runs the harness suite
task verify    # everything CI runs, and the checklist before tagging
task wasm      # rebuilds through the pinned Rust 1.88 + Binaryen 131 builder

There are two suites, split by build tag:

  • anydoc_test.go runs under -tags anydoc_nowasm against a stub built with Go's own wasip1 target. The stub speaks the same ABI without converting anything, so the harness — stdio wiring, exit-code mapping, concurrency, cancellation, memory containment — is testable with no Rust toolchain in the loop. See testdata/README.md.
  • anydoc_real_test.go is tagged !anydoc_nowasm, so it compiles exactly when anydoc.wasm is in the tree, and covers what the harness is for: real conversion output, format detection, and the error codes the crate actually emits.

anydoc.wasm is a build artifact committed to the repo, because Go modules have no build step: whatever is committed is what go get delivers. It is built from the pinned crate by task wasm through the clean pinned builder; anydoc.wasm.sha256 records the checksum of the committed copy. See anydoc.wasm.README for the exact toolchain and digest pins.

Versioning

This module's version is independent of the crate's. The crate is pinned with = in rust/Cargo.toml, and moving to a new upstream release is a deliberate act: edit the pin, run task wasm, review what changed in the conversion output, then tag. An upstream release on its own changes nothing here.

anydoc.EmbeddedAnydocVersion reports which crate version the embedded module was built from. anydoc.EmbeddedWASMRevision() and anydoc.Info() add the full WASM digest, making the shim and optimization pipeline part of the behavioral identity. The crate version is copied from rust/Cargo.lock by task sync-version, and task check-version fails the build if the two ever disagree.

rust/Cargo.lock is committed too. The = pin only fixes anydoc itself; the lockfile is what stops a transitive dependency from silently changing the conversion output between one rebuild and the next.

License

MIT for this package — see LICENSE. The embedded module is built from anydoc, also MIT — see LICENSE-anydoc.

Documentation

Overview

Package anydoc converts office documents to Markdown by running the anydoc Rust library as WebAssembly, with no cgo and no external processes.

The wasm module is embedded, so a binary built with this package is self-contained and cross-compiles anywhere Go does:

CGO_ENABLED=0 GOOS=windows GOARCH=arm64 go build ./...

Basic use:

c, err := anydoc.New()
defer c.Close(ctx)
md, err := c.Convert(ctx, docBytes, "docx")

Index

Constants

View Source
const (
	// MaxMarkdownBytes protects the host from a guest that emits output that
	// cannot be accepted by the product. The product's normalized-content limit
	// is a separate, smaller domain rule enforced by the caller.
	MaxMarkdownBytes = 10 * 1024 * 1024

	// MaxStderrBytes keeps document-derived diagnostics bounded. The binding
	// never uses stderr to decide which typed outcome occurred.
	MaxStderrBytes = 32 * 1024
)
View Source
const EmbeddedAnydocVersion = "0.1.9"

EmbeddedAnydocVersion is the upstream crate version this wasm was built from. Copied from rust/Cargo.lock by `task sync-version`; `task check-version` fails the build if the two drift apart.

Variables

View Source
var (
	// ErrUnsupported means the input was not a format anydoc can parse, either
	// because the content signature matched nothing or the hint named a format
	// that does not exist.
	ErrUnsupported = errors.New("anydoc: unsupported format")

	// ErrInvalid means a recognised document is malformed or lacks a required
	// package part. Both are terminal document-input outcomes.
	ErrInvalid = errors.New("anydoc: invalid document")

	// ErrEncrypted means the document is password-protected. anydoc does not
	// decrypt; obtain a decrypted copy first.
	ErrEncrypted = errors.New("anydoc: document is encrypted")

	// ErrScannedOnly means a PDF contains no usable text layer and requires OCR.
	ErrScannedOnly = errors.New("anydoc: scanned-only document")

	// ErrResourceLimit means a guard inside anydoc, a guest memory ceiling, or a
	// host output ceiling tripped.
	ErrResourceLimit = errors.New("anydoc: resource limit exceeded")

	// ErrWASM means the guest trapped or otherwise failed without a typed
	// document outcome. It is an internal execution error.
	ErrWASM = errors.New("anydoc: wasm execution failed")

	// ErrNoWASM means no module was available: the build used the
	// anydoc_nowasm tag and no WithWASM option was supplied.
	ErrNoWASM = errors.New("anydoc: no wasm module (build without anydoc_nowasm, or pass WithWASM)")
)

Sentinel errors returned by Convert. Match them with errors.Is.

The numeric codes behind these live in rust/src/main.rs and abi/exit-codes.tsv and are part of the embedded module ABI. A changed table requires a rebuilt artifact and a full acceptance run.

Functions

func EmbeddedWASMDigest

func EmbeddedWASMDigest() string

EmbeddedWASMDigest returns the full SHA-256 digest of the module carried by this build. A caller that supplies an out-of-band module must record that module's digest separately; it is intentionally not reported as embedded.

func EmbeddedWASMRevision

func EmbeddedWASMRevision() string

EmbeddedWASMRevision is the immutable behavioral identity of the embedded converter. The upstream crate version alone is not sufficient because the shim and optimization pipeline are part of the artifact.

func Info

func Info() string

Info reports what this build is carrying, for diagnostics and version reporting in host applications.

Types

type ConvertError

type ConvertError struct {
	Kind   error  // one of the sentinels above
	Detail string // bounded guest stderr or host-side detail, may be empty
	Code   int    // raw ABI exit code, for debugging and provenance
}

ConvertError carries a bounded diagnostic alongside a sentinel. The exit code, never the diagnostic text, determines Kind.

func (*ConvertError) Error

func (e *ConvertError) Error() string

func (*ConvertError) Unwrap

func (e *ConvertError) Unwrap() error

type Converter

type Converter struct {
	// contains filtered or unexported fields
}

Converter runs conversions. It is safe for concurrent use and should be created once and reused: New compiles the module, which is the expensive part, and Convert then instantiates a cheap short-lived guest per document.

func New

func New(opts ...Option) (*Converter, error)

New prepares the wasm module and runtime once for reuse across conversions.

func (*Converter) Close

func (c *Converter) Close(ctx context.Context) error

Close releases the runtime. The Converter is unusable afterwards.

Close must not run concurrently with Convert. A caller that shares one Converter across requests must first stop accepting conversions and wait for the active calls to finish, then call Close. The application adapter owns that quiescence boundary because wazy does not make runtime shutdown safe against an active module invocation.

func (*Converter) Convert

func (c *Converter) Convert(ctx context.Context, doc []byte, hint string) (string, error)

Convert turns a document into Markdown.

hint is a bare extension such as "docx" that selects the parser. Pass "" to detect from content, which works for every format except CSV, which has no signature and must be named.

Each call gets a fresh guest instance with its own linear memory. A large document therefore cannot leave memory permanently claimed, and a malformed one cannot leak state into the next call.

func (*Converter) ConvertReader

func (c *Converter) ConvertReader(ctx context.Context, r io.Reader, hint string) (string, error)

ConvertReader is a convenience wrapper that reads r fully before converting. The whole document has to be in memory regardless: it is copied into the guest's linear memory.

type Option

type Option func(*config)

Option configures a Converter.

func WithCompiler

func WithCompiler() Option

WithCompiler trades startup cost and memory for throughput, by having wazy compile the module to native code instead of interpreting it.

The compilation is paid once, in New, not per document: Convert only instantiates the already-compiled module. So this pays off in a long-lived process that reuses one Converter, and is a pure loss in a short-lived one that converts a single small document and exits. Leave it off for tight containers too.

This is a request, not a guarantee. The compiler backend needs amd64 or arm64 (with SSE4.1 on amd64) on a mainstream OS, and needs the host to allow mmap'd executable pages -- macOS hardened runtime and some seccomp profiles refuse them. Where it is unavailable, wazy falls back to the interpreter silently: the conversion still happens, at interpreter speed. Nothing here affects cross-compilation, since wazy is pure Go.

func WithConcurrency

func WithConcurrency(n int) Option

WithConcurrency caps simultaneous guest instances. Each holds its own linear memory, so this is the main lever on peak memory. Default 1.

func WithMaxInputBytes

func WithMaxInputBytes(n int) Option

WithMaxInputBytes rejects documents larger than n before any wasm runs. Zero disables the check. Default 20 MiB.

func WithMemoryLimitPages

func WithMemoryLimitPages(pages uint32) Option

WithMemoryLimitPages caps one guest's linear memory in 64 KiB pages. Default 1024 (64 MiB).

What a guest needs tracks the uncompressed content rather than the input's size on disk, so a compact file can still be expensive. Measured against the real module: 64 pages is the module's own floor and converts nothing, a docx with a 0.4 MB body needs 192, a 2 MB body 576, a 5 MB body 1280, and a 7.5 MB PDF needs between 512 and 1024.

Raise this when a representative input hits the guest memory ceiling and returns ErrResourceLimit; input and host-output limits are separate. Each concurrent guest can claim up to this much, so this multiplied by WithConcurrency is the real ceiling.

Validated at New time against the module's declared minimum, so too low a value fails immediately rather than at conversion.

func WithWASM

func WithWASM(r io.Reader) Option

WithWASM supplies the module instead of using the embedded one.

This is the counterpart to building with -tags anydoc_nowasm, where nothing is embedded and this option becomes mandatory. It is also useful without the tag: pinning a different anydoc build, loading from a shared volume, or keeping the payload in its own container layer.

The module is read immediately; r is not retained.

func WithWASMBytes

func WithWASMBytes(b []byte) Option

WithWASMBytes is WithWASM for a module already in memory.

Directories

Path Synopsis
examples
convert command
internal
fixturegen command
Command fixturegen writes the deterministic, content-free Phase 1 contract corpus.
Command fixturegen writes the deterministic, content-free Phase 1 contract corpus.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL