- Zig 71.4%
- TypeScript 28.6%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| .zed | ||
| examples | ||
| src | ||
| wasm | ||
| .gitignore | ||
| build.zig | ||
| build.zig.zon | ||
| README.md | ||
| test_json.zig | ||
| unizip.md | ||
| wasmbench | ||
Alchemy 🧪
Transmuting compressed archives into the purest knowledge
A modern EPUB reader library written in Zig that transforms the chaotic mess of ZIP files, XML namespaces, and nested manifests into beautifully structured stories. Like the ancient alchemists who sought to turn lead into gold, Alchemy takes the unreadable garble of EPUB internals and distills it into clean, accessible text.
Works on both native and WebAssembly targets—because transmutation should happen everywhere.
Features
- 📚 EPUB 3.x Support - The philosopher's stone for modern ebooks
- 🎯 Cross-platform - Transmute on any platform supported by Zig
- 🌐 WebAssembly Ready - Practice your craft in the browser
- 🔍 Full Metadata Parsing - Extract the essence of titles, authors, and identifiers
- 📖 Chapter Management - Organize the prima materia into coherent chapters
- 🗜️ ZIP Archive Handling - Decompress the base matter with unikizip
- 📝 XML Parsing - Distill meaning from the XML crucible
Requirements
- Zig 0.15.2 or later
Installation
Add Alchemy as a dependency in your build.zig.zon:
.dependencies = .{
.alchemy = .{
.url = "https://github.com/yourusername/alchemy/archive/main.tar.gz",
.hash = "...", // Run `zig build` to get the hash
},
},
Then in your build.zig:
const alchemy = b.dependency("alchemy", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("alchemy", alchemy.module("alchemy"));
Usage
Basic Example
const std = @import("std");
const alchemy = @import("alchemy");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// Load EPUB from file
const file_path = "path/to/book.epub";
const zip_data = try std.fs.cwd().readFileAlloc(allocator, file_path, 100 * 1024 * 1024);
defer allocator.free(zip_data);
var reader = try alchemy.EpubReader.initFromMemory(allocator, zip_data);
defer reader.deinit();
// Transmute the raw archive into pure book data
const book = try reader.getBookData();
// Access metadata
std.debug.print("Title: {s}\n", .{book.metadata.title});
std.debug.print("Language: {s}\n", .{book.metadata.language});
for (book.metadata.creators) |creator| {
std.debug.print("Author: {s}\n", .{creator});
}
// Read chapters
for (book.chapters) |chapter| {
std.debug.print("\nChapter: {s}\n", .{chapter.name});
for (chapter.content) |content| {
std.debug.print("{s}\n", .{content});
}
}
}
WebAssembly Usage
Build the WASM module:
zig build wasm
The compiled WASM file will be in zig-out/www/alchemy.wasm.
Use it with the TypeScript wrapper (see wasm/ directory):
import { Alchemy, Epub } from "./wasm/index.ts";
import { readFile } from "fs/promises";
// Example: Load an EPUB file and read its contents
async function main() {
try {
// Initialize the WASM module
console.log("Initializing Alchemy WASM...");
await Alchemy.init();
console.log("✓ Alchemy initialized successfully");
// Load EPUB file from disk
const epubPath = "./example.epub";
const fileBuffer = await readFile(epubPath);
const epubData = fileBuffer.buffer.slice(
fileBuffer.byteOffset,
fileBuffer.byteOffset + fileBuffer.byteLength,
);
// Create an Epub instance with the binary data
const epub = new Epub(epubData);
// Get book metadata and chapters
const bookData = epub.getBookData();
console.log(`\nBook Information:`);
console.log(` Title: ${bookData.title}`);
console.log(` Language: ${bookData.language}`);
console.log(` Chapters: ${bookData.chapters.length}`);
// Display chapter information
console.log(`\nChapters:`);
for (let i = 0; i < Math.min(5, bookData.chapters.length); i++) {
const chapter = bookData.chapters[i];
const paragraphCount = chapter.getParagraphs().length;
console.log(` ${i + 1}. ${chapter.name} (${paragraphCount} paragraphs)`);
// Display first paragraph of chapter as preview
const paragraphs = chapter.getParagraphs();
if (paragraphs.length > 0) {
const preview = paragraphs[0].substring(0, 100);
console.log(` Preview: ${preview}...`);
}
}
} catch (err) {
console.error("Error:", err);
}
}
main();
API Reference
EpubReader
The main interface for reading EPUB files.
Methods
init(allocator, file_path)- Initialize from a file path (native only)initFromMemory(allocator, zip_data)- Initialize from ZIP data in memorydeinit()- Clean up resourcesgetBookData()- Parse and return complete book dataanalyze()- Print debug information about the EPUB structureprintStructure()- List all files in the archive
BookData
Contains the parsed book content and metadata.
pub const BookData = struct {
chapters: []Chapter,
metadata: ContentOpf,
};
Chapter
Represents a single chapter with its content.
pub const Chapter = struct {
name: []const u8,
content: [][]const u8, // Array of content sections
};
ContentOpf
EPUB metadata from the content.opf file.
pub const ContentOpf = struct {
path: []const u8,
title: []const u8,
navfile: []const u8,
coverfile: []const u8,
creators: [][]const u8,
identifers: [][]const u8,
date: []const u8,
description: []const u8,
language: []const u8,
manifest: []OpfManifestItem,
spine: []SpineItem,
};
Building
# Build native executable
zig build
# Run the example
zig build run
# Build WebAssembly module
zig build wasm
# Run tests
zig build test
Project Structure
alchemy/
├── src/
│ ├── root.zig # Main library implementation (EpubReader)
│ ├── main.zig # Example CLI application
│ ├── wasm.zig # WebAssembly exports
│ └── xml.zig # XML parsing utilities
├── examples/ # Example HTML/JS files
├── build.zig # Build configuration
└── build.zig.zon # Dependencies
Dependencies
Limitations
- Only EPUB 3.x is supported (EPUB 2.x will return an error)
- Maximum file size: 100MB (configurable)
- Some advanced EPUB features may not be fully supported
Contributing
Contributions are welcome! Please ensure:
- Code follows Zig style guidelines
- All tests pass with
zig build test - New features include appropriate tests
License
MIT
Author
The Ducktor