Open in a new tab

Pick a document (or press "Try a sample") and convert it to Markdown in oconv's bundled worker, off the page's thread; the sample is first written as a DOCX by the same worker, then read back. Nothing is uploaded.

Uses @awacloud/oconv (AGPL-3.0-only) over @awacloud/fw (Apache-2.0). This example's code is AGPL-3.0-only.

When to use it

A large file — a long report, a workbook, a slide deck — takes long enough to convert that the page would stop answering clicks and scrolls if it ran on the main thread. In a worker the page stays responsive, and the file still never leaves the browser.

Copy-paste steps

  1. npm install @awacloud/oconv (it depends on @awacloud/fw, md, ooxml, odf, pdf and fonts).
  2. Serve node_modules/@awacloud/oconv/src/ at /vendor/oconv/ with any static server (node serve.js from the examples root does this). The worker is the single file src/worker.js: it imports nothing, so it needs neither the other packages served nor an import map of its own.
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link. Keep the legal notice under </main>: copy ../../LICENSES/AGPL-3.0-only.txt along, or point its link at your copy. The page's import map resolves the worker's specifier; you can drop it and write new Worker('/vendor/oconv/worker.js', { type: 'module' }) instead.
  4. Keep ask, toDocx and toMarkdown as your worker client: one message in, one reply out, matched by id.

What it shows

  • Starting the worker: import.meta.resolve('@awacloud/oconv/worker.js') gives the worker file's URL through the import map (/vendor/oconv/worker.js here); new Worker(url, { type: 'module' }) starts it on first use. No ModuleRuntime runs on the page: the worker builds its own.
  • The protocol: each message carries an id, and ask resolves with the reply that has the same id, so two conversions can overlap. A message with markdown is fromMd (the reply carries bytes); one with bytes and no target is toMd (the reply carries markdown, and at, an ISO-8601 date, is recorded in the front matter). Every reply has ms and losses.
  • Transfer, not copy: toMarkdown copies the caller's bytes once and transfers that ArrayBuffer to the worker (postMessage(message, [buffer])), so a large file is not duplicated on the way.
  • Errors as data: a failed conversion never throws across the boundary; the reply's error is a string (oconv: unsupported format for a .txt), shown in the status line.
  • Not shown: convert (document to document, target set), the fromMd options (opts, assets, fonts), and a pool of workers for many files at once.

Code

main.js

javascriptAGPL-3.0-only73 lines

// SPDX-License-Identifier: AGPL-3.0-only
// No ModuleRuntime on this page: the converter runs in oconv's bundled worker, which imports nothing.

/** The worker file, through the import map (`/vendor/oconv/worker.js` on this site). */
export const WORKER_URL = import.meta.resolve('@awacloud/oconv/worker.js');
export const SAMPLE = '# Quarterly report\n\nRevenue grew **12 %**.\n\n- Hire\n- Ship\n';

let nextId = 0;

/**
 * Post one message and await the reply with the same `id`. A failed conversion
 * comes back as data (`error` set), never as an exception across the boundary.
 * @param {Worker} worker @param {object} message @param {Transferable[]} [transfer]
 * @returns {Promise<any>}
 */
export function ask(worker, message, transfer = []) {
    const id = ++nextId;
    return new Promise((resolve) => {
        const onReply = (/** @type {MessageEvent} */ ev) => {
            if (ev.data?.id !== id) return;
            worker.removeEventListener('message', onReply);
            resolve(ev.data);
        };
        worker.addEventListener('message', onReply);
        worker.postMessage({ id, ...message }, transfer);
    });
}

/** Markdown to a DOCX file (`fromMd`: the reply carries `bytes`). @param {Worker} worker @param {string} markdown */
export const toDocx = (worker, markdown) => ask(worker, { name: 'sample.docx', markdown });

/**
 * A document to Markdown (`toMd`). The bytes are transferred, not copied; the
 * format comes from the name's extension; `at` is recorded in the front matter.
 * @param {Worker} worker @param {string} name @param {Uint8Array} bytes
 */
export function toMarkdown(worker, name, bytes) {
    const buffer = bytes.slice().buffer;
    return ask(worker, { name, bytes: buffer, at: new Date().toISOString() }, [buffer]);
}

/** @type {Worker | undefined} */
let worker;
const getWorker = () => (worker ??= new Worker(WORKER_URL, { type: 'module' })); // started on first use
const input = /** @type {HTMLInputElement} */ (document.getElementById('file'));
const status = /** @type {HTMLElement} */ (document.getElementById('status'));
const output = /** @type {HTMLElement} */ (document.getElementById('markdown'));
const losses = /** @type {HTMLElement} */ (document.getElementById('losses'));

/** @param {string} name @param {Uint8Array} bytes @param {string} [before] what ran first */
async function read(name, bytes, before = '') {
    const reply = await toMarkdown(getWorker(), name, bytes);
    output.textContent = reply.markdown ?? '';
    const codes = reply.losses.map((/** @type {{ code: string }} */ loss) => loss.code);
    if (!codes.length) codes.push('no loss recorded');
    losses.replaceChildren(...codes.map((code) => Object.assign(document.createElement('li'), { textContent: code })));
    const ms = Math.round(reply.ms);
    status.textContent = reply.error ? `${name}: ${reply.error}` : `${before}${name} read in ${ms} ms in the worker`;
}

input.addEventListener('change', async () => {
    const [file] = input.files ?? [];
    if (file) await read(file.name, new Uint8Array(await file.arrayBuffer()));
});
document.getElementById('sample')?.addEventListener('click', async () => {
    const built = await toDocx(getWorker(), SAMPLE);
    if (built.error) {
        status.textContent = `sample: ${built.error}`;
        return;
    }
    const made = `sample.docx built (${built.bytes.length} bytes) in ${Math.round(built.ms)} ms; `;
    await read('sample.docx', built.bytes, made);
});

index.html

htmlAGPL-3.0-only54 lines

<!doctype html>
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>oconv · Convert in a Web Worker</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/",
    "@awacloud/pdf": "/vendor/pdf/main.js", "@awacloud/pdf/": "/vendor/pdf/",
    "@awacloud/fonts": "/vendor/fonts/main.js", "@awacloud/fonts/": "/vendor/fonts/",
    "@awacloud/oconv": "/vendor/oconv/main.js", "@awacloud/oconv/": "/vendor/oconv/",
    "@awacloud/md": "/vendor/md/main.js", "@awacloud/md/": "/vendor/md/",
    "@awacloud/ooxml": "/vendor/ooxml/main.js", "@awacloud/ooxml/": "/vendor/ooxml/",
    "@awacloud/odf": "/vendor/odf/main.js", "@awacloud/odf/": "/vendor/odf/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Convert in a Web Worker</h1>
    <p>
      <label for="file">Document (DOCX, XLSX, PPTX, ODT, ODS, ODP or PDF)</label>
      <input id="file" type="file" accept=".docx,.xlsx,.pptx,.odt,.ods,.odp,.pdf">
      <button id="sample" type="button">Try a sample</button>
    </p>
    <p>The conversion runs in a worker, off the page's thread; the file never leaves the browser.</p>
    <p id="status" aria-live="polite"></p>
    <h2>Markdown</h2>
    <pre id="markdown"></pre>
    <h2>Loss ledger</h2>
    <ul id="losses"></ul>
  </main>
  <!-- aln:begin (AGPL-3.0 sections 0, 5d and 13; derived by _harness/contract.js legalNotice, checked by C7) -->
  <footer id="legal" aria-label="Legal notices">
    <p>Copyright (c) 2026 AwaCloud SAS. This page is free software under the GNU Affero General Public License,
      version 3 only (AGPL-3.0-only), with ABSOLUTELY NO WARRANTY:
      <a href="../../LICENSES/AGPL-3.0-only.txt">licence text</a>.</p>
    <p>It runs these packages, each with its own LICENSE and NOTICE file (third-party notices included):</p>
    <ul>
      <li>@awacloud/fw · Apache-2.0</li>
      <li>@awacloud/pdf · AGPL-3.0-only</li>
      <li>@awacloud/fonts · AGPL-3.0-only</li>
      <li>@awacloud/oconv · AGPL-3.0-only</li>
      <li>@awacloud/md · AGPL-3.0-only</li>
      <li>@awacloud/ooxml · AGPL-3.0-only</li>
      <li>@awacloud/odf · AGPL-3.0-only</li>
    </ul>
  </footer>
  <!-- aln:end -->
</body>
</html>