Changes
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..4c1dba5
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+/build_wasm/
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 6609e9f..65fd17f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -44,10 +44,56 @@ target_include_directories(macrodown_lib PUBLIC
target_link_libraries(macrodown_lib PUBLIC uni-algo::uni-algo)
-# Executables and Testing
-# Only build these if MacroDown is the top-level project, avoiding pollution of consumer builds.
-if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
-
+# Browser library and preview assets.
+option(MACRODOWN_BUILD_WASM "Build the WebAssembly module and demo" ${EMSCRIPTEN})
+if(MACRODOWN_BUILD_WASM)
+ if(NOT EMSCRIPTEN)
+ message(FATAL_ERROR "Use emcmake to build MACRODOWN_BUILD_WASM")
+ endif()
+
+ target_compile_options(macrodown_lib PRIVATE -fexceptions)
+ add_executable(macrodown_wasm src/wasm_bindings.cpp)
+ target_link_libraries(macrodown_wasm PRIVATE macrodown_lib)
+ target_compile_options(macrodown_wasm PRIVATE -fexceptions)
+ target_link_options(macrodown_wasm PRIVATE
+ --no-entry
+ -lembind
+ -fexceptions
+ -sMODULARIZE=1
+ -sEXPORT_ES6=1
+ -sEXPORT_NAME=createMacroDown
+ -sALLOW_MEMORY_GROWTH=1
+ -sENVIRONMENT=web,worker,node
+ )
+ set_target_properties(macrodown_wasm PROPERTIES
+ OUTPUT_NAME macrodown
+ SUFFIX ".mjs"
+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/web"
+ )
+ foreach(asset index.html preview.css preview.js render_worker.js)
+ configure_file(web/${asset} web/${asset} COPYONLY)
+ endforeach()
+endif()
+
+# Native executables and tests default to top-level native builds only.
+set(MACRODOWN_NATIVE_DEFAULT OFF)
+if(PROJECT_IS_TOP_LEVEL AND NOT EMSCRIPTEN)
+ set(MACRODOWN_NATIVE_DEFAULT ON)
+endif()
+option(MACRODOWN_BUILD_CLI "Build the command-line tool"
+ ${MACRODOWN_NATIVE_DEFAULT})
+option(MACRODOWN_BUILD_TESTS "Build native tests"
+ ${MACRODOWN_NATIVE_DEFAULT})
+
+if(MACRODOWN_BUILD_CLI)
+ add_executable(macrodown src/main.cpp)
+ target_link_libraries(macrodown PRIVATE macrodown_lib)
+endif()
+
+if(MACRODOWN_BUILD_TESTS)
+ if(EMSCRIPTEN)
+ message(FATAL_ERROR "Use the Node smoke test for WebAssembly")
+ endif()
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/refs/heads/main.zip
@@ -56,9 +102,6 @@ if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
- add_executable(macrodown src/main.cpp)
- target_link_libraries(macrodown PRIVATE macrodown_lib)
-
# Testing
enable_testing()
diff --git a/README.md b/README.md
index 5b2f37d..2271e7a 100644
--- a/README.md
+++ b/README.md
@@ -154,3 +154,77 @@ cd build
* `src/`: Source code.
* `tests/`: Unit and integration tests.
* `design.md`: Detailed design document.
+
+## WebAssembly and live preview
+
+Install and activate [Emscripten](https://emscripten.org/docs/getting_started/downloads.html),
+then configure a separate build directory:
+
+```sh
+emcmake cmake -S . -B build_wasm -DCMAKE_BUILD_TYPE=Release
+cmake --build build_wasm -j24
+python3 -m http.server 8000 --directory build_wasm/web
+```
+
+Open <http://localhost:8000>. The demo renders locally in a module Web Worker
+with a 150 ms typing debounce. It displays the generated HTML in a sandboxed
+iframe that blocks scripts and network requests, including external images.
+Serve the files over HTTP rather than opening `index.html` directly.
+
+### Smaller production builds
+
+To optimize for download size, use `-Oz` and link-time optimization instead
+of the release build above:
+
+```sh
+emcmake cmake -S . -B build_wasm \
+ -DCMAKE_BUILD_TYPE=MinSizeRel \
+ '-DCMAKE_CXX_FLAGS_MINSIZEREL=-Oz -DNDEBUG -flto' \
+ -DCMAKE_EXE_LINKER_FLAGS=-flto
+cmake --build build_wasm -j24
+```
+
+With Emscripten 6.0.12, this reduced the Wasm file from approximately
+342 KiB to 279 KiB. The size-optimized file compressed to approximately
+90 KiB with gzip or 74 KiB with Brotli. Sizes vary with the toolchain and
+source version; size optimization may trade some execution speed for size.
+The release Wasm already omits debug and symbol-name sections, so additional
+stripping offers little benefit.
+
+Enable gzip or Brotli compression on your production HTTP server for both
+the `.wasm` and `.mjs` files. Serve `.wasm` as `application/wasm`, `.mjs` as
+JavaScript, and compressed responses with the matching `Content-Encoding`
+header. The Python server above is for local preview and does not enable
+compression automatically.
+
+### JavaScript API
+
+The build produces `macrodown.mjs` and `macrodown.wasm`. Keep these files
+alongside one another when using the module in another frontend:
+
+```js
+import createMacroDown from "./macrodown.mjs";
+
+const macrodown = await createMacroDown();
+const html = macrodown.renderMarkdown("# Hello");
+```
+
+`renderMarkdown(source)` returns an HTML string synchronously after module
+initialization. Every call uses a fresh document and macro environment.
+Custom macros defined in the source work as in the native renderer. The API
+does not yet expose programmatic macro or markup registration. For large
+documents, use a worker as the demo does; each update parses the full source.
+Generated HTML is not sanitized. Use an appropriate sandbox or sanitizer
+when displaying untrusted documents in your application.
+
+Native CLI and GoogleTest targets default to off under Emscripten, and retain
+their existing defaults for native builds. They can be controlled separately
+with `MACRODOWN_BUILD_CLI` and `MACRODOWN_BUILD_TESTS`.
+`MACRODOWN_BUILD_WASM` defaults to on under Emscripten.
+
+Run the JavaScript/Wasm smoke tests with Node (optionally providing a native
+binary to check output parity):
+
+```sh
+node tests/test_wasm.mjs build_wasm/web/macrodown.mjs build/macrodown
+```
diff --git a/src/wasm_bindings.cpp b/src/wasm_bindings.cpp
new file mode 100644
index 0000000..9dbbdfc
--- /dev/null
+++ b/src/wasm_bindings.cpp
@@ -0,0 +1,21 @@
+#include <emscripten/bind.h>
+
+#include "macrodown.h"
+
+namespace
+{
+
+// Render one independent document without retaining its macro definitions.
+std::string renderMarkdown(const std::string& source)
+{
+ macrodown::MacroDown document;
+ auto root = document.parse(source);
+ return document.render(*root);
+}
+
+} // namespace
+
+EMSCRIPTEN_BINDINGS(macrodown)
+{
+ emscripten::function("renderMarkdown", &renderMarkdown);
+}
diff --git a/tests/test_wasm.mjs b/tests/test_wasm.mjs
new file mode 100644
index 0000000..8805b82
--- /dev/null
+++ b/tests/test_wasm.mjs
@@ -0,0 +1,46 @@
+import assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {resolve} from "node:path";
+import {pathToFileURL} from "node:url";
+import {spawnSync} from "node:child_process";
+
+// Exercise the actual JS/Wasm boundary and optionally compare a native binary.
+const module_path = resolve(process.argv[2] ?? "build_wasm/web/macrodown.mjs");
+const {default: createMacroDown} = await import(pathToFileURL(module_path));
+const renderer = await createMacroDown({
+ wasmBinary: readFileSync(module_path.replace(/\.mjs$/, ".wasm"))
+});
+const cases = [
+ "",
+ "# Hello\n\nParagraph with *em* and %code{macros}.",
+ "Unicode: café, 中文, 🌍.\n",
+ "%def[greet]{name}{Hello, %strong{%name}!}\n\n%greet{World}",
+ "- One\n- Two\n\n[Example](https://example.com)",
+ "```cpp\nint main() {}\n```",
+ "%def[temporary]{}{DEFINED}\n\n%temporary",
+ "Plain document"
+];
+for(const source of cases)
+{
+ const html = renderer.renderMarkdown(source);
+ assert.equal(typeof html, "string");
+ if(process.argv[3])
+ {
+ const native = spawnSync(resolve(process.argv[3]), [],
+ {input: source, encoding: "utf8", timeout: 5000});
+ assert.equal(native.status, 0, native.stderr);
+ assert.equal(html, native.stdout, source);
+ }
+}
+assert.equal(renderer.renderMarkdown("# Hello"), "<h1>Hello</h1>\n");
+assert.match(renderer.renderMarkdown(cases[2]), /café, 中文, 🌍/u);
+assert.match(renderer.renderMarkdown(cases[3]), /Hello, <strong>World<\/strong>!/);
+renderer.renderMarkdown(cases[6]);
+assert.equal(renderer.renderMarkdown("%temporary"), "<p>%temporary</p>\n");
+assert.equal(renderer.renderMarkdown("Plain document"),
+ "<p>Plain document</p>\n");
+for(let index = 0; index < 100; index += 1)
+{
+ assert.equal(renderer.renderMarkdown("# Repeat"), "<h1>Repeat</h1>\n");
+}
+console.log("Wasm smoke tests passed (Unicode, macros, isolation, repeats).");
diff --git a/web/index.html b/web/index.html
new file mode 100644
index 0000000..0aa047c
--- /dev/null
+++ b/web/index.html
@@ -0,0 +1,37 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>MacroDown live preview</title>
+ <link rel="stylesheet" href="preview.css">
+ <script type="module" src="preview.js"></script>
+</head>
+<body>
+ <header>
+ <h1>MacroDown</h1>
+ <p>Live Markdown and macro preview · rendered in your browser</p>
+ <p id="status" role="status">Loading renderer…</p>
+ </header>
+ <main>
+ <section>
+ <label for="source">Source</label>
+ <textarea id="source" spellcheck="false"># Hello, MacroDown
+
+Edit this document to update the preview.
+
+%def[greet]{name}{Hello, %strong{%name}!}
+
+%greet{World}
+
+Unicode works too: café, 中文, 🌍.
+</textarea>
+ </section>
+ <section>
+ <h2>Preview</h2>
+ <iframe id="preview" title="Rendered document" sandbox=""
+ referrerpolicy="no-referrer"></iframe>
+ </section>
+ </main>
+</body>
+</html>
diff --git a/web/preview.css b/web/preview.css
new file mode 100644
index 0000000..98a8dbd
--- /dev/null
+++ b/web/preview.css
@@ -0,0 +1,48 @@
+:root
+{
+ color-scheme: light dark;
+ font-family: system-ui, sans-serif;
+}
+body
+{
+ margin: 0 auto;
+ max-width: 100rem;
+ padding: 1.5rem;
+}
+h1 { margin: 0; }
+header p { margin: 0.5rem 0; }
+#status { min-height: 1.5em; }
+main
+{
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 1.5rem;
+}
+section { min-width: 0; }
+label, h2
+{
+ display: block;
+ font-size: 1rem;
+ font-weight: 600;
+ margin: 0 0 0.75rem;
+}
+textarea, iframe
+{
+ box-sizing: border-box;
+ width: 100%;
+ height: 65vh;
+ border: 1px solid #888;
+ border-radius: 0.4rem;
+}
+textarea
+{
+ padding: 1rem;
+ font: 1rem/1.6 ui-monospace, monospace;
+ resize: vertical;
+}
+iframe { background: white; }
+@media(max-width: 48rem)
+{
+ main { grid-template-columns: 1fr; }
+ textarea, iframe { height: 45vh; }
+}
diff --git a/web/preview.js b/web/preview.js
new file mode 100644
index 0000000..3aba901
--- /dev/null
+++ b/web/preview.js
@@ -0,0 +1,68 @@
+const source = document.getElementById("source");
+const preview = document.getElementById("preview");
+const status = document.getElementById("status");
+const worker = new Worker(new URL("./render_worker.js", import.meta.url),
+ {type: "module"});
+let ready = false;
+let busy = false;
+let revision = 0;
+let timer;
+
+function render()
+{
+ if(!ready || busy)
+ {
+ return;
+ }
+ busy = true;
+ status.textContent = "Rendering…";
+ worker.postMessage({id: revision, source: source.value});
+}
+
+function scheduleRender()
+{
+ revision += 1;
+ clearTimeout(timer);
+ timer = setTimeout(render, 150);
+}
+
+function receiveMessage(event)
+{
+ const result = event.data;
+ if(result.type === "ready")
+ {
+ ready = true;
+ render();
+ return;
+ }
+ busy = false;
+ if(result.id !== undefined && result.id !== revision)
+ {
+ render();
+ return;
+ }
+ if(result.type === "error")
+ {
+ status.textContent = `Renderer error: ${result.message}`;
+ return;
+ }
+ // Keep document HTML isolated, with scripts and network requests blocked.
+ preview.srcdoc = `<!doctype html><html><head><meta charset="utf-8">
+ <meta http-equiv="Content-Security-Policy"
+ content="default-src 'none'; style-src 'unsafe-inline'">
+ <style>body { font: 16px/1.6 system-ui; padding: 1rem;
+ overflow-wrap: anywhere; } pre { overflow: auto; }</style>
+ </head><body>${result.html}</body></html>`;
+ status.textContent = `Updated in ${result.duration.toFixed(1)} ms`;
+}
+
+function workerFailed(event)
+{
+ ready = false;
+ busy = false;
+ status.textContent = `Could not load renderer: ${event.message}`;
+}
+
+source.addEventListener("input", scheduleRender);
+worker.addEventListener("message", receiveMessage);
+worker.addEventListener("error", workerFailed);
diff --git a/web/render_worker.js b/web/render_worker.js
new file mode 100644
index 0000000..3c7783d
--- /dev/null
+++ b/web/render_worker.js
@@ -0,0 +1,28 @@
+import createMacroDown from "./macrodown.mjs";
+
+let renderer;
+try
+{
+ renderer = await createMacroDown();
+ self.postMessage({type: "ready"});
+}
+catch(error)
+{
+ self.postMessage({type: "error", message: String(error)});
+}
+
+self.onmessage = function(event)
+{
+ const {id, source} = event.data;
+ try
+ {
+ const start = performance.now();
+ const html = renderer.renderMarkdown(source);
+ self.postMessage({type: "result", id, html,
+ duration: performance.now() - start});
+ }
+ catch(error)
+ {
+ self.postMessage({type: "error", id, message: String(error)});
+ }
+};