accessible-books-in-browsers

How a book is converted

This is how the converter (convert/) turns an EPUB into a web book, step by step. Each step links to the code that does it, with the reasons behind it. The v0 contract describes what the output contains, and The conversion report and log explains the report each conversion writes.

It’s for people working on the converter. The line links point at the code as of 2026-11-17. If a line has moved, search the file for the function name.

The rules every step follows

Everything below follows these rules. If a change seems to need breaking one, ask first.

The steps

convert() runs the steps below, in this order.

1. Stage the output

First, checkOutputPath refuses an output folder that is, contains or is inside the EPUB or the template (through links too), since replacing it would delete them. createOutputStaging makes a temporary folder, and everything is written there. At the end, finalizeOutput moves it into place: an earlier book in the output folder is moved aside first and deleted only once the new one is there. If anything fails, discardOutputStaging deletes the temporary folder, so a failed conversion never leaves a half-written book behind. The log (output.log) starts here (logger/).

2. Read the EPUB

epubParser.parse unzips the EPUB if it’s a file (unzip-epub.ts). A damaged archive gets repaired and unzipped again. An EPUB with a symbolic link in it is refused. Then it finds the package through META-INF/container.xml and reads two things.

Spine items marked linear="no" are left out, unless you use --include-non-linear (parseSpine).

3. Build the site model

buildSiteModel works out the plan for the web book, without writing anything yet.

4. Prepare the shared parts

Back in convert(), a few things are set up for the whole book.

5. Find the narration

For each content document with a media overlay, getMediaSegments reads its SMIL, with each phrase’s text target and audio clip. Each clip goes with the output page that has its target, which matters when a document was split. This happens first so that every page’s table of contents can show which pages have narration.

6. Transform each page

transformContent runs once per page, on one in-memory DOM, in this order.

  1. Read the book’s stylesheets on the whole source page, before anything changes, so the publisher’s selectors match the way they were written (readPageStylesheets).
  2. Turn meaningful styles into reader classes. Writing mode, direction, emphasis, alignment, indents and so on carry meaning, so they need to show in My settings too (applyWritingStyles). Vertical writing and -epub- properties are kept here.
  3. Track the publisher’s styles (PublisherSelectors). If a later change would stop a publisher rule from matching, that rule is “frozen” first, so As published still looks the way it was published.
  4. Remove the book’s scripts (removeActiveContent), on every page, whatever the cleanup option: script elements (SVG’s too), event handler attributes (onclick and so on), srcdoc, SVG animations of an href, and href, src, action and similar attributes that start with javascript: or vbscript:. The element a link was on stays, with its words. SVG image files get the same treatment as they’re copied, since an SVG opened by itself runs its scripts. The book’s body styles and stylesheet links go here too: the rewritten head style is the only book CSS in the output.
  5. EPUB semantics. epub:type becomes epubtype_* classes and, where DPUB-ARIA has one, a role (translateEpubTypes). Old rearnote(s) count as endnote(s), and deprecated doc-endnote roles are dropped.
  6. Images, and the book’s own audio and video (audio, video, source and track, and a video’s poster, as opposed to its narration) are registered for copying into images/, and their references are rewritten. A book’s hrefs are URLs, so they’re decoded before they name a file (chapter%20one.xhtml is chapter one.xhtml), here and wherever the converter reads one (resolveHrefPath). The copies’ own names are encoded where a URL needs it (a space, #, ? or %).
  7. Splitting. For a split document, only this page’s piece is kept (extractDocumentPiece), and links are rewritten to the final file names. A link to the book’s own navigation document goes to toc.html, the web book’s table of contents.
  8. Markup cleanup (cleanPublicationMarkup). These are the small mechanical fixes, and each one is counted in the report.
    • A heading’s title attribute is shown as its text if the heading is otherwise empty, and dropped if it repeats the text. An empty heading that only repeats the one next to it is removed (repairHeadingTitles).
    • xml:lang doesn’t do anything in HTML, so it’s copied to lang when the element’s text is in the expected script, and then removed. If the script doesn’t match, it isn’t copied, and the report says so (repairLanguages).
    • Numbered equations are marked (markNumberedEquations).
    • Empty <span>s are unwrapped and empty paragraphs are removed. If the publisher’s CSS styles them, they’re kept, and the paragraphs only show in As published (webbook-publisher-only), since publishers use them for spacing.
    • Table header cells without a scope get one.
    • A publication’s own <main> becomes a div, because the reader has its own main.
    • Positive tabindex values become 0. Media lose autoplay and get controls.
    • Tables are wrapped so they scroll sideways on narrow screens (wrapTables).

    It also looks for things to review and adds them to the report as warnings (analyzeWarnings). MathML alttext is left the way the book has it.

  9. Heading permalinks. Each heading gets a link to itself, with tabindex="-1" on the heading so following the link moves focus.
  10. Search passages are collected from the cleaned-up text (collectSearchPassages).
  11. Narration targets. Ids are only kept where something needs them (narration, navigation, links, or the publisher’s CSS). If a narrated phrase’s id isn’t needed for anything else, the phrase is found by a CSS path from the nearest kept id instead (applyStructureIds). This keeps the book’s markup clean.
  12. Id collisions. An id that clashes with one of the reader’s own is renamed, and everything that points to it is updated (renameCollidingIds).
  13. The publisher’s CSS for this page is written out. It’s scoped to the book’s content, in cascade layers under the reader’s settings, and frozen rules are padded to keep their specificity (publisherStyles). Fonts and images it uses are copied. --no-publisher-styles leaves it out completely.

7. Make each page’s narration

createAudioForPage makes one audio file and one cue file for each narrated page.

  1. Cut each clip into an uncompressed WAV, four at a time. Each source the page uses is first decoded once, from its first clip to its last, and the clips are cut from that (decodeSourceRanges, cutToWav). Pages are converted up to four at a time, half the computer’s cores.
  2. Fade each clip in and out over 5 ms, so the joins don’t click (applyClipFades).
  3. Join the clips, byte for byte, into one WAV (joinPcmFiles).
  4. Clean up (cleanupFilters). This cuts everything below 90 Hz (rumble), softens “p” and “b” pops, applies the chosen enhancements (warm EQ, compression, noise reduction, de-essing, click removal). Then it measures the loudness once (measureLoudness) and raises narration quieter than −18 LUFS to that level. Louder narration keeps its level. A limiter holds the peaks under −1.5 dB without delaying the audio (loudnessFilters).
  5. Encode once to the output format. With --small-audio (the default) that’s mono MP3, 24 kHz, 32 kb/s (SMALL_AUDIO_ENCODING). Otherwise it matches the source.
  6. Measure loudness, peaks and noise floor for the report (analyzeAudio).

Some decisions behind this:

The cue file (createVtt) is WebVTT. Each cue’s text is a JSON selector for its phrase, either an id or a CSS path from the nearest id (step 6.11).

8. Render and shape each page

TemplateRenderer.renderPage copies the template and fills it in. That means the page’s content in main, its title and language, the table of contents (with the current page marked and narrated pages flagged, renderToc), previous and next links, the audio and its cue track, the page list, the About panel’s metadata and accessibility summary, and the link to the publisher’s stylesheet. Writing direction and mode go on the page as attributes (applyWritingStylesToPage). Identical publisher stylesheets are only written once, named by their hash (styles/publisher-<hash>.css).

Then shapeBookPage turns the rendered page into the book’s plain page (plan 11). Each page gets:

With the first page, the navigation pages are written too. These are toc.html, about.html (all the EPUB’s metadata, credited to its source) and, if the book has a page list, pages.html. They’re regular pages that work on their own, even from the file system. Their names are reserved, so a source chapter called about.xhtml becomes about-content.html, and its links are updated.

9. Book-wide files

10. Report

11. Finish

The staging folder replaces the output folder (finalizeOutput).

Converting in the browser

The same code runs in a browser, bundled with stand-ins for Node’s file system, jsdom, logging and FFmpeg (plan 19). It’s in converter/, and each stand-in is listed in its Shims section. Narration works a little differently there. The browser decodes each audio source once and cuts the clips itself, lined up sample for sample with FFmpeg’s decoding, and ffmpeg.wasm does the fades, joins, cleanup and encoding. The results and measurements are in .claude/19_BROWSER_CONVERTER_FINDINGS.md.

The converter page has every option above except the audio cache, the optional checks and --ui-base-url (the page always uses the v0 update channel). Reader updates is always shown, and starts on the channel. The page asks you to confirm the EPUB passes EPUBCheck, since the browser can’t run it. Then it works in two steps. First you preview one of the book’s content documents (often a chapter), converted from a copy of the EPUB whose reading order is just that document, and shown right on the page. Then you convert the whole book and get a zip of the files to put on any website. Nothing is kept in the browser for good. The preview’s files are in the browser’s Cache Storage until the next preview replaces them, or the converter page is opened again. By default the preview stops the narration after 5 minutes, keeping only the phrases that start before then, so it converts in seconds instead of taking as long as the whole chapter.

Changing the converter